seq_id stringlengths 7 11 | text stringlengths 156 1.7M | repo_name stringlengths 7 125 | sub_path stringlengths 4 132 | file_name stringlengths 4 77 | file_ext stringclasses 6
values | file_size_in_byte int64 156 1.7M | program_lang stringclasses 1
value | lang stringclasses 38
values | doc_type stringclasses 1
value | stars int64 0 24.2k ⌀ | dataset stringclasses 1
value | pt stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
7065948190 | # -*- coding: utf-8 -*-
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox
class MyWindow(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.myButton = QtWidgets.QPushButton(self)
self.myButton.clicked.connect(self.msg)
self.msg()
def msg(self):
... | kRayvison/Pycharm_python36 | k_test/temp_test.py | temp_test.py | py | 727 | python | en | code | 1 | github-code | 6 |
40880620153 | from flask import Flask, request, jsonify
import requests
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, StringType, BooleanType
import threading
import logging
import time
app = Flask(__name__)
# Create a SparkSession (Singleton)
spark = SparkSession.builder.appName("APID... | DennisVW0/DE_TASK | app.py | app.py | py | 3,411 | python | en | code | 0 | github-code | 6 |
38453053872 | import sys
input = sys.stdin.readline
n,m,r = map(int,input().split())
items = [0] + list(map(int,input().split()))
graph = [[int(5e6)]*(n+1) for _ in range(n+1)]
for _ in range(r):
s,e,w = map(int,input().split())
graph[s][e] = w
graph[e][s] = w
for i in range(1,n+1):
graph[i][i] = 0
def floyd():
... | LightPotato99/baekjoon | graph/floyd/pubg.py | pubg.py | py | 670 | python | en | code | 0 | github-code | 6 |
16930073280 | import shutil
import difflib
import filecmp
import logging
from prettyconf import config
BOOTSTRAP_TESTS = config("BOOTSTRAP_TESTS", default=False)
LOG = logging.getLogger(__name__)
def compare_files(*, got, expected):
"""Compares the contents of a test file against expected
Args:
got: file with t... | huiwenke/3d-beacons-client | tests/tests_cli/utils.py | utils.py | py | 1,186 | python | en | code | null | github-code | 6 |
71578318267 | import torch.nn as nn
from utils.config import config
import torch
import numpy as np
from model.bbox_tools import *
import torch.nn.functional as F
from torchvision.ops import nms
def nograd(f):
def new_f(*args, **kwargs):
with torch.no_grad():
return f(*args, **kwargs)
retur... | langfengQ/FasterRCNN-expanded-VOC2007 | model/faster_rcnn.py | faster_rcnn.py | py | 4,074 | python | en | code | 1 | github-code | 6 |
29702682927 | #!/usr/bin/env python3
import os
import numpy as np
import matplotlib.pyplot as plt
import sklearn
import pandas as pd
from pandas import DataFrame as df
from sklearn import svm
from sklearn.model_selection import KFold, cross_val_score
from scipy import stats
import seaborn as sns
from sklearn.linear_model ... | maybje/Fake-News-Detection | logistic.py | logistic.py | py | 3,056 | python | en | code | 0 | github-code | 6 |
29322733814 | from google.cloud import bigquery
import plotly.express as px
dataset_id = "salestest"
class DatasetManager(object):
def __init__(self, dataset_id):
self.dataset_id = dataset_id
self.client = self._get_client()
def print_listed_projeto(self):
"""INFORMA O NOME DO PROJETO DO SERVICE ... | luizgnunes/PesquisaJsonECriacaoGrafico | main.py | main.py | py | 4,026 | python | en | code | 0 | github-code | 6 |
32717608076 | import gymnasium as gym
from gymnasium import error, spaces, utils, Env
from gymnasium.spaces import MultiDiscrete, Box
from gymnasium.utils import seeding
import math
import pymunk
import pygame
from pymunk import pygame_util
screen_width = 1904
screen_height = 960
target = 350
class Robot():
def __init__(self, sp... | robertofiguz/2dWalker | Walker/envs/Walker_env.py | Walker_env.py | py | 15,192 | python | en | code | 0 | github-code | 6 |
21794976008 | # Example test given in the question
n = 3
p = [90, 80, 40]
x = 1000
def f(n: int):
if n <= 400:
return 1
else:
return 20
def Sell_Stocks(days, stocks, p, f):
opt = [[0 for i in range(stocks + 1)] for i in range(days + 1)] # opt table
s = [[0 for i in range(stocks + 1)] for i in range(days + 1)] # pri... | Asi4nn/UTSC | Year3/CSCC73/Assignments/a5_q2.py | a5_q2.py | py | 1,298 | python | en | code | 1 | github-code | 6 |
8413183584 | # %% markdown
## Experiment 3 Trials
# %%
import numpy as np
import fire
import random
import pandas as pd
import json
from itertools import product
from markdown import markdown
import textwrap
from copy import deepcopy
import os, sys, json, pprint
from vgc_project.gridutils import transformations, getFeatureXYs
# %%... | markkho/value-guided-construal | experiments/exp3/generate_trials.py | generate_trials.py | py | 25,424 | python | en | code | 20 | github-code | 6 |
29216406296 | import logging
import os
import pwd
import sys
from aiohttp import web
from aiomisc.utils import bind_socket
from configargparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from setproctitle import setproctitle
from yarl import URL
from megamarket.api.app import create_app
from megamarket.utils.argparse impo... | Dest0re/backend-school2022 | megamarket/api/__main__.py | __main__.py | py | 1,960 | python | en | code | 0 | github-code | 6 |
26239065759 | from __future__ import unicode_literals, absolute_import, print_function, division
import datetime
import time
from sopel.module import commands, rule, priority, thread
from sopel.tools import Identifier
from sopel.tools.time import seconds_to_human
@commands('seen')
def seen(bot, trigger):
"""Reports when and ... | examknow/Exambot-Source | sopel/modules/seen.py | seen.py | py | 2,014 | python | en | code | 2 | github-code | 6 |
21456848433 | #works but need to find out how to add sound
import datetime
from playsound import playsound
alarmhour = int(input("Enter Hour: "))
alarmins = int(input("Enter Minutes: "))
alarmAm = input("AM / PM: ").upper()
if alarmAm == "pm".upper():
alarmhour += 12
while True:
if alarmhour == datetime.datetime.now().hou... | MortalKhangbat/MACnCHEESE | alarm_clock.py | alarm_clock.py | py | 479 | python | en | code | 0 | github-code | 6 |
26244884344 | #! /usr/bin/env/python3
import sys
rawdata = sys.stdin.read().split('\n')
ID, dna = [], []
i = 0
while i < len(rawdata):
if rawdata[i] == '':
break
if rawdata[i][0] == '>':
ID.append(rawdata[i][1:])
dna.append("")
else:
dna[-1] += rawdata[i]
i += 1
gc = [100*(i.count(... | tak0kada/procon | rosalind/python/gc.py | gc.py | py | 434 | python | en | code | 0 | github-code | 6 |
137183376 | import ROOT
def safe_factory(func):
def wrapper(self, *args):
result = func(self, *args)
if not result:
raise ValueError('invalid factory input "%s"' % args)
return result
return wrapper
ROOT.RooWorkspace.factory = safe_factory(ROOT.RooWorkspace.factory)
def safe_decorato... | wiso/StatisticsLectures | create_example_ws.py | create_example_ws.py | py | 4,634 | python | en | code | 10 | github-code | 6 |
44613554676 | # coding=utf-8
import tensorflow as tf
import numpy as np
from data_helper import *
import gensim
import os
import time
import datetime
import csv
# TF log level
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# Parameters
# ==================================================
flags = tf.flags
logging = tf.logging
# Data Param... | anonymous-2018-COLING/pan11 | eval.py | eval.py | py | 5,829 | python | en | code | 1 | github-code | 6 |
70485936189 | import mysql.connector
connect_DB = mysql.connector.connect(user="root", passwd="S@b3d0ri@My5ql", host="localhost")
print(connect_DB)
mycursor = connect_DB.cursor()
# Quick introduction to the program
print("This is a simple Bank Account Model Design in Python.")
print("You will be able to add a new account, make dep... | MagnoCarlos/Bank_Account_Model_Py | Bank_AccountPy/main.py | main.py | py | 4,395 | python | en | code | 1 | github-code | 6 |
33511701341 | from collections import defaultdict
from src.data import data_manager
from src.data.neuron_info import ntype
from src.data.dataset_info import all_datasets, datasets_with_adj, timepoint
from src.plotting import plotter
class Figure(object):
def __init__(self, output_path, page_size=7.20472):
self.plt =... | dwitvliet/nature2021 | src/figures/feedforward.py | feedforward.py | py | 7,340 | python | en | code | 13 | github-code | 6 |
71484309308 | N = int(input())
ans = 0
ansx = []
for i in range(max(1, N-9*(len(str(N)))), N+1):
if i + sum([int(x) for x in str(i)]) == N:
ans += 1
ansx.append(i)
print(ans)
for x in ansx: print(x)
| knuu/competitive-programming | atcoder/arc/arc034_b.py | arc034_b.py | py | 208 | python | en | code | 1 | github-code | 6 |
70518540349 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ServiceInterval
Application implementation classes.
"""
from copy import copy
from datetime import date, timedelta
from numbers import Number
import os
import pickle
import re
import warnings
__author__ = 'Don D.S.'
# Version of ServiceInterval.
VERSION = (1, 0)
cl... | zokalo/pyServiceInterval | servint_utils.py | servint_utils.py | py | 29,824 | python | en | code | 0 | github-code | 6 |
9264229712 | from fnames import FileNames
import getpass
from socket import getfqdn
user = getpass.getuser() # Username of the user running the scripts
host = getfqdn() # Hostname of the machine running the scripts
print('Running on %s@%s' % (user, host))
if user == 'wmvan':
# My work laptop
target_path = 'M:/scratch/ep... | wmvanvliet/beamformer_simulation | megset/config.py | config.py | py | 5,242 | python | en | code | 4 | github-code | 6 |
26185561724 | """
Example:
words = ['cat', 'baby', 'dog', 'bird', 'car', 'ax']
string1 = 'tabncihjs'
find_embedded_word(words, string1) -> cat (the letters do not have to be in order)
"""
import collections
from typing import List
import unittest
# Using sorting
# words = ['cat', 'baby', 'dog', 'bird', 'car', 'ax'] -> act, abbbd... | 01o91939/leetcode | embeddedWord.py | embeddedWord.py | py | 2,392 | python | en | code | 0 | github-code | 6 |
32976566194 | from myNet import *
def to_one_hot(labels,n_labels):
new_labels = []
for label in labels:
new = [0]*n_labels
new[label] = 1
new_labels.append(new)
return new_labels
class FATWiSARD:
def __init__(self,nIn,nClasses,nRams,rInit=1):
self.brain = Brain(nIn,nC... | Alantlb/FAT-WiSARD | FATWiSARD.py | FATWiSARD.py | py | 1,771 | python | en | code | 0 | github-code | 6 |
8101746211 | # coding=utf-8
import streamlit as st
class selectValues():
def __init__(self):
self.points = ['腕', '肘', '膝', '頭', '投げ手', '足']
self.eval_kinds = ['パフォーマンス観点', '怪我観点']
self.timings = ['投げ始め', 'リリース時', '投げ終わり']
self.evaluates = ['○', '×']
self.total_evaluates = ['未評価', '1', '2... | ys201810/baseball_scoring_work | src/utils.py | utils.py | py | 743 | python | en | code | 0 | github-code | 6 |
41211516987 | import sys
import numpy as np
import pylab as plt
#
# read overview file
#----------------------------------------
def read_overview_file( fbase, NT ):
tmprtr = np.zeros( (NT) )
xH1 = np.zeros( (NT) )
xH2 = np.zeros( (NT) )
xHe1 = np.zeros( (NT) )
xHe2 = np.zeros( (NT) )
xHe3 = np.zeros( (NT... | galtay/rabacus | cloudy/cooling/read_cloudy.py | read_cloudy.py | py | 13,599 | python | en | code | 4 | github-code | 6 |
3504372122 | #!/usr/bin/python3
"""This is the square class """
class Square:
"""This is an empty Square class
"""
def __init__(self, size=0):
"""This is the initilization function
it has a private size member
Args:
size: size of square
"""
if (not isinstance(size, ... | MATRIX30/alx-higher_level_programming | 0x06-python-classes/2-square.py | 2-square.py | py | 484 | python | en | code | 0 | github-code | 6 |
70211358588 | import json
import glob
import os
import re
import collections
import yaml
from yaml.parser import ParserError, ScannerError
from saddlebags import exceptions
SUPPORTED_FILE_TYPES = ['json', 'yaml', 'yml']
class Saddlebag(collections.MutableMapping):
"""
Provides access to the contents of JSON/YAML config... | eikonomega/saddlebags | saddlebags/saddlebag.py | saddlebag.py | py | 5,393 | python | en | code | 0 | github-code | 6 |
33502453233 | # encoding: utf-8
"""
"""
__author__ = 'Richard Smith'
__date__ = '31 Jul 2020'
__copyright__ = 'Copyright 2018 United Kingdom Research and Innovation'
__license__ = 'BSD - see LICENSE file in top-level package directory'
__contact__ = 'richard.d.smith@stfc.ac.uk'
from django.core.management.base import BaseCommand, ... | cedadev/archive-opensearch | django_opensearch/management/commands/retrieve_vocab_cache.py | retrieve_vocab_cache.py | py | 681 | python | en | code | 0 | github-code | 6 |
16000963484 | import datetime
import ipaddress
import unittest
from typing import Any, Optional
from dataclasses import dataclass
from podman import api
class ParseUtilsTestCase(unittest.TestCase):
def test_parse_repository(self):
@dataclass
class TestCase:
name: str
input: Any
... | mgorny/podman-py | podman/tests/unit/test_parse_utils.py | test_parse_utils.py | py | 2,083 | python | en | code | null | github-code | 6 |
10422156393 | from __future__ import annotations
import os
import platform
import re
import subprocess
import typing
from pathlib import Path
from PySide6 import QtCore, QtGui, QtWidgets
import randovania
from randovania import get_data_path
if typing.TYPE_CHECKING:
from collections.abc import Iterator
def map_set_checked(... | randovania/randovania | randovania/gui/lib/common_qt_lib.py | common_qt_lib.py | py | 9,466 | python | en | code | 165 | github-code | 6 |
72470151548 | import cv2
import numpy as np
import os
import zipfile
from show import blob_imagem,alturaXlargura
from work import deteccoes, funcoes_imagem
from drive import driveFile
if not os.path.exists("modelo.zip"):
"""
Verifica se o modelo já se encontra no diretório
se não se encontra no diretória, então baixa o mesmo... | mauriciobenjamin700/IC_V2 | YOLO/experimentos/teste1/main.py | main.py | py | 2,342 | python | pt | code | 0 | github-code | 6 |
22252725239 | import numpy as np
import optuna
import pandas as pd
import xgboost as xgb
from sklearn.metrics import f1_score, precision_score
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import recall_score
from sklearn.metrics import accuracy_score
def objective(trial, df, y):
params = {
'... | lutianzhou001/RegPull | ML/optuna_XGBoost.py | optuna_XGBoost.py | py | 3,097 | python | en | code | 2 | github-code | 6 |
73952569148 | import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.style.use('SVA1StyleSheet.mplstyle')
def parse_args():
import argparse
parser = argparse.ArgumentParser(description='Correlation of reserved stars')
parser.add_argument('--tausflask1',
default='/ho... | des-science/Y3_shearcat_tests | alpha-beta-eta-test/code/tests/taus_v1v2.py | taus_v1v2.py | py | 4,389 | python | en | code | 1 | github-code | 6 |
44687752877 | def order(a):
counter_as = 0
counter_des = 0
b = 0
for i in a:
if i > b:
counter_as += 1
else:
counter_des += 1
b = i
if counter_as < 2:
k = 'descending'
elif counter_des < 2:
k = 'ascending'
else:
k = 'not sorted'
r... | Krimets/python-online-marathon | sprint01/task06.py | task06.py | py | 397 | python | en | code | 0 | github-code | 6 |
8280574767 | from heapq import heapify, heappop, heappush
import collections
'''
Time: O(n) + O(nlogk)
Space: O(n)
'''
class Solution:
def __init__(self, nums, k):
self.heap = []
self.k = k
self.nums = nums
def topk(self):
freq = collections.defaultdict(int)
for num in self.nu... | gadodia/Algorithms | algorithms/Arrays/topkfrequent.py | topkfrequent.py | py | 685 | python | en | code | 0 | github-code | 6 |
9174130850 | load(":common/cc/semantics.bzl", "semantics")
load(":common/cc/cc_helper.bzl", "cc_helper")
load(":common/cc/cc_common.bzl", "cc_common")
CcToolchainInfo = cc_common.CcToolchainInfo
TemplateVariableInfo = _builtins.toplevel.platform_common.TemplateVariableInfo
ToolchainInfo = _builtins.toplevel.platform_common.Toolcha... | bazelbuild/bazel | src/main/starlark/builtins_bzl/common/cc/cc_toolchain_alias.bzl | cc_toolchain_alias.bzl | bzl | 1,537 | python | en | code | 21,632 | github-code | 6 |
70267272829 |
import epyk as pk
from epyk.mocks import randoms
# Create a basic report object
page = pk.Page()
page.headers.dev()
# Create JavaScript data
js_data = page.data.js.record(js_code="myData", data=randoms.languages)
# Add a filter object
filter1 = js_data.filterGroup("filter1")
# Add a dropdown box to drive the data ... | epykure/epyk-templates | locals/components/quickstart.py | quickstart.py | py | 1,052 | python | en | code | 17 | github-code | 6 |
71723914428 | """
-*- coding: utf-8 -*-
File : basepage.py
Version : 0.1
Author : usrpi
Date :2021/1/4
"""
import logging
import datetime
import os
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# 封装基本函数 -- 执行日志、处理异常、失败截图
# 所有的页面公共部分,不涉及业务
class Base... | xianghuanng/futureloan_web | Common/basepage.py | basepage.py | py | 3,889 | python | en | code | 0 | github-code | 6 |
14852879493 | import logging
from datetime import timedelta
import requests
from django.db import models
from django.utils.six import string_types
from django.utils import timezone
from requests_oauthlib import OAuth2Session
from killboard import app_settings
from killboard.errors import TokenError, IncompleteResponseError
logger... | DeForce/py_killboard | killboard/managers.py | managers.py | py | 5,176 | python | en | code | 1 | github-code | 6 |
74923808826 | from app.views import v_menu
from app.controllers import c_input
from app.models import m_search
from app.models import m_players
from app.models import m_list
from app.models import m_tournaments
class Controller:
def main_menu(self):
v_menu.View().main_menu()
self.menu_number = c_input.Input().... | MaeRiz/OC_P4_Chess | app/controllers/c_menu.py | c_menu.py | py | 4,766 | python | en | code | 0 | github-code | 6 |
8866112441 | import numpy as np
import cv2 as cv
def bitfield(n):
return [int(digit) for digit in bin(n)[2:]]
def gerar_mensagem(mensagem):
lista = []
for m in mensagem:
val = ord(m)
bits = bitfield(val)
if len(bits) < 8:
for a in range(8-len(bits)):
bits.insert(0... | joaofxp/computer-science-univali | Python/M2/Trabalho 2/main.py | main.py | py | 3,084 | python | pt | code | 0 | github-code | 6 |
10132276502 | import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
from plotly.subplots import make_subplots
import os
import plotly.io as pio
pio.renderers.default = "browser"
num_of_interviews = [0, 1, 2, 3]
y_list = 3
x_list = 6
current = False
trend = False
# example: communication = 0
specific_a... | Fabbochan/master_thesis_figures | datavisualization_heatmap.py | datavisualization_heatmap.py | py | 5,880 | python | en | code | 0 | github-code | 6 |
9828876779 | import sys
import os
from django.conf import settings
from django.core.management import execute_from_command_line
from django.conf.urls import url
from django.http import HttpResponse
from django.core.wsgi import get_wsgi_application
DEBUG = os.environ.get('DEBUG', 'on') == 'on'
print(DEBUG)
SECRET_KEY = os.environ... | wesksky/MyDjangoProject | TinyDjango/hello.py | hello.py | py | 913 | python | en | code | 0 | github-code | 6 |
35266444899 | import os
# os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import tensorflow as tf
import keras
# from keras import layers
from sempler import Dataset, DatasetSide, DatasetSoft
from wave_u_net import wave_u_net
from loss import combined_loss, ScatterLoss, RegulatedLoss
from call_back import CustomCallback
from keras.callb... | ondra117/lil_neuron | learning.py | learning.py | py | 3,143 | python | en | code | 1 | github-code | 6 |
37107835911 | #!/usr/bin/python
# -*- coding: utf8 -*-
import sys
import cherrypy
import platform
import os
import time
cur_dir = os.path.dirname(os.path.abspath(__file__))
#python 2.4为simplejson,python 2.6以上为json
try:
import json
except ImportError:
import simplejson as json
... | lxcong/lvs-manager | monitor_agent/run.py | run.py | py | 12,755 | python | en | code | 160 | github-code | 6 |
33237880927 | from numpy import mean
from numpy import std
from matplotlib import pyplot as plt
from sklearn.model_selection import KFold
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2... | husainasad/Digit-Classifier | model.py | model.py | py | 3,607 | python | en | code | 0 | github-code | 6 |
34075191892 | '''
Write your code
Push
MinMaxStack
st = [(1,1,1), (1,2,3)]
self.st[-1][2]
0 1 2
(9 1 10)
1
8
7
(7 7 10)
10 None None
'''
class Stack:
def __init__(self):
self.st = []
def pop(self):
if(self.isEmpty()):
raise Exception("stack is empty!")
else:
element = self.st... | Anurag808Tripathi/algo-ds | algo-ds-scratch/stack.py | stack.py | py | 1,190 | python | en | code | 0 | github-code | 6 |
38796663707 | #Tutorial 4
number = int(input('Enter the number: '))
cycle = int(input('Enter number of cycles you want: '))
count = 1
while count <= cycle:
output = count*number
count += 1
print(output)
num = 0
sum = 0
while num != -1:
num = int(input('Enter the number: '))
sum = sum + num
prin... | Sathila01/Year-1-Python | Tut4.py | Tut4.py | py | 1,842 | python | en | code | 0 | github-code | 6 |
16030870954 | import os
import cv2
import time
import random
import numpy as np
import pandas as pd
import keras.api._v2.keras as keras
import tensorflow as tf
tf.__version__, np.__version__
from tensorflow.keras.applications.inception_v3 import preprocess_input
from tensorflow.keras import backend, layers, metrics
from tensorflow.... | gamal-abdelhakm/Handwritten-Signature-Identification-Verification-and-Detection | Script/Functions.py | Functions.py | py | 8,768 | python | en | code | 2 | github-code | 6 |
16128165567 | N, M = map(int, input().split())
a = list(map(int, input().split()))
g = {i + 1: [] for i in range(N)}
for ai in a:
g[ai].append(ai + 1)
g[ai + 1].append(ai)
flag = [False] * (N + 1)
def dfs(i):
route.append(i)
flag[i] = True
for gi in g[i]:
if flag[gi]:
continue
ret... | keimoriyama/Atcoder | ABC/289/b.py | b.py | py | 495 | python | en | code | 0 | github-code | 6 |
70452856507 | def lab_blackjack():
deck = ['A', '2', '3', '4', '5', '6',
'7', '8', '9', '10', 'J', 'Q', 'K', 'A', '2', '3', '4', '5', '6',
'7', '8', '9', '10', 'J', 'Q', 'K', 'A', '2', '3', '4', '5', '6',
'7', '8', '9', '10', 'J', 'Q', 'K', 'A', '2', '3', '4', '5', '6',
'7', '8', '9', '10', ... | austenc-id/Guild | 1 - Python/7/blackjack.py | blackjack.py | py | 3,002 | python | en | code | 0 | github-code | 6 |
10629931945 | import logging
import pytest
import nengo
from nengo.builder import Model
from nengo.builder.ensemble import BuiltEnsemble
def test_seeding(Simulator, allclose):
"""Test that setting the model seed fixes everything"""
# TODO: this really just checks random parameters in ensembles.
# Are there other ... | Kanaderu/Neural-Networks | nengo-master/nengo/tests/test_builder.py | test_builder.py | py | 4,239 | python | en | code | 0 | github-code | 6 |
35014338143 | # coding: utf-8
from flask import jsonify
from app import app
class Error():
'''
HTTP Response Error
'''
def __init__(self):
self.status = None
self.code = None
self.message = None
self.errors = None
def _ready(self, log_level='info'):
if log_level == 'cr... | jasonsmithj/spam_public | app/http/error.py | error.py | py | 2,234 | python | en | code | 0 | github-code | 6 |
19355802413 | from datetime import datetime
import csv
AIRPORTS_DB_LINK = "https://raw.githubusercontent.com/cohaolain/ryanair-py/develop/ryanair/airports.csv"
AIRPORTS_DB_FILE = "data/airports.csv"
AIRPORTS_TIMESTAMP_FILE = "data/airports_timestamp.txt"
airports = None
def get_distance(lat1, lat2, lon1, lon2):
from math impo... | slotruglio/flights-radar | utils/airports.py | airports.py | py | 3,444 | python | en | code | 0 | github-code | 6 |
27741403931 | import math
def get_last_L2_error(lines,name,LastLines=35) :
"""Get L_2 eror value from a set of lines for the last timestep.
The set of lines correspond to the output-lines of a flexi-run"""
for l in lines[-LastLines:] : # read the last XX lines (default is 35)
# search for name, e.g., "L2_Part" or "L... | piclas-framework/reggie2.0 | analyze_functions.py | analyze_functions.py | py | 3,161 | python | en | code | 2 | github-code | 6 |
9816914464 | #!/usr/bin/env python
# coding: utf-8
# # Ici on va importer les packages de Python
# In[14]:
import gudhi as gd
import scipy.io as sio
import math
import matplotlib.pyplot as plt
import numpy as np
# # On donne les coordonnées de chaque atome
# In[16]:
coords = {'Ti':[[5,5,5]], 'O':[[5, 5, 10], [5, 10, 5], ... | Fouad-Mazguit/rapport-data | Data/CaTiO3/les nombres de Betti.py | les nombres de Betti.py | py | 1,641 | python | en | code | 2 | github-code | 6 |
37048610245 |
from flask import Blueprint, jsonify, render_template,request,flash,redirect,url_for, session
import json
import sqlite3
from numpy import empty
from .excel_data import Device_Excel_Table, get_arr, get_by_ID_from_table
from .location import get_all_location
from .data_processing.index import database_initialization
fr... | Kelly-Kxx/fyp_selenium_flask | website/views.py | views.py | py | 6,347 | python | en | code | 0 | github-code | 6 |
43736972444 | import sys
from pyspark import SparkConf, SparkContext
import re
from bwt import reverseBwt
from radix import radixSort
from segment import segSort
from default import defaultSort
from partition import partitionSort
# config spark context, set master, name and memory size
def getSC(master, name):
conf = (Spa... | xniu7/jhuclass.genome.indexing | code/python/sort.py | sort.py | py | 3,476 | python | en | code | 1 | github-code | 6 |
7815075534 | class PartyAnimal:
x = 0
name = ''
def __init__(self, name):
self.name = name
print('Name:', self.name)
def party(self):
self.x = self.x + 1
print(self.name, 'Party count', self.x)
person1 = PartyAnimal('Amjed')
person1.party()
print('\n')
person2 = PartyAnimal('Danw... | amjedsaleel/Python-for-Everybody | Using Databases with Python/cons.py | cons.py | py | 342 | python | en | code | 0 | github-code | 6 |
22534736697 | # Write a Python program to count the occurrences of each word in a given sentence.
string=str(input("Enter a string :"))
words=string.split() #store splitted string into variable
count=dict() #initiate a dictionary
for word in words: ... | ABHISHEKSUBHASHSWAMI/String-Manipulation | str11.py | str11.py | py | 623 | python | en | code | 1 | github-code | 6 |
9797629811 | #client berada di sisi remote, client hanya mmebutuhkan
# dependency kepada library Pyro5
import Pyro5.api
if __name__=='__main__':
# untuk mengecek service apa yang ada di ns, gunakan pyro5-nsc -p 9900 list
#dalam kasus ini namanya adalah phonebook.server
phonebook = Pyro5.api.Proxy('PYRONAME:phonebook... | rm77/sister2020 | client/client.py | client.py | py | 600 | python | id | code | 0 | github-code | 6 |
70280896828 | from abc import ABC, abstractmethod
from nltk.translate.bleu_score import sentence_bleu
from bert_score import score as bert_score
from BARTScore import bart_score
import argparse
class SimilarityClass(ABC):
def __init__(self):
pass
@abstractmethod
def get_similarity(self):
pass
class ... | esteng/ambiguous_vqa | analysis/abstract_class.py | abstract_class.py | py | 3,112 | python | en | code | 5 | github-code | 6 |
73998046587 | import os
import pandas as pd
pd.set_option('display.max_columns', None) # or 1000
pd.set_option('display.max_rows', None) # or 1000
pd.set_option('display.max_colwidth', None) # or 199
import numpy as np
import pickle
from tabulate import tabulate
def create_empty_table_lr_micro_macro():
classifiers = ['logis... | K-Shah3/SimCLR_HCHS | chapman/predictions/create_table.py | create_table.py | py | 2,607 | python | en | code | 0 | github-code | 6 |
10552839170 | import abc
import dataclasses
from typing import Optional, Union
import numpy as np
import numpy.typing as npt
import rod
from rod import logging
@dataclasses.dataclass
class PrimitiveBuilder(abc.ABC):
name: str
mass: float
element: Union[
rod.Model, rod.Link, rod.Inertial, rod.Collision, rod.V... | ami-iit/rod | src/rod/builder/primitive_builder.py | primitive_builder.py | py | 8,450 | python | en | code | 11 | github-code | 6 |
32569222248 |
# -*- coding: utf-8 -*-
###############################################################################
# License, author and contributors information in: #
# __manifest__.py file at the root folder of this module. #
#######################################################... | dip-ergo/tex-fasteners | mto_chain/models/inherit.py | inherit.py | py | 4,293 | python | en | code | 0 | github-code | 6 |
38713930072 | from collections import defaultdict, deque
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
vertex = queue.popleft()
if vertex not in visited:
visited.add(vertex)
print(vertex, end=' ')
for neighbor in graph[verte... | pogchumpus55/AI | bfs.py | bfs.py | py | 765 | python | en | code | 0 | github-code | 6 |
30138374155 | # !/usr/local/python/bin/python
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <wudong@eastwu.cn>'
# @Time: '2020-04-01 09:47'
# sys
import typing as t
from functools import wraps
from inspect import isfunction
from inspect import getfullargspec
# 3p
from flask import ( # pylint:... | Eastwu5788/pre-request | pre_request/request.py | request.py | py | 13,075 | python | en | code | 55 | github-code | 6 |
13006979973 |
a = list(range(10))
def lp() :
b = list(a)
return b
def tp() :
b = tuple(a)
return b
def main() :
from timeit import timeit
print("with list" , timeit(lp , number = 1))
print("with tuple" , timeit(tp , number = 1))
#? To return the sequence with least time of executi... | nishadkindre/python-concepts | list_vs_tuple.py | list_vs_tuple.py | py | 1,878 | python | en | code | 0 | github-code | 6 |
41762485594 | from tkinter import *
from forex_python.converter import CurrencyRates
FONT = ("Arial", 20, "bold")
BG = "#B6D0E2"
def display_selected_1(choice):
""" Select first currency from dropdown menu and display on label """
choice = clicked_1.get()
enter_amount_label.config(text=choice)
def display... | vaibhav-bisen/Python_Projects | Currency Convertor/main.py | main.py | py | 2,666 | python | en | code | 0 | github-code | 6 |
12011303368 | import os
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple
import pandas as pd
import textstat
# Set absl logging to warning s.t. we don't see "INFO:absl:Using default tokenizer." for each rouge calculation
from absl import logging
from langdetect import detect
from sitaevals.common i... | AsaCooperStickland/situational-awareness-evals | sitaevals/tasks/assistant/evaluator.py | evaluator.py | py | 17,920 | python | en | code | 23 | github-code | 6 |
35014660899 | #!/usr/bin/env python3
from thermostat import Thermostat
from indoor_air_sensor import IndoorAirSensor
try:
import polyinterface
except ImportError:
import pgc_interface as polyinterface
import sys
import os
from api_helper import ApiHelper
LOGGER = polyinterface.LOGGER
class Controller(polyinterface.Cont... | dbarentine/udi-honeywellhome-poly | honeywellhome-poly.py | honeywellhome-poly.py | py | 6,441 | python | en | code | 0 | github-code | 6 |
13303955971 | from fastapi import APIRouter
from app.libraries.libpermission import Permission
from app.schemas.permission import PermissionModel, PermissionUpdateModel, PermissionCreateModel
router = APIRouter(tags=["permission"])
oPermission = Permission()
@router.get("/permission/schema")
async def get_permission_schema(joined:... | treytose/Pyonet-API | pyonet-api/app/routers/permission.py | permission.py | py | 1,440 | python | en | code | 0 | github-code | 6 |
38364668471 | r, c, t = map(int, input().split())
graph = [list(map(int, input().split())) for _ in range(r)]
for i in range(r):
if graph[i][0] == -1:
gx = i
gx2 = i+1
break
def spread():
tmp = [[0] * c for _ in range(r)]
dx = [-1,0,1,0]
dy = [0,-1,0,1]
for i in range(r):
for j in range(c):
if... | jy9922/AlgorithmStudy | Baekjoon/17144번 미세먼지 안녕.py | 17144번 미세먼지 안녕.py | py | 1,560 | python | en | code | 0 | github-code | 6 |
24749481019 | # Write your solution below
# Follow the instructions in the tab to the right
# Use this exchange rate
NAIRA_PER_DOLLAR = 410.59 # exchange rate as of Nov 10 2021
# Enter USD Value
usd = float(input('Enter USD Value: '))
# Naira Equivalent
naira = usd * NAIRA_PER_DOLLAR
# Round to 2 decimal place
naira = f'{naira:.... | Abeeujah/kibo | weekone/forex.py | forex.py | py | 341 | python | en | code | 0 | github-code | 6 |
30378927343 | def reverse(s):
return s[::-1]
def verifyPalindrome(str):
if (str==reverse(str)):
return True
return False
# main function
words = ["aaa","a","aa","aba","abcdcba","abccba","aabbcaa","abcddba","abcabc"]
for i in range(0,len(words)-1):
ans=verifyPalindrome(words[i])
if ans==1 :
print(words[i]+" is palindro... | biancagavrilescu/practice | PycharmProjects/p1/palindrome.py | palindrome.py | py | 328 | python | en | code | 0 | github-code | 6 |
19491332687 | import requests
import hashlib
import datetime
import pandas as pd
"""Script that accesses Marvel API and gets 30 characters."""
#Access Marvel API (needed: Timestamp, privkey, publickey, hash)
timestamp = datetime.datetime.now().strftime('%Y-%m-%d%H:%M:%S')
pub_key = '' #insert public key
priv_key = '' #insert priva... | Guibas1812/create-api-marvel-characters | initial_data.py | initial_data.py | py | 3,441 | python | en | code | 0 | github-code | 6 |
24470944971 | import tensorflow as tf
import numpy as np
from malaya.text.function import (
language_detection_textcleaning,
summarization_textcleaning,
split_into_sentences,
transformer_textcleaning,
pad_sentence_batch,
upperfirst,
)
from malaya.text.rouge import postprocess_summary
from malaya.text.bpe impo... | MuzyAce/malaya | malaya/model/tf.py | tf.py | py | 20,513 | python | en | code | null | github-code | 6 |
27638879954 | # -*- coding: utf-8 -*-
""" Region/Anvil Serializer and Deserializer
https://minecraft.gamepedia.com/Region_file_format
https://minecraft.gamepedia.com/Anvil_file_format
"""
from collections import defaultdict
# from datetime import datetime
from enum import IntEnum
import gzip
from math import ceil
import os
import ... | xSetech/aPyNBT | aPyNBT/region.py | region.py | py | 8,686 | python | en | code | 1 | github-code | 6 |
32504966149 | def BuyukSayı(sayı1,sayı2):
if(sayı1> sayı2):
return sayı1
print( "buyuk sayı: ", sayı1 )
else:
return sayı2
print("buyuk sayı: ",sayı2)
def Ebob (sayı1,sayı2):
sonuc=1
buyuk=BuyukSayı(sayı1,sayı2)
for i in range(buyuk+1,1,-1):
if((sayı1%i==0) and... | candilek/Python-Projeler | EbobBulma.py | EbobBulma.py | py | 514 | python | az | code | 1 | github-code | 6 |
42344160389 | import pandas as pd # pip install pandas openpyxl
import plotly.express as px # pip install plotly-express
import streamlit as st # pip install streamlit
# emojis: https://www.webfx.com/tools/emoji-cheat-sheet/
st.set_page_config(page_title="Segmentation Analysis", page_icon=":bar_chart:", layout="wide")
# ---- RE... | yodialfa/Segmentation_Recomendation | app.py | app.py | py | 7,164 | python | en | code | 1 | github-code | 6 |
70465705787 | import numpy as np
import scipy
import scipy.sparse.linalg
import scipy.sparse as sparse
from scipy.linalg import expm
from copy import deepcopy
##################################################
# auxiliary function for time evolution method #
##################################################
def TEO_two_sites(MPO... | ZhaoYilin/modelham | modelham/tensornetwork/auxiliary.py | auxiliary.py | py | 12,711 | python | en | code | 0 | github-code | 6 |
39176281823 | #Import files
import sys
import serial
import SLMC601V17_RS485_COM_Frames as SLMC_Frames
#Determine determine which port was provided
PORT = sys.argv[1]
#Check that port provided...
# contains ttyUSB
sizeOfPort = len(PORT)
sizeOfTTY = len("ttyUSB#")
subString = PORT[sizeOfPort-sizeOfTTY:sizeOfPort-1]
if(subString !... | aarontwillcock/SLMC601V1.7-RS485-Tool | SLMC601V17_RS485_COM_RX.py | SLMC601V17_RS485_COM_RX.py | py | 3,797 | python | en | code | 1 | github-code | 6 |
34496233274 | """
Window function module
"""
import numpy as np
import lssps._lssps as c
def compute_grid3d(grid, *, pk_fac=None, shot_noise=None):
"""
Compute 3D window function grid |W(k)|^2
"""
if grid.mode == 'real-space':
grid.fft()
if grid.shifted and not grid.interlaced:
grid.interlace(... | junkoda/lss-ps | py/lssps/window.py | window.py | py | 1,047 | python | en | code | 1 | github-code | 6 |
37122133332 | from flask import request
from flask_restx import Resource
from app.main.util.decorator import admin_token_required
from ..service.inventory_service import get_all_inventories, save_new_inventory, get_an_inventory, update_inventory, delete_inventory_method
from ..util.dto import InventoryDto
api = InventoryDto.api
in... | miteshnath/inventory-management-module | app/main/controller/inventory_controller.py | inventory_controller.py | py | 2,780 | python | en | code | 0 | github-code | 6 |
23089748371 | import pygame as pg
class Scoreboard:
"""Represents the score in game"""
def __init__(self, game):
"""Initializes the properties of the scoreboard"""
self.settings = game.settings
self.screen = game.screen
self.screen_rect = self.screen.get_rect()
self.text_color = (... | jackloague1/Space-Invaders-Project | Space-Invaders-Project/scoreboard.py | scoreboard.py | py | 1,770 | python | en | code | 0 | github-code | 6 |
14279218231 | from .IngestorInterface import IngestorInterface
from .QuoteModel import QuoteModel
from typing import List
import subprocess
import os
import random
class PDFIngest(IngestorInterface):
"""Subclass of IngestorInterface specific for .docx files."""
ingestMode =['pdf']
@classmethod
def parse(cls, pa... | JPNaan/MEMEGenerator | MEMEGenerator/src/QuoteEngine/IngestPDF.py | IngestPDF.py | py | 1,466 | python | en | code | 0 | github-code | 6 |
11046378915 | def main():
v = open('newOutput-LACounty.csv','r')
c = v.read()
v.close()
w = open('join_blocks_coordinates.csv','r')
d = w.read()
w.close()
c_list = d.split('\n') # list of coords for census bgs
#print(c_list[-2])
mod_list = c.split('\n') #job flow
#print(mod_list[3])
retStr... | hjames034/LODES-Analysis | coord-match.py | coord-match.py | py | 1,974 | python | en | code | 0 | github-code | 6 |
43721467284 | # -*- coding: utf-8 -*-
__author__ = 'SinGle'
__date__ = '2020/06/26 14:39'
import re
from flask import current_app
from app.lib.Snapshot import Snapshot
def param_handler(params, action):
if "SNAPSHOTNAME" not in params.keys() or re.search("[\\\\,./\\x20]", params["SNAPSHOTNAME"]):
snapshot_name = Non... | xSinGle/Snapshot | app/lib/Helper.py | Helper.py | py | 1,419 | python | en | code | 0 | github-code | 6 |
41792906760 | from sys import stdout
class ProgressWriter:
"""
A utility to show the progress of long processes. A common use case would
be to initialize, then in the loop, call show_progress() with the index
of the position in the loop, and then after the loop, call end_progress().
"""
def __init__(self, ... | nwoodbury/progresswriter | progresswriter/progresswriter.py | progresswriter.py | py | 1,852 | python | en | code | 0 | github-code | 6 |
35869561775 | # debugged the program
import random
guess = ''
# added a tuple to use 'toss' variable as an index
glst = ('tails', 'heads')
# moved tuple from while statement to a variable
while guess not in glst:
print('Guess the coin toss! Enter heads or tails:')
guess = input()
toss = random.randint(0, 1) # 0 is tails... | rarog2018/AtBSwP | C10 Debugging/coinToss.py | coinToss.py | py | 645 | python | en | code | 0 | github-code | 6 |
74025602427 | import modules
from templates.quick_replies import add_quick_reply
from templates.text import TextTemplate
from templates.button import *
entities = {
'type':None,
'choice':None
}
def process(input, entities = None):
print('process',input,entities)
output = {}
if entities['type'] == None:
... | anne030303/messenger-landbot | modules/src/lease_contract.py | lease_contract.py | py | 5,963 | python | en | code | 0 | github-code | 6 |
13031397171 | import rospy, sys, tf
import moveit_commander
from math import *
from geometry_msgs.msg import PoseStamped
from moveit_commander import MoveGroupCommander, PlanningSceneInterface
from moveit_msgs.msg import PlanningScene, ObjectColor
from moveit_msgs.msg import Grasp, GripperTranslation
from moveit_msgs.msg import Move... | sniper0110/Turtlebot_arm | turtlebot_arm_moveit_demos/bin/pick_and_place.py | pick_and_place.py | py | 17,847 | python | en | code | 4 | github-code | 6 |
19409761077 | import asyncio
import os
import datetime
import discord
from discord import channel
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext, cog_ext
from discord_slash.utils.manage_commands import create_option, create_choice
from core.classes import CogExtension
class System(CogExtensio... | TimTsai0316/MinatoBot | cmds/system.py | system.py | py | 2,045 | python | en | code | 0 | github-code | 6 |
33560462969 | """Program to List, Create, Add, Edit, Delete contacts and save to a JSON file"""
import json
class CreateContact:
""""""
def __init__(self, fname, lname, phone): #constructor
self.fname = fname
self.lname = lname
self.phone = phone
def create_new_contact(self):
cont... | alenantony/Alokin-Task | Day2/contact.py | contact.py | py | 10,501 | python | en | code | 0 | github-code | 6 |
29373295052 | # External Packages
from fastapi import APIRouter
from fastapi import Request
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.templating import Jinja2Templates
from khoj.utils.rawconfig import TextContentConfig, OpenAIProcessorConfig, FullConfig
# Internal Packages
from khoj.utils import constant... | debanjum/khoj | src/khoj/routers/web_client.py | web_client.py | py | 6,990 | python | en | code | 485 | github-code | 6 |
71714038267 | import unittest
import json
from unittest.mock import patch, mock_open
from models.club_model import Club
import repository.club as club_repo
class ClubRepoTest(unittest.TestCase):
@patch("repository.club.filename_club", new='tests/test.json')
def test_load_clubs_should_return_list_of_club_obj(self):
... | Chfrlt/p11_GUDLFT | tests/unit_tests/test_club_repository.py | test_club_repository.py | py | 1,844 | python | en | code | 0 | github-code | 6 |
9790493238 | """backend URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... | wiksla/f5-bigip-journeys-app | journeys/backend/urls.py | urls.py | py | 1,978 | python | en | code | 0 | github-code | 6 |
26247501666 | from delfin.api import common
from delfin.api import extensions
from delfin.api.v1 import access_info
from delfin.api.v1 import alert_source
from delfin.api.v1 import alerts
from delfin.api.v1 import controllers
from delfin.api.v1 import disks
from delfin.api.v1 import filesystems
from delfin.api.v1 import ports
from d... | sodafoundation/delfin | delfin/api/v1/router.py | router.py | py | 7,550 | python | en | code | 201 | github-code | 6 |
25598775886 | import sys
import numpy as np
import cv2
def main():
source_window = "source_image"
gray_window = "gray"
otsu_window = "otsu_threshold"
edge_window = "edge"
gray_img = cv2.imread(sys.argv[1], cv2.IMREAD_GRAYSCALE)
threshold1 = 0
threshold2 = 100
edge_img = cv2.Canny(gray_img, threshol... | NMurata07/findContours | main.py | main.py | py | 852 | python | en | code | 0 | github-code | 6 |
6727548995 | from django.utils import timezone
from .models import Post, IP
from django.shortcuts import render, get_object_or_404, redirect
from .forms import PostForm, Login
from django.contrib.auth.decorators import login_required, PermissionDenied, user_passes_test
import json
from datetime import timedelta
from django.utils.ti... | Dado-pixel/my-second-blog | blog/views.py | views.py | py | 4,046 | python | en | code | 1 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.