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
15807183248
# -------------------------------------------------------- # PYTHON PROGRAM # Here is where we are going to define our set of... # - Imports # - Global Variables # - Functions # ...to achieve the functionality required. # When executing > python 'this_file'.py in a terminal, # the Python interpreter will load...
segunar/BIG_data_sample_code
Spark/Workspace/2_Spark_Streaming/2_Stateless_Transformations/02_word_count.py
02_word_count.py
py
15,508
python
en
code
0
github-code
36
19631354561
from __future__ import unicode_literals from zope.component.interfaces import ObjectEvent, IObjectEvent from zope.interface import Attribute, implements class IGSJoinSiteEvent(IObjectEvent): """ An event issued after someone has joined a site.""" siteInfo = Attribute('The site that is being joined') membe...
groupserver/gs.site.member.base
gs/site/member/base/event.py
event.py
py
1,050
python
en
code
0
github-code
36
27453713164
class Mafia(): def __init__(self, player_id, player_name): self.name = "Mafia" self.changed_name = self.name self.can_act = True self.act_time = "Night" self.alignment = "Mafia" self.need_await = False self.player_id = player_id self.player_name = play...
0h90/Mafioso
Mafia.py
Mafia.py
py
1,400
python
en
code
0
github-code
36
73583260585
import phunspell import inspect import unittest class TestItIT(unittest.TestCase): pspell = phunspell.Phunspell('it_IT') def test_word_found(self): self.assertTrue(self.pspell.lookup("fisciù")) def test_word_not_found(self): self.assertFalse(self.pspell.lookup("phunspell")) def test...
dvwright/phunspell
phunspell/tests/test__it_IT.py
test__it_IT.py
py
590
python
en
code
4
github-code
36
6363206566
from itertools import count global_index = 1 global_bank_fee = 1 global_bank_win = 2 global_bank_lose = 3 class smartPlayer: _ids = count(0) def __init__(self, trustor_or_trustee, trust_coefficient, beta): global global_bank_fee global_bank_fee = beta self.id = next(self._ids) ...
snirsh/TrustGame
SmartPlayer.py
SmartPlayer.py
py
2,264
python
en
code
0
github-code
36
15987055483
def assign_to_projects(self, data): result = [] for x in data: user = self.users.find_one({'email': x['email']}) if not user: result.append((False, 'User not found!', 404)) continue project = self.projects.find_one({'name': x['project']}) if not project: ...
DvaMishkiLapa/diplom_se_2019
code/assign_to_projects_server_func.py
assign_to_projects_server_func.py
py
780
python
en
code
0
github-code
36
74838938664
# environment import sys, os import argparse import json from board import Tiles, Board from player import Player import shape def pprint(thing): sys.stdout.write(thing + '\n') sys.stdout.flush() if __name__ == '__main__': parser = argparse.ArgumentParser() player = [] parser.add_argument("--...
FineArtz/Game3_Blokus
environment.py
environment.py
py
3,602
python
en
code
1
github-code
36
3685311565
# coding: utf-8 import collections import os try: import StringIO except: from io import StringIO import sys import tarfile import tempfile import urllib import numpy as np from PIL import Image, ImageDraw import collections import tensorflow as tf import random if tf.__version__ < '1.5.0': raise Impor...
MatthieuBlais/tensorflow-clothing-detection
background.py
background.py
py
3,761
python
en
code
11
github-code
36
1700285316
#!/usr/bin/python3 """ @author : Chris Phibbs @created : Wednesday Nov 18, 2020 21:12:41 AEDT @file : buySell """ # TC: O(N) - We make one pass of the list # SC: O(1) - We use same amount of space regardless of list size class Solution: def maxProfit(self, prices): # If there's no ...
phibzy/InterviewQPractice
Solutions/BuySellStockI/buySell.py
buySell.py
py
884
python
en
code
0
github-code
36
26090442688
import pandas as pd import numpy as np import matplotlib.pyplot as plt from basic.bupt_2017_11_28.type_deco import prt import joblib from sklearn import preprocessing from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from basic.bupt_2017_11_28.type_deco import prt import se...
Mr-cpc/idea_wirkspace
learnp/basic/bupt_2018_1_23/shortpalin.py
shortpalin.py
py
1,697
python
en
code
0
github-code
36
24843380202
import os import pandas as pd def renameProteins(cols_to_rename,somadict): # Rename proteins new_cols = [] for s in cols_to_rename: if 'seq' in s: if 'ratio' in s: s1 = s.split('_seq')[1] new_s1 = '-'.join(s1.split('.')[1:]) try: ...
BorgwardtLab/LongCOVID
combineInterpretations.py
combineInterpretations.py
py
2,880
python
en
code
0
github-code
36
13510402136
################################################################################ ''' Name : powerBy Purpose : Function to get the exponential value for a value for an value. ''' ################################################################################ import sys print("Current value of recursion limit is",sy...
gopinathrajamanickam/DSA
Recursion/powerBy.py
powerBy.py
py
821
python
en
code
0
github-code
36
36059095725
#!/usr/bin/env python # coding: utf-8 # In[1]: import torch as torch # In[2]: import torch.nn as nn import pandas as pd from torch.autograd import Variable from sklearn.model_selection import train_test_split from torch.utils.data import DataLoader, TensorDataset # In[3]: df = pd.read_csv("yoochoose-clicks.d...
fahadkh2019/Capstone_Project
LSTM Modeling-updated.py
LSTM Modeling-updated.py
py
4,722
python
en
code
0
github-code
36
72644950504
import os import subprocess from itertools import chain from pathlib import Path import pytest from netCDF4 import Dataset from pkg_resources import resource_filename from compliance_checker.cf import util from compliance_checker.suite import CheckSuite def glob_down(pth, suffix, lvls): """globs down up to (lvl...
ioos/compliance-checker
compliance_checker/tests/conftest.py
conftest.py
py
2,919
python
en
code
92
github-code
36
24797529159
#coding=utf-8 """ PGCNet batch data generator two different type input :point cloud and multi-view image __author__ = Cush shen """ import numpy as np from tqdm import tqdm import h5py import time import tensorflow as tf image_color_gray = 158 image_color_white = 255 def getDataFiles(list_filenam...
conzyou/PGVNet
train_utils.py
train_utils.py
py
19,697
python
en
code
3
github-code
36
35376158594
# fit to time dependent function of chance of having activity of any length during a single labeling window # infer k_on parameter based on single window for 4SU (though here it is the 2nd window) # based on different window lengths # window_lengths = [15, 30, 45, 60, 120, 180] # fit based on (hidden) presence of activ...
resharp/scBurstSim
analysis/infer_parameters_example.py
infer_parameters_example.py
py
7,414
python
en
code
3
github-code
36
71873731623
import pygame from Helper.global_variables import * from Helper.text_helper import drawTextcenter, drawText pygame.init() def update_display(win, height, color_height, numswaps, algorithm, number_of_elements, speed, time, running): win.fill(BLACK) # call show method to display the list items s...
andreidumitrescu95/Python-Sorting-Algorithm-Visualizer
Display/display.py
display.py
py
2,692
python
en
code
3
github-code
36
40799230806
case_num = int(input()) for c_num in range(1, case_num+1): input_len = int(input()) price_lst = list(map(int, input().split())) my_profit = 0 while True: if len(price_lst) == 0: break max_idx = price_lst.index(max(price_lst)) p_left = price_lst[:max_idx+1] ...
devjunmo/PythonCodingTest
SWEA/D2/1859. 백만 장자 프로젝트.py
1859. 백만 장자 프로젝트.py
py
746
python
en
code
0
github-code
36
36375251491
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from moderation.moderator import GenericModerator from moderation.tests.apps.test_app1.models import UserProfile,\ ModelWithModeratedFields from moderation.tests.utils.testsettingsmanager import SettingsTestCase from moderatio...
arowla/django-moderation
src/moderation/tests/acceptance/exclude.py
exclude.py
py
4,091
python
en
code
null
github-code
36
483706012
import hashlib import json import os import struct import sys import textwrap from fnmatch import fnmatch from pathlib import Path from typing import Dict, List, Union import cryptography from cryptography.fernet import Fernet if sys.version_info < (3, 8): TypedDict = dict else: from typing import TypedDict ...
dihi/datavault
dihi_datavault/__init__.py
__init__.py
py
14,958
python
en
code
0
github-code
36
28356972055
import logging import sys from kodi_interface import KodiObj LOGGING = logging.getLogger(__name__) def get_input(prompt: str = "> ", choices: list = [], required = False) -> str: ret_val = input(prompt) if choices: while not ret_val in choices: print(f'Invalid selection. Valid entr...
JavaWiz1/kodi-cli
kodi_help_tester.py
kodi_help_tester.py
py
2,077
python
en
code
6
github-code
36
19033902872
"""Module contains functionality for parsing HTML page of a particular vulnerability.""" import re import urllib.request from lxml import etree from cve_connector.vendor_cve.implementation.parsers.general_and_format_parsers\ .html_parser import HtmlParser from cve_connector.vendor_cve.implementation.parsers.vendor...
CSIRT-MU/CRUSOE
crusoe_observe/cve-connector/cve_connector/vendor_cve/implementation/parsers/vendor_parsers/cisco_parsers/cisco_vulnerability_parser.py
cisco_vulnerability_parser.py
py
13,807
python
en
code
9
github-code
36
42583588575
# -*- coding: utf-8 -*- """ Created on Sun Dec 1 20:41:25 2019 @author: hp """ import aiml # Create the kernel and learn AIML files kernel = aiml.Kernel() kernel.learn("custom.aiml") # Press CTRL-C to break this loop while True: userinput = input("Enter your message >> ") output = kernel....
syeda-mahrukh-wajid/assignment
chatbot1.py
chatbot1.py
py
357
python
en
code
0
github-code
36
28613178416
#!/usr/bin/env python """PySide port of the network/http example from Qt v4.x""" import sys from PySide import QtCore, QtGui, QtNetwork class HttpWindow(QtGui.QDialog): def __init__(self, parent=None): QtGui.QDialog.__init__(self, parent) self.urlLineEdit = QtGui.QLineEdit("http://www.ietf.org/...
pyside/Examples
examples/network/http.py
http.py
py
5,973
python
en
code
357
github-code
36
43867560541
n = int(input()) job = [list(map(int, input().split())) for _ in range(n)] job.sort(key=lambda x: x[1]) ans = True time = 0 for i, j in job: time += i if time > j: ans = False break print("Yes") if ans else print("No")
cocoinit23/atcoder
abc/abc131/D - Megalomania.py
D - Megalomania.py
py
245
python
en
code
0
github-code
36
14772991298
class Audit(object): def __init__(self): """ Constructor method for audit. Attributes ========== global_audit (dictionary): Audit of high level metrics unit_audit (dictionary): Audit at unit level """ # Initialise global au...
MichaelAllen1966/2105_london_acute_stroke_unit
sim_utils/audit.py
audit.py
py
2,714
python
en
code
0
github-code
36
42211647592
import tensorflow as tf session = tf.Session() state = tf.placeholder("float", [None, 3]) weights = tf.Variable(tf.constant(0., shape=[3, 2])) value_function = tf.matmul(state, weights) session.run(tf.initialize_all_variables()) ans = session.run(value_function, feed_dict={state: [[1., 0., 0.]]}) print(ans)
RhysJMartin/reinforcement_learning
break_out/temp.py
temp.py
py
314
python
en
code
0
github-code
36
11892203140
class Solution: def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: max_dist = 0 i = 0 j = 0 while i < len(nums1) and j < len(nums2): if nums2[j] < nums1[i]: i = i+1 elif nums2[j] >= nums1[i]: max_di...
bandiatindra/DataStructures-and-Algorithms
Additional Algorithms/LC 1855. Max Distance Between Pair of Values.py
LC 1855. Max Distance Between Pair of Values.py
py
394
python
en
code
3
github-code
36
32559830813
import jwt from functools import wraps from app import request, jsonify, app from app.use_db.tools import quarry def token_required(f): @wraps(f) def _verify(*args, **kwargs): auth_headers = request.headers.get('Authorization', '').split() invalid_msg = { 'message': 'Invalid token...
Baral-Chief-of-Compliance/ice_tracing_software
prototype/v1/backend/authorization/decorator_for_authorization.py
decorator_for_authorization.py
py
1,506
python
en
code
0
github-code
36
11490438190
import base64 import io from PIL import Image from pyzbar.pyzbar import decode from requests_ntlm import HttpNtlmAuth import requests def get_js(sc, shop): username = r'WebService' password = 'web2018' auth = HttpNtlmAuth(username, password) strParam = shop + '/' + sc list_url = r"https://ts.offp...
otitarenko/djangoqr
qrapp/decoder.py
decoder.py
py
2,047
python
en
code
0
github-code
36
71707011944
# Write code to extract the number at the end of the line below. # Convert the extracted value to a floating point number and print it out. text = "Lorem ipsum dolor sit amet elit, consectetur adipiscing elit 20.65434" ftext = text.find("adipiscing") find_text = text.find(' ', ftext) part_text = text[find_text + ...
Sarah-Rz/finding-value-in-string
ex_1.py
ex_1.py
py
374
python
en
code
0
github-code
36
74062234985
import pytest from fauxcaml.semantics.check import Checker from fauxcaml.semantics.typ import * from fauxcaml.semantics.unifier_set import UnificationError def test_concrete_atom_unification(): checker = Checker() checker.unify(Int, Int) def test_concrete_poly_unification(): checker = Checker() che...
eignnx/fauxcaml
fauxcaml/tests/test_unification.py
test_unification.py
py
2,419
python
en
code
2
github-code
36
5183501759
primelist = [2,3,5,7] adder = [1,3,7,9] inc = 1 while(1): for i in adder: num = int(str(inc)+str(i)) flg = False for j in range(3,num//2,2): if num%j==0: flg = True break if flg==False: primelist.append(num) #print(num) inc+=1 if len(primelist)==10001: print(primelist[...
pythonic-shk/Euler-Problems
euler7.py
euler7.py
py
336
python
en
code
0
github-code
36
25607915801
class Solution: def rightSideView(self, root: Optional[TreeNode]) -> List[int]: if not root: return None queue = deque() queue.append(root) result = [] while queue: result.append(queue[-1].val) f...
Nirmalkumarvs/programs
Trees/Binary Tree Right Side View.py
Binary Tree Right Side View.py
py
589
python
en
code
0
github-code
36
36322979415
#! /usr/bin/env python import sys import pygame import os import argparse import logging from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler from subprocess import Popen from pygame.locals import * logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)...
hreck/PyBooth
pyBooth.py
pyBooth.py
py
7,007
python
en
code
0
github-code
36
73708087464
"""Covariance-free Partial Least Squares""" # Author: Artur Jordao <arturjlcorreia[at]gmail.com> # Artur Jordao import numpy as np from scipy import linalg from sklearn.utils import check_array from sklearn.utils.validation import FLOAT_DTYPES from sklearn.base import BaseEstimator from sklearn.pr...
arturjordao/IncrementalDimensionalityReduction
Code/CIPLS.py
CIPLS.py
py
4,113
python
en
code
6
github-code
36
35251633118
#prob.8 from timeit import default_timer as dt #repetitive calling of the isprime improves the performance #use isPrime in Prob.7 #=========================prob.7================================= primenumbers :list[int] = [2] #prime number cache #find the number is prime def isPrime (num :int) ->bool: """Check ...
lila-lalab/SDDataExpertProgram2021
이재호/day3/test_8_cache_for.py
test_8_cache_for.py
py
2,858
python
en
code
0
github-code
36
37055431378
import asyncio import ciberedev # creating our client instance client = ciberedev.Client() async def main(): # starting our client with a context manager async with client: # taking our screenshot screnshot = await client.take_screenshot("www.google.com") # printing the screenshots u...
cibere/ciberedev.py
examples/take_screenshot.py
take_screenshot.py
py
572
python
en
code
1
github-code
36
718080167
from re import S import re from django.db.models.signals import pre_init from django.shortcuts import render from .models import * from .serializers import * from django.shortcuts import render from rest_framework import viewsets, mixins, generics from rest_framework.views import APIView from rest_framework.decorators ...
haydencordeiro/FoodDeliveryDjango
food/views.py
views.py
py
20,986
python
en
code
1
github-code
36
39924477846
from rest_framework import serializers from core.models import Match class MatchSerializer(serializers.ModelSerializer): """ The `season` field is read only for the external API, because we force it to use the currently active season inside the MatchViewSet.perform_create() method. This means th...
dannymilsom/poolbot-server
src/api/serializers/match.py
match.py
py
805
python
en
code
4
github-code
36
34495102899
import adijif import pprint clk = adijif.ad9545(solver="gekko") clk.avoid_min_max_PLL_rates = True clk.minimize_input_dividers = True input_refs = [(0, 1), (1, 10e6)] output_clocks = [(0, 30720000)] input_refs = list(map(lambda x: (int(x[0]), int(x[1])), input_refs)) # force to be ints output_clocks = list(map(lam...
analogdevicesinc/pyadi-jif
examples/ad9545_example.py
ad9545_example.py
py
493
python
en
code
6
github-code
36
70295398824
import torch from torch import nn from torch.utils.tensorboard import SummaryWriter from models.convnet import ConvNet from utils.data_loader import load_cifar10, create_dataloaders from utils.train import train device = 'cuda' if torch.cuda.is_available() else 'cpu' writer = SummaryWriter('runs/exercise-2_1') train_...
simogiovannini/DLA-lab1
2_1.py
2_1.py
py
1,300
python
en
code
0
github-code
36
44210134673
# -*- coding: utf-8 -*- #!/usr/bin/env python3 #(pandas)求出每個檔案中,一組值的總和與平均值 """ Created on Fri Sep 22 11:23:54 2017 @author: vizance """ import pandas as pd import sys import glob import os input_path = sys.argv[1] output_file = sys.argv[2] all_files = glob.glob(os.path.join(input_path, 'sales_*')) all_data_frames =[] ...
vizance/Python_Data_Analysis
第二章_CSV檔案處理/pandas_sum_average_from_multiple_files.py
pandas_sum_average_from_multiple_files.py
py
1,354
python
en
code
0
github-code
36
35599138078
from pandas import Series from matplotlib import pyplot from statsmodels.tsa.ar_model import AR from sklearn.metrics import mean_squared_error series = Series.from_csv('daily-minimum-temperatures.csv', header=0) # split dataset X = series.values train, test = X[1:len(X)-7], X[len(X)-7:] # train autoregression model = A...
yangwohenmai/TimeSeriesForecasting
AR自回归模型/自回归模型.py
自回归模型.py
py
828
python
en
code
183
github-code
36
9355826258
import requests import re def check_link(url_parent, url_child): pattern = r"href=\"(.*)\"" res = requests.get(url_parent) if res.status_code == 200: all_inclusions = re.findall(pattern, res.text) else: print("No") return for link in all_inclusions: res = requests.ge...
ArtemevIvanAlekseevich/Python_course
module 3/3.3-step_6-check_link.py
3.3-step_6-check_link.py
py
625
python
en
code
0
github-code
36
17062759580
import Account class SavingAccount(Account.BaseAccount): def __init__(self,accNum,accHolderName): super().__init__(accNum,accHolderName) self._minimumBalance = 5000 self._rateOfInterest = 10 def withdraw(self,withdrawMoney): if self._currentBalance > self._minimumBalance: ...
AmenTauhid/Bank-Management-System
SavingAccount.py
SavingAccount.py
py
466
python
en
code
0
github-code
36
28725034067
import os from tkinter import * from tkinter import filedialog def openfile(): filename = filedialog.askopenfilenames(parent=root, initialdir="C:\\Users\\Tri Nguyen\\Documents", title="Select File") print(filename) root = Tk() root.geometry("300x300") menubar = Menu(root) filemenu = Menu(menubar, tearoff=0) f...
ninjanaruto1012/PDFTool
app2.py
app2.py
py
463
python
en
code
0
github-code
36
44310786559
import serial, time, syslog, string def scoredisp(score): # initializes the serial port port = '/dev/ttyACM0' ard = serial.Serial(port,9600) # writes the inputted score to the serial port ard.write(str(score).encode('ascii'))
RamboTheGreat/Minigame-Race
test.py
test.py
py
237
python
en
code
0
github-code
36
18321986402
import numpy def MoveToChange(move): r1=r2=c1=c2=0 c1,c2 = ord(move[0])-97,ord(move[2])-97 r1,r2 = 8-int(move[1]),8-int(move[3]) if len(move) == 6: return r1,c1,r2,c2,move[5] return r1,c1,r2,c2,None def ChangeToMove(r1,c1,r2,c2): return ''.join((chr(c1+97),str(8-r1),chr(c2+97),str(8-r2...
hwright01/General
Python/Chess/ChessEngine.py
ChessEngine.py
py
12,133
python
en
code
0
github-code
36
13870439802
# 10~99 사이의 난수 n개 생성하기(13이 나오면 중단) import random print('10~99 사이의 난수 n개 생성하기(13이 나오면 중단)') n = int(input('난수의 개수를 입력하세요.: ')) for _ in range(n): rn = random.randint(10, 99) print(rn,'', end='') if rn == 13: print('\n프로그램을 중단합니다.') break else: print('\n난수 생성을 중단합니다.')
hye0ngyun/PythonPractice
books/AlgorithmWithPython/chap01/01_2/chap01_2Ex9.py
chap01_2Ex9.py
py
428
python
ko
code
0
github-code
36
17078297023
from django.shortcuts import render from django.core.mail import send_mail from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.conf import settings from .forms import Contact_us_form, SupportForm import urllib import json def contact_us(request): if request.method ...
Pavlo-Olshansky/E-market
get_in_touch/views.py
views.py
py
3,028
python
en
code
2
github-code
36
35305572933
from flask import Flask, jsonify, request from flask_cors import CORS import database app = Flask(__name__) app.config["ERROR_404_HELP"] = False # allow all for simplicity CORS(app) @app.route("/") def landing(): return """ Hello, this is the News Article Searcher of Koen Douterloigne! <br> Plea...
tobneok/isentia_test
server/app.py
app.py
py
851
python
en
code
0
github-code
36
12834488522
''' 1. 최대 수익을 저장하는 변수를 만들고 0을 저장합니다. 2. 지금까지의 최저 주가를 저장하는 변수를 만들고 첫째 날의 주가를 기록합니다. 3. 둘째 날의 주가부터 마지막 날의 주가까지 반복합니다. 4. 반복하는 동안 그날의 주가에서 최저 주가를 뺀 값이 현재 최대 수익보다 크면 최대 수익 값을 그 값으로 고칩니다. 5. 그날의 주가가 최저 주가보다 낮으면 최저 주가 값을 그날의 주가로 고칩니다. 6. 처리할 날이 남았으면 4번 과정으로 돌아가 반복하고, 다 마쳤으면 최대 수익에 저장된 값을 결괏값으로 돌려주고 종료합니다. ''' # n = int(inpu...
ohjooyeong/codingame
stock exchange losses.py
stock exchange losses.py
py
1,551
python
ko
code
0
github-code
36
5163641580
import yaml import sys import xarray as xr import time import glob def subset_vars(argv): if(len(argv)!=7): print("USAGE: wrf-subset-vars.py <in nc path> <in nc file> <out nc path> <out nc file> <var list path> <var list file>\n") sys.exit(1) innc_path = argv[1] innc_file = argv[2] ...
LEAF-BoiseState/py-wrf-postproc
wrf-subset-vars.py
wrf-subset-vars.py
py
1,265
python
en
code
3
github-code
36
16583267084
from datetime import datetime, date from email.mime.text import MIMEText from flask import Flask import os import schedule import smtplib import time # import threading from mailjet_rest import Client from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail from config import * startupTs = dateti...
wjewell3/email
main.py
main.py
py
6,000
python
en
code
0
github-code
36
10663976037
# -*- coding: utf-8 -*- """ Created on Fri Dec 4 15:43:55 2015 Plot coodinate time series for radio sources. @author: Neo """ import numpy as np import matplotlib.pyplot as plt from fun import ADepoA, ADepoS cos = np.cos dat_dir = '../data/opa/' res_dir = '../plot/timeseries/' t0 = 2000.0 def tsplot(soun, pmra, p...
Niu-Liu/thesis-materials
sou-selection/progs/TimeseriesPlot.py
TimeseriesPlot.py
py
1,827
python
en
code
0
github-code
36
8209022862
# from gen_captcha import gen_captcha_text_and_image # from gen_captcha import number # from gen_captcha import alphabet # from gen_captcha import ALPHABET from custom import gen_captcha_text_and_image from custom import number from custom import alphabet from custom import ALPHABET import time import numpy as np imp...
lensv/Captcha
training.py
training.py
py
13,040
python
zh
code
0
github-code
36
22140484347
from django.core.exceptions import ValidationError from django.http import HttpResponse from django.http.response import HttpResponseForbidden, JsonResponse from django.shortcuts import redirect, get_object_or_404 from django.template import loader from django.views.decorators.csrf import csrf_exempt from .models impo...
njsh4261/url_shortener
backend/url_shortener/views.py
views.py
py
2,785
python
en
code
0
github-code
36
19743419969
from os import sep from subprocess import call import click path_ini_alembic_file = 'app_config/config_files/alembic.ini'.replace('/', sep) @click.group('db') def db(): ... @db.command() @click.option('-m', 'message', default='migração via CLI', help='Mensagem para identificar a migrations do al...
isaquefel/ensaio_app
app_rotinas/cli/migrations_management.py
migrations_management.py
py
760
python
en
code
0
github-code
36
73488163624
class Animal: is_alive: bool = True def breeze(self): print("I'm breezing") class Mammal(Animal): leg_amount: int kid_food_type: str = 'Milk' def voice(self): raise NotImplementedError def do_bad_things(self): raise NotImplementedError class Cat(Mammal): def ...
VladPetrov19/Lessons
venv/lesson_14.py
lesson_14.py
py
2,024
python
en
code
0
github-code
36
5501591657
### IMPORT THE REQUIRED LIBRARIES # To read the dataset in .mat format import scipy.io as sio # For matrix operations import numpy as np # Keras functions to create and compile the model from keras.layers import Input, Conv2D, Lambda, Reshape, Multiply, Add, Subtract from keras.activations import relu from keras.opt...
hansinahuja/ISTA-Net
ista_net.py
ista_net.py
py
11,288
python
en
code
4
github-code
36
11538172081
#!/usr/bin/python3 """ a module that queries API """ from requests import get def top_ten(subreddit): """ A function that queries the Reddit API Args: subreddit (str): the name of the subreddit Returns: str: print valid titles """ load = {'limit': 10} headers = ...
Rashnotech/alx-system_engineering-devops
0x16-api_advanced/1-top_ten.py
1-top_ten.py
py
737
python
en
code
0
github-code
36
5340116338
from globals import * DEFAULT_LATITUDE = 45.943161 DEFAULT_LONGITUDE = 24.96676 class _New_Hub(webocrat_Request): def get(self): self.show_form(False) def post(self): self.show_form(True) @need_registered_user def show_form(self, post = False): errors = dict() if pos...
webocrat/webocrat
py/new_hub.py
new_hub.py
py
1,450
python
en
code
1
github-code
36
39763274152
from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ url(r'^$', views.assignments, name='assignments'), url(r'^addnewassignments/$', views.addnewassignments, name='addnewassignments'), # url(r'^deleteassignments/$', views.deleteassignments, name='deleteassignment...
hafeezurrahmansaleh/Daily-Lab-Assistance
assignments/urls.py
urls.py
py
744
python
en
code
0
github-code
36
43859197331
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: res = [] for i in range(len(nums)): b = target - nums[i] for j in range(1, len(nums) - i): if nums[i+j] == b: res.append(i) res.append(j+i) ...
CocoKe98/LeetCode
1. Two Sum.py
1. Two Sum.py
py
335
python
en
code
0
github-code
36
74833825384
import sqlite3 import argparse import logging # Optional argument to use a listed database file. otherwise use vics.sqlite # argparse with usage # If no vics.sqlite3 then create it, and make the 'all' table. parser = argparse.ArgumentParser() parser.add_argument("-f", "--file", dest="db_file", help="Optional. Path to...
fine-fiddle/vics
vics.py
vics.py
py
1,888
python
en
code
0
github-code
36
36955901449
import wttest from helper_tiered import TieredConfigMixin, gen_tiered_storage_sources from wtscenario import make_scenarios # test_schema06.py # Repeatedly create and drop indices class test_schema06(TieredConfigMixin, wttest.WiredTigerTestCase): """ Test basic operations """ nentries = 1000 ty...
mongodb/mongo
src/third_party/wiredtiger/test/suite/test_schema06.py
test_schema06.py
py
5,452
python
en
code
24,670
github-code
36
38801618139
from transformers import pipeline # classifier = pipeline('sentiment-analysis') # res = classifier( # 'We are not very happy to introduce pipeline to the transformers repository.') pipe = pipeline('question-answering') res = pipe({ 'question': 'What is the name of the repository ?', 'context': 'Pipeline h...
taterboom/simple-tts
index.py
index.py
py
397
python
en
code
0
github-code
36
7690180947
def method1(X, Y): m = len(X) n = len(Y) L = [[None] * (n + 1) for i in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: L[i][j] = 0 elif X[i - 1] == Y[j - 1]: L[i][j] = L[i - 1][j - 1] + 1 els...
thisisshub/DSA
T_dynamic_programming/problems/A_longest_common_subsequence.py
A_longest_common_subsequence.py
py
921
python
en
code
71
github-code
36
16509838314
import netmanthan from netmanthan.model.document import Document from netmanthan.query_builder import Interval from netmanthan.query_builder.functions import Now class ErrorSnapshot(Document): no_feed_on_delete = True def onload(self): if not self.parent_error_snapshot: self.db_set("seen", 1, update_modified=...
netmanthan/Netmanthan
netmanthan/core/doctype/error_snapshot/error_snapshot.py
error_snapshot.py
py
1,244
python
en
code
0
github-code
36
74863821545
import json import unittest from api.tests.base import BaseTestCase class TestSimulationsService(BaseTestCase): """ Tests for the Simulation Service """ def test_simulations(self): """ Ensure the /ping route behaves correctly. """ response = self.client.get("/simulations/ping") data ...
door2door-io/mi-code-challenge
backend/api/tests/test_simulations.py
test_simulations.py
py
555
python
en
code
0
github-code
36
37986564283
import sys import scipy from scipy import io from scipy.io import wavfile def getVolume(sound): value = 0 for sample in sound: value += abs(sample) print(value) def main(): file = sys.argv[1] print(file) sampling_rate, sound = scipy.io.wavfile.read(file) getVolume(sound) if __nam...
emilymacq/Project-Clear-Lungs
ARCHIVE/Python files/TestTemplate.py
TestTemplate.py
py
349
python
en
code
2
github-code
36
22542096057
#!/usr/bin/env python # coding: utf-8 # In[ ]: #Answer no 1 n = int(input()) divBy7 = [i for i in range(0,n) if (i % 7 == 0)] print(divBy7) def divCheck(n): for i in range(n): if i % 7 == 0: value = True else: value = False print(i,value) divCheck(n) # ...
Gaurav262701/Assgnmnt-no-14
Assgnmnt_No14.py
Assgnmnt_No14.py
py
1,912
python
en
code
0
github-code
36
822226274
#!/usr/bin/env python # coding: utf-8 # import all packages from nilearn.connectome import ConnectivityMeasure from nilearn.input_data import NiftiLabelsMasker from load_confounds import Scrubbing from nilearn import datasets from os.path import join import nibabel as nib import numpy as np import shutil import os ...
PSY6983-2021/clandry_project
codes/data_prep.py
data_prep.py
py
2,355
python
en
code
0
github-code
36
7853730185
class Sorter: def bubblesort(self, array): l = len(array) i = l - 1 while i > 0: for j in range(i): print(array) if array[j] > array[j+1]: array[j], array[j+1] = array[j+1], array[j] i = i - 1 def quicks...
midasevil/Babel
Sorter.py
Sorter.py
py
1,068
python
en
code
0
github-code
36
2894241909
import sys from src.dialog.common.Dialog import Dialog from src.dialog.common.DialogContainer import DialogContainer from src.dialog.common.DialogFactory import DialogFactory from src.dialog.common.form_doc import FormDocContainer from src.dialog.common.manage_entity import ManageEntityContainer from src.dialog.common...
andreyzaytsev21/MasterDAPv2
src/dialog/common/table/TableContainer.py
TableContainer.py
py
2,644
python
en
code
0
github-code
36
25422749814
from util import get_history_identifier, get_user_identifier, calculate_num_tokens, calculate_num_tokens_by_prompt, say_ts, check_availability from typing import List, Dict class GPT_4_CommandExecutor(): """GPT-4を使って会話をするコマンドの実行クラス""" MAX_TOKEN_SIZE = 8192 # トークンの最大サイズ COMPLETION_MAX_TOKEN_SIZE = 2048 #...
sifue/chatgpt-slackbot
opt/gpt_4.py
gpt_4.py
py
4,222
python
ja
code
54
github-code
36
12423007297
class Carro: def __init__(self,request): self.request = request # Guardamos la peticion self.session = request.session # guardamos la sesion carro = self.session.get("carro") # igualamos la sesion del carro con la del usuario if not carro: # Si no hay carro en la sesion c...
Rojas-Andres/proyecto-web-django
carro/carro.py
carro.py
py
2,220
python
es
code
0
github-code
36
6395344004
import operator from intersection import Movement, Phase from agent import Agent class Demand_Agent(Agent): """ The class defining an agent which controls the traffic lights using the demand based approach always prioritizing the phase with the biggest demand """ def __init__(self, eng, ID=''): ...
mbkorecki/rl_traffic
src/demand_agent.py
demand_agent.py
py
912
python
en
code
1
github-code
36
13784383950
import pynmea2, serial, os, time, sys, glob, datetime def logfilename(): now = datetime.datetime.now() return 'datalog.nmea' #return '/home/pi/Desktop/PiCameraApp/Source/datalog.nmea' ''' return 'NMEA_%0.4d-%0.2d-%0.2d_%0.2d-%0.2d-%0.2d.nmea' % \ (now.year, now.month, now.day, ...
Keshavkant/RpiGeotaggedImages
GeoLogger.py
GeoLogger.py
py
2,636
python
en
code
0
github-code
36
35842604532
from django.urls import path from CafeStar import views app_name = 'CafeStar' urlpatterns = [ path('', views.homePage, name='home_page'), path('homePage', views.homePage, name='home_page'), path('drinkDetail', views.drinkDetail, name='drink_detail'), path('drinks', views.drinks, name='drinks'), pa...
zhengx-2000/CafeStar
CafeStar/urls.py
urls.py
py
843
python
en
code
1
github-code
36
39060336799
from obspy import read from numpy import genfromtxt,sin,cos,deg2rad,array,c_ from matplotlib import pyplot as plt n=read(u'/Users/dmelgar/kestrel/BRIC/BRIC.BK/BYN.00.D/BRIC.BK.BYN.00.D.2016.232') e=read(u'/Users/dmelgar/kestrel/BRIC/BRIC.BK/BYE.00.D/BRIC.BK.BYE.00.D.2016.232') z=read(u'/Users/dmelgar/kestrel/BRIC/BRIC...
Ogweno/mylife
kestrel/plot_data.py
plot_data.py
py
1,542
python
en
code
0
github-code
36
43891326692
from math import factorial n = float(input('Digite um número qualquer para ver seu fatorial: ')) print(factorial(n)) continua = str(input('Quer continuar? [S/N] ')).upper() while continua == 'S': n = float(input('Digite outro número: ')) print(factorial(n)) continua = str(input('Quer continuar? [S/N] ')).up...
Kaue-Romero/Python_Repository
Exercícios/exerc_60.py
exerc_60.py
py
457
python
pt
code
0
github-code
36
28891628391
"""Tests for traces.traces.""" import ast import collections import sys import textwrap from pytype import config from pytype.pytd import pytd from pytype.pytd import pytd_utils from pytype.tests import test_utils from pytype.tools.traces import traces import unittest _PYVER = sys.version_info[:2] _BINMOD_OP = "BINA...
google/pytype
pytype/tools/traces/traces_test.py
traces_test.py
py
11,794
python
en
code
4,405
github-code
36
19074906476
from collections import Iterator, Iterable #global set_num #set_num = 0 class Disjoint_set(Iterable): def __init__(self, element=None): self.head = element self.tail = element element.set = self #global set_num #set_num += 1 def add_element(self, element): ...
LouisYLWang/Algorithms
Clustering_algorithm/Disjoint_set.py
Disjoint_set.py
py
2,199
python
en
code
0
github-code
36
36740712303
# coding=UTF-8 # Importamos las librerías import sys import os import math import csv import numpy as np from itertools import groupby from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt from matplotlib import cm # Función que permite reiniciar el programa def reiniciar(): pyth...
DNC87/EM-Dataset-Generator
generador_datos/main.py
main.py
py
4,438
python
es
code
0
github-code
36
26486114880
# Following information from PEP 440 (https://peps.python.org/pep-0440/) __version__ = "2022.02.dev1" class TableParseError(Exception): """Excpetion when error hit while converting a *_table file to YAML""" def __init__(self, file, lineno, line, message=None): self.file = file self.lin...
NOAA-GFDL/fms_yaml_tools
fms_yaml_tools/__init__.py
__init__.py
py
614
python
en
code
0
github-code
36
9286381152
""" ## Max Value ## Write a function, max_value, that takes in list of numbers as an argument. The function should return the largest number in the list. Solve this without using any built-in list methods. You can assume that the list is non-empty. """ from time import time # Defining a decorato...
RuthraVed/programming-practice-solutions
structy-practice-solutions/01-max-value.py
01-max-value.py
py
1,393
python
en
code
0
github-code
36
74588531623
# coding=utf-8 __author__ = "Arnaud KOPP" __copyright__ = "© 2015-2016 KOPP Arnaud All Rights Reserved" __credits__ = ["KOPP Arnaud"] __license__ = "GNU GPL V3.0" __maintainer__ = "Arnaud KOPP" __email__ = "kopp.arnaud@gmail.com" __status__ = "Production" from collections import OrderedDict import logging import panda...
ArnaudKOPP/BioREST
BioREST/Fasta.py
Fasta.py
py
8,602
python
en
code
0
github-code
36
9048437267
fire_stations = ["Alpha", "Beta", "Theta", "Center", "Railway", "Harbor", "Suburb"] personnel = [12,13,23,44,23,11,42] fire_duty = [] station_on_duty = "" a = 0 i = 0 min = personnel[0] understaffed = "" input_device = "" for i in range(7): fire_duty.append(fire_stations[i]) for m in range(7): ...
Mierln/Computer-Science
Dylan/Fire_Station.py
Fire_Station.py
py
1,062
python
en
code
0
github-code
36
9786188527
import cv2 import numpy as np from scipy.ndimage.filters import gaussian_filter from scipy.ndimage.interpolation import map_coordinates def threshold_normalize(data,transform): threshold = 254 maxVal = 255 ret, thresh = cv2.threshold(np.uint8(data), threshold, maxVal, cv2.THRESH_BINARY) if transform: copy = th...
sheldon-benard/DigitClassification
551-project/preprocessing.py
preprocessing.py
py
1,107
python
en
code
0
github-code
36
35609489128
from math import sqrt import torch from torch import nn class FSRCNN(nn.Module): """ Args: upscale_factor (int): Image magnification factor. """ def __init__(self, upscale_factor: int) -> None: super(FSRCNN, self).__init__() # Feature extraction layer. self.feature_ex...
gmlwns2000/sharkshark-4k
src/upscale/model/fsrcnn/model.py
model.py
py
2,315
python
en
code
14
github-code
36
33844865336
import sys banned_words = ["os.sys","rmdir","subprocess","allowed_modules.csv","package.json","pyme.py","server.js","v.py","vx.py","clear.py","index.html","script.js","style.css","sleep","exec","eval"] def validate(s): flag=True for _ in banned_words: if(_ in s): print(_) flag=False if(flag): ...
SayadPervez/py-me
app/vx.py
vx.py
py
448
python
en
code
2
github-code
36
12201340474
def one(list, elem): low = 0 high = len(list) - 1 mid = (low + high) // 2 while elem != list[mid]: if elem not in list: return print('-1') elif elem > list[mid]: low = mid + 1 else: high = mid - 1 mid = (low + high) // 2 return prin...
Dary311/PythonLabs
laba 4.py
laba 4.py
py
3,731
python
en
code
0
github-code
36
73574130663
import torch import torch.nn as nn import torch.nn.functional as F from policy import discrete_policy_net from critic import attention_critic import numpy as np from buffer import replay_buffer from make_env import make_env import os import random from gym.spaces.discrete import Discrete from gym.spaces.box ...
deligentfool/MAAC_pytorch
model_mpe.py
model_mpe.py
py
12,313
python
en
code
0
github-code
36
40211358205
#%% [markdown] # ## Preliminaries #%% from pkg.utils import set_warnings set_warnings() import time import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from giskard.utils import get_random_seed from myst_nb import glue as default_glue from pkg.data import load_network_palette...
neurodata/bilateral-connectome
misc_scripts/perturbations_unmatched_deep_dive.py
perturbations_unmatched_deep_dive.py
py
6,901
python
en
code
5
github-code
36
34955294737
""" Multithreaded JSONRPCServer example addr = "http://localhost:8848" requests.post(addr, data='{"method": "get_data", "params":{"parser": "cpuinfo", "get": "model_name"}, "id":456}').json() curl -X POST http://localhost:8848 -d '{"method": "get_data", "id":"2", "params":{"path":"/proc/uptime"}}' reply {"jsonrpc": ...
niallobroin/slashproc_parsers
slashproc_parser/basic_server.py
basic_server.py
py
6,073
python
en
code
0
github-code
36
16528708499
from pywebio.input import * from pywebio.output import * from pywebio import start_server import matplotlib.pyplot as plt import numpy as np from PIL import Image import io def data_gen(num=100): """ Generates random samples for plotting """ a = np.random.normal(size=num) return a def plot_raw(a):...
tirthajyoti/PyWebIO
apps/matplotlib_demo.py
matplotlib_demo.py
py
1,955
python
en
code
9
github-code
36
26090415788
import pandas as pd import numpy as np import matplotlib.pyplot as plt from collections import defaultdict from basic.bupt_2017_11_28.type_deco import prt import joblib from sklearn import preprocessing from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from basic.bupt_2017...
Mr-cpc/idea_wirkspace
learnp/basic/bupt_2018_1_19/mxpoontheline.py
mxpoontheline.py
py
1,897
python
en
code
0
github-code
36
22568917957
from .workspace import get_workspace_location, get_workspace_state, resolve_this from .cache import Cache from .config import Config from .resolver import find_dependees from .ui import warning, fatal, show_conflicts from .cmd_git import has_package_path, get_head_branch from .util import iteritems, yaml_dump from pygi...
fkie/rosrepo
src/rosrepo/cmd_export.py
cmd_export.py
py
3,924
python
en
code
5
github-code
36