max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
dcn/__init__.py
draklowell/DCNNode
0
6622151
from . import packet from . import server from . import handler from . import info
from . import packet from . import server from . import handler from . import info
none
1
1.114228
1
PythonExercicios/ex101.py
raulgranja/Python-Course
0
6622152
def voto(ano): from datetime import datetime idade = datetime.now().year - ano if 16 <= idade < 18 or idade > 65: return f'Com {idade} anos: VOTO OPCIONAL' elif idade >= 18: return f'Com {idade} anos: VOTO OBRIGATÓRIO' else: return f'Com {idade} anos: VOTO NEGADO' # main na...
def voto(ano): from datetime import datetime idade = datetime.now().year - ano if 16 <= idade < 18 or idade > 65: return f'Com {idade} anos: VOTO OPCIONAL' elif idade >= 18: return f'Com {idade} anos: VOTO OBRIGATÓRIO' else: return f'Com {idade} anos: VOTO NEGADO' # main na...
none
1
3.805221
4
interpret.py
Timothy102/covid-ct
1
6622153
<reponame>Timothy102/covid-ct import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy.signal import savgol_filter import seaborn as sns from tqdm import tqdm from config import OUTPUT_CSV def parseArguments(): parser = argparse.ArgumentParser() parser.add_argument("--path", type=str,...
import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy.signal import savgol_filter import seaborn as sns from tqdm import tqdm from config import OUTPUT_CSV def parseArguments(): parser = argparse.ArgumentParser() parser.add_argument("--path", type=str, default=TRAIN_PATH, ...
sl
0.260245
# Prvo je treba izračunat thresholde s calculate_thresholds() # AB diskriminacija # AC diskriminacija
2.660109
3
synclottery/sd.py
beiji-zhouqi/syncLottery
2
6622154
#!/usr/bin/env python # encoding: utf-8 import re import time import datetime from synclottery.requestData import GetData ''' url: 使用的是360彩票官网接口数据,修改startTime和endTime获取期间数据 sd_re: 获取数据正则表达式 ''' def runSql(start_Time, end_Time): url = "https://chart.cp.360.cn/kaijiang/sd?lotId=210053&spanType=2&span=" + start_Ti...
#!/usr/bin/env python # encoding: utf-8 import re import time import datetime from synclottery.requestData import GetData ''' url: 使用的是360彩票官网接口数据,修改startTime和endTime获取期间数据 sd_re: 获取数据正则表达式 ''' def runSql(start_Time, end_Time): url = "https://chart.cp.360.cn/kaijiang/sd?lotId=210053&spanType=2&span=" + start_Ti...
zh
0.765544
#!/usr/bin/env python # encoding: utf-8 url: 使用的是360彩票官网接口数据,修改startTime和endTime获取期间数据 sd_re: 获取数据正则表达式
2.810466
3
createtest_images.py
mrrocketraccoon/AdvancedLaneDetection
0
6622155
<gh_stars>0 from CameraCalibration import CameraCalibration from Thresholds import abs_sobel_thresh, mag_thresh, dir_threshold, color_r_threshold from SlidingWindows import sliding_windows from FitPolynomial import fit_polynomial import matplotlib.image as mpimg import cv2 import numpy as np import matplotlib.pyplot as...
from CameraCalibration import CameraCalibration from Thresholds import abs_sobel_thresh, mag_thresh, dir_threshold, color_r_threshold from SlidingWindows import sliding_windows from FitPolynomial import fit_polynomial import matplotlib.image as mpimg import cv2 import numpy as np import matplotlib.pyplot as plt #Calib...
en
0.595038
#Calibrate camera #img = mpimg.imread('test_images/test4.jpg') #Threshold #Sobel kernel size #Apply each of the thresholding functions #Try a combination #Perform perspective transform from source to bird's eyeview #cv2.imshow('test_images/calibrated_image.jpg',warped) #cv2.waitKey(0) ######The histogram shows that the...
2.363641
2
restore.py
CurryEleison/workdocs-disaster-recovery
0
6622156
<reponame>CurryEleison/workdocs-disaster-recovery from argparse import ArgumentParser, ArgumentTypeError from os.path import isdir from pathlib import Path import logging from workdocs_dr.cli_arguments import clients_from_input, bucket_url_from_input, logging_setup, organization_id_from_input, wdfilter_from_input from...
from argparse import ArgumentParser, ArgumentTypeError from os.path import isdir from pathlib import Path import logging from workdocs_dr.cli_arguments import clients_from_input, bucket_url_from_input, logging_setup, organization_id_from_input, wdfilter_from_input from workdocs_dr.directory_restore import DirectoryRes...
en
0.677008
# Restorer goes here
2.380693
2
lib3to2/tests/test_itertools.py
hajs/lib3to2_fork
3
6622157
<filename>lib3to2/tests/test_itertools.py from lib3to2.tests.support import lib3to2FixerTestCase class Test_itertoools(lib3to2FixerTestCase): fixer = "itertools" def test_map(self): b = """map(a, b)""" a = """from itertools import imap\nimap(a, b)""" self.check(b, a) def test_unch...
<filename>lib3to2/tests/test_itertools.py from lib3to2.tests.support import lib3to2FixerTestCase class Test_itertoools(lib3to2FixerTestCase): fixer = "itertools" def test_map(self): b = """map(a, b)""" a = """from itertools import imap\nimap(a, b)""" self.check(b, a) def test_unch...
en
0.408972
map(a, b) from itertools import imap\nimap(a, b) obj.filter(a, b) def map(): pass for key, val in zip(a, b):\n\tdct[key] = val from itertools import izip\nfor key, val in izip(a, b):\n\tdct[key] = val from itertools import function, filterfalse, other_function from itertools import function, ifilterfalse, o...
2.549675
3
plugin/utils/include_parser.py
LexouDuck/EasyClangComplete
648
6622158
"""Find all includes.""" import os import logging from os import path import sublime from ..utils import thread_job log = logging.getLogger("ECC") FILE_TAG = "📄 " FOLDER_TAG = "📂 " class IncludeCompleter(): """Handle the include completion in the quick panel.""" MATCHING_CHAR = { '<': '>', ...
"""Find all includes.""" import os import logging from os import path import sublime from ..utils import thread_job log = logging.getLogger("ECC") FILE_TAG = "📄 " FOLDER_TAG = "📂 " class IncludeCompleter(): """Handle the include completion in the quick panel.""" MATCHING_CHAR = { '<': '>', ...
en
0.883893
Find all includes. Handle the include completion in the quick panel. Initialize the object. Start completing includes. Pick this error to navigate to a file. Parse all the folders and return all headers. We might want to have back slashes intead of slashes.
2.790229
3
train.py
xinyuan-liu/NL2PL
0
6622159
<reponame>xinyuan-liu/NL2PL<filename>train.py import torch from torch.utils.data import Dataset, DataLoader, TensorDataset import dataset from transformer import * device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") hs=dataset.hearthstone() X_train,Y_train=hs.dataset('train') trainloader = DataLoade...
import torch from torch.utils.data import Dataset, DataLoader, TensorDataset import dataset from transformer import * device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") hs=dataset.hearthstone() X_train,Y_train=hs.dataset('train') trainloader = DataLoader(TensorDataset(torch.from_numpy(X_train),torc...
en
0.379099
# encoder # decoder #model = torch.nn.DataParallel(model)
2.339157
2
diagrams/firebase/extentions.py
bry-c/diagrams
17,037
6622160
<filename>diagrams/firebase/extentions.py<gh_stars>1000+ # This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _Firebase class _Extentions(_Firebase): _type = "extentions" _icon_dir = "resources/firebase/extentions" class Extensions(_Extentions): _icon = "extensions.png" ...
<filename>diagrams/firebase/extentions.py<gh_stars>1000+ # This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _Firebase class _Extentions(_Firebase): _type = "extentions" _icon_dir = "resources/firebase/extentions" class Extensions(_Extentions): _icon = "extensions.png" ...
en
0.645514
# This module is automatically generated by autogen.sh. DO NOT EDIT. # Aliases
1.288313
1
pipeline/0x00-pandas/3-rename.py
Naouali/holbertonschool-machine_learning
0
6622161
#!/usr/bin/env python3 import pandas as pd from_file = __import__('2-from_file').from_file df = from_file('coinbaseUSD_1-min_data_2014-12-01_to_2019-01-09.csv', ',') # YOUR CODE HERE df.rename(columns={"Timestamp": "Datetime"}, inplace=True) df['Datetime'] = pd.to_datetime(df['Datetime']) df = df[['Datetime', 'Close...
#!/usr/bin/env python3 import pandas as pd from_file = __import__('2-from_file').from_file df = from_file('coinbaseUSD_1-min_data_2014-12-01_to_2019-01-09.csv', ',') # YOUR CODE HERE df.rename(columns={"Timestamp": "Datetime"}, inplace=True) df['Datetime'] = pd.to_datetime(df['Datetime']) df = df[['Datetime', 'Close...
fr
0.272059
#!/usr/bin/env python3 # YOUR CODE HERE
3.214015
3
robotics/openrave/fixed_tamp_holding.py
nishadg246/stripstream-ivan-nishad
0
6622162
<gh_stars>0 from manipulation.motion.single_query import cspace_traj_helper, vector_traj_helper from stripstream.pddl.examples.openrave.utils import solve_inverse_kinematics, \ object_trans_from_manip_trans, set_manipulator_conf, Conf, \ sample_manipulator_trajectory from manipulation.bodies.robot import manip_fro...
from manipulation.motion.single_query import cspace_traj_helper, vector_traj_helper from stripstream.pddl.examples.openrave.utils import solve_inverse_kinematics, \ object_trans_from_manip_trans, set_manipulator_conf, Conf, \ sample_manipulator_trajectory from manipulation.bodies.robot import manip_from_pose_grasp...
en
0.667034
# Enables or disables all bodies for collision checking #################### # Collision free test between an object at pose1 and an object at pose2 #################### # Collision free test between a robot executing traj and an object at pose # Collision free test between an object held at grasp while executing traj ...
2.454939
2
standaloneBeta/DIGFL_vfl/DIG-FL_LinR.py
qmkakaxi/DIG_FL
1
6622163
import numpy as np import pandas as pd from sklearn import preprocessing from sklearn.model_selection import train_test_split import pickle class LinearRegression_DIGFL(): def __init__(self, n_iterations=3000, learning_rate=0.00001, num_participant=1, gradient=True): self.n_iterations = n_iterations ...
import numpy as np import pandas as pd from sklearn import preprocessing from sklearn.model_selection import train_test_split import pickle class LinearRegression_DIGFL(): def __init__(self, n_iterations=3000, learning_rate=0.00001, num_participant=1, gradient=True): self.n_iterations = n_iterations ...
none
1
2.800606
3
src/onegov/onboarding/models/assistant.py
politbuero-kampagnen/onegov-cloud
0
6622164
<gh_stars>0 import inspect import time class Assistant(object): """ Describes an assistant guiding a user through onboarding. """ def __init__(self, app, current_step_number=1): self.app = app methods = (fn[1] for fn in inspect.getmembers(self)) methods = (fn for fn in methods if in...
import inspect import time class Assistant(object): """ Describes an assistant guiding a user through onboarding. """ def __init__(self, app, current_step_number=1): self.app = app methods = (fn[1] for fn in inspect.getmembers(self)) methods = (fn for fn in methods if inspect.ismeth...
en
0.867129
Describes an assistant guiding a user through onboarding. Describes a step in an assistant.
2.889534
3
libs/jinja/template_var.py
janbodnar/Python-Course
13
6622165
#!/usr/bin/python from jinja2 import Template tm = Template("{% set name='Peter' -%} My name is {{ name }}") msg = tm.render() print(msg)
#!/usr/bin/python from jinja2 import Template tm = Template("{% set name='Peter' -%} My name is {{ name }}") msg = tm.render() print(msg)
ru
0.258958
#!/usr/bin/python
2.543889
3
stairs/solutions/stairs_ns_ok1.py
upmltech/hmopen2019
0
6622166
n, x = map(int, input().split()) a = list(map(int, input().split())) ans = 0 for i in range(n - 1): ans += (a[i + 1] - a[i] - 1) // x print(ans)
n, x = map(int, input().split()) a = list(map(int, input().split())) ans = 0 for i in range(n - 1): ans += (a[i + 1] - a[i] - 1) // x print(ans)
none
1
2.765993
3
accounts/urls.py
Wings30306/callingmrschristmas
4
6622167
from django.urls import path, reverse_lazy from django.contrib.auth.views import ( PasswordResetView, PasswordResetDoneView) from .views import logout, login, register, user_profile app_name = "accounts" urlpatterns = [ path('logout', logout, name="logout"), path('login', login, name="login"), path('re...
from django.urls import path, reverse_lazy from django.contrib.auth.views import ( PasswordResetView, PasswordResetDoneView) from .views import logout, login, register, user_profile app_name = "accounts" urlpatterns = [ path('logout', logout, name="logout"), path('login', login, name="login"), path('re...
none
1
1.946119
2
proxies/detran/tests/test_views.py
MinisterioPublicoRJ/api-cadg
6
6622168
<reponame>MinisterioPublicoRJ/api-cadg<gh_stars>1-10 from unittest import mock from django.conf import settings from django.test import TestCase, override_settings from django.urls import reverse from proxies.exceptions import ( DataDoesNotExistException, DetranAPIClientError, WaitDBException, ) TEST_TO...
from unittest import mock from django.conf import settings from django.test import TestCase, override_settings from django.urls import reverse from proxies.exceptions import ( DataDoesNotExistException, DetranAPIClientError, WaitDBException, ) TEST_TOKEN = "<PASSWORD>" @override_settings(SIMPLE_AUTH_T...
en
0.174723
# View must remove padding zero
2.374443
2
code/backend/billing/serializers.py
rollethu/noe
16
6622169
<filename>code/backend/billing/serializers.py from django.utils.translation import gettext as _ from rest_framework.exceptions import ValidationError from rest_framework import serializers from . import models as m class BillingDetailSerializer(serializers.HyperlinkedModelSerializer): is_company = serializers.Bo...
<filename>code/backend/billing/serializers.py from django.utils.translation import gettext as _ from rest_framework.exceptions import ValidationError from rest_framework import serializers from . import models as m class BillingDetailSerializer(serializers.HyperlinkedModelSerializer): is_company = serializers.Bo...
none
1
2.15293
2
mittens/interfaces/spatial.py
pfotiad/MITTENS
7
6622170
# -*- coding: utf-8 -*- from __future__ import print_function, division, unicode_literals, absolute_import from .base import MittensBaseInterface, IFLOGGER import os.path as op import numpy as np from nipype.interfaces.base import (traits, File, isdefined, BaseInterfaceInputSpec, TraitedSpec) from...
# -*- coding: utf-8 -*- from __future__ import print_function, division, unicode_literals, absolute_import from .base import MittensBaseInterface, IFLOGGER import os.path as op import numpy as np from nipype.interfaces.base import (traits, File, isdefined, BaseInterfaceInputSpec, TraitedSpec) from...
en
0.6807
# -*- coding: utf-8 -*- Replaces a DSI Studio affine with a real affine.
1.959779
2
desafio109/moeda109.py
marcelocmedeiros/RevisaoPython
0
6622171
# <NAME> # ADS UNIFIP # REVISÃO DE PYTHON # AULA 22 Modularização---> <NAME> ''' Modifique as funções que foram criadas no desafio 107 para que elas aceitem um parâmetro a mais, informando se o valor retornado por elas vai ser ou não formatado pela função moeda(), desenvolvida no desafio 108. ''' print('='*30) pri...
# <NAME> # ADS UNIFIP # REVISÃO DE PYTHON # AULA 22 Modularização---> <NAME> ''' Modifique as funções que foram criadas no desafio 107 para que elas aceitem um parâmetro a mais, informando se o valor retornado por elas vai ser ou não formatado pela função moeda(), desenvolvida no desafio 108. ''' print('='*30) pri...
pt
0.95499
# <NAME> # ADS UNIFIP # REVISÃO DE PYTHON # AULA 22 Modularização---> <NAME> Modifique as funções que foram criadas no desafio 107 para que elas aceitem um parâmetro a mais, informando se o valor retornado por elas vai ser ou não formatado pela função moeda(), desenvolvida no desafio 108. # def passa ter 3 parametros...
3.990495
4
face.py
PDahal2871/Emotion-Detection
0
6622172
<gh_stars>0 import cv2 import numpy as np from tensorflow.keras.models import load_model classifier = load_model('model1.h5') cap = cv2.VideoCapture(0) haar = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') while True: ret, frame = cap.read() if ret: fcs=[] bbx=[] preds=[] ...
import cv2 import numpy as np from tensorflow.keras.models import load_model classifier = load_model('model1.h5') cap = cv2.VideoCapture(0) haar = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') while True: ret, frame = cap.read() if ret: fcs=[] bbx=[] preds=[] gray...
en
0.85476
#reshaping from (1,150,150) to (150,150,1) # Changing to 4d for CNN # Putting rectangle of bbox in frames # Putting text in live frames # pressing 'q' or 'esc' keys destroys the window The accuracy of the classifier can be increased by changing it with a new, more accurate classifier or fine tuning the current one agai...
2.894622
3
MIHF/Bayes/BayesMatrixFactorEvaluator.py
revygabor/HWTester
0
6622173
import Evaluator from io import StringIO import numpy as np class BayesMatrixFactorEvaluator(Evaluator.Evaluator): def __init__(self, details): pass def evaluate(self, input, target_output, output, log): try: M = output.split('\n\n') U = np.loadtxt(StringIO(unicode(M[0]...
import Evaluator from io import StringIO import numpy as np class BayesMatrixFactorEvaluator(Evaluator.Evaluator): def __init__(self, details): pass def evaluate(self, input, target_output, output, log): try: M = output.split('\n\n') U = np.loadtxt(StringIO(unicode(M[0]...
none
1
2.857721
3
KNN.py
kongxiaoshuang/KNN
2
6622174
<reponame>kongxiaoshuang/KNN #-*- coding: utf-8 -*- from numpy import * import operator import matplotlib import matplotlib.pyplot as plt def createDataSet(): group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]]) labels = ['A', 'A', 'B', 'B'] return group, labels def classify0(inX, dataSet, labels, k...
#-*- coding: utf-8 -*- from numpy import * import operator import matplotlib import matplotlib.pyplot as plt def createDataSet(): group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]]) labels = ['A', 'A', 'B', 'B'] return group, labels def classify0(inX, dataSet, labels, k): #inX为用于分类的输入向量,dataSet为输入的...
zh
0.841819
#-*- coding: utf-8 -*- #inX为用于分类的输入向量,dataSet为输入的训练样本集, labels为训练标签,k表示用于选择最近的数目 #dataSet的行数 #将inX数组复制成与dataSet相同行数,与dataSet相减,求坐标差 #diffMat的平方 #将sqDiffMat每一行的所有数相加 #开根号,求点和点之间的欧式距离 #将distances中的元素从小到大排列,提取其对应的index,然后输出到sortedDistIndicies #创建字典 #前k个标签数据 #判断classCount中有没有对应的voteIlabel, # 如果有返回voteIlabel对应的值,如果没有则返回0,在最...
2.993564
3
DOSELECT/script.py
ritwik1503/Competitive-Coding-1
29
6622175
import json import requests
import json import requests
none
1
1.020308
1
src/mta/model/mf.py
JalexChang/cross-media-attribution
0
6622176
<reponame>JalexChang/cross-media-attribution import numpy from copy import copy from mta.dataset import Dataset from mta.ds.rating_row import RatingRow from mta.ds.touch_row import TouchRow import time class MF: trained = False dataset_loaded = False def __init__ (self,max_iters=100, user_biased =False, ...
import numpy from copy import copy from mta.dataset import Dataset from mta.ds.rating_row import RatingRow from mta.ds.touch_row import TouchRow import time class MF: trained = False dataset_loaded = False def __init__ (self,max_iters=100, user_biased =False, item_biased =False, alpha=0.001, beta=0.01, d...
en
0.765185
#R_predicted = self.predict(R_list) #update features by stochastic gradient descent #calculate overall error (with regularization) #updated factors #update biases # prediction errors # regularization errors
2.198554
2
oldtests/test_value.py
tokikanno/mosql
85
6622177
#!/usr/bin/env python # -*- coding: utf-8 -*- from getpass import getuser from itertools import product import mosql.util import mosql.std import mosql.mysql def connect_to_postgresql(): import psycopg2 conn = psycopg2.connect(user=getuser()) cur = conn.cursor() cur.execute('show server_encoding') ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from getpass import getuser from itertools import product import mosql.util import mosql.std import mosql.mysql def connect_to_postgresql(): import psycopg2 conn = psycopg2.connect(user=getuser()) cur = conn.cursor() cur.execute('show server_encoding') ...
en
0.319585
#!/usr/bin/env python # -*- coding: utf-8 -*- create temporary table _test_value_in_postgresql ( k varchar(128) primary key, v text ) # Test V-P-1: Value - PostgreSQL - All BMP Chars # # It will include all BMP chars, except # # 1. the null byte (U+0000) # 2. utf-16 surrogates (U+D800-U+...
2.447391
2
test/unit/test_cli.py
jsm84/ScalitySproxydSwift
4
6622178
<reponame>jsm84/ScalitySproxydSwift # Copyright (c) 2015 Scality # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2015 Scality # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
en
0.776395
# Copyright (c) 2015 Scality # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
1.832617
2
webgrid_ta/grids.py
sourcery-ai-bot/webgrid
9
6622179
from __future__ import absolute_import from webgrid import BaseGrid as BaseGrid from webgrid import ( Column, ColumnGroup, DateColumn, DateTimeColumn, EnumColumn, LinkColumnBase, NumericColumn, TimeColumn, YesNoColumn, ) from webgrid.filters import ( DateFilter, DateTimeFilt...
from __future__ import absolute_import from webgrid import BaseGrid as BaseGrid from webgrid import ( Column, ColumnGroup, DateColumn, DateTimeColumn, EnumColumn, LinkColumnBase, NumericColumn, TimeColumn, YesNoColumn, ) from webgrid.filters import ( DateFilter, DateTimeFilt...
en
0.055744
# default sort # default sort # default sort # default sort
2.17835
2
scripts/prune_inconsistent.py
shouc/corbfuzz
1
6622180
<reponame>shouc/corbfuzz<gh_stars>1-10 import sys import os import z3 def check(arr): mappings = {} gated = [] cter = 0 s = z3.Solver() for i in arr: i = i.split(",") if len(i) < 2: continue if i[0].startswith("isset"): sym, is_defined = i[1], int(i[...
import sys import os import z3 def check(arr): mappings = {} gated = [] cter = 0 s = z3.Solver() for i in arr: i = i.split(",") if len(i) < 2: continue if i[0].startswith("isset"): sym, is_defined = i[1], int(i[2]) if f"gated_{sym}" not i...
es
0.20724
# IS_SMALLER_OR_EQUAL # neq # eq # IS_SMALLER
2.687891
3
easy/24.py
pisskidney/leetcode
0
6622181
<reponame>pisskidney/leetcode #!/usr/bin/python class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def swapPairs(self, head): if not head or not head.next: return head p, res, prev = head, p.next, ListNode(0) ...
#!/usr/bin/python class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def swapPairs(self, head): if not head or not head.next: return head p, res, prev = head, p.next, ListNode(0) while p and p.next: ...
ru
0.258958
#!/usr/bin/python
3.438342
3
handcam/ltt/datasets/handcam/OniProcessingCpp.py
luketaverne/handcam
1
6622182
import cv2 import numpy as np import itertools import os # import h5py #put this back in after the h5py package has a new update on pip. See <https://github.com/h5py/h5py/issues/995> import sys from handcam.ltt.datasets.handcam.OrbbecCamParams import OrbbecCamParams # from handcam.ltt.util.Utils import write_progress...
import cv2 import numpy as np import itertools import os # import h5py #put this back in after the h5py package has a new update on pip. See <https://github.com/h5py/h5py/issues/995> import sys from handcam.ltt.datasets.handcam.OrbbecCamParams import OrbbecCamParams # from handcam.ltt.util.Utils import write_progress...
en
0.776331
# import h5py #put this back in after the h5py package has a new update on pip. See <https://github.com/h5py/h5py/issues/995> # from handcam.ltt.util.Utils import write_progress_bar # from subprocess import Popen, PIPE # grasp_labels = ['grasp_1', 'grasp_2', 'grasp_3', 'grasp_4', 'grasp_5', 'grasp_6', 'grasp_7'] # Need...
2.018207
2
synthetic_data/metrics/plots.py
rustamzh/synthetic_data
8
6622183
import os import sys import joblib import numpy as np import pickle as pkl import pandas as pd import seaborn as sns import scipy.stats as stats from sklearn import metrics import matplotlib.pyplot as plt import matplotlib.pylab as pylab from sklearn.utils import shuffle from sklearn.decomposition import PCA as PCA fro...
import os import sys import joblib import numpy as np import pickle as pkl import pandas as pd import seaborn as sns import scipy.stats as stats from sklearn import metrics import matplotlib.pyplot as plt import matplotlib.pylab as pylab from sklearn.utils import shuffle from sklearn.decomposition import PCA as PCA fro...
en
0.720266
Uses `matplotlib` and `seaborn` to plot the test loss, generator loss, discriminator loss across several epochs. Parameters ---------- log_file : string, required The pickle file with all the log values generated by HealthGAN. Plot the loss graph. Parameters ---------- savefig: boolean, optional If ...
2.415501
2
fcmpy/expert_fcm/defuzz.py
maxiuw/FcmBci
5
6622184
from abc import ABC, abstractclassmethod import skfuzzy as fuzz from fcmpy.expert_fcm.input_validator import type_check class Defuzzification(ABC): """ Defuzzification methods. """ @abstractclassmethod def defuzz() -> float: raise NotImplementedError('defuzzification method is not def...
from abc import ABC, abstractclassmethod import skfuzzy as fuzz from fcmpy.expert_fcm.input_validator import type_check class Defuzzification(ABC): """ Defuzzification methods. """ @abstractclassmethod def defuzz() -> float: raise NotImplementedError('defuzzification method is not def...
en
0.452967
Defuzzification methods. Centroid difuzzification method (i.e., center of gravity). Centroid difuzzification method (i.e., center of gravity). Other Parameters ---------- **x: numpy.ndarray universe of discourse **mfx: numpy.ndar...
2.835195
3
models/ivae/mnist.py
lim0606/pytorch-ardae-vae
11
6622185
import math import numpy as np from scipy import stats import torch import torch.nn as nn import torch.nn.functional as F from torch import autograd from torch.distributions import MultivariateNormal from models.layers import Identity, MLP, WNMLP, ContextConcatMLP, ContextScaleMLP, ContextWNScaleMLP, ContextSPScaleML...
import math import numpy as np from scipy import stats import torch import torch.nn as nn import torch.nn.functional as F from torch import autograd from torch.distributions import MultivariateNormal from models.layers import Identity, MLP, WNMLP, ContextConcatMLP, ContextScaleMLP, ContextWNScaleMLP, ContextSPScaleML...
en
0.379649
#torch.nn.init.xavier_normal_(m.weight) #'gaussian', #True, #ctx_dim = noise_dim if not enc_noise else h_dim #self.inp_encode = MLP(input_dim=input_dim, hidden_dim=h_dim, output_dim=h_dim, nonlinearity=nonlinearity, num_hidden_layers=num_hidden_layers-1, use_nonlinearity_output=True) #self.nos_encode = Identity() if no...
2.059899
2
napari_imsmicrolink/_tests/test_imsmicrolink.py
NHPatterson/napari-imsmicrolink
3
6622186
<reponame>NHPatterson/napari-imsmicrolink # import os # from pathlib import Path # from napari_imsmicrolink._dock_widget import IMSMicroLink # # # def test_ims_data_read(make_napari_viewer): # HERE = os.path.dirname(__file__) # data_fp = Path(HERE) / "data_tests" / "_test_data" / "bruker_spotlist.txt" # vie...
# import os # from pathlib import Path # from napari_imsmicrolink._dock_widget import IMSMicroLink # # # def test_ims_data_read(make_napari_viewer): # HERE = os.path.dirname(__file__) # data_fp = Path(HERE) / "data_tests" / "_test_data" / "bruker_spotlist.txt" # viewer = make_napari_viewer() # imsml = I...
en
0.400634
# import os # from pathlib import Path # from napari_imsmicrolink._dock_widget import IMSMicroLink # # # def test_ims_data_read(make_napari_viewer): # HERE = os.path.dirname(__file__) # data_fp = Path(HERE) / "data_tests" / "_test_data" / "bruker_spotlist.txt" # viewer = make_napari_viewer() # imsml = I...
2.135181
2
fab_deploy_tests/test_project3/test_project3/geo_app/urls.py
erlaveri/django-fab-deploy
0
6622187
# -*- coding: utf-8 -*- from __future__ import absolute_import from django.conf.urls import patterns, include, url urlpatterns = patterns('test_project3.geo_app.views', url(r'^distance/$', 'distance'), )
# -*- coding: utf-8 -*- from __future__ import absolute_import from django.conf.urls import patterns, include, url urlpatterns = patterns('test_project3.geo_app.views', url(r'^distance/$', 'distance'), )
en
0.769321
# -*- coding: utf-8 -*-
1.494726
1
test_project/test_export.py
admariner/django-sql-dashboard
293
6622188
<reponame>admariner/django-sql-dashboard def test_export_requires_setting(admin_client, dashboard_db): for key in ("export_csv_0", "export_tsv_0"): response = admin_client.post( "/dashboard/", { "sql": "SELECT 'hello' as label, * FROM generate_series(0, 10000)", ...
def test_export_requires_setting(admin_client, dashboard_db): for key in ("export_csv_0", "export_tsv_0"): response = admin_client.post( "/dashboard/", { "sql": "SELECT 'hello' as label, * FROM generate_series(0, 10000)", key: "1", }, ...
none
1
2.134319
2
venv/lib/python3.8/site-packages/numpy/lib/tests/test__datasource.py
Retraces/UkraineBot
2
6622189
/home/runner/.cache/pip/pool/1c/b8/43/a6a237eaa2165dd2e663da4f5e965265d45c70c299fa1d94e6397ada01
/home/runner/.cache/pip/pool/1c/b8/43/a6a237eaa2165dd2e663da4f5e965265d45c70c299fa1d94e6397ada01
none
1
0.836136
1
geocoder/regex_library.py
taurenk/Py-Geocoder
0
6622190
<filename>geocoder/regex_library.py """ 12/24/2014 Compile ALL reusable regex in one location, for centralized use. """ import re import standards class RegexLib: number_regex = re.compile( r'^\d+[-]?(\w+)?') po_regex = re.compile( r'(?:(PO BOX|P O BOX)\s(\d*[- ]?\d*))' ) intersection_test = re.compile(r'(?:\s(A...
<filename>geocoder/regex_library.py """ 12/24/2014 Compile ALL reusable regex in one location, for centralized use. """ import re import standards class RegexLib: number_regex = re.compile( r'^\d+[-]?(\w+)?') po_regex = re.compile( r'(?:(PO BOX|P O BOX)\s(\d*[- ]?\d*))' ) intersection_test = re.compile(r'(?:\s(A...
en
0.49639
12/24/2014 Compile ALL reusable regex in one location, for centralized use. #][A-Z0-9]*') Generate the US States regex string
2.530848
3
JiYouMCC/0017/0017.py
hooting/show-me-the-code-python
0
6622191
# -*- coding: utf-8 -*- import xlrd from xml.dom.minidom import Document from xml.etree.ElementTree import Comment, Element import json infos = [] info_file = xlrd.open_workbook('students.xls') info_table = info_file.sheets()[0] row_count = info_table.nrows doc = Document() root = doc.createElement('root') doc.appendC...
# -*- coding: utf-8 -*- import xlrd from xml.dom.minidom import Document from xml.etree.ElementTree import Comment, Element import json infos = [] info_file = xlrd.open_workbook('students.xls') info_table = info_file.sheets()[0] row_count = info_table.nrows doc = Document() root = doc.createElement('root') doc.appendC...
en
0.769321
# -*- coding: utf-8 -*-
2.886786
3
eqstats/catalogs.py
egdaub/eqstats
1
6622192
<reponame>egdaub/eqstats import numpy as np def omori_times(ncat, nevents, tmin, tmax, b, p=1., detectprob = None): """ creates ncat synthetic realizations of an Omori decay in seismicity parameters are nevents (number of events), tmin (minimum catalog time, main shock is t=0) tmax (maximum catalog ti...
import numpy as np def omori_times(ncat, nevents, tmin, tmax, b, p=1., detectprob = None): """ creates ncat synthetic realizations of an Omori decay in seismicity parameters are nevents (number of events), tmin (minimum catalog time, main shock is t=0) tmax (maximum catalog time), b (Omori time offset...
en
0.671957
creates ncat synthetic realizations of an Omori decay in seismicity parameters are nevents (number of events), tmin (minimum catalog time, main shock is t=0) tmax (maximum catalog time), b (Omori time offset, R \propto 1/(b+t)^p) Inputs: ncat = number of realizations nevents = number of events per...
2.831908
3
WhileLoop/EasterGuests.py
Rohitm619/Softuni-Python-Basic
1
6622193
import math from math import ceil number_of_guests = int(input()) budget = float(input()) number_of_kozunak = number_of_guests / 3 #ceil number_of_eggs_needed = number_of_guests * 2 kozunak_price = ceil(number_of_kozunak) * 4 egg_price = number_of_eggs_needed * 0.45 total = kozunak_price + egg_price diff = total ...
import math from math import ceil number_of_guests = int(input()) budget = float(input()) number_of_kozunak = number_of_guests / 3 #ceil number_of_eggs_needed = number_of_guests * 2 kozunak_price = ceil(number_of_kozunak) * 4 egg_price = number_of_eggs_needed * 0.45 total = kozunak_price + egg_price diff = total ...
none
1
3.500434
4
Q617.py
Linchin/python_leetcode_git
0
6622194
""" Q617 Merge Two Binary Trees Easy Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new ...
""" Q617 Merge Two Binary Trees Easy Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new ...
en
0.952031
Q617 Merge Two Binary Trees Easy Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new valu...
3.827987
4
tests/stubreferencetest.py
netcharm/ironclad
0
6622195
<reponame>netcharm/ironclad import os from tests.utils.runtest import makesuite, run from tests.utils.gc import gcwait from tests.utils.testcase import TestCase from Ironclad import dgt_getfuncptr, dgt_registerdata, Unmanaged, StubReference from System import IntPtr class StubReferenceTest(TestCase): ...
import os from tests.utils.runtest import makesuite, run from tests.utils.gc import gcwait from tests.utils.testcase import TestCase from Ironclad import dgt_getfuncptr, dgt_registerdata, Unmanaged, StubReference from System import IntPtr class StubReferenceTest(TestCase): def testMapInitUnmapLibrary...
en
0.823827
# safe to call Dispose twice # if func not found and callable, error
2.083995
2
thai2transformers/auto.py
modem888/thai2transformers
64
6622196
from collections import OrderedDict from transformers import ( AutoConfig, PretrainedConfig ) from transformers.modeling_bert import BertConfig from transformers.modeling_roberta import RobertaConfig from transformers.modeling_xlm_roberta import XLMRobertaConfig from .models import ( XLMRobertaForMultiLa...
from collections import OrderedDict from transformers import ( AutoConfig, PretrainedConfig ) from transformers.modeling_bert import BertConfig from transformers.modeling_roberta import RobertaConfig from transformers.modeling_xlm_roberta import XLMRobertaConfig from .models import ( XLMRobertaForMultiLa...
en
0.600123
Instantiates one of the model classes of the library---with a sequence classification head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transforme...
2.594154
3
renderable_core/services/autoscaler.py
therenderable/renderable-core
0
6622197
<gh_stars>0 import time from threading import Thread, Lock import docker class Autoscaler: def __init__(self, hostname, port, certificate_path, cleanup_period, cooldown_period): self.hostname = hostname self.port = port self.certificate_path = certificate_path self.cleanup_period = cleanup_period ...
import time from threading import Thread, Lock import docker class Autoscaler: def __init__(self, hostname, port, certificate_path, cleanup_period, cooldown_period): self.hostname = hostname self.port = port self.certificate_path = certificate_path self.cleanup_period = cleanup_period self.cool...
none
1
2.453247
2
app/models.py
kasamsharif/tdd-flask
1
6622198
<reponame>kasamsharif/tdd-flask<gh_stars>1-10 from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class ChoiceList(db.Model): """This class represents choice list""" __tableaname__ = "choicelists" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255)) created_on = db....
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class ChoiceList(db.Model): """This class represents choice list""" __tableaname__ = "choicelists" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255)) created_on = db.Column(db.DateTime, default=db.func.current_ti...
en
0.782571
This class represents choice list initialize with name.
3.046776
3
src/primaires/scripting/extensions/nombre.py
vlegoff/tsunami
14
6622199
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of...
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of...
fr
0.540872
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of ...
1.308947
1
codes/GP-obtain-2D-LLS.py
AbhilashMathews/gp_extras_applications
1
6622200
<filename>codes/GP-obtain-2D-LLS.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 27 15:56:39 2019 @author: mathewsa This script is used for plotting the length scales learned by the GP across the 2D (i.e. radial and temporal) domain specified by the user. This script is to be run only after ...
<filename>codes/GP-obtain-2D-LLS.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 27 15:56:39 2019 @author: mathewsa This script is used for plotting the length scales learned by the GP across the 2D (i.e. radial and temporal) domain specified by the user. This script is to be run only after ...
en
0.777849
#!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Fri Sep 27 15:56:39 2019 @author: mathewsa This script is used for plotting the length scales learned by the GP across the 2D (i.e. radial and temporal) domain specified by the user. This script is to be run only after first running and saving the GP after it...
2.660349
3
lib/GuiMain.py
KorvinSilver/proverbial_hangman
0
6622201
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'GuiMain.ui' # # Created: Sun Nov 26 20:51:18 2017 # by: pyside-uic 0.2.15 running on PySide 1.2.4 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_MainWindow(object): def setupUi(s...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'GuiMain.ui' # # Created: Sun Nov 26 20:51:18 2017 # by: pyside-uic 0.2.15 running on PySide 1.2.4 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_MainWindow(object): def setupUi(s...
en
0.79589
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'GuiMain.ui' # # Created: Sun Nov 26 20:51:18 2017 # by: pyside-uic 0.2.15 running on PySide 1.2.4 # # WARNING! All changes made in this file will be lost!
1.713277
2
12.Highly divisible triangular number.py
iFun/Project-Euler
0
6622202
from math import sqrt def main(): count = 0 totalNumber = 0 tmp = 10001 result = 0 total = 0 while tmp != 20001: total = getSum(tmp) result = findDivisor(total) if len(result) > count: count = len(result) totalNumber = total print (co...
from math import sqrt def main(): count = 0 totalNumber = 0 tmp = 10001 result = 0 total = 0 while tmp != 20001: total = getSum(tmp) result = findDivisor(total) if len(result) > count: count = len(result) totalNumber = total print (co...
en
0.658862
# print(count) # print(totalNumber)
3.625025
4
src/main/python/app/workers/CategorySaverWorker.py
karlpet/WadLauncher
2
6622203
import sys, json, os, uuid from configparser import ConfigParser from dataclasses import asdict from PyQt5.QtCore import QThread, pyqtSignal from app.config import Config from app.workers.WorkerPool import * def category_saver_worker_wrapper(items, progress_handlers=[], done_handlers=[]): worker = CategorySaverW...
import sys, json, os, uuid from configparser import ConfigParser from dataclasses import asdict from PyQt5.QtCore import QThread, pyqtSignal from app.config import Config from app.workers.WorkerPool import * def category_saver_worker_wrapper(items, progress_handlers=[], done_handlers=[]): worker = CategorySaverW...
none
1
2.072729
2
reports/jasa/transcet_map.py
nedlrichards/tau_decomp
0
6622204
<filename>reports/jasa/transcet_map.py<gh_stars>0 import numpy as np import matplotlib.pyplot as plt import cartopy.crs as ccrs import matplotlib.tri as tri from scipy.ndimage import gaussian_filter from src import Config plt.ion() cf=Config() woa_file = np.genfromtxt('data/external/woa18_decav81B0_t14mn04.csv', ...
<filename>reports/jasa/transcet_map.py<gh_stars>0 import numpy as np import matplotlib.pyplot as plt import cartopy.crs as ccrs import matplotlib.tri as tri from scipy.ndimage import gaussian_filter from src import Config plt.ion() cf=Config() woa_file = np.genfromtxt('data/external/woa18_decav81B0_t14mn04.csv', ...
en
0.331613
#m.fillcontinents(color="#FFDDCC", lake_color='#DDEEFF') #parallels = np.linspace(20, 50, 5) #m.drawparallels(parallels,labels=[False,True,True,False]) #meridians = np.linspace(-115, -155, 5) #m.drawmeridians(meridians,labels=[True,False,False,True])
1.903875
2
module1-introduction-to-sql/rpg_queries.py
lucaspetrus/DS-Unit-3-Sprint-2-SQL-and-Databases
0
6622205
<filename>module1-introduction-to-sql/rpg_queries.py # Questions for Today """How many total Characters are there? How many of each specific subclass? How many Items are there? How many of the Items are weapons? How many are not? How many Items does each character have? (Return first 20 rows) How many Weapons does eac...
<filename>module1-introduction-to-sql/rpg_queries.py # Questions for Today """How many total Characters are there? How many of each specific subclass? How many Items are there? How many of the Items are weapons? How many are not? How many Items does each character have? (Return first 20 rows) How many Weapons does eac...
en
0.853223
# Questions for Today How many total Characters are there? How many of each specific subclass? How many Items are there? How many of the Items are weapons? How many are not? How many Items does each character have? (Return first 20 rows) How many Weapons does each character have? (Return first 20 rows) On average, how ...
3.266214
3
util/env_util/wrappers/action_wrappers.py
joelouismarino/variational_rl
15
6622206
import gym from gym.spaces import Box import numpy as np class NormalizeAction(gym.ActionWrapper): """ Normalizes the reward to [-1, 1]. """ def __init__(self, env): gym.ActionWrapper.__init__(self, env) self._wrapped_env = env ub = np.ones(env.action_space.shape) self....
import gym from gym.spaces import Box import numpy as np class NormalizeAction(gym.ActionWrapper): """ Normalizes the reward to [-1, 1]. """ def __init__(self, env): gym.ActionWrapper.__init__(self, env) self._wrapped_env = env ub = np.ones(env.action_space.shape) self....
en
0.777374
Normalizes the reward to [-1, 1].
2.851144
3
PreFRBLE/PreFRBLE/parameter.py
FRBs/PreFRBLE
5
6622207
<gh_stars>1-10 redshift_accuracy = 4 # number decimals for redshift accuracy (to prevent numerical misidentification of redshifts) ## regions along LoS regions = ['MW', 'IGM', 'Inter', 'Host', 'Local'] linestyle_region = {'MW':'--', 'IGM':'-', 'Inter':":", 'Host':"-.", 'Local':"-."} N_sample = { ## !!! hardcoded, f...
redshift_accuracy = 4 # number decimals for redshift accuracy (to prevent numerical misidentification of redshifts) ## regions along LoS regions = ['MW', 'IGM', 'Inter', 'Host', 'Local'] linestyle_region = {'MW':'--', 'IGM':'-', 'Inter':":", 'Host':"-.", 'Local':"-."} N_sample = { ## !!! hardcoded, find a better sol...
en
0.758201
# number decimals for redshift accuracy (to prevent numerical misidentification of redshifts) ## regions along LoS ## !!! hardcoded, find a better solution # 'MW' : 1, ## number of events in sample to estimate likelihood of host redshift ## available models for all regions ## telescopes and cosmic population scenar...
1.884232
2
python/flask_tox_pytest_helloworld/helloworld/main.py
mir-dhaka/coding_playground
2
6622208
<reponame>mir-dhaka/coding_playground #! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2019 damian <damian@C-DZ-E5500> # # Distributed under terms of the MIT license. from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): '''hello_world''' return 'Hell...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2019 damian <damian@C-DZ-E5500> # # Distributed under terms of the MIT license. from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): '''hello_world''' return 'Hello World' if __name__ == "__main__": ...
en
0.642924
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2019 damian <damian@C-DZ-E5500> # # Distributed under terms of the MIT license. hello_world
2.386165
2
backend/bin/test/test_traffic_analyzer.py
anjo-ba/PCAP-Analyzer
4
6622209
import unittest from io import StringIO from unittest.mock import patch import main.traffic_analyzer as traffic_analyzer class TestTrafficAnalyzerMethods(unittest.TestCase): @patch("sys.stdout", new_callable=StringIO) @patch("sys.argv", "test") def test_main_function(self, mock_stdout) -> None:...
import unittest from io import StringIO from unittest.mock import patch import main.traffic_analyzer as traffic_analyzer class TestTrafficAnalyzerMethods(unittest.TestCase): @patch("sys.stdout", new_callable=StringIO) @patch("sys.argv", "test") def test_main_function(self, mock_stdout) -> None:...
none
1
2.727658
3
perform.py
amolenaar/roles
16
6622210
"""Test performance between roles and zope3 implementations.""" from timeit import timeit setup_role = """ from roles import RoleType class A: pass class Role(metaclass=RoleType): def func(self): pass a = A() """ setup_rolefactory = """ from roles import RoleType from roles.factory import assignto class ...
"""Test performance between roles and zope3 implementations.""" from timeit import timeit setup_role = """ from roles import RoleType class A: pass class Role(metaclass=RoleType): def func(self): pass a = A() """ setup_rolefactory = """ from roles import RoleType from roles.factory import assignto class ...
en
0.572622
Test performance between roles and zope3 implementations. from roles import RoleType class A: pass class Role(metaclass=RoleType): def func(self): pass a = A() from roles import RoleType from roles.factory import assignto class A: pass class Role(metaclass=RoleType): def func(self): pass @assignto...
2.582439
3
archiv/models.py
acdh-oeaw/gtrans
1
6622211
import re import reversion import lxml.etree as ET from django.contrib.auth.models import User from django.db import models from django.urls import reverse from idprovider.models import IdProvider from vocabs.models import SkosConcept from entities.models import Person, Place, Institution from browsing.browsing_util...
import re import reversion import lxml.etree as ET from django.contrib.auth.models import User from django.db import models from django.urls import reverse from idprovider.models import IdProvider from vocabs.models import SkosConcept from entities.models import Person, Place, Institution from browsing.browsing_util...
de
0.749971
Beschreibt eine (archivalische) Resource Saves a copy of the current object and returns it
1.868942
2
hadar/optimizer/lp/mapper.py
hadar-solver/hadar
1
6622212
<filename>hadar/optimizer/lp/mapper.py # Copyright (c) 2019-2020, RTE (https://www.rte-france.com) # See AUTHORS.txt # This Source Code Form is subject to the terms of the Apache License, version 2.0. # If a copy of the Apache License, version 2.0 was not distributed with this file, you can obtain one at http://www...
<filename>hadar/optimizer/lp/mapper.py # Copyright (c) 2019-2020, RTE (https://www.rte-france.com) # See AUTHORS.txt # This Source Code Form is subject to the terms of the Apache License, version 2.0. # If a copy of the Apache License, version 2.0 was not distributed with this file, you can obtain one at http://www...
en
0.672865
# Copyright (c) 2019-2020, RTE (https://www.rte-france.com) # See AUTHORS.txt # This Source Code Form is subject to the terms of the Apache License, version 2.0. # If a copy of the Apache License, version 2.0 was not distributed with this file, you can obtain one at http://www.apache.org/licenses/LICENSE-2.0. # SP...
2.44755
2
union/admin.py
HASSAN1A/Student-Union
2
6622213
from django.contrib import admin from .models import StudentUnion,Business,Post,EmergencyService # Register your models here. admin.site.register(StudentUnion) admin.site.register(Business) admin.site.register(Post) admin.site.register(EmergencyService)
from django.contrib import admin from .models import StudentUnion,Business,Post,EmergencyService # Register your models here. admin.site.register(StudentUnion) admin.site.register(Business) admin.site.register(Post) admin.site.register(EmergencyService)
en
0.968259
# Register your models here.
1.36081
1
mycnn/data/__init__.py
jacky10001/tf2-mycnn
0
6622214
<reponame>jacky10001/tf2-mycnn<filename>mycnn/data/__init__.py # -*- coding: utf-8 -*- from .cats_vs_dogs import cats_vs_dogs_from_MSCenter from .cats_vs_dogs import cats_vs_dogs_by_kaggle_zipfile from .voc_dataset import download_pascal_voc_dataset from .voc_segment import make_voc_segment_dataset from .classificat...
# -*- coding: utf-8 -*- from .cats_vs_dogs import cats_vs_dogs_from_MSCenter from .cats_vs_dogs import cats_vs_dogs_by_kaggle_zipfile from .voc_dataset import download_pascal_voc_dataset from .voc_segment import make_voc_segment_dataset from .classification import generate_classification_dataset from .segmentation i...
en
0.769321
# -*- coding: utf-8 -*-
1.394727
1
pyChocolate/Chocolate.py
kaankarakoc42/pyChocolate
1
6622215
<filename>pyChocolate/Chocolate.py from inspect import stack, getframeinfo,getsource from colorama import Fore,init from datetime import datetime # Before reading code u should know # -> getframeinfo(stack()[1][0]) function getting data about used code line and # -> that why we can get debug of a code part from ...
<filename>pyChocolate/Chocolate.py from inspect import stack, getframeinfo,getsource from colorama import Fore,init from datetime import datetime # Before reading code u should know # -> getframeinfo(stack()[1][0]) function getting data about used code line and # -> that why we can get debug of a code part from ...
en
0.482206
# Before reading code u should know # -> getframeinfo(stack()[1][0]) function getting data about used code line and # -> that why we can get debug of a code part from program #-----------ChocolateFuncs---------- #-----------exporting--------------- #-------------Done------------------
2.747956
3
Neural Collaborative Filtering/CleanData.py
IanSullivan/Recommendation
0
6622216
<reponame>IanSullivan/Recommendation<gh_stars>0 import pandas as pd import numpy as np import random import time src = "D:\\data\\h&m images\\h-and-m-personalized-fashion-recommendations\\transactions_train.csv" # src = "dummy.csv" final_df_name = 'indexCustomersLabeled20.csv' df_size = 20000 df = pd.read_csv...
import pandas as pd import numpy as np import random import time src = "D:\\data\\h&m images\\h-and-m-personalized-fashion-recommendations\\transactions_train.csv" # src = "dummy.csv" final_df_name = 'indexCustomersLabeled20.csv' df_size = 20000 df = pd.read_csv(src) df = df[:df_size] # Looking for all un...
en
0.733328
# src = "dummy.csv" # Looking for all unique values to map them to an index, embedding layer requires indexes # loop through the data frame with relevant columns, label of 1 indicates it is a real customer item pair # label of 0 indicates it is a fake customer item pair ie; the customer never purchased the item in the ...
3.053117
3
config.py
Alexwell/flask-task-manager
0
6622217
<filename>config.py # -*- coding: utf-8 -*- import os from dotenv import load_dotenv basedir = os.path.abspath(os.path.dirname(__file__)) load_dotenv(os.path.join(basedir, '.env')) class Config(object): SECRET_KEY = os.environ.get('SECRET_KEY') or 'test-secret-key-12ew5fesa7azo14cWfgQfghNccf55' WTF_CSRF_ENAB...
<filename>config.py # -*- coding: utf-8 -*- import os from dotenv import load_dotenv basedir = os.path.abspath(os.path.dirname(__file__)) load_dotenv(os.path.join(basedir, '.env')) class Config(object): SECRET_KEY = os.environ.get('SECRET_KEY') or 'test-secret-key-12ew5fesa7azo14cWfgQfghNccf55' WTF_CSRF_ENAB...
en
0.625722
# -*- coding: utf-8 -*- # SQLAlchemy settings
1.857419
2
aug_runner.py
pabloduque0/cnn_deconv_viz
0
6622218
<reponame>pabloduque0/cnn_deconv_viz from augmentation.combineds import wassersteingan import numpy as np from preprocessing.imageparser import ImageParser from constants import * import gc import os import cv2 parser = ImageParser(path_utrech='../Utrecht/subjects', path_singapore='../Singapore/su...
from augmentation.combineds import wassersteingan import numpy as np from preprocessing.imageparser import ImageParser from constants import * import gc import os import cv2 parser = ImageParser(path_utrech='../Utrecht/subjects', path_singapore='../Singapore/subjects', path_am...
en
0.359067
LABELS DATA T1 DATA FLAIR DATA DATA CONCAT
2.23494
2
loot_generator/__init__.py
Tengro/lootgenerator
1
6622219
<filename>loot_generator/__init__.py<gh_stars>1-10 __version__ = '0.1.0' __author__ = '<NAME>' # Version synonym VERSION = __version__
<filename>loot_generator/__init__.py<gh_stars>1-10 __version__ = '0.1.0' __author__ = '<NAME>' # Version synonym VERSION = __version__
en
0.963459
# Version synonym
1.024621
1
ex-mundo1/ex025.py
PedroPegado/ex-cursoemvideo
0
6622220
print('\033[1;35m===== EX 025 =====\033[m') x = input('Ponha seu nome completo: ') y = x.lower() z = 'silva' in y print(f'Seu nome contém o sobrenome Silva? {z}')
print('\033[1;35m===== EX 025 =====\033[m') x = input('Ponha seu nome completo: ') y = x.lower() z = 'silva' in y print(f'Seu nome contém o sobrenome Silva? {z}')
none
1
3.609927
4
archivematica/fetchDip.py
kngreaves/scripts
15
6622221
#! usr/bin/env python # fetch_dip.py # This script is designed to be run at regular intervals, for example from a crontab. # # Downloads a DIP from Archivematica to the TMP_DIR and extracts the tarball. # Derivatives are created for each file in its objects directory, and they are moved, # along with the original file...
#! usr/bin/env python # fetch_dip.py # This script is designed to be run at regular intervals, for example from a crontab. # # Downloads a DIP from Archivematica to the TMP_DIR and extracts the tarball. # Derivatives are created for each file in its objects directory, and they are moved, # along with the original file...
en
0.871718
#! usr/bin/env python # fetch_dip.py # This script is designed to be run at regular intervals, for example from a crontab. # # Downloads a DIP from Archivematica to the TMP_DIR and extracts the tarball. # Derivatives are created for each file in its objects directory, and they are moved, # along with the original file,...
2.461854
2
stlearn/spatials/trajectory/set_root.py
duypham2108/stLearn
67
6622222
from anndata import AnnData from typing import Optional, Union import numpy as np from stlearn.spatials.trajectory.utils import _correlation_test_helper def set_root(adata: AnnData, use_label: str, cluster: str, use_raw: bool = False): """\ Automatically set the root index. Parameters ---------- ...
from anndata import AnnData from typing import Optional, Union import numpy as np from stlearn.spatials.trajectory.utils import _correlation_test_helper def set_root(adata: AnnData, use_label: str, cluster: str, use_raw: bool = False): """\ Automatically set the root index. Parameters ---------- ...
en
0.549744
\ Automatically set the root index. Parameters ---------- adata Annotated data matrix. use_label Use label result of clustering method. cluster Choose cluster to use as root use_raw Use the raw layer Returns ------- Root index # Subset the data ba...
2.520762
3
test_repo/a/a.py
antoniopugliese/module-structure
0
6622223
""" This is module a. """ from ..b import b_func a = "this is file 'a'" def a_func(): inside_a_func = 'inside a_func()' b_func() print("a")
""" This is module a. """ from ..b import b_func a = "this is file 'a'" def a_func(): inside_a_func = 'inside a_func()' b_func() print("a")
en
0.221108
This is module a.
3.218747
3
particletracking/statistics/order_6.py
JamesDownsLab/particletracking
0
6622224
<filename>particletracking/statistics/order_6.py import numpy as np from scipy import spatial def order_process(features): points = features[['x', 'y', 'r']].values orders = order_and_neighbors(points[:, :2]) features['order_r_nearest_6'] = np.real(orders).astype('float32') features['order_i_nearest_6...
<filename>particletracking/statistics/order_6.py import numpy as np from scipy import spatial def order_process(features): points = features[['x', 'y', 'r']].values orders = order_and_neighbors(points[:, :2]) features['order_r_nearest_6'] = np.real(orders).astype('float32') features['order_i_nearest_6...
none
1
2.228335
2
notebooks/plot_3freq.py
nedlrichards/canope_gw_scatter
0
6622225
import numpy as np import scipy.signal as sig import scipy.io as load_mat from math import pi import matplotlib.pyplot as plt from src import xponder #plt.ion() xp = xponder() for hr in range(24): load_file = 'nav_253' + f'{hr:02}' + '5458.nc' try: p_raw, p_raw_ft = xp.load_raw(load_file) excep...
import numpy as np import scipy.signal as sig import scipy.io as load_mat from math import pi import matplotlib.pyplot as plt from src import xponder #plt.ion() xp = xponder() for hr in range(24): load_file = 'nav_253' + f'{hr:02}' + '5458.nc' try: p_raw, p_raw_ft = xp.load_raw(load_file) excep...
ru
0.419184
#plt.ion()
2.002217
2
backend/server/tests/wrapper_test/mock_fixture.py
FlickerSoul/Graphery
5
6622226
<filename>backend/server/tests/wrapper_test/mock_fixture.py import os import pathlib from uuid import UUID import pytest from django.conf import settings from django.core.files import File from backend.model.TutorialRelatedModel import Category, Tutorial, Graph, GraphPriority, Code, ExecResultJson, Uploads from backe...
<filename>backend/server/tests/wrapper_test/mock_fixture.py import os import pathlib from uuid import UUID import pytest from django.conf import settings from django.core.files import File from backend.model.TutorialRelatedModel import Category, Tutorial, Graph, GraphPriority, Code, ExecResultJson, Uploads from backe...
en
0.955627
# omitted since the password field is a encrypted version of it # omitted since the password field is a encrypted version of it # omitted since the password field is a encrypted version of it # no breakpoints for now # no breakpoints for now
2.111997
2
hlrobot_gazebo/scripts/publisher.py
liuxiao916/HLRobot_gazebo
8
6622227
<filename>hlrobot_gazebo/scripts/publisher.py #!/usr/bin/env python import rospy from std_msgs.msg import Float64MultiArray #path = '/home/liuxiao/catkin_ws/src/HLRobot_gazebo/cubicTrajectoryPlanning/data/PPB/littlestar.txt' parent_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) path = os.path.join...
<filename>hlrobot_gazebo/scripts/publisher.py #!/usr/bin/env python import rospy from std_msgs.msg import Float64MultiArray #path = '/home/liuxiao/catkin_ws/src/HLRobot_gazebo/cubicTrajectoryPlanning/data/PPB/littlestar.txt' parent_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) path = os.path.join...
en
0.383555
#!/usr/bin/env python #path = '/home/liuxiao/catkin_ws/src/HLRobot_gazebo/cubicTrajectoryPlanning/data/PPB/littlestar.txt'
2.178475
2
screens/mobility.py
IvyHan2013/Mobile-Visualization
0
6622228
from . import HomeScreen from kivy.lang import Builder Builder.load_file('screens/mobility.kv') class MobilityScreen(HomeScreen): pass
from . import HomeScreen from kivy.lang import Builder Builder.load_file('screens/mobility.kv') class MobilityScreen(HomeScreen): pass
none
1
1.175871
1
python/raft/timer_thread.py
chenzhaoplus/vraft
23
6622229
import sys import threading from random import randrange import logging from monitor import send_state_update logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', datefmt='%H:%M:%S', level=logging.INFO) from Candidate import Candidate, VoteRequest from Follower import Follower from Leader import Le...
import sys import threading from random import randrange import logging from monitor import send_state_update logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', datefmt='%H:%M:%S', level=logging.INFO) from Candidate import Candidate, VoteRequest from Follower import Follower from Leader import Le...
en
0.640115
# input: candidate (id, term, lastLogIndex, lastLogTerm) # output: term, vote_granted # rule: # 1. return false if candidate.term < current_term # 2. return true if (voteFor is None or voteFor==candidate.id) and candidate's log is newer than receiver's
2.61062
3
cap_4/listagem/digits.py
rsmonteiro2021/execicios_python
1
6622230
#Estatíticas simples com uma lista de números. digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print(min(digits)) print(max(digits)) print(sum(digits)) #List Comprehensions squares = [value**2 for value in range(1,11)] print(squares)
#Estatíticas simples com uma lista de números. digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print(min(digits)) print(max(digits)) print(sum(digits)) #List Comprehensions squares = [value**2 for value in range(1,11)] print(squares)
pt
0.981839
#Estatíticas simples com uma lista de números. #List Comprehensions
4.023802
4
capital_spans.py
patmanteau/panflutist
0
6622231
#!/usr/bin/env python """ Panflute filter for setting C A P I T A L text, with tracking. Use if []{.smallcaps} is too weak. Usage: - In Pandoc markdown, use a bracketed Span of class allcaps: [TRAJAN]{.allcaps} - The produced LaTeX output has several requirements: - The Microtype package for tracking (i.e., its \\t...
#!/usr/bin/env python """ Panflute filter for setting C A P I T A L text, with tracking. Use if []{.smallcaps} is too weak. Usage: - In Pandoc markdown, use a bracketed Span of class allcaps: [TRAJAN]{.allcaps} - The produced LaTeX output has several requirements: - The Microtype package for tracking (i.e., its \\t...
en
0.59151
#!/usr/bin/env python Panflute filter for setting C A P I T A L text, with tracking. Use if []{.smallcaps} is too weak. Usage: - In Pandoc markdown, use a bracketed Span of class allcaps: [TRAJAN]{.allcaps} - The produced LaTeX output has several requirements: - The Microtype package for tracking (i.e., its \\textl...
2.54065
3
sdk/python/pulumi_aws_native/apigateway/get_gateway_response.py
pulumi/pulumi-aws-native
29
6622232
<filename>sdk/python/pulumi_aws_native/apigateway/get_gateway_response.py # coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, M...
<filename>sdk/python/pulumi_aws_native/apigateway/get_gateway_response.py # coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, M...
en
0.731317
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** A Cloudformation auto generated ID. The response parameters (paths, query strings, and headers) for the response. The response templates for the respons...
1.821557
2
keshe/models.py
kongqiahaha/databasekeshe
0
6622233
<filename>keshe/models.py<gh_stars>0 from django.utils import timezone from django.contrib.auth.models import User from django.db import models # Create your models here. # 图书 class Book(models.Model): b_id = models.AutoField(primary_key=True) b_name = models.CharField(max_length=30) b_author = models.Ch...
<filename>keshe/models.py<gh_stars>0 from django.utils import timezone from django.contrib.auth.models import User from django.db import models # Create your models here. # 图书 class Book(models.Model): b_id = models.AutoField(primary_key=True) b_name = models.CharField(max_length=30) b_author = models.Ch...
zh
0.67504
# Create your models here. # 图书 # 老师 # 学生 # 职称类型 # 老师借阅 # 学生借阅 # 图书类型
2.459894
2
tests/hmc_test.py
dfm/rmhmc
4
6622234
import jax.numpy as jnp import numpy as np from jax import random from rmhmc.hmc import hmc from .problems import banana def test_divergence() -> None: system = hmc(banana(False, False), initial_step_size=1000.0) state = system.init(jnp.array([0.3, 0.5])) state_ = system.step(state, random.PRNGKey(5)) ...
import jax.numpy as jnp import numpy as np from jax import random from rmhmc.hmc import hmc from .problems import banana def test_divergence() -> None: system = hmc(banana(False, False), initial_step_size=1000.0) state = system.init(jnp.array([0.3, 0.5])) state_ = system.step(state, random.PRNGKey(5)) ...
none
1
2.369296
2
control_input_value.py
EFatihAydin/random_sentence
0
6622235
from functools import reduce import numpy as np #clean : clean text by turkish words def clean(text): d = { "Ş":"ş", "İ":"i", "Ü":"ü", "Ç":"ç", "Ö":"ö", "Ğ":"ğ", "I":"ı", "Î":"ı", "Û":"u", "Â":"a" , "â":"a" , "î":"ı" , "û":"u" } text = reduce( lambda x, y: x.replace( y,d[y] ),d,text ) text = text.lower() text = t...
from functools import reduce import numpy as np #clean : clean text by turkish words def clean(text): d = { "Ş":"ş", "İ":"i", "Ü":"ü", "Ç":"ç", "Ö":"ö", "Ğ":"ğ", "I":"ı", "Î":"ı", "Û":"u", "Â":"a" , "â":"a" , "î":"ı" , "û":"u" } text = reduce( lambda x, y: x.replace( y,d[y] ),d,text ) text = text.lower() text = t...
en
0.548031
#clean : clean text by turkish words #trinity: parse line into three characters #variable #char: columns name for matrix #twchar: rows name for matrix #print(len(char))#53 #print(len(twchar))#2809 #add number to name for create matrix #print( mrowname ) #print( mcolname ) #read matrix in file #trial steps
3.742527
4
mundo_02_est_controle/ex052.py
icarofilho/estudonauta_python
0
6622236
num = int(input("Digite um número: ")) qtd = 0 for n in range(1,num+1): if num % n == 0: print(f"\033[34m{n}",end="\033[m ") qtd += 1 else: print(f"\033[33m{n}",end="\033[m ") if qtd == 2: print(f"\nO número {num} foi divisível {qtd} vezes.\nE por isso ele é PRIMO") else: print(...
num = int(input("Digite um número: ")) qtd = 0 for n in range(1,num+1): if num % n == 0: print(f"\033[34m{n}",end="\033[m ") qtd += 1 else: print(f"\033[33m{n}",end="\033[m ") if qtd == 2: print(f"\nO número {num} foi divisível {qtd} vezes.\nE por isso ele é PRIMO") else: print(...
none
1
4.043223
4
utils/quantize_model.py
raja-kumar/Hybrid_and_Non-uniform_quantization
0
6622237
import torch import torch.nn as nn import copy from .quantization_utils.quant_modules import * from pytorchcv.models.common import ConvBlock from pytorchcv.models.shufflenetv2 import ShuffleUnit, ShuffleInitBlock def quantize_model(model): """ Recursively quantize a pretrained single-precision model...
import torch import torch.nn as nn import copy from .quantization_utils.quant_modules import * from pytorchcv.models.common import ConvBlock from pytorchcv.models.shufflenetv2 import ShuffleUnit, ShuffleInitBlock def quantize_model(model): """ Recursively quantize a pretrained single-precision model...
en
0.716891
Recursively quantize a pretrained single-precision model to int8 quantized model model: pretrained single-precision model # quantize convolutional and linear layers to 8-bit # quantize all the activation to 8-bit # recursively use the quantized module to replace the single-precision module freeze the activation ra...
2.607368
3
nucosMQ/nucosServer.py
NuCOS/nucosMQ
1
6622238
from __future__ import print_function from __future__ import absolute_import from .nucos23 import ispython3 if ispython3: import socketserver import queue else: import SocketServer as socketserver import Queue as queue from threading import Thread import time import copy import socket from ins...
from __future__ import print_function from __future__ import absolute_import from .nucos23 import ispython3 if ispython3: import socketserver import queue else: import SocketServer as socketserver import Queue as queue from threading import Thread import time import copy import socket from ins...
en
0.7116
#palace = {} #disconnect-handler #connect-handler #receive-handler cleans all traces of connection data in the globals close the socket if close-flag is True, otherwise not #except: # pass #TODO remove singular rooms #print(connection_sid, connection_auth, palace) The server handler class #longest possible open ...
1.957857
2
tdc3/models/py/data/Util.py
TDC3Tool/TDC3
0
6622239
from os import listdir from os.path import isfile, join from torch.utils.data import random_split def json_files_in_dir(dir): return [join(dir, f) for f in listdir( dir) if isfile(join(dir, f)) and f.endswith(".json")] def split_dataset(dataset, train_perc): print("Splitting data into training and v...
from os import listdir from os.path import isfile, join from torch.utils.data import random_split def json_files_in_dir(dir): return [join(dir, f) for f in listdir( dir) if isfile(join(dir, f)) and f.endswith(".json")] def split_dataset(dataset, train_perc): print("Splitting data into training and v...
none
1
2.747796
3
src/Crawler.py
dubzzz/py-linkedin-crawler
0
6622240
<reponame>dubzzz/py-linkedin-crawler<filename>src/Crawler.py import sys import json import re import requests from collections import deque class Crawler: # Static attributes PROFILE_URL = "https://www.linkedin.com/profile/view?id={id}" CONTACTS_PER_PROFILE = 10 PROFILE_CONTACTS = "https://www.linkedin...
import sys import json import re import requests from collections import deque class Crawler: # Static attributes PROFILE_URL = "https://www.linkedin.com/profile/view?id={id}" CONTACTS_PER_PROFILE = 10 PROFILE_CONTACTS = "https://www.linkedin.com/profile/profile-v2-connections?id={id}&offset={offset}&c...
en
0.812948
# Static attributes # Open login page in order to avoid CSRF problems # Find the form # Find relevant fields details # Add login/password in the fields # Log in # Save cookies for next calls Add a profile in self.to_be_tested Perform checks before adding anything # Check Crawl from connections conditions # Upda...
2.791581
3
ophelia/reactrole/dm_lock.py
zanzivyr/Ophelia
2
6622241
""" DM Queue Module. Pylint's too few public methods is disabled here since we're not really using DMLock for a purpose that something else might satisfy better, such as dataclasses. The implementation here can be hard to follow, and while there is a variable inside asyncio.Lock that would help with this (_waiters), ...
""" DM Queue Module. Pylint's too few public methods is disabled here since we're not really using DMLock for a purpose that something else might satisfy better, such as dataclasses. The implementation here can be hard to follow, and while there is a variable inside asyncio.Lock that would help with this (_waiters), ...
en
0.958774
DM Queue Module. Pylint's too few public methods is disabled here since we're not really using DMLock for a purpose that something else might satisfy better, such as dataclasses. The implementation here can be hard to follow, and while there is a variable inside asyncio.Lock that would help with this (_waiters), that...
2.873784
3
setup.py
janelia-pypi/lickport_array_python
0
6622242
import pathlib import codecs import setuptools here = pathlib.Path(__file__).resolve().parent with codecs.open(here.joinpath('DESCRIPTION.rst'), encoding='utf-8') as f: long_description = f.read() setuptools.setup( name='lickport_array_interface', use_scm_version = True, setup_requires=['setuptools...
import pathlib import codecs import setuptools here = pathlib.Path(__file__).resolve().parent with codecs.open(here.joinpath('DESCRIPTION.rst'), encoding='utf-8') as f: long_description = f.read() setuptools.setup( name='lickport_array_interface', use_scm_version = True, setup_requires=['setuptools...
none
1
1.297128
1
example.py
dogeplusplus/sandbox
0
6622243
import torch import torch.nn as nn import torch.nn.functional as F b = 20 t = 30 k = 10 x = torch.ones((b,t,k)) raw_weights = torch.bmm(x, x.transpose(1,2)) weights = F.softmax(raw_weights, dim=2) y = torch.bmm(weights, x) class SelfAttention(nn.Module): def __init__(self, k, heads=8): super().__init_...
import torch import torch.nn as nn import torch.nn.functional as F b = 20 t = 30 k = 10 x = torch.ones((b,t,k)) raw_weights = torch.bmm(x, x.transpose(1,2)) weights = F.softmax(raw_weights, dim=2) y = torch.bmm(weights, x) class SelfAttention(nn.Module): def __init__(self, k, heads=8): super().__init_...
none
1
2.633807
3
wifid.py
mertkoc/wifidirect_linux
1
6622244
<gh_stars>1-10 import os import time def _copy_file_no_overwriting(src, dst): import shutil if not os.path.isfile(dst): print('copying... ', dst) shutil.copyfile(src, dst) def setup_conf_files(): """Setup configuration files that are needed to run start_as_go~(). :return: None ...
import os import time def _copy_file_no_overwriting(src, dst): import shutil if not os.path.isfile(dst): print('copying... ', dst) shutil.copyfile(src, dst) def setup_conf_files(): """Setup configuration files that are needed to run start_as_go~(). :return: None """ dir_ = ...
en
0.762429
Setup configuration files that are needed to run start_as_go~(). :return: None # a directory those .conf files are in Starts a Wifi direct interface as GO (Tested on Fedora 26) 1. Destroy dhcpd and a wifi connection. (It usually takes some little time to kill off a wifi thing so wait for couple seconds...) ...
2.561586
3
Kai/python/modules/simpletrigger.py
NJManganelli/FourTopNAOD
1
6622245
import ROOT import collections, math from PhysicsTools.NanoAODTools.postprocessing.framework.datamodel import Collection, Object from PhysicsTools.NanoAODTools.postprocessing.framework.eventloop import Module class Trigger(Module): def __init__(self, Trigger): self.counting = 0 self.maxEventsToProc...
import ROOT import collections, math from PhysicsTools.NanoAODTools.postprocessing.framework.datamodel import Collection, Object from PhysicsTools.NanoAODTools.postprocessing.framework.eventloop import Module class Trigger(Module): def __init__(self, Trigger): self.counting = 0 self.maxEventsToProc...
en
0.654863
process event, return True (go to next module) or False (fail, go to next event) #First N events #run = getattr(event, "run") #evt = getattr(event, "event") #lumi = getattr(event, "luminosityBlock") #print(getattr(event, trig)) #else: #print("No trigger fired")
2.452106
2
Display/Pages/RoomPage.py
nataliap13/PT-Warcaby
0
6622246
from selenium.webdriver.common.by import By from Locators import Locator class Room(object): def __init__(self, driver): self.driver = driver self.KindOfRoom = driver.find_element(By.XPATH, Locator.KindOfRoom) def click_OpenList(self): self.KindOfRoom.click()
from selenium.webdriver.common.by import By from Locators import Locator class Room(object): def __init__(self, driver): self.driver = driver self.KindOfRoom = driver.find_element(By.XPATH, Locator.KindOfRoom) def click_OpenList(self): self.KindOfRoom.click()
none
1
2.68371
3
TEST3D/GUI/0010200_page_pixsel/log.py
usnistgov/OOF3D
31
6622247
<gh_stars>10-100 # -*- python -*- # This software was produced by NIST, an agency of the U.S. government, # and by statute is not subject to copyright in the United States. # Recipients of this software assume all responsibilities associated # with its operation, modification and maintenance. However, to # facilitate ...
# -*- python -*- # This software was produced by NIST, an agency of the U.S. government, # and by statute is not subject to copyright in the United States. # Recipients of this software assume all responsibilities associated # with its operation, modification and maintenance. However, to # facilitate maintenance we as...
en
0.949105
# -*- python -*- # This software was produced by NIST, an agency of the U.S. government, # and by statute is not subject to copyright in the United States. # Recipients of this software assume all responsibilities associated # with its operation, modification and maintenance. However, to # facilitate maintenance we ask...
1.76617
2
RT_Task.py
SamuelBishop/AVSS
0
6622248
#!/usr/bin/python import queue import threading import time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, q): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.q = q def run(self): print("Starting " + self.name) ...
#!/usr/bin/python import queue import threading import time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, q): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.q = q def run(self): print("Starting " + self.name) ...
en
0.633932
#!/usr/bin/python # logging.error(time_now, e) # logging.error(time_now, e) # logging.error(timeNow, e) # Create new threads # Fill the queue # Wait for queue to empty # Notify threads it's time to exit # Wait for all threads to complete
3.201757
3
tti/utils/plot.py
Bill-Software-Engineer/trading-technical-indicators
68
6622249
""" Trading-Technical-Indicators (tti) python library File name: plot.py Plotting methods defined under the tti.utils package. """ import pandas as pd import matplotlib.pyplot as plt def linesGraph(data, y_label, title, lines_color, alpha_values, areas, x_label='Date'): """ Returns a line...
""" Trading-Technical-Indicators (tti) python library File name: plot.py Plotting methods defined under the tti.utils package. """ import pandas as pd import matplotlib.pyplot as plt def linesGraph(data, y_label, title, lines_color, alpha_values, areas, x_label='Date'): """ Returns a line...
en
0.734471
Trading-Technical-Indicators (tti) python library File name: plot.py Plotting methods defined under the tti.utils package. Returns a lines graph of type matplotlib.pyplot. The graph can be either a figure with a single plot, or a figure containing two vertical subplots. Parameters: data (panda...
3.60033
4
Python-For-Everyone-Horstmann/Chapter10-Inheritance/test_10_8.py
islayy/Books-solutions
0
6622250
<reponame>islayy/Books-solutions<gh_stars>0 # Unit tests for P10_8.py # IMPORTS from P10_8 import Person from P10_8 import Student import unittest class PersonTests(unittest.TestCase): def setUp(self): self.p = Person("John", 1986) def test_get_name(self): self.assertEqual("John", self.p.ge...
# Unit tests for P10_8.py # IMPORTS from P10_8 import Person from P10_8 import Student import unittest class PersonTests(unittest.TestCase): def setUp(self): self.p = Person("John", 1986) def test_get_name(self): self.assertEqual("John", self.p.get_name()) def test_get_birth_year(self)...
en
0.633987
# Unit tests for P10_8.py # IMPORTS # PROGRAM RUN
3.454525
3