seq_id
stringlengths
4
11
text
stringlengths
113
2.92M
repo_name
stringlengths
4
125
sub_path
stringlengths
3
214
file_name
stringlengths
3
160
file_ext
stringclasses
18 values
file_size_in_byte
int64
113
2.92M
program_lang
stringclasses
1 value
lang
stringclasses
93 values
doc_type
stringclasses
1 value
stars
int64
0
179k
dataset
stringclasses
3 values
pt
stringclasses
78 values
5559929525
import requests import json import time from pygame import mixer #Enter your url here and enjoy your free offer!! url = 'https://www.cricbuzz.com/match-api/21859/commentary.json' f = 0 c = time.time() while True: try: current_scorecard = requests.get(url).json()['score']['prev_overs'] except: mixer.init() mixe...
smit2k14/SWIGGY6
SWIGGY6.py
SWIGGY6.py
py
561
python
en
code
1
github-code
36
34678033656
import logging import re from streamlink.plugin import Plugin, pluginmatcher from streamlink.stream import HLSStream log = logging.getLogger(__name__) @pluginmatcher( re.compile(r"https?://(?:www\.)?auftanken\.tv/livestream/?") ) class AuftankenTV(Plugin): _hls_url_re = re.compile(r"(https://.+?/http_adapti...
oe-mirrors/streamlink-plugins
auftanken.py
auftanken.py
py
753
python
en
code
1
github-code
36
17164740168
from sqlite3 import Error as sqliteError from sqlite3 import OperationalError as sqliteOperationalError from loggingSystem import LoggingSystem import sqlite3,sys,os,time from typing import Union class ProcessamentoSqlite: def __init__(self,sqlite_db="./initial_db.db",sql_file_pattern="scripts/sqlitePattern.sql", ...
mzramna/algoritimo-de-testes-de-benchmark-de-bancos-de-dados
scripts/processamentoSqlite.py
processamentoSqlite.py
py
7,284
python
en
code
0
github-code
36
5127076250
# coding:utf-8 import numpy as np from chainer import cuda, Function, gradient_check, report, training, utils, Variable from chainer import datasets, iterators, optimizers, serializers import chainer.functions as F import chainer.links as L import sys import argparse import _pickle as pickle import MeCab from LSTM imp...
SPJ-AI/lesson
text_generator/generate.py
generate.py
py
2,202
python
en
code
6
github-code
36
25625597173
class Node: def __init__(self,val): self.val = val self.children = [] class Solution: def maxAvg(self,node): if node is None: return None else: self.ans = float('-inf') def helper(node): if node is None: ret...
Akashdeepsingh1/project
2020/Max Avg Subtree.py
Max Avg Subtree.py
py
806
python
en
code
0
github-code
36
33214014538
import torch import torch.nn.functional as F from torch.autograd import Variable import torch.nn as nn # Credict: https://github.com/kefirski/pytorch_Highway class Highway(nn.Module): def __init__(self, size, num_layers, f): super(Highway, self).__init__() self.num_layers = num_layers se...
dwaydwaydway/KKStream-Deep-Learning-Workshop
Model.py
Model.py
py
3,619
python
en
code
0
github-code
36
6848009196
from django.shortcuts import render, redirect from users.forms import CustomUserCreationForm, CustomUserChangeForm from django.contrib.auth.decorators import login_required from users.models import CustomUser # Create your views here. @login_required(login_url='/login/') def home(request): """show users view""" ...
sistematizaref/lecesse
lecesse/users/views.py
views.py
py
1,771
python
en
code
0
github-code
36
33161621406
import csv from scipy.interpolate import interp1d from typing import Dict def app() -> None: # Separated govt bonds and c bonds because calculating benchmark yield spread # checks 1 corporate bond against all govt bonds f_name = input("csv name (with.csv): ") g_bonds, c_bonds = load_csv(f_name) p...
shermansjliu/overbond-dev-test-submission
app.py
app.py
py
3,333
python
en
code
0
github-code
36
7182787702
#!/usr/bin/env python # encoding: utf-8 # # facke-guider.py # # Created by José Sánchez-Gallego on 29 Mar 2017. from __future__ import division from __future__ import print_function from __future__ import absolute_import import opscore from opscore.protocols.parser import CommandParser from opscore.utility.qstr impo...
albireox/lcoHacks
python/lcoHacks/fake-guider.py
fake-guider.py
py
12,732
python
en
code
0
github-code
36
36086641490
#!/usr/bin/python3 ################################# ## Author: Heini Bergsson Debes ################################# # Purpose is to: # (1) encode the adjacency list (optionally padded) # (2) get the hash of the encoded adjacency list, translator, and recorded execution path (after padding) # (3) format inputs for ZE...
HeiniDebes/ZEKRA
scripts/circuit_input_formatter.py
circuit_input_formatter.py
py
26,081
python
en
code
5
github-code
36
9817545855
from PyQt5 import QtGui from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QWidget import ResourceNavigator from back.css.style import cssLoader from back.osuLoader.AppBackend import AppBackendInit from view.window.osuLoader.layout.OsuLoaderWindowLayout import OsuLoaderWindowLayout class OsuLoaderWindow(QWidg...
animousen4/osuLoader-2.0
view/window/osuLoader/OsuLoaderWindow.py
OsuLoaderWindow.py
py
1,590
python
en
code
0
github-code
36
15974646573
# *-* coding: utf-8 *-* """ Created on dim 07 fév 2021 09:27:34 UTC @author: vekemans """ import time import math as mt import numpy as np import scipy.sparse as spr import matplotlib.pyplot as plt nfig = 1 pi = mt.pi # ----------------------------------------------- # Orginal Signal N = np.power(2,12) h = 2*pi / ...
abbarn/lmeca2300
homeworks/p1.py
p1.py
py
1,733
python
en
code
0
github-code
36
17894590970
import collections import time from typing import Any, Dict from absl import logging import numpy as np import robustness_metrics as rm from sklearn.metrics import accuracy_score from sklearn.metrics import auc from sklearn.metrics import log_loss from sklearn.metrics import precision_recall_curve from sklearn.metrics...
google/uncertainty-baselines
baselines/diabetic_retinopathy_detection/utils/eval_utils.py
eval_utils.py
py
52,854
python
en
code
1,305
github-code
36
19090035035
from datetime import datetime from ueaglider.data.db_session import create_session from ueaglider.data.db_classes import Pins, Audit, Missions, Targets, Gliders, Dives, ArgosTags from ueaglider.services.argos_service import tag_info from ueaglider.services.glider_service import glider_info from ueaglider.services.user...
ueaglider/ueaglider-web
ueaglider/services/db_edits.py
db_edits.py
py
4,822
python
en
code
0
github-code
36
20255004169
from blog_api import api from flask import json def test_blog_post(): # Post method test for blog posting # It includes data and check response out response = api.test_client().post( '/api/post', data=json.dumps({'title': '1', 'body': '2', 'author': '3'}), content_type='appl...
hebertsonm/blog-assignment
pytest.py
pytest.py
py
1,650
python
en
code
0
github-code
36
25607964221
class TrieNode: def __init__(self): self.children = dict() self.isEndOfWord = False self.num = dict() root = None def getNewTrieNode(): pNode = TrieNode() return pNode def insertWord(word): global root current = roo...
Nirmalkumarvs/programs
Trie/Count number of strings with given prefix.py
Count number of strings with given prefix.py
py
1,335
python
en
code
0
github-code
36
29326208812
#! /usr/bin/env python # -*- coding: utf-8 -*- """ @version: ?? @author: li @file: rnn_model.py @time: 2018/3/27 下午5:41 """ import tensorflow as tf import os os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" class TRNNConfig(object): embedding_dim = 64 # 词向量维度 seq_length = 600 # 序列长度 num_classes = 10 # 类别数 ...
STHSF/DeepNaturalLanguageProcessing
TextClassification/text_classification/TextRNN/rnn_model.py
rnn_model.py
py
3,377
python
en
code
16
github-code
36
11920060681
import random, hashlib from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.x509.oid import NameOID from playground.common import CipherUtil from ..contants import PATH_PREFIX class CertFactory(object): ...
Pandafriendd/peep
src/factory/CertFactory.py
CertFactory.py
py
1,996
python
en
code
0
github-code
36
33319769200
WIN_WIDTH = 1524 WIN_HEIGHT = 720 DISPLAY = (WIN_WIDTH, WIN_HEIGHT) FPS = 60 GAME_TITLE = 'Fly' TITLE_FONT_SIZE = 196 FONT_SIZE = 82 FONT_FAMILY = 'Showcard Gothic' END_GAME_TIME = 2 START_POSITION = {1: [-100, -100, 1, 2], 2: [WIN_WIDTH / 2, -100, 0, 2], 3: [WIN_WIDTH + 100, -100, -1, 1], 4: [WIN_WID...
MrRamka/FlyGame
config.py
config.py
py
616
python
en
code
0
github-code
36
8000518173
import numpy as np from numpy import linalg from scipy import sparse import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator def read_dataset(path: str): with open(path, 'r') as f: lines = f.readlines() x = np.zeros([len(lines), 123]) y = np.zeros([len(lines)]) fo...
LyricZhao/IRLS
main.py
main.py
py
2,358
python
en
code
0
github-code
36
24222891293
import numpy as np from collections import namedtuple from abc import ABCMeta, abstractmethod, abstractstaticmethod # 决策树结点 # Parameters # ---------- # feature : 特征,需要进行比对的特征名 # val : 特征值,当特征为离散值时,如果对应的特征值等于val,将其放入左子树,否则放入右子树 # left : 左子树 # right : 右子树 # label : 所属的类 TreeNode = namedtuple("TreeNode", 'feature val lef...
samzzyy/RootCauseAnalysisOfProductionLineFailure
PathAna/DT_IV2.py
DT_IV2.py
py
5,356
python
en
code
5
github-code
36
38715871602
#!/usr/bin/env python import re valid_triangles = 0 data = [] with open('input.txt', 'r') as f: for line in f: data.append([int(x) for x in re.split(r'\s+', line.strip())]) # values = sorted([int(x) for x in re.split(r'\s+', line.strip())]) # assert len(values) == 3 # if values[0] ...
lvaughn/advent
2016/3/triangles_2.py
triangles_2.py
py
617
python
en
code
1
github-code
36
13421938791
import os import io import re import sys import pandas as pd import ujson as json from argparse import ArgumentParser, FileType from rasm import rasm RULE_GROUPS = { 'ASSIM-M': ['M1', 'M2'], 'ASSIM-N': ['N2.1.1.A', 'N2.1.1.B', 'N2.1.1.C', 'N2.1.1.D', 'N2.1.2.A', 'N2.1.2.B', 'N2.1.2.C', 'N2.1.2.D', 'N2.2.A', ...
kabikaj/tajweed
src/tajweed2df.py
tajweed2df.py
py
5,564
python
en
code
1
github-code
36
39366464180
import numpy as np import tensorflow as tf import datetime n = 10 A = np.random.rand(10000, 10000).astype('float32') B = np.random.rand(10000, 10000).astype('float32') c1 = [] c2 = [] def matpow(M, n): if n == 1: return M else: return tf.matmul(M, matpow(M, n-1)) with t...
PacktPublishing/Deep-Learning-with-TensorFlow-Second-Edition
Chapter07/gpu/gpu_example.py
gpu_example.py
py
1,141
python
en
code
48
github-code
36
29936731116
def my_comp(a): return(-a[0], a[1]) words = [] # почему - то не работает ввод line = "test" while line: line = input() tmp = line.split() for i in tmp: words.append(i) d = {} for x in words: if x in d.keys(): d[x] += 1 else: d[x] = 1 ans = list(tuple()) for x in d: ...
Alvanerle/PP2_Python
TSIS/TSIS 3/2/6.py
6.py
py
418
python
en
code
0
github-code
36
17751518002
from __future__ import absolute_import, division, print_function, unicode_literals import argparse import copy import json import os SPLITS = ["train", "dev", "devtest", "teststd"] def get_image_name(scene_ids, turn_ind): """Given scene ids and turn index, get the image name. """ sorted_scene_ids = sor...
facebookresearch/simmc2
model/ambiguous_candidates/format_ambiguous_candidates_data.py
format_ambiguous_candidates_data.py
py
4,414
python
en
code
98
github-code
36
11274648981
def returnConfidenceIntervals(IDs,pathtemp,pnumbers,listnames): #Imports import string import re #Action for item in IDs: obsid = item path = pathtemp.replace('++++++++++',obsid) for elem in pnumbers: temporarylist = [] alphabet_list = list(string.asci...
thissop/MAXI-J1535
older/recovered/Steiner2.0/20November/Related to finishing ci.py/ci.py
ci.py
py
3,847
python
en
code
1
github-code
36
73049130343
from collections import UserDict from datetime import datetime from datetime import timedelta class CacheDict(UserDict): times = {} def __init__(self, dict={}, keytime=60, **kwargs): super().__init__(dict, **kwargs) self.keytime = keytime def __getitem__(self, key): if not sel...
desk467/moto
moto/cache.py
cache.py
py
718
python
en
code
1
github-code
36
27145304602
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/7/9 11:05 # @Author : wenlei ''' 数据流随时取中位数 ''' import heapq import random # 小根堆 class MinHeap(): def __init__(self): self.heap = [] def insert(self, node): if not node: return heapq.heappush(self.heap, node)...
sherryxiata/zcyNowcoder
basic_class_07/MedianQuick.py
MedianQuick.py
py
3,517
python
en
code
0
github-code
36
15478667002
import numpy as np import glog import pandas as pd import os import gzip def export_roi_gene(file_path: str, roi: list): """ Args: file_path: path of gene file roi: [x0, y0, w, h] Returns: None """ if file_path.endswith('.gz'): f = gzip.open(file_path, 'rb') else: f = ...
BGIResearch/StereoCell
scripts/utils.py
utils.py
py
2,150
python
en
code
18
github-code
36
12365150707
#TCP Server side import socket #creating the server socket using IPv4(AF_INET) and TCP(SOCK_STREAM) server_socket= socket.socket(socket.AF_INET,socket.SOCK_STREAM) #binding our server socket #server_socket.bind((socket.gethostbyname(socket.gethostname()),12346)) server_socket.bind(("127.0.0.1",12346)) #listening f...
glynzr/network-programming
basic_tcp_server_client/server.py
server.py
py
779
python
en
code
0
github-code
36
19557215570
import sys input = sys.stdin.readline n = int(input()) for _ in range(n): a, b, c = map(int, input().split()) print(f"Data set: {a} {b} {c}") for _ in range(c): if a > b: a //= 2 else: b //= 2 print(max(a, b), min(a, b)) print()
hyotaime/PS.py
Bronze/Bronze4/26340.py
26340.py
py
290
python
en
code
0
github-code
36
7661874071
from django.template import Library from hx_lti_initializer.models import LTIProfile register = Library() @register.filter_function def list_of_possible_admins(already_in_course): list_of_usernames_already_in_course = [] list_of_unique_names = [] result = [] for profile in LTIProfile.objects.all(): ...
lduarte1991/hxat
hx_lti_initializer/templatetags/possible_admins.py
possible_admins.py
py
780
python
en
code
11
github-code
36
41076588706
import os import zipfile def unzip(filename: str, extract_to: str) -> None: """ This method run unzip a file to specified path :param filename: Path/filename of zip file :param extract_to: Path with name of output folder :return: None """ this_folder = os.path.dirname(os.path.abspath(...
samuelterra22/Analysis-of-antenna-coverage
src/main/python/support/extract_zip_file.py
extract_zip_file.py
py
466
python
en
code
5
github-code
36
4107020337
import sys from collections import deque input = sys.stdin.readline def check(a, b, size): return 0 == psa[a + size - 1][b + size - 1] - psa[a - 1][b + size - 1] - psa[a + size - 1][b - 1] + psa[a - 1][b - 1] moves = ((1, 0), (0, 1), (-1, 0), (0, -1)) n, m = [int(x) for x in input().split()] psa = [[0] * (m + 1...
AAZZAZRON/DMOJ-Solutions
aac2p3.py
aac2p3.py
py
1,238
python
en
code
1
github-code
36
370424566
from selenium import webdriver from amazon_pages.home_page import HomePage def test__amazon(): """ Go to book_page categorie, add first item to cart, change quantity to 2""" driver = webdriver.Chrome() home = HomePage(driver) cart_page = home.accept_cookie()\ .open_all_book()\ .select...
ClemiDouce/TP-pageobject
test_amazon.py
test_amazon.py
py
450
python
en
code
1
github-code
36
4711979655
# Patryk Kostek # Lab 6 Problem 3 ''' Design and implement a program that allows the user to play a game similar to Wheel of Fortune. Wheel of Fortune is a popular word game in which the player is given a category (Movie, Famous Person) and some number of blanks representing each character in the name of the movie or ...
Perrtyk/python
lab_6_strings/Problem_3.py
Problem_3.py
py
7,479
python
en
code
0
github-code
36
1889257914
''' Created on 08.02.2016. @author: Lazar ''' from concepts.row import Row from textx.exceptions import TextXSemanticError class View(object): basic_type_names = ['text', 'number', 'checkbox', 'link', 'email', 'password', 'menuitem', 'menu', 'button', 'radio', 'for...
lazer-nikolic/GenAn
src/concepts/view.py
view.py
py
2,115
python
en
code
2
github-code
36
18362653657
""" Class containing the display of the Chip8 emulator. """ import pygame class Chip8Display: def __init__(self, width, height, scale=10): ########################### # CONSTANTS ########################### self.BG_COLOR = (0, 0, 0) self.MAIN_COLOR = (255, 255, 255) ...
trd-db/PyChip8
chip8/Chip8Display.py
Chip8Display.py
py
4,194
python
en
code
0
github-code
36
35866822598
import sys,os import gmsh import numpy as np from mpi4py import MPI import dolfinx dir = os.path.dirname(__file__) gmsh.initialize() lc = 0.2 num_airfoil_refinement = 100 L = 4 H = 1 gdim = 2 """ Defining the shape of the airfoil using Bézier Curves Geometrical parameters of the airfoil according to ...
niravshah241/MDFEniCSx
demo/3_airfoil_displacement/mesh_data/mesh.py
mesh.py
py
6,178
python
en
code
1
github-code
36
29455040883
def lenIter(aStr): ''' aStr: a string returns: int, the length of aStr ''' count = 0 assert type(aStr) == str for char in aStr: count += 1 return count def lenRecur(aStr): ''' aStr: a string returns: int, the length of aStr ''' if aStr == '': ...
MichaelrMentele/MIT-6.002-Intro-to-CS
PythonScripts/lenIter.py
lenIter.py
py
379
python
en
code
1
github-code
36
6791731710
""" Class for acting as a server inside of a simpy simulation. This server is nothing more than a resource with some additional patches. @author Tycho Atsma <tycho.atsma@gmail.com> @file lib/Server.py """ # dependencies from simpy import PreemptiveResource from numpy.random import exponential, uniform class Serve...
miloshdrago/discrete-event-simulation-ing
app/lib/Server.py
Server.py
py
4,703
python
en
code
0
github-code
36
24495985471
from __future__ import print_function, unicode_literals from ._util import compact_json_dumps, TERMINALS, NONTERMINALS from ._util import follow_path, in_array, in_object, range, compat_kwargs import copy import bisect import sys import json def diff(left_struc, right_struc, array_align=True, compare_length...
opensvc/igw_envoy
src/json_delta/_diff.py
_diff.py
py
16,258
python
en
code
2
github-code
36
72311227944
import os import shutil import subprocess import traceback from typing import Any, List from src.manager.launcher.launcher_interface import ILauncher, LauncherException class LauncherRos(ILauncher): """ Launcher for ROS/Gazebo It's configuration should follow this spec: { "type": "module", ...
JdeRobot/RoboticsApplicationManager
manager/manager/launcher/launcher_ros.py
launcher_ros.py
py
2,764
python
en
code
2
github-code
36
32879521112
from matplotlib import pyplot as plt def visualize(flight): altitude = [t.position.y for t in flight] velocity = [t.velocity.y for t in flight] time = list(range(len(flight))) plt.figure() plt.subplot(211) plt.xlabel("Time (secs)") plt.ylabel("Altitude(m)") plt.plot(time, altitude) ...
mirman-school/hoc-rocketflight
visualizer.py
visualizer.py
py
442
python
en
code
0
github-code
36
27662925156
"""" MeGaNeKo 2022 - https://github.com/MeGaNeKoS/Discord-Bot-Template Description: This is a template to create your own discord bot in python. Version: 1.0 """ import logging class STDERRLogger: def __init__(self): self.logger = logging.getLogger("STDERR") formatter = logging.Formatter('%(leveln...
MeGaNeKoS/Discord-Bot-Template
utils/sys_logger.py
sys_logger.py
py
933
python
en
code
3
github-code
36
9607048047
import tensorflow as tf slim = tf.contrib.slim def inference(X, Y, is_training=True): with slim.arg_scope([slim.model_variable], device='/cpu:0'): prediction, tensor_collection = prime_classifier(inputs = X, is_training = is_training) tf.losses.sigmoid_cross_entropy(Y, prediction) losses = ...
ThorJonsson/PrimalityClassification
inference.py
inference.py
py
2,310
python
en
code
0
github-code
36
72094365545
#coding utf-8 # Среди натуральных чисел, которые были введены, найти наибольшее по сумме цифр. Вывести на экран это число и сумму его цифр. count = int(input('Введите кол-во элементов ряда: ')) sum = 0 max_sum = 0 max_num = 0 for i in range(1, count + 1): num = int(input('Введите натуральное число: ')) num_...
Jecteroid/python
alg_pyt/less02_task09.py
less02_task09.py
py
784
python
ru
code
0
github-code
36
72178607465
import falcon from math import sqrt from wsgiref.simple_server import make_server class Calc(): def on_get(self, req, resp): qs = req.params resp.body = "Waiting for input\n" resp.status = falcon.HTTP_200 def on_post(self, req, resp): chunk = req.stream.read(4096) val...
Lovelykira/Microservices
DBServer/db_server.py
db_server.py
py
1,388
python
en
code
0
github-code
36
18913990683
from collections import deque def neighbors(position: tuple[int, int, int]) -> list[tuple[int, int, int]]: x, y, step = position return [ (x + 1, y, step + 1), (x - 1, y, step + 1), (x, y + 1, step + 1), (x, y - 1, step + 1), ] class Solution: def nearestExit(self, ma...
lancelote/leetcode
src/nearest_exit_from_entrance_in_maze.py
nearest_exit_from_entrance_in_maze.py
py
1,325
python
en
code
3
github-code
36
44404785763
""" inout.py Calculate the number of years one must be without avocado toast in order to afford the down payment for a $750,000 home. """ import sys while True: print("In order to afford a 20% down payment for a home in Brooklyn at the median sale price of $750,000, how many avocado toasts will you, A Millen...
kathyvsinternet/Python-INFO1-CE9990
inout.py
inout.py
py
1,649
python
en
code
0
github-code
36
4359525162
import os import pandas as pd import numpy as np import surprise as sp from surprise.model_selection import GridSearchCV, train_test_split from surprise.accuracy import rmse from surprise import dump print('Losading reviews') reviews_df = pd.read_csv('/media/einhard/Seagate Expansion Drive/3380_data/data/user_book_rat...
dzmare/3380
Models/Recommender/model_SVDpp.py
model_SVDpp.py
py
879
python
en
code
0
github-code
36
32752187332
from multiprocessing import Pool from argparse import ArgumentParser from tbselenium.tbdriver import TorBrowserDriver from tbselenium.utils import launch_tbb_tor_with_stem from tbselenium.common import STEM_SOCKS_PORT, USE_RUNNING_TOR,\ STEM_CONTROL_PORT JOBS_IN_PARALLEL = 3 def run_in_parallel(inputs, worker, n...
webfp/tor-browser-selenium
examples/parallel.py
parallel.py
py
1,379
python
en
code
483
github-code
36
11473308179
from typing import Optional, Union import numpy as np import pandas as pd from lightfm import LightFM from lightfm.evaluation import precision_at_k from scipy import sparse as sps from .base import BaseRecommender class FMRecommender(BaseRecommender): """FM recommender based on `LightFM`. Args: int...
smartnews/rsdiv
src/rsdiv/recommenders/fm.py
fm.py
py
1,837
python
en
code
7
github-code
36
32983223303
# basics import argparse import os import pickle import pandas as pd import matplotlib.pyplot as plt import numpy as np # sklearn imports from sklearn.model_selection import train_test_split, cross_val_score from sklearn.neighbors import NearestNeighbors from sklearn.preprocessing import normalize # our code import...
akshi96/Coursework
CPSC340 - Machine Learning/a3/code/main.py
main.py
py
8,956
python
en
code
0
github-code
36
30502653408
from collections import defaultdict f = open('/Users/moishe/src/aoc-21/day-10/input/input.txt') xlat_closer = { '>': '<', ']': '[', '}': '{', ')': '(' } score_lookup = { ')': 3, ']': 57, '}': 1197, '>': 25137 } counters = defaultdict(int) score = 0 for l in f: l = l.rstrip() current_open = [] ...
Moishe/aoc-21
day-10/part-1.py
part-1.py
py
640
python
en
code
0
github-code
36
25099906773
import ast import re import tokenize import unicodedata from sympy.parsing import sympy_parser from sympy.core.basic import Basic ##### # Process Unicode characters into equivalent allowed characters: ##### # Unicode number and fraction name information: _NUMBERS = {"ZERO": 0, "ONE": 1, "TWO": 2, "THREE": 3, "FOUR"...
isaacphysics/equality-checker
checker/parsing/utils.py
utils.py
py
18,953
python
en
code
7
github-code
36
35022463878
# -*- coding: utf-8 -*- """ Authors: Ioanna Kandi & Konstantinos Mavrogiorgos """ # code import numpy as np import pandas as pd import sklearn import matplotlib.pyplot as plt import seaborn as sns import json from flask import * from flask_cors import CORS, cross_origin import warnings warnings.simplefilter(action='ig...
ioannakandi/recSys
main.py
main.py
py
6,875
python
en
code
1
github-code
36
22235734648
# Create a function to calculate the sum of all the numbers in a jagged array # (contains numbers or other arrays of numbers on an unlimited number of # levels) def sumjegged(arr): sum = 0 for num in arr: if type(num) == list: num = sumjegged(num) sum += num return sum print(s...
YopaNelly/code-P2
Ex45/Ex45.py
Ex45.py
py
372
python
en
code
1
github-code
36
32860540539
from django.http import HttpResponse from django.shortcuts import render,redirect from django.contrib.sites.shortcuts import get_current_site from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.utils.encoding import force_bytes, force_text from django.template.loader import render_to_...
chandrika-gavireddy/Django-Email_Verfication_while_RegisteringUser
accounts/views.py
views.py
py
2,581
python
en
code
0
github-code
36
3576654470
from sklearn.metrics import accuracy_score from sklearn.metrics import f1_score from sklearn.metrics import roc_auc_score from sklearn.metrics import average_precision_score from sklearn.metrics import recall_score # accuracy_scores: return the correctly classified samples. The set of labels predicted for a sample mus...
ClarissaW/Predict-tags-on-StackOverflow
evaluation.py
evaluation.py
py
1,960
python
en
code
0
github-code
36
39095371429
# coding: utf-8 # In[1]: #define a listener which listens to tweets in real time import tweepy # to install tweepy, use: pip install tweepy # import twitter authentication module from tweepy import OAuthHandler # import tweepy steam module from tweepy import Stream # import stream listener from tweepy.streaming...
vigneshsriram/Python-Tutorials
WebScrapping2/WebScraping2.py
WebScraping2.py
py
5,546
python
en
code
0
github-code
36
32268751295
#!/usr/bin/env python import sys import os import shutil #os.environ['OPENBLAS_NUM_THREADS'] = '1' import argparse import subprocess import requests import stat import json import pathlib import zipfile import pysam import pandas as pd import numpy as np from collections import Counter from functools import reduce fr...
BimberLab/nimble
nimble/__main__.py
__main__.py
py
13,434
python
en
code
1
github-code
36
12522230634
from hmac import new import streamlit as st import pandas as pd from google.cloud import bigquery import pandas_gbq from datetime import datetime, timedelta import yagmail import os st.set_page_config(layout="wide") days_mapping = { 'Monday': 'lunedì', 'Tuesday': 'martedì', 'Wednesday': 'mercoledì', '...
davins90/editable_table
prod/app.py
app.py
py
3,761
python
en
code
0
github-code
36
9037012840
import os import math import json import asyncio from operator import itemgetter import aiohttp from aiohttp import ClientConnectorError, ServerTimeoutError, TooManyRedirects from aiolimiter import AsyncLimiter from fastapi import FastAPI, Path app = FastAPI() # allow for 10 concurrent entries within a 2 second wind...
treybrooks/TopCryptosAPI
ranking/app/main.py
main.py
py
2,688
python
en
code
0
github-code
36
2360933175
# -*- coding: utf-8 -*- """ DIAGNOSTICS OF THE CARDIOVASCULAR SYSTEM BASED ON NEURAL NETWORKS Classify ECG-Signals to CAD-Symptoms by means of artificial neural networks Skript containing function to plot results. """ import os import numpy as np import seaborn as sns import matplotlib.pyplot as plt from matplotlib im...
Judweep/ECG_Classifier
Source_code/Plotting_Functions.py
Plotting_Functions.py
py
5,669
python
en
code
0
github-code
36
70619296105
import gym import numpy as np import random #from gym_minigrid.wrappers import * #import gym_minigrid #from gym_minigrid import Window import matplotlib #env = gym.make('MiniGrid-Empty-6x6-v0',render_mode='human') env = gym.make('MiniGrid-Empty-8x8-v0') #env = gym.make('MiniGrid-Empty-8x8-v0') #window = Wind...
VaibhavMishra02001/Implementation-of-RL-algorithms
sarsa1.py
sarsa1.py
py
2,633
python
en
code
0
github-code
36
74517741544
# -*- coding: utf-8 -*- """ Created on Mon Aug 24 18:27:02 2020 @author: Tomi """ import random # for random number selection def lotto(): '''ask user for 6 numbers in certain range. Program then displays 6 random numbers from the same range, and check the numbers the user guessed correctly''' input...
tomisile/PythonDemos
lotto.py
lotto.py
py
1,098
python
en
code
0
github-code
36
35906653499
''' 1. Средствами языка Python сформировать текстовый файл (.txt), содержащий последовательность из целых положительных и отрицательных чисел. Сформировать новый текстовый файл (.txt) следующего вида, предварительно выполнив требуемую обработку элементов: Исходные данные: Количество элементов: Минимальный элемент: Коли...
jmblx/PZ
PZ_11/PZ_11_1.py
PZ_11_1.py
py
1,370
python
ru
code
0
github-code
36
27769973712
import numpy as np ''' 李航-统计学习方法 p159-adaboost例子 最终结果由两部分构成:分类器系数alpha+{分类器阈值:分类器标记值} ''' x = np.arange(10) y = np.array([1] * 3 + [-1] * 3 + [1] * 3 + [-1]) # 节点域 r r = np.arange(0.5, 10, 1) print('x:',x) print('y:',y) print('r:',r) print('=============================') #分类器 # G(a,b,threh) <=threh则a,否...
kshsky/PycharmProjects
machinelearning/sklearn/AdaboostTestOri.py
AdaboostTestOri.py
py
4,264
python
en
code
0
github-code
36
5234262149
from .models import User from django.conf import settings from django.templatetags import static from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): avatar = serializers.SerializerMethodField() class Meta: model = User fields = ( 'username', ...
Zomba4okk/MyMovies
backend/apps/users/serializers.py
serializers.py
py
930
python
en
code
0
github-code
36
24650095567
from equationsimplier import stackCopy input = ['5', '4', '*', '4', 'x', '3', '*', '-', '='] input = ['5', '4', '*', 'x', '3', '*', '='] def varStack(stack): operator = stack.pop() stackCount = 0 paraCount = 0 LHSStack = [] RHSStack = [] oper = 0 dualOper = ['+', '-', '/', '*'] if opera...
jtjayesh98/EquationParser
test.py
test.py
py
1,917
python
en
code
0
github-code
36
29284640142
import boto3 import json def create_aws_resource(name, region, KEY, SECRET): """ Creates an AWS resource, e.g., ec2, s3. :param str name - the name of the resource :param str region - the name of the AWS region that will contain the resource. :param str KEY - the aws access key :param str ...
Hyacinth-Ali/data-warehouse-S3-to-Redshift-ETL
provision_resource_helper.py
provision_resource_helper.py
py
2,716
python
en
code
0
github-code
36
1386058348
import random from typing import Set import numpy as np def random_rotate(x: np.ndarray, rotation_directions: Set[int], mirror_directions: Set[int] = None, mirror_first=True) -> np.ndarray: if mirror_directions is None: mirror_directions = rotation_di...
veeramallirajesh/CT-Vertebrae-Detection
load_data/random_rotate.py
random_rotate.py
py
1,232
python
en
code
0
github-code
36
13925791934
import numpy as np import cv2 as cv import scipy.io from PIL import Image import time import os import errno import random from sklearn.model_selection import train_test_split import shutil import cv2 ############################################################################### #####################################...
haynec/yolov5_4_channel
fuse_and_reorg_dataset.py
fuse_and_reorg_dataset.py
py
4,190
python
en
code
0
github-code
36
70061727464
from myautograd.DataStructure import Node, Mat, DimNotMatchError from myautograd.op import op import unittest import math class TestNodeMethods(unittest.TestCase): def test_long_term_gradient(self): A = Node(2) B = Node(3) C = A * B D = Node(4) E = C * D F = B + E ...
luo3300612/MyAutoGrad
test_autograd.py
test_autograd.py
py
6,941
python
en
code
4
github-code
36
1734227672
# Mongodb 测试 from pymongo import MongoClient # 连接 mongodb,得到一个客户端对象 client = MongoClient('mongodb://localhost:27017') # 获取名为 scrapy_db 的数据库对象 db = client.scrapy_db # 获取名为 person 的集合对象 collection = db.person doc = { 'name':'刘硕', 'age':34, 'sex':'M' } # 将文件插入集合 collection.insert_one(do...
zkzhang1986/-Scrapy-
practise/scrapyMongodbTest.py
scrapyMongodbTest.py
py
443
python
zh
code
11
github-code
36
23280705402
''' Description: Author: weihuang Date: 2021-11-18 15:47:44 LastEditors: weihuang LastEditTime: 2021-11-22 22:38:26 ''' import torch import torch.nn.functional as F import torch.nn as nn from torch.autograd import Variable class CrossEntropy2d(nn.Module): def __init__(self, reduction="mean", ignore_label=255): ...
weih527/DA-ISC
scripts/loss/loss.py
loss.py
py
3,347
python
en
code
14
github-code
36
14412924035
import util.settings as settings import time import sys, getopt from util.logging import * from colorama import init import supermarkets.runner as srunner def main(argv): init() # Parsing of arguments try: #opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) opts, args = getopt.getopt(argv,"hve",["hel...
tonsmets/SupermarketScraper
supermarketscraper/main.py
main.py
py
1,164
python
en
code
21
github-code
36
34611052590
""" Author: Yanrui Hu Date: 2022-9-29 Description: Encrypt the sensitive message. Keyword: encryption, str-process Reason: HouLaoShi is a person who takes special message seriously. Version: 0.0.2 """ import random def encrypt_message(msg: str, key: int = 0x3f) -> str: encrypted_msg = [chr(ord(ch) + key) for ch i...
yanruiHu/Notes
python/encrypt_msg.py
encrypt_msg.py
py
904
python
en
code
0
github-code
36
41324119909
''' Multiples of 3 or 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' def number_multiples(number_1, number_2, number_range): """Takes two integers finds their multiples...
Infinite-series/Project-Euler
problem_1.py
problem_1.py
py
1,274
python
en
code
0
github-code
36
2863726451
import matplotlib.pyplot as plt import csv # 1. 读取数据;数据数组 data = [] headers = ['工作年限' ,'学历','职位','薪水','城市','发布时间'] city = set() with open('jobs.csv', 'r', encoding='utf-8') as fd: reader = csv.DictReader(fd, fieldnames=headers) # 返回的是迭代器 next(reader) # 把头略过 for row in reader: data.append(row['城市...
XiaJune/A-small
d16_plot_linalg/demo_hist.py
demo_hist.py
py
944
python
en
code
0
github-code
36
11539648952
from flask_restful import reqparse, abort, Resource, fields, marshal_with from cliente import Cliente from tipocliente import TipoCliente from produto import Produto from notafiscal import NotaFiscal from itemnotafiscal import ItemNotaFiscal CLIENTES = [] PRODUTOS = [] NOTAS = [] cliente_resource_fields = { 'id'...
Adriely-Silva/Adriely-Silva-POO-INFO-P7
AV06 API Nota Fiscal Router/controlador.py
controlador.py
py
10,481
python
pt
code
1
github-code
36
25947248538
# idea: do dfs, put current coordinate and node, # but put left node first and pop most left element firts from stack # than add coordinate and node to dict # than sort dict and return values from collections import defaultdict from typing import List, Optional class TreeNode: def __init__(self, val=0, left=Non...
dzaytsev91/leetcode-algorithms
medium/314_binary_tree_vertical_order_traversal.py
314_binary_tree_vertical_order_traversal.py
py
857
python
en
code
2
github-code
36
16055989419
import discord from discord.ext import commands from core.classes import Cog_Extension import json, asyncio, datetime, sqlite3, shutil, os, time class Task(Cog_Extension): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.time_task_counters = 0 self.bg_tas...
healthyvitamin/discord_bot
discord_bot/cmds/background_task.py
background_task.py
py
3,875
python
en
code
0
github-code
36
28662940889
import logging from ..models.formularios.form_accion_sort import Form_Accion_Sorteable from ..models.formularios.form_campo import Form_Campo from ..models.formularios.form_campo_sort import Form_Campo_Sorteable from ..models.formularios.form_elemento import Form_Elemento from ..models.formularios.form_filtro_param_so...
juanceweb/mayan_local
mayan/apps/unq/functions/functions_formularios.py
functions_formularios.py
py
8,973
python
es
code
0
github-code
36
74050675304
from copy import deepcopy from typing import Optional, List from types import MethodType from collections import defaultdict from nltk.tokenize import sent_tokenize from nltk.corpus import stopwords import random import spacy import torch from parlai.core.agents import create_agent, create_agent_from_shared from parla...
facebookresearch/ParlAI
projects/k2r/stacked_agent/task/agents.py
agents.py
py
28,080
python
en
code
10,365
github-code
36
12404712601
from vegetation_index import psri_index from osgeo import gdal import numpy as np import zipfile import os # adjust with band data filename target_band = ["B04_10m.jp2", "B08_10m.jp2"] print(target_band) zip_folder_path = "./data/2020" files = os.listdir(zip_folder_path) # make folder if not exits output_folder = f...
primagiant/auto-mapping-and-predicting-crops-production
utils/index/psri_calc.py
psri_calc.py
py
2,539
python
en
code
0
github-code
36
12212108701
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. def print_hi(name): # Use a breakpoint in the code line below to debug your script. print(f'Hi, {name}') # Press ...
LazyShake/ML-Tasks-Iskortsev
Zadanie 6 Zanyatie 1 iskor/main.py
main.py
py
1,010
python
en
code
0
github-code
36
27162959135
import gym import numpy as np import matplotlib.pyplot as plt NUM_RUNS = 50 MAX_EPISODE_STEPS = 5000 NUM_EPISODES = 100 NUM_ACTIONS = 3 env = gym.make('MountainCar-v0').env env._max_episode_steps = MAX_EPISODE_STEPS POLYNOMIAL_FEATURES = True POLYNOMIAL_DEGREE = 2 ''' https://github.com/openai/gym/wiki/MountainC...
MaximilianSamsinger/Advanced-Machine-Learning
Assignment 3/Mountain_Car.py
Mountain_Car.py
py
4,287
python
en
code
1
github-code
36
1418015547
# # @lc app=leetcode.cn id=376 lang=python # # [376] 摆动序列 # # @lc code=start class Solution(object): def wiggleMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) < 2: return len(nums) cur_diff = pre_diff = 0 res...
yangyuxiang1996/leetcode
376.摆动序列.py
376.摆动序列.py
py
732
python
en
code
0
github-code
36
3085767064
"""A Python Pulumi program""" import pulumi from pulumi_spacelift import Stack stack = Stack("my-stack", administrative=False, autodeploy=False, branch="main", description="A simple stack", name="simple-stack-python-pulumi", repository="empty", project_root="", terraform_version="1.3.0" )
spacelift-io/pulumi-spacelift
examples/simple-stack/py/__main__.py
__main__.py
py
308
python
en
code
0
github-code
36
36956162379
import fnmatch, os, time from suite_subprocess import suite_subprocess from wtscenario import make_scenarios import wttest class test_txn05(wttest.WiredTigerTestCase, suite_subprocess): logmax = "100K" tablename = 'test_txn05' uri = 'table:' + tablename remove_list = ['true', 'false'] sync_list = [...
mongodb/mongo
src/third_party/wiredtiger/test/suite/test_txn05.py
test_txn05.py
py
8,600
python
en
code
24,670
github-code
36
10744043731
import glob import pandas as pd export_path = 'dataset.csv' def make_data(export_path): files = [] path = '/home/moby/PycharmProjects/data/gpt/csv2/' files.extend(glob.glob(path + '*/*/*.csv')) path = '/home/moby/PycharmProjects/data/IDMT-SMT-32/' files.extend(glob.glob(path + '*/csv2/*.csv')) ...
SergWh/datasets_processing
make_dataset.py
make_dataset.py
py
827
python
en
code
0
github-code
36
39660373641
from collections import Counter class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: if len(nums) == 1: return [nums] counter = Counter(nums) result = [] def backtracking(perm): if len(perm) == len(nums): resul...
deusi/practice
47-permutations-ii/47-permutations-ii.py
47-permutations-ii.py
py
686
python
en
code
0
github-code
36
8574496857
from djoser.views import UserViewSet from rest_framework.pagination import LimitOffsetPagination from rest_framework.permissions import IsAuthenticated class DjoserUserViewSet(UserViewSet): pagination_class = LimitOffsetPagination permission_classes = [IsAuthenticated] def me(self, request, *args, **kwar...
ticpragma/foodgram-project-react
foodgram/users/views.py
views.py
py
452
python
en
code
0
github-code
36
6290474507
# Extract Adobe Analytics data strings from Adobe Assurance (Project Griffon) logs # 24 Oct 2022 11:18 # Michael Powe # reminder of what we are looking for # (json_data['events'][3]['payload']['ACPExtensionEventData']['hitUrl']) import json import urllib.parse from argparse import ArgumentParser from pprint import ppr...
nyambol/adobe-assurance-json
json-parser.py
json-parser.py
py
4,571
python
en
code
0
github-code
36
2846513143
#User function Template for python3 # https://practice.geeksforgeeks.org/problems/quick-sort/1 class Solution: #Function to sort a list using quick sort algorithm. def quickSort(self,arr,low,high): # code here if(low>=high):return pi = self.partition(arr,low,high) self.quick...
mohitsinghnegi1/CodingQuestions
Algorithms/QuickSort.easy.py
QuickSort.easy.py
py
1,446
python
en
code
2
github-code
36
25606396016
import math from random import randint def generic_agency_or_account(number_of_digits=4): account = list() for i in range(0, number_of_digits): account.append(randint(0, 9)) return account def generic_multiplier(multipliers): sum_numbers = 0 for i, j in enumerate(reversed(multipliers), s...
MarcosSx/CursoGuanabara
Exercicios/desafios_extras/gerador_conta.py
gerador_conta.py
py
6,452
python
en
code
0
github-code
36
37005905790
from pathlib import Path import pytest from helpers.regression import verify_output RINOH_PATH = Path(__file__).parent / 'rinoh' OUTPUT_PATH = Path(__file__).parent / 'output' def test_version(script_runner): ret = script_runner.run('rinoh', '--version') assert ret.success assert ret.stderr == '' de...
Chris-Jr-Williams/rinohtype
tests_regression/test_rinoh.py
test_rinoh.py
py
1,189
python
en
code
null
github-code
36