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
16480545674
from django.db.models.signals import post_save, post_delete from django.contrib.auth.models import User from django.template.loader import render_to_string from django.conf import settings from django.core.mail import send_mail from .models import Profile def create_profile(sender, instance, created, **kwargs): i...
finnsterfran/BuddyClubhouse-MS4
users/signals.py
signals.py
py
1,674
python
en
code
1
github-code
90
6661346274
from APIs.API import ItemAPI class RedisItemAPI(ItemAPI.ItemAPI): db = None orders = None market = None def __init__(self, db, orders, market): self.db = db self.orders = orders self.market = market def addItem(self, itemID, name, gameID, description, imageLink=None): ...
elikir/4300steam
APIs/RedisAPI/RedisItemAPI.py
RedisItemAPI.py
py
1,644
python
en
code
0
github-code
90
35645423775
# -*- coding: utf-8 -*- from weibopy import WeiboOauth2, WeiboClient import webbrowser client_key = '4255203274' # 你的 app key client_secret = '75589625cde7902ab73fab1df7844dfe' # 你的 app secret redirect_url = 'https://api.weibo.com/oauth2/default.html' auth = WeiboOauth2(client_key, client_secret, redirect_url) # 获取认...
zzm99/Simple-code-demo
pyciyun/weiboqinggan.py
weiboqinggan.py
py
1,811
python
zh
code
1
github-code
90
30236541243
import numpy as np import sys def process(pos012_file,gene_file,output_file): f1=open(pos012_file,'rt') f2=open(gene_file,'rt') f3=open(output_file,'wt') chr_pos = {} chrom="Gm00" pos=[] for line in f1.readlines(): l = line.split() if l[0]==chrom: pos.appen...
limeizhong/hard-soft-sweeps
gene.index.py
gene.index.py
py
1,030
python
en
code
0
github-code
90
6911475857
# coding = utf-8 # autuor = zhangchenzuo # date = 2020/05/16 # email = chenzuozhang@buaa.edu.cn """ EM算法实现,高斯混合模型 GMM(Gaussian mixed model) """ import numpy as np import random import time class EM(object): def __init__(self, data_train): self.samplenum = len(data_train) self.data = np.array(data...
zhangchenzuo/Statistical-Learning-Method-by-Python
EM/EM.py
EM.py
py
3,929
python
en
code
2
github-code
90
13455057028
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 27 21:28:04 2020 @author: jensen """ import cobra import model import base import gurobi as gp from gurobi import GRB import numpy as np import matplotlib.pyplot as plt ## ------------ loading iSMU model ------------ smu_cobra = cobra.io.read_s...
pauljensen/tigerpy
scripts/nn_dual.py
nn_dual.py
py
1,296
python
en
code
0
github-code
90
34120304145
import numpy as np from math import pi from os.path import join import matplotlib.pyplot as plt from src import EngProc, Config plt.style.use('elr') plt.ion() fc = 400 #fc = 1e3 source_depth = "shallow" load_dir = 'data/processed/' int_1000 = np.load(join(load_dir, 'int_eng_shallow_1000.npz')) def blocking_featur...
nedlrichards/tau_decomp
reports/jasa/ml_blocking_14.py
ml_blocking_14.py
py
3,382
python
en
code
0
github-code
90
897997069
import numpy as np import logging OUTPUT_LEVEL = 0 ''' L-BFGS-B wrapper ''' import scipy as sp def bfgs_solve(x_init, bounds, hessian, bo): res = sp.optimize.minimize(fun=bo.acquisition, x0=x_init, method='L-BFGS-B', jac=...
oxfordcontrol/Bayesian-Optimization
methods/solvers.py
solvers.py
py
6,580
python
en
code
44
github-code
90
33491925378
#!/usr/bin/env python # -*- encoding: utf-8 -*- # import lib import json from aliyunsdkcore.client import AcsClient from aliyunsdkdts.request.v20200101.DescribeSynchronizationJobsRequest import DescribeSynchronizationJobsRequest def dts_sync_info(credential, region) -> list: instances = [] page_size = 30 # ...
wsongl/aliyun-exporter
alicloud/dts_sync.py
dts_sync.py
py
1,235
python
en
code
0
github-code
90
18201228469
N, K = map(int, input().split()) As = list(map(int, input().split())) for i in range(K): #imos法(メモ) table = [0 for _ in range(N+1)] #数値がN個なのでN個の0の要素を作る #index0は空白、index1からx軸のランプがある位置に対応 #1-Nまでのランプが格納されている for j in range(1,N+1): ai = As[j-1] #電球jが照らす左端をメモ #電球jが照らす左端はj-ai...
Aasthaengg/IBMdataset
Python_codes/p02647/s723346503.py
s723346503.py
py
1,248
python
ja
code
0
github-code
90
13117534579
"""This file contains my solutions to Leetcode problem 34: Find First and Last Position of Element in Sorted Array. """ # Binary Search Solution Recursive # time comeplxity: O(log n), where 'n' is the length of nums # space complexity: O(log n) class Solution: FIRST = 0 LAST = 1 def searchRange...
EricMontague/Leetcode-Solutions
medium/problem_34_find_first_and_last_position_of_element_in_sorted_array.py
problem_34_find_first_and_last_position_of_element_in_sorted_array.py
py
2,804
python
en
code
0
github-code
90
39577289180
''' ------------------------------------------------------------- Code By : Sairaj Bhise Topic : Data Structures and Algorithms (Tree Data Structure) ------------------------------------------------------------- ''' class Node: def __init__(self, item): self.item = item self.left = None self.right = None #...
sairajbhise98/Python-Study
Data Structures in Python/Trees/full_binary.py
full_binary.py
py
917
python
en
code
0
github-code
90
29864777793
import pyspeckit import itertools from astropy import wcs import pylab as pl import numpy as np from FITS_tools import strip_headers do_some_plots=True np.seterr(all='ignore') datapath = '/Users/adam/work/h2co/maps/W51/' figpath = '/Users/adam/work/h2co/figures/' def spectral_grid(cube11=pyspeckit.Cube(datapath+'W51_...
keflavich/w51_singledish_h2co_maps
plot_scripts/specgrid.py
specgrid.py
py
3,515
python
en
code
0
github-code
90
40360151731
class Solution(object): def findContentChildren(self, g, s): g.sort() s.sort() minlen = min(len(g), len(s)) cnt = 0 coockiesidx = 0 for i, v in enumerate(g): # print(v, ) if coockiesidx >= len(s): break if i == minle...
seoseokbeom/leetcode
455AssignCocies.py
455AssignCocies.py
py
664
python
en
code
1
github-code
90
25572379914
from concurrent import futures from typing import Any, Tuple import gevent import grpc from src.proto.grpc.testing import messages_pb2 from src.proto.grpc.testing import test_pb2_grpc LONG_UNARY_CALL_WITH_SLEEP_VALUE = 1 class TestServiceServicer(test_pb2_grpc.TestServiceServicer): def UnaryCall(self, request,...
grpc/grpc
src/python/grpcio_tests/tests_gevent/unit/_test_server.py
_test_server.py
py
1,583
python
en
code
39,468
github-code
90
18333646409
s = input() k = int(input()) l = len(s) cnt = 0 cnt_list = [0] for i in range(l-1):#sの中での連続数 if s[i] == s[i+1]: cnt += 1 cnt_list.append(cnt) else: cnt = 0 cnt_list.append(cnt) #print(cnt_list) for i in range(l-1):#sの末尾と最初がつながっているとき if s[-1] == s[i]: cnt += 1 ...
Aasthaengg/IBMdataset
Python_codes/p02891/s864413298.py
s864413298.py
py
1,281
python
en
code
0
github-code
90
21735850811
class Cat: def __init__(self,new_name): # 加了一个new_name形参 print("这是一个初始化方法") self.name = new_name # self.属性名 = 属性的初始值 ;所有的对象都默认拥有这个属性 def eat(self): print("%s 爱吃鱼" % self.name) # 使用类名()创建对象的时候,会自动调用初始化方法_init_ tom = Cat("Tom") # 在创建对象时,使用类名(属性1,属性2...)调用 ;属性为实参 print(tom.name) ...
niushufeng/Python_202006
算法代码/面向对象/初始化/初始化方法及在初始化的同时设置初始值.py
初始化方法及在初始化的同时设置初始值.py
py
556
python
zh
code
3
github-code
90
11002559663
# ============================================ # =============== 发布/订阅模式 =============== # ============================================ from PySide2.QtCore import QObject, Slot, Signal, QMutex, QThread, QCoreApplication # 发布/订阅 服务类 class __PubSubServiceClass: def __init__(self): # 事件字典,元素为 回调函数列表 ...
hiroi-sora/Umi-OCR_v2
UmiOCR-data/py_src/event_bus/pubsub_service.py
pubsub_service.py
py
3,669
python
zh
code
917
github-code
90
32619805924
from __future__ import annotations from typing import List, Dict, Union from abc import ABC, abstractmethod import datetime from ..metadata import Metadata from ..file import File from ..diff import Diff class Dataset(ABC): """ Attributes: _metadata (Metadata): Metadata _files (list): Files lis...
ITC-CRIB/fairly
src/fairly/dataset/__init__.py
__init__.py
py
6,449
python
en
code
19
github-code
90
18333250900
import pygame import csv from pygame.sprite import Sprite class World(Sprite): """This class handles the game world.""" def __init__(self, game): super().__init__() self.screen = game.screen self.settings = game.settings self.display = game.display self.block_size ...
mmartin46/Pixel2PGame
open_world.py
open_world.py
py
1,268
python
en
code
0
github-code
90
8082005296
"""Various helper functions to create embeds from data.""" from disnake import Embed from . import rules def create_rule_embed(rule: rules.Rule) -> Embed: """Create an embed for a rule for the get rule command. Args: rule: The rule. Returns: The embed. """ return Embed( ...
interrrp/rulebot
bot/embeds.py
embeds.py
py
782
python
en
code
0
github-code
90
39144823187
import re class Operation(object): @staticmethod def Sum(numbers): sum = 0 for number in numbers: sum += float(number) return sum def getting(msg): return "Hello: " + msg.capitalize() msg = Operation.getting("world") print(msg) numbers = re.split(', | ', "1 ...
wargerun/PyTutorial
GetStarted/HelloWorld.py
HelloWorld.py
py
380
python
it
code
0
github-code
90
26718685759
#https://pl.spoj.com/problems/PP0601B/ t=int(input()) for i in range(t): n, x, y = map(int, input().split()) for liczba in range(x,n,x): if(liczba%y != 0): print(liczba, end=" ") print("")
Mrozinski/SPOJ
pp0601b_podzielnosc/PP0601B.py
PP0601B.py
py
217
python
pl
code
1
github-code
90
28634019405
# apps/social_media/urls.py from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views from views import MyAlbumListView, ViewPostDetailView, MyAccountListView app_name = 'social_media' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^myAccount/$',...
KyleSeem/social_cats
apps/social_media/urls.py
urls.py
py
1,688
python
en
code
0
github-code
90
2208382070
from sklearn import svm, metrics from sklearn.externals import joblib from pathlib import Path def readCsv(file, maxcnt): labels = [] images = [] with open(file, "r") as f: for i, line in enumerate(f): if i >= maxcnt: break cols = line.split(",") ...
pidokige02/Python_study
hello-master/mytests/ml5.py
ml5.py
py
1,107
python
en
code
1
github-code
90
17249605998
""" Text-based Minesweeper for the Terminal Made in Python 3 By PseudoMon Version 1.0 """ from random import shuffle def mapping_letters(letters): marks = {} num = 0 for letter in letters: marks[letter] = num num += 1 return marks def newgame(s=9, numbomb=10): print("...
PseudoMon/pysweeper
main.py
main.py
py
6,036
python
en
code
0
github-code
90
21790855852
''' This file defines the architecture for the neural network model. ''' import tensorflow as tf from layers import * image_h = 28 image_w = 28 image_ch = 1 output_cls = 10 # Input Layer: with tf.name_scope('Input'): x = tf.placeholder(tf.float32, shape=[None, image_h, image_w, image_ch]) y_ = tf.placeholder(...
Kaiwenkevinz/hand-written-digit
model.py
model.py
py
1,129
python
en
code
2
github-code
90
41686458997
from graph_old import Network from edmondskarp import edmonds_karp def network_from_bipartite(X, Y, E): net = Network() net.vertices = X | Y | {0, -1} net.source = 0 net.sink = -1 net.edges = E | {(0, x) for x in X} | {(y, -1) for y in Y} net.capacity = {e: 1 for e in net.edges} return net ...
alexdoty/p1-5_219-algoritmer
modules/bipartite.py
bipartite.py
py
476
python
en
code
0
github-code
90
23713194491
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] print(alphabet.index("a")) def alphabet_position(text): #making sure it's all in lower case text = text.lower() numbers = [] for char in text: #try an...
MohammedNagdy/Logic-Problems
Replace_with_alphabet_position.py
Replace_with_alphabet_position.py
py
613
python
en
code
0
github-code
90
39474525722
# First index def recursion(a,e,i): length=len(a) if(i < length): if (a[i] == e): return i else: return recursion(a,e,i+1) else: return "Not Found" if __name__ == "__main__": element=int(input()) array=list(map(int,input().split())) print(recurs...
Kshitij3003/Python
Recursion/01.py
01.py
py
341
python
en
code
0
github-code
90
72024542056
"""Тестирование сборки базы локаций""" from __future__ import annotations import pathlib import unittest from processing import Location, LocationsBuilder, LOCATION_TYPES class TestLocation(unittest.TestCase): """Тестирование локаций""" def test_location_type(self): """Выбрасывается исключение на со...
lastick1/rexpert
tests/unit/test_locations_builder.py
test_locations_builder.py
py
5,308
python
en
code
1
github-code
90
18419239519
N=int(input()) H=list(map(int,input().split())) MAX=H[0] count=1 for i in range(1,N): if H[i]>=MAX: count += 1 MAX = H[i] print(count)
Aasthaengg/IBMdataset
Python_codes/p03072/s913903262.py
s913903262.py
py
145
python
en
code
0
github-code
90
27105235991
fname = input('Enter file: ') if len(fname) < 1 : fname = 'mbox-short.txt' hand = open(fname) dic = dict() for line in hand: if not line.startswith('From'): continue if line.startswith('From:'): words = line.split() sender = words[1] dic[sender] = dic.get(sender,0) + 1 bigc...
kapowski/PY4E-Exercises
py4e_exercises_9_4.py
py4e_exercises_9_4.py
py
508
python
en
code
0
github-code
90
18589113019
n = input() nums = [int(i) for i in input().split(" ")] def is_even(num_list): for num in num_list: if num % 2 != 0: return False return True counter = 0 while(is_even(nums)): counter += 1 nums = [n/2 for n in nums] print(counter)
Aasthaengg/IBMdataset
Python_codes/p03494/s456112701.py
s456112701.py
py
251
python
en
code
0
github-code
90
24869894404
class APOG1121: def __init__(self, master): self.fdict= master.csv self.master= master self.load("11/ A-Pog","21/ A-Pog","11/ A-Pog mm","21/ A-Pog mm","APOG11","APOG21","APOG11MM","APOG21MM","APOG1121") def load(self, fator1, fator2, fator3, fator4, name1, name2, name3, name4, relacao): try: self.master.f...
gstechcode/ProtoLab
Models/Cores/Compass/Functions/APOG1121.py
APOG1121.py
py
711
python
en
code
0
github-code
90
40655368477
import logging import os import sqlalchemy import unittest from studi import app from studi import sqlalchemy_orm, upload, util, custom_error def gen_logger(test_name): logger = logging.getLogger(test_name) logger.setLevel(logging.DEBUG) logger_handler = logging.FileHandler(os.path.join(app.config['TEST_...
GTedHa/studi
tests/test_insert.py
test_insert.py
py
5,482
python
en
code
0
github-code
90
34869226895
import os import folium import time # import sys # from geodata import * # from folium.features import DivIcon # import webbrowser import pygeoj as pgj from geographiclib.geodesic import Geodesic from shapely.geometry import Point, Polygon import numpy as np # from pyroutelib3 import Router from osrm_routes import osr...
deck34/map_prestige_territory
map.py
map.py
py
10,824
python
en
code
0
github-code
90
20200406876
# coding = utf-8 from scapy.all import * import matplotlib.pyplot as plt path = "Exp2pcap.pcapng" pcapfile = rdpcap(path) p1 = False p2 = False p3 = False t_dst = ['218.75.123.181', '218.75.123.182'] for i in range(0,len(pcapfile)): if (str(pcapfile[i][IP].dst) == t_dst[1] and str(pcapfile[i][TCP].flags) == ...
iCyris/NPEC
Exp2/Exp2.py
Exp2.py
py
2,428
python
en
code
0
github-code
90
34072701823
import pdb import time from model import Graph2Gauss from utils import load_dataset, score_node_classification from preprocessor import preprocessor # g = load_dataset('data/cora_ml.npz') g = preprocessor(domain="computers") A, X, z = g['A'], g['X'], g['z'] for i in range(5): print("##############" + str(i) + "##...
Xiaoshunxin/GNN-Survey
G2G-tensorflow/train.py
train.py
py
950
python
en
code
8
github-code
90
43602766654
"""Unit tests for the CANLayer class.""" import pytest import torch from topomodelx.nn.cell.can_layer_bis import CANLayer class TestCANLayer: """Unit tests for the CANLayer class.""" def setup_method(self): """Set up the CAN for tests.""" self.n_1_cells = 30 self.channels = 10 ...
LFesser97/simplicial_complex_neural_networks
test/nn/cell/test_can_layer_bis.py
test_can_layer_bis.py
py
2,356
python
en
code
1
github-code
90
18360995639
n= int(input()) if n==1: print('Yes') exit() h=list(map(int,input().split())) ans='Yes' for i in range(n-1): if h[i+1]>h[i]: h[i+1]-=1 elif h[i+1]<h[i]: print('No') exit() print(ans)
Aasthaengg/IBMdataset
Python_codes/p02953/s763548232.py
s763548232.py
py
202
python
en
code
0
github-code
90
75108474855
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import random import threading import time def get_bbox(posecnn_rois,border_list,img_width,img_length,idx): rmin = int(posecnn_rois[idx][3]) + 1 rmax = int(posecnn_rois[idx][5]) - 1 cmin = int(posecnn_rois[idx][2]) +...
yiwc/OdysseyAlpha
DenseFusion/tools/YWTools.py
YWTools.py
py
4,301
python
en
code
6
github-code
90
36600368328
import pandas as pd df = pd.read_excel('score.xlsx',index_col='지원번호') print(df) # print(df['지원번호']) #index설정 되어 있으면 columns 검색 ### row추가 df.loc['9번'] = ['이순신','디지털고',200,100,100,70,90,80,'java'] print(df) # 1명row값 변경 # df.loc['4번','SW특기'] = 'python' ### 4번,5번 2명 학생 값 변경 # df.loc[['4번','5번'],'SW특기'] = 'python' ### 1...
onulee/https---github.com-onulee-kdigital1
06.pandas/d0502/d0502_06_컬럼순서변경.py
d0502_06_컬럼순서변경.py
py
1,389
python
ko
code
0
github-code
90
70489503978
import os,sys import csv name = 'to_do.txt' if not os.path.exists(name): open(name, 'w').close() todo_dict = {} note1 = 'Hi' note2 = 'Hell' notes = [note1,note2] for i in range(len(notes)): todo_dict[i] = notes[i] with open(name, 'w') as wf: for key in todo_dict: wf.write('{0:d},{1:s}'.format(...
blaufer/Note-Taking
other/csv_dict.py
csv_dict.py
py
500
python
en
code
0
github-code
90
18463428149
import math,sys,bisect,heapq from collections import defaultdict,Counter,deque from itertools import groupby,accumulate #sys.setrecursionlimit(200000000) input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ ilele = lambda: map(int,input().split()) alele = lambda: list(map(int, input().split())) def list...
Aasthaengg/IBMdataset
Python_codes/p03165/s722921137.py
s722921137.py
py
1,345
python
en
code
0
github-code
90
3424730130
# text='''将110kV孟平线线路由检修转为运行 # 核对相关设备运行方式。 # 合上16P 110kV孟平线保护屏110kV孟平线1551开关控制电源1DK2。 # 取下110kV孟平线线路侧15514刀闸操作把手上的“禁止合闸,线路有人工作”标示牌。 # 投上110kV孟平线线路抽取电压5ZK。 # 拉开110kV孟平线线路侧155140接地刀闸。 # 检查110kV孟平线线路侧155140接地刀闸三相确在拉开位置。 # 汇报调度。 # 再经调度令。 # 检查110kV孟平线1551开关确在分闸位置。 # 在110kV孟平线2M侧15512刀闸机构箱: # 合上刀闸控制电源QF2空气开关。 # 合上刀闸电机电源QF3空气...
transformeris/elastic_net_fin
操作票分析.py
操作票分析.py
py
5,076
python
zh
code
3
github-code
90
26961382855
from django.test import TestCase from .models import Book, Review class BookReviewModelTest(TestCase): @classmethod def setUpTestData(cls): cls.book = Book.objects.create( title = 'Ein Titel', author = 'Mr X' ) cls.review = Review.objects.create( ...
kismX/portfolio
23-11-02_book_review_API/reviews/tests.py
tests.py
py
917
python
en
code
0
github-code
90
18616513358
import os import os.path as osp from glob import glob from tqdm import tqdm def get_folder_list(root_dir): folder_list = [entry.path for entry in os.scandir(root_dir) if entry.is_dir()] folder_list = sorted(folder_list) return folder_list data_root = "/home/haimingzhang/Research/Programming/cv-fighter/H...
Zahidsqldba07/programming-learning-examples
Python_learning/filesystem_utils/stat_bad_data.py
stat_bad_data.py
py
868
python
en
code
null
github-code
90
12724872668
from tkinter import * from tkinter.ttk import * import math import sys def my_frame(master): w = Frame(master) w.pack(side=TOP, expand=YES, fill=BOTH) return w def exit(): sys.exit() return exit def my_button(master, text, command): w = Button(master, text=text, command=command, width=6) ...
LwEminent/project
Calc.py
Calc.py
py
4,892
python
en
code
0
github-code
90
18568617909
# APC001C - Vacant Seat def main(): # if no vacant seat in [0, i) # -> seat[0] == seat[i] if i % 2 else seat[0] != seat[i] N = int(input()) print(0, flush=1) seat_zero = input().rstrip() if seat_zero == "Vacant": return left, right = 0, N for _ in range(19): mid = (left +...
Aasthaengg/IBMdataset
Python_codes/p03439/s007198660.py
s007198660.py
py
599
python
en
code
0
github-code
90
22687841726
#!/usr/bin/env python # -*- coding:utf-8 -*- # author:wpaifang # datetime:2019/7/15 9:36 # software: PyCharm # function: import urllib import requests import re import json from bs4 import BeautifulSoup as bs book = ['/wordbook/106306/', '/wordbook/106300/', '/wordbook/106312/', '/wordbook/106330/', '/wordboo...
wangshuai20170831/autoCreateTopic
English/Spider_word.py
Spider_word.py
py
3,451
python
en
code
0
github-code
90
18045867519
from sys import exit S = input() #0回判定 x = len(S) if S.count("B") == x or S.count("W") == x: print(0) exit() cntw=0 for s in S.split("W"): if s: cntw += 1 cntb=0 for s in S.split("B"): if s: cntb += 1 print(abs(cntb - cntw) + min(cntb, cntw) * 2 - 1)
Aasthaengg/IBMdataset
Python_codes/p03945/s421796572.py
s421796572.py
py
291
python
en
code
0
github-code
90
2179448511
from collections import Counter class Solution: def longestPalindrome(self, s: str) -> int: cnt = Counter(s) has_odd = False twos = 0 for i in cnt: if cnt[i] % 2: has_odd = True if cnt[i] >= 2: twos += int(cnt[i] / 2) ...
wlyu1208/Leet-Code
0409-longest-palindrome/0409-longest-palindrome.py
0409-longest-palindrome.py
py
360
python
en
code
1
github-code
90
22031637672
from dolfin import * from rbnics import * from rbnics.backends import export, import_ from problems import * from reduction_methods import * class GeostrophicOptimalControl(GeostrophicOptimalControlProblem): def __init__(self, W, **kwargs): GeostrophicOptimalControlProblem.__init__(self, W, **kwargs) ...
RBniCS/RBniCS
tutorials/15_quasi_geostrophic_optimal_control/tutorial_quasi_geostrophic_optimal_control.py
tutorial_quasi_geostrophic_optimal_control.py
py
8,969
python
en
code
83
github-code
90
25863222564
def spectrum_plot(out_filename, input_file, extensions, locations, location_unit='pixel', center_wavelength=-1, velocity=0, fit_file=None, edge_buffer=None, out_file_type='png', units=None, **kwargs): """ Plots the spectra and uncertainty range for any amount of given pix...
kjdoore/spec_map_analysis
spec_map_analysis/plots/spectrum_plot.py
spectrum_plot.py
py
10,502
python
en
code
1
github-code
90
23640863001
from django import forms from utils.api.client import MarketAccessAPIClient class FeedbackForm(forms.Form): satisfaction = forms.ChoiceField( label="Overall, how would you rate your experience with Digital Market Access Service (DMAS) today?", choices=( ("VERY_SATISFIED", "Very satisf...
uktrade/market-access-python-frontend
barriers/forms/feedback.py
feedback.py
py
4,497
python
en
code
5
github-code
90
70298346217
import argparse import os import asyncio import sys import logging import json import pprint from asyncio.streams import StreamWriter, FlowControlMixin from aioraft.client import Client from aioraft import settings log = logging.getLogger('aioraft.cli') client, reader, writer = None, None, None @asyncio.coroutine...
lisael/aioraft
aioraft/cli.py
cli.py
py
2,892
python
en
code
29
github-code
90
17245503745
import sys import os sys.path.append(os.getcwd()) import tools.io_utils as io import dgl import torch as th from tqdm import tqdm from dgl.data.utils import load_graphs as lg import numpy as np import json import random import scipy def normalize(field, field_name, statistics, norm_dict_label): """ Normalize f...
StanfordCBCL/gROM
graph1d/generate_normalized_graphs.py
generate_normalized_graphs.py
py
19,051
python
en
code
15
github-code
90
28576380777
from lddecode.core import ( RFParams_PAL, RFParams_NTSC, SysParams_PAL, SysParams_NTSC, ) # Default thresholds for rf dropout detection. DEFAULT_THRESHOLD_P_DDD = 0.18 DEFAULT_THRESHOLD_P_CXADC = 0.35 DEFAULT_HYSTERESIS = 1.25 # Merge dropouts if they there is less than this number of samples between t...
cmeh/vhs-decode
vhsdecode/formats.py
formats.py
py
4,837
python
en
code
null
github-code
90
3122984768
def fadeOut(cycle,period,incrementer): for i in range(1, 100): while True: if(period * cycle < 0): break GPIO.output(led, True) time.sleep(period * cycle) GPIO.output(led, False) time.sleep(period-(period*cycle)) cycle =...
ohrainier/raspberry-pi-iot
ExerciseLedEdge.py
ExerciseLedEdge.py
py
1,131
python
en
code
1
github-code
90
30768647540
# -*- coding: utf-8 -*- import unicodedata import re import random from itertools import product from collections import defaultdict def _TLD_list(): TLDs = [] with open("data/TLDs.txt", "r") as f: for line in f.readlines(): TLDs.append(line.strip()) return TLDs def _unicode_list(): ...
h13t0ry/UnicodeToy
toy.py
toy.py
py
3,359
python
en
code
40
github-code
90
73552242858
import os.path from fabric import task CONFIG = { 'deploy': { 'base_dir': "/var/www/asselect.uk", 'var_dir': "/var/ukair", 'service': "ukair_wsgi.service", 'site': "asselect.uk" }, 'staging': { 'base_dir': "/var/www/staging.asselect.uk", 'var_dir': "/var/uka...
ahsparrow/ukair
fabfile.py
fabfile.py
py
2,876
python
en
code
0
github-code
90
38933004590
#!/usr/bin/env python ''' Author: djs Date: 2012-07-02 Description: Quick analysis of historical market data using Markov chains. Interesting to note after analyzing several stocks going back 10 years the statistics in the Markov chain for a given stock show the likelihood of moving up or down in price based on the pr...
danshea/python
MarkovChains/Kreskin.py
Kreskin.py
py
2,387
python
en
code
2
github-code
90
6063665865
#!/usr/bin/env python # -*- coding: utf-8 -*- #@Author : Aixiu import os # 和操作系统相关的模块 import time # 和时间相关的模块 import pathlib # 案例文本原始内容 '''第一行 第二行 第三行 第四行 猜猜这是第几行? 猜猜这是第几行? 张观博 张欣竹 张欣阳 张刚军 李扬阳 李靖阳 李熙阳''' # 文件修改 把文件中的 李 -> 汪 with open("./test.txt", mode="r", encoding="utf-8") as f...
aixiu/PythonABC
python文件修改经典案例.py
python文件修改经典案例.py
py
1,163
python
zh
code
0
github-code
90
10759270682
import json import traceback import requests as requests class Relatorios: baseApi = " " api = None _token = '' def __init__(self, chaves, registros): self.lista = [] self.getToken() self._chaves = chaves self._registros = registros def run(self): for cha...
diogordmiranda/APItoTXT
api/desk/relatorios.py
relatorios.py
py
2,194
python
en
code
0
github-code
90
69799497576
#!/usr/bin/python3 import sys def print_stats(total_file_size, status_codes): """ Function to print the current statistics """ print("File size: {}".format(total_file_size)) for status_code in sorted(status_codes.keys()): if status_codes[status_code] > 0: print("{}: {}".format(s...
lucadavid075/alx-interview
0x03-log_parsing/0-stats.py
0-stats.py
py
1,326
python
en
code
0
github-code
90
35725182275
from pyspark.context import SparkContext from pyspark import SparkConf from pyspark.sql import SQLContext from pyspark.sql.session import SparkSession from pyspark.streaming import StreamingContext from utils import process from mqtt import MQTTUtils import json # configure environment sc = SparkContext.getOrCreate() ...
hoangviet148/Foody
app/load_pretrained.py
load_pretrained.py
py
2,439
python
en
code
0
github-code
90
73214222058
import pandas as pd import statsmodels.api as sm from statsmodels.iolib.summary2 import * def factor_tests(fac_port, anom_ret, anom_shocks, factor_port_list): num_of_fac = len(factor_port_list) fac_port_copy = fac_port.copy() fac_port_copy['no_of_port'] =...
youjing18/iv-anomaly-decomposition
factor_tests.py
factor_tests.py
py
6,994
python
en
code
0
github-code
90
5705024380
class Solution(object): def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ Total_len = len(candies) s = set(candies) Distribute_len = len(s) if Distribute_len<=Total_len/2: return Distribute_len else:...
lll109512/LeetCode
Hash/Distribute Candies.py
Distribute Candies.py
py
352
python
en
code
0
github-code
90
21815243387
import tkinter as tk import webbrowser from tkinter import BooleanVar, ttk from typing import Any from subsearch.data import __version__ from subsearch.data.constants import DEVICE_INFO, FILE_PATHS from subsearch.gui.resources import config as cfg from subsearch.utils import decorators, io_toml, io_winreg, update cl...
vagabondHustler/subsearch
src/subsearch/gui/screens/subsearch_options.py
subsearch_options.py
py
9,664
python
en
code
27
github-code
90
7165688920
import pandas as pd import numpy as np import imblearn import random from collections import Counter import maldi_learn.utilities as ml_utilities import maldi_learn.driams as ml_driams import maldi_learn.filters as ml_filters import sys del sys.modules['const'] import const from sklearn.cluster import KMeans import...
irmlerjo/maldi-prediction
utils.py
utils.py
py
42,782
python
en
code
0
github-code
90
24158448592
''' 2023-09-20 201795016 김명규 선택문 if else 교통 카드의 종류로 '청소년', '성인' 카드가 있다고 하자 사용자에게 카드의 종류를 입력받아 청소년이면 청소년입니다 성인이면 성인입니다 출력하기 ''' # 선언 및 초기화 inputStr = input('카드의 종류를 입력하세요(청소년 or 성인) >> ') # 연산 및 출력 if inputStr != "청소년" and inputStr != "성인" : print("둘중에 하나를 입력하셔야 합니다.") else ...
kuma2156/Python
ch4/04_ifelse3.py
04_ifelse3.py
py
581
python
ko
code
0
github-code
90
19657500162
#!/usr/bin/env python3 from rest_framework import serializers from .models import Book, Chapter, Character, Narrator, Point class PointSerializer(serializers.ModelSerializer): class Meta: model = Point fields = ( "narrator", "x", "y", "type" ...
spaceqorgi/waygate
waygate/map/serializers.py
serializers.py
py
1,427
python
en
code
1
github-code
90
39170518219
import cv2 import torch import argparse import sys import os sys.path.append('.') from fastreid.modeling.meta_arch import build_model from fastreid.config import get_cfg from fastreid.utils.checkpoint import Checkpointer from fastreid.utils.logger import setup_logger setup_logger(name="fastreid") def setup_cfg(args):...
scott01272001/fastReid-2-torchscript
fast-reid/torchscript_tools/pth_to_torchscript.py
pth_to_torchscript.py
py
2,487
python
en
code
0
github-code
90
1304991303
from urllib.parse import urlparse import praw import prawcore.exceptions from bs4 import BeautifulSoup from ..keys import getID, getSecret, getAgent from .User import User from .Utils import scrub_text, SubmissionType, TimeFrame, remove_stopwords, rank_items, ignore_website class Subreddit: # Set up connection ...
chuckgreenman/senior-design
src/reddit_live_api/Subreddit.py
Subreddit.py
py
11,792
python
en
code
0
github-code
90
18574761783
import time import matplotlib.pyplot as plt import numpy as np import torch as th # from tpp.processes.hawkes.r_terms import get_r_terms as naive from tpp.processes.hawkes.r_terms_recursive import get_r_terms as recursive from tpp.processes.hawkes.r_terms_recursive_v import get_r_terms as recursive_v from tpp.utils.te...
babylonhealth/neuralTPPs
profiling/get_r_terms_profile.py
get_r_terms_profile.py
py
2,568
python
en
code
24
github-code
90
12503041741
import os from aiogram import types import aiogram.utils.markdown as aimd import logging from config import dp, bot, QR, TARGET_DIR, DB_FILE from answers import kb_start, help_mssg, info_mssg, error_mssg from sq_statement import select_users, write_user @dp.message_handler(commands=['start']) async def ...
DVolodyslavD/QR-coder_bot
bot.py
bot.py
py
2,110
python
en
code
4
github-code
90
39239064801
from django.urls import path, include from drf_yasg import openapi from drf_yasg.views import get_schema_view from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView schema_view = get_schema_view( openapi.Info( title="SimpleInventory API", default_version='v1', desc...
Nojipiz/SimpleInventory
backend/backend/urls.py
urls.py
py
719
python
en
code
0
github-code
90
24999783743
"""empty message Revision ID: 3c2b157c96db Revises: Create Date: 2021-04-24 22:46:35.272467 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '3c2b157c96db' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto gene...
ivandeveloper506/Code-StarWars-RESTAPI-With-Python-Flask
migrations/versions/3c2b157c96db_.py
3c2b157c96db_.py
py
6,292
python
en
code
0
github-code
90
18578353019
N, Y= map(int, input().split()) Y //= 1000 for x in range(N + 1): for y in range(N-x+1): z = N - (x + y) yen = x * 10 + y * 5 + z if Y == yen: print(x, y, z) exit() print(-1, -1, -1)
Aasthaengg/IBMdataset
Python_codes/p03471/s092789971.py
s092789971.py
py
237
python
en
code
0
github-code
90
27093386538
from spack import * class Portage(CMakePackage): """Portage is a framework that computational physics applications can use to build a highly customized, hybrid parallel (MPI+X) conservative remapping library for transfer of field data between meshes. """ homepage = "http://portage.lanl.gov/"...
matzke1/spack
var/spack/repos/builtin/packages/portage/package.py
package.py
py
1,236
python
en
code
2
github-code
90
18697197133
import pygame import numpy as np from scipy import stats # Define some colors BACKGROUND = (107,142,35) BOXCOLOR = (189,183,107) NUM_START=15 VIOLET = (138,43,226) TOMATO = (255,99,71) SEAGREEN = (50,205,50) PINK = (219,112,147) YELLOW=(255,255,0) CYAN = (0,255,255) colors = [SEAGREEN,CYAN,VIOLET,PINK,YELLOW,TOMATO] NU...
YimRegister/RandomScience
lilbox.py
lilbox.py
py
6,689
python
en
code
0
github-code
90
18565537859
cs = [list(map(int,input().split()))for _ in range(3)] for i in range(2): yoko = abs(cs[0][i] - cs[0][i + 1]) for j in range(1,3): if yoko - abs(cs[j][i] - cs[j][i + 1]) != 0: print('No') exit() for i in range(2): tate = abs(cs[0+i][0] - cs[1+i][0]) for j in range(1,3): ...
Aasthaengg/IBMdataset
Python_codes/p03435/s235744965.py
s235744965.py
py
426
python
en
code
0
github-code
90
2026809915
import FreeCAD import FreeCADGui from FreeCAD import Base from PySide import QtCore, QtGui import numpy as np import Mesh import os class CreateSurface: """ Command to create a new surface """ def __init__(self): self.Path = os.path.dirname(__file__) self.resources = { '...
GitHub-XK/FreeCAD-Geomatics-Workbench
Surfaces/CreateSurface.py
CreateSurface.py
py
5,048
python
en
code
0
github-code
90
12626851682
import typing import jwt from starlette.authentication import ( AuthCredentials, AuthenticationBackend, AuthenticationError, BaseUser, ) from starlette.requests import Request from collages.constants import AUTH_HEADER_SCHEME, AUTH_COOKIE_NAME from collages.errors import EntityDoesNotExistError from c...
dyachoksa/collage-generator
backend/collages/http/security.py
security.py
py
2,057
python
en
code
0
github-code
90
30554246315
# run.py import json, os, flask from flask import jsonify from trip.forms import TripForm from trip.location import Location from trip.trip_calculator.trip_calculator import calculateTrip, getRemainingTankLevel, getCostOfTrip from trip.trip_calculator.database.filters import GasStationBrandMultipleFilter, GasStationBra...
WSJ-2018SE-CPP/gasme
app.py
app.py
py
7,822
python
en
code
1
github-code
90
23829682251
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import telepot from telepot.delegate import per_chat_id, create_open import threading import time import datetime from random import randint from ChatData import ChatData, ScheduleTime days = ['lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado', 'dom...
MatiasDwek/llegando_los_bot
llegando_los_bot.py
llegando_los_bot.py
py
5,005
python
en
code
0
github-code
90
38811655926
import random import torch from tensorboardX import SummaryWriter from plotting_utils import plot_alignment_to_numpy, plot_spectrogram_to_numpy from plotting_utils import plot_gate_outputs_to_numpy #BL :added form live audio from hparams import create_hparams from layers import TacotronSTFT, STFT from audio_processing...
Mathematicator/Fr-Tacotoron
logger.py
logger.py
py
4,698
python
en
code
1
github-code
90
41978267429
import ctypes import pytest c_lib = ctypes.CDLL('../solutions/0977-sorted-squares/sorted-squares.so') @pytest.mark.skip(reason="how to check C allocated array?") def test_sorted_squares(): array = [-4,-1,0,3,10] arr = (ctypes.c_int * len(array))(*array) # out = (ctypes.c_int * len(array))(*array) arr_...
msztylko/2020ify-leetcoding
tests/test_0977.py
test_0977.py
py
463
python
en
code
0
github-code
90
11698304027
from tqdm import tqdm def sessionize_rows(itbl, cid): pmidPrev=None sess=[] it = itbl().__iter__() it.__next__() # TSV header for row in it: pmid=row[cid] if pmid != pmidPrev and len(sess)>0: yield sess sess=[] pmidPrev=pmid sess...
jeffhhk/datriples
lib/sessionize.py
sessionize.py
py
1,300
python
en
code
0
github-code
90
3066301087
from Chips.chip import Chip from Chips.chip_collector import ChipCollector class Bag: def __init__(self) -> None: self.__chips = [ # จำนวนตัวเบี้ยของแต่ละตัว ChipCollector("0", 5), ChipCollector("1", 6), ChipCollector("2", 6), ChipCollector("3", 5), ChipCollector("4", 5), Chip...
mdrijwan-uddin/a_math_demo
Draw/bag.py
bag.py
py
2,916
python
en
code
1
github-code
90
11029303643
""" Manage user and organization robot accounts. """ from flask import abort, request from auth import scopes from auth.auth_context import get_authenticated_user from auth.permissions import ( AdministerOrganizationPermission, OrganizationMemberPermission, ) from data.model import InvalidRobotException from e...
quay/quay
endpoints/api/robot.py
robot.py
py
12,891
python
en
code
2,281
github-code
90
9007655822
def show_table(table): for string in table: for elem in string: print(elem, end='\t') print() def round_table(table): return [round(elem, 3) for elem in table] def pretty_table(table): res = [[], [], [], []] n = 0 for i in range(4): for j in range(4): ...
Ivanhahanov/NVV_Lab3
main.py
main.py
py
2,314
python
en
code
0
github-code
90
25044849242
import json from click.testing import CliRunner from ml_enabler.cli import main_group from ml_enabler.tests.mockserver import MockServer import flask def test_upload(): def get_model_all_response(): data = [ { "modelId": 1, "created": "2019-05-31T10:55:27.63645...
hotosm/ml-enabler-cli
ml_enabler/tests/test_upload.py
test_upload.py
py
1,527
python
en
code
4
github-code
90
86531984486
import itertools import requests from bs4 import BeautifulSoup from abc import ABC, abstractmethod def remove_white_spaces(string): if string: return " ".join(string.split()) return "" class Parser(ABC): """ An abstract class representing a parser for web pages. Attributes: ------...
Aku1795/klubnacht-stats
get_data/scraper/parsers.py
parsers.py
py
4,028
python
en
code
0
github-code
90
24010676125
#stars in stars in stars import turtle draw = turtle.Turtle() def star(turtle,size): if size<=10: return else: for i in range(5): turtle.forward(size) star(turtle,size/3) turtle.left(216) draw.penup() draw.goto((-200,70)) draw.pendown() screen=turtle.Screen...
esipiderman/python_projects_with_turtle
stars2.py
stars2.py
py
390
python
en
code
0
github-code
90
1295309992
from tkinter import messagebox import random import dbConnection,random from datetime import date class Employee: def __init__(self,id,username,password,fname,lname,age,address,role,license_no,dept,url): self.Db=dbConnection.get_connection() self.Cursor=dbConnection.get_cursor(self.Db) if i...
UyaoJan/CityHealthOffice
employee.py
employee.py
py
14,584
python
en
code
1
github-code
90
25743033368
import random import numpy as np import matplotlib.pyplot as plt import math from math import sin, cos, sqrt, atan2, radians import os import pdb # finds the number of lines in a file def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 #...
blakethompson82/ECEN403-404-CTSDD
Ron Hadri/randNum.py
randNum.py
py
8,563
python
en
code
0
github-code
90
40185570891
#Couldn't figure out how to add the delay without module. import random, time def Mathquiz(): x = random.randint(0,9) y = random.randint(0,9) print(f"{x} x {y}") chances = 0 answer = 100 while(answer != x*y): answer= int(input('Your answer is : ')) ...
gyanchith28/Automating_the_boring_stuff
chapter08/multiplicationQuiz2.py
multiplicationQuiz2.py
py
783
python
en
code
0
github-code
90
176961394
from basic import * from chiseler import chiseler import numpy as np import cv2 import sys def compresser(img): # this file will compress big file in to small one dimention ,image = chiseler(img) image = image.tolist() height,width =image_size(image) # array of zeros of requirment dimentions git...
rishi23root/git-commit-drawing
compresser.py
compresser.py
py
1,436
python
en
code
1
github-code
90