max_stars_repo_path
stringlengths
3
269
max_stars_repo_name
stringlengths
4
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.05M
score
float64
0.23
5.13
int_score
int64
0
5
readfile.py
timfox456/testRNN
0
53400
<filename>readfile.py import numpy as np import scipy.io as scio import argparse import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt parser = argparse.ArgumentParser(description='Coverage Updating Plot') parser.add_argument('--output', dest='filename', default='./log_folder/record.txt', help='') pa...
2.59375
3
tests/api_interface/test_runbooks/test_files/parallel_task.py
tuxtof/calm-dsl
37
53401
""" Calm DSL Sample Runbook for parallel task """ from calm.dsl.runbooks import runbook, parallel, branch from calm.dsl.runbooks import RunbookTask as Task @runbook def ParallelTask(): "Runbook Service example" with parallel() as p: with branch(p): Task.Delay(60, name="Delay1") w...
2.46875
2
server.py
awstanley/swm.js
0
53402
<filename>server.py<gh_stars>0 #!/bin/env python3 import sys import socketserver from http.server import SimpleHTTPRequestHandler class TestServer(SimpleHTTPRequestHandler): def end_headers(self): self.send_header('Access-Control-Allow-Origin', '*') SimpleHTTPRequestHandler.end_he...
2.609375
3
.ci/test_lint_doctests.py
ravi-mosaicml/ravi-composer
0
53403
<filename>.ci/test_lint_doctests.py<gh_stars>0 # Pytest stub for running lint tests and doctests # Running these checks through pytest allows us to report any errors in Junit format, # which is posted directly on the PR import os import pathlib import shutil import subprocess import textwrap import pytest def chec...
2.15625
2
cogs/helpers/gamedeals.py
santoshpanna/Discord-Bot
0
53404
<filename>cogs/helpers/gamedeals.py import re from common import database, common # acceptable store list # TODO - shift to database stores = ['steampowered.com', 'humblebundle.com', 'epicgames.com', 'reddit.com'] steamlinks = ('steampowered.com/app', 'steampowered.com/bundle', 'steampowered.com/sub') # removes uri ...
2.46875
2
bot/__main__.py
Temmon/Bibliomantic_Oracles
11
53405
<filename>bot/__main__.py from bot import bot bot.bot.run(bot.getToken())
1.34375
1
modules/templates.py
w-renk/p2e-monbuild
0
53406
from .scripts import ClearScreen from PyInquirer import prompt def SelectTemplateGraft(statBlock): ClearScreen() print("You can optionally use a template graft to start the creation process. Template grafts grant specific bonuses and unique abilities. They also " + "largely determine the creature t...
2.546875
3
photo2tactile.py
jolks/tactile_patterns
14
53407
""" Convert scenery image to tactile image. # Algorithm 1. Read scenery image. 2. Grayscale. 3. Histogram equalize. 4. Compute fine-grained saliency map. 5. Scale to [0, 255] 6. Compute binary threshold map. 7. Invert binary threshold map. 8. Write tactile image. References at the corresponding source code below. """...
3.203125
3
src/new/main.py
AIM-Harvard/DeepConstrast
3
53408
import os import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as pltimport glob from time import gmtime, strftime from datetime import datetime import timeit import yaml from tensorflow.keras.optimizers import Adam import argparse from get_data.get_img_dataset import get_img_dataset from g...
1.859375
2
codelab/DDP/train.py
LIZHICHAOUNICORN/Toolkits
0
53409
<reponame>LIZHICHAOUNICORN/Toolkits<filename>codelab/DDP/train.py import argparse import logging import yaml import torch import torch.distributed as dist import torch.optim as optim from torch.optim.lr_scheduler import StepLR import torch.nn.functional as F from torch.nn.parallel import DistributedDataParallel as DDP...
2.1875
2
oef/query.py
ip-config/oef-sdk-python
2
53410
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018 Fetch.AI Limited # # 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 Lice...
1.664063
2
waveform.py
nenslen/chords
1
53411
<filename>waveform.py<gh_stars>1-10 import numpy as np import matplotlib.pyplot as plt import wavio plt.style.use('ggplot') class Waveform: def __init__(self, points, sample_rate=44100): ''' Parameters ---------- points : list of floats The points of this waveform ...
2.875
3
train_switch_joint_obs.py
rossamurphy/pytorch-dqn
0
53412
<reponame>rossamurphy/pytorch-dqn<gh_stars>0 import datetime as dt from pathlib import Path import time from typing import List import numpy as np from torch.utils.tensorboard import SummaryWriter import gym import ma_gym from ma_gym.wrappers import Monitor from agent import DQNAgent from agent_args import AGENT_ARG...
2.0625
2
algorithm/greedy.py
CodeSopranos/KnapsackProblem
4
53413
import numpy as np from algorithm.base import Algorithm class Greedy(Algorithm): def __init__(self, knapsack): assert isinstance(knapsack, dict) self.capacity = knapsack['capacity'][0] self.weights = knapsack['weights'] self.profits = knapsack['profits'] self.n = ...
3.40625
3
main/tools.py
dario-fumarola/nQueens
0
53414
""" File: tools.py """ import random import time def getRandomList(n): """Returns a list of unique random numbers in the range 0..n-1""" items = list(range(n)) random.shuffle(items) return items def compare(titleList, functionList, sizeList, dataSet=lambda x: x, counter=None, compar...
3.859375
4
metrics.py
fair-trec/trec2021-fair-public
3
53415
<filename>metrics.py """ Implementation of metrics for TREC Fair Ranking 2021. """ import logging import numpy as np import pandas as pd from scipy.spatial.distance import jensenshannon _log = logging.getLogger('metrics') world_pop = pd.Series({ 'Africa': 0.155070563, 'Antarctica': 1.54424E-07, 'Asia': 0...
2.625
3
grove/grove_button.py
chousemath/grove.py
0
53416
#!/usr/bin/env python # # This library is for Grove - Button(https://www.seeedstudio.com/s/Grove-Button-p-766.html) # # This is the library for Grove Base Hat which used to connect grove sensors for raspberry pi. # ''' ## License The MIT License (MIT) Grove Base Hat for the Raspberry Pi, used to connect grove senso...
1.960938
2
pso.py
pgalatic/graph-heuristic-study
0
53417
<reponame>pgalatic/graph-heuristic-study<filename>pso.py # author: <NAME> # # Graph heuristic study -- particle swarm optimization # # https://en.wikipedia.org/wiki/Particle_swarm_optimization # standard lib import sys import math import copy import random import operator # required lib import numpy as np # project ...
2.9375
3
python/dataset/tatoeba_loader.py
yweweler/ctc-asr
1
53418
"""Load the Tatoeba dataset.""" import sys import os import csv import subprocess import time from multiprocessing import Pool, Lock, cpu_count from tqdm import tqdm from scipy.io import wavfile from python.params import MIN_EXAMPLE_LENGTH, MAX_EXAMPLE_LENGTH from python.dataset.config import CACHE_DIR, CORPUS_DIR f...
2.40625
2
aiotdlib/api/types/mask_position.py
jraylan/aiotdlib
37
53419
# =============================================================================== # # # # This file has been generated automatically!! Do not change this manually! # # ...
2.921875
3
app.py
venkattrj/Refresh
0
53420
from flask import Flask, request, json from TextSummarizer import Preprocess app = Flask(__name__) app.debug = True @app.route('/summarize', methods=['POST']) def summrize(): text = request.json['text'] serve = Preprocess() log, slead, srefresh, sgold = serve.run_textmode(text) return json.dumps({'st...
2.4375
2
main.py
SamanBeh/MLpkg
0
53421
''' This is a ready to use package consisting of several supervised machine learning algorithms with a predefined parameter-grid (which then you can update its values) to fine tune these models on your data. You can calculate some features from your peptides data set using our feature extraction tool to feed these ...
2.78125
3
api/utils/input/__init__.py
mmangione/alcali
306
53422
from shlex import split import json class RawCommand: def __init__(self, command, client="local", posix=True, inline=False): # TODO: check shlex.quote, raw string, etc.. if inline: self.command = split(command, posix=posix) else: self.command = split(command, posix=...
2.484375
2
fcrepo_verify/iterators.py
awoods/fcrepo-import-export-verify
5
53423
<reponame>awoods/fcrepo-import-export-verify from os.path import basename, isfile from .utils import get_directory_contents, get_child_nodes from .utils import get_data_dir class Walker: """Walk a set of Fedora resources.""" def __init__(self, root, logger): self.to_check = [root] self.logger ...
2.375
2
parallel_gradient/parallel_gradient.py
gschramm/python_tutorials
0
53424
# script to test the parallelized gradient / divergence from pymirc import numpy as np import pymirc.image_operations as pi # seed the random generator np.random.seed(1) # create a random 3D/4D image shape = (6,200,190,180) # create random array and pad with 0s x = np.pad(np.random.rand(*shape), 1) # allocate arra...
2.75
3
enthought/developer/helper/image_library_editor.py
enthought/etsproxy
3
53425
<reponame>enthought/etsproxy # proxy module from __future__ import absolute_import from etsdevtools.developer.helper.image_library_editor import *
0.96875
1
tests/test_ns.py
TheCuriousNerd/happy-transformer
277
53426
from happytransformer import HappyNextSentence def test_sp_true(): happy_ns = HappyNextSentence() result = happy_ns.predict_next_sentence( "Hi nice to meet you. How old are you?", "I am 21 years old." ) assert result > 0.5 def test_sp_false(): happy_ns = HappyNextSentence() r...
2.65625
3
setup.py
slafi/pysqlizer
0
53427
from setuptools import setup with open("Readme.md", 'r') as f: long_description = f.read() setup( name='pysqlizer', version='1.0', description='A module that can be used to convert a CSV file into a SQL file', author='<NAME>', author_email='<EMAIL>', url="https://github.com/slafi", license="M...
1.65625
2
notes/notes/profiles/urls.py
BoyanPeychinov/python_web_basics
1
53428
<filename>notes/notes/profiles/urls.py from django.urls import path from notes.profiles.views import show_profile, create_profile, delete_profile urlpatterns = [ path('', show_profile, name='show profile'), path('create/', create_profile, name='create profile'), # path('edit/<int:pk>', edit_profile, 'edit...
1.921875
2
TransaqReplayServer.py
dandolbilov/TransaqReplayer
0
53429
<reponame>dandolbilov/TransaqReplayer<gh_stars>0 # -*- coding: utf-8 -*- """ File: TransaqReplayServer.py Author: <NAME> Created: 18-Oct-2020 """ import logging import threading import time from multiprocessing.connection import Listener class TransaqReplayServer: def __init__(self, xdf_file, ho...
2.296875
2
modules/CalDavManager/__init__.py
Majroch/anime-checker
0
53430
<reponame>Majroch/anime-checker<filename>modules/CalDavManager/__init__.py<gh_stars>0 from modules.Config import Config import datetime from urllib.parse import urlparse import os try: import vobject #pylint: disable=import-error except ImportError: print("No module found: vobject. Trying to Install") try:...
2.359375
2
grid/grid_world.py
akurmustafa/rl
0
53431
import numpy as np class Grid: def __init__(self, width, heigth, discount = 0.9): self.width = width self.heigth = heigth self.x_pos = 0 self.y_pos = 0 self.values = np.zeros((heigth, width)) self.discount = discount self.vertex_sources = [] self.vert...
2.890625
3
nemo/utils/formatters/utils.py
borisdayma/NeMo
10
53432
# Copyright (C) <NAME>. All Rights Reserved. # # 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 agree...
2.15625
2
proj/ud120-projects/choose_your_own/test.py
askldjd/udacity-machine-learning
2
53433
<filename>proj/ud120-projects/choose_your_own/test.py from sklearn.cross_validation import cross_val_score from sklearn.datasets import load_iris from sklearn.ensemble import AdaBoostClassifier iris = load_iris() clf = AdaBoostClassifier(n_estimators=100) scores = cross_val_score(clf, iris.data, iris.target) print scor...
2.5
2
faker_nonprofit/__init__.py
SFDO-Community-Sprints/Snowfakery-Nonprofit
0
53434
<reponame>SFDO-Community-Sprints/Snowfakery-Nonprofit """Provider for Faker which adds fake nonprofit names, and program names.""" import faker.providers PREFIXES = [ '', '1st', '2nd', 'Best', 'Eastern', 'Friends of the', 'Legal', 'Lower', 'Northern', 'Southern', 'Upper', ...
1.671875
2
bagpy/__init__.py
jmscslgroup/rosbagpy
107
53435
<reponame>jmscslgroup/rosbagpy # Initial Date: March 2, 2020 # Author: <NAME> # Copyright (c) <NAME>, Arizona Board of Regents # All rights reserved. from .bagreader import bagreader from .bagreader import animate_timeseries from .bagreader import create_fig
1.15625
1
Festival/Festival_StreamlabsSystem.py
NewtC1/Salamandbot
0
53436
#!/usr/bin/python # -*- coding: utf-8 -*- # pylint: disable=invalid-name """Let viewers pay currency to boost currency payouts for everyone in chat for x seconds""" import json import os, os.path import operator import time import codecs #--------------------------------------- # [Required] Script information #-------...
2.34375
2
training/encoder.py
BinahHu/stylegan2
0
53437
import numpy as np import tensorflow as tf #---------------------------------------------------------------------------- # Encoder network. # Extract the feature of content and style image # Use VGG19 network to extract features. ENCODER_LAYERS = ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2...
2.53125
3
src/dataloaderinterface/urls.py
ODM2/ODM2DataSharingPortal
18
53438
"""WebSDL URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-base...
2.546875
3
warmup_1/parrot_trouble.py
nhutnamhcmus/coding-bat-solutions
1
53439
# ======================================================================================================================================= # VNU-HCM, University of Science # Department Computer Science, Faculty of Information Technology # Authors: <NAME> (<NAME>) # © 2020 """ We have a loud talking parrot. The "hour" ...
3.71875
4
Signal-Viewer/Signal-Viewer.py
Radwa-Saeed/Didital-Signal-Processing-PyQt-GUI
0
53440
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'newGui.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, ...
2.28125
2
optimal_transport_morphometry/core/rest/__init__.py
girder/otm-server
0
53441
from .atlas import AtlasViewSet from .dataset import DatasetViewSet from .feature_image import FeatureImageViewSet from .image import ImageViewSet from .jacobian_image import JacobianImageViewSet from .pending_upload import PendingUploadViewSet from .preprocess import PreprocessingViewSet from .registered_image import ...
1.171875
1
src/docs/rizvi2017_sakmapper/sakmapper/network.py
SMRUCC/Erica
0
53442
<filename>src/docs/rizvi2017_sakmapper/sakmapper/network.py from math import sqrt import numpy as np import pandas as pd from scipy.spatial.distance import pdist, squareform, euclidean import networkx as nx from sklearn import cluster from lens import apply_lens import scipy def davies_bouldin(dist_mu, sigma): DB...
2.1875
2
iso8583_dlib/parser.py
eocode/ISO8583-Dlib
0
53443
"""Main Parser Class""" import json from .segments.utilities.operations import convert_bitmap_to_active_bits from .segments.iso import ISO from .segments.header import Header from .segments.mti import MTI from .segments.primary_bitmap import PrimaryBitmap from .segments.data_elements import DataElements class Parser...
2.921875
3
league_builder.py
Nocks/Soccer-League
0
53444
<reponame>Nocks/Soccer-League<filename>league_builder.py<gh_stars>0 import csv import random # read and copy details of players from the supplied CSV file def load_players(filename, all_players): with open(filename, 'r') as csvfile: players = csv.DictReader(csvfile, delimiter=',') for player in pla...
3.59375
4
binp/action.py
reddec/binp
0
53445
from dataclasses import dataclass from logging import getLogger from typing import List, Callable, Awaitable, Optional, Dict from pydantic.main import BaseModel @dataclass class ActionHandler: name: str description: str handler: Callable[[], Awaitable] async def __call__(self): return await ...
2.859375
3
cnetzer/day2/day2.py
chadnetzer/advent2020
0
53446
from collections import Counter def parse_policy(policy): range_str, c = policy.split() lo,hi = range_str.split('-') lo,hi = int(lo),int(hi) return lo,hi,c def pwcheck(pw, policy): counts = Counter(pw) lo,hi,char = parse_policy(policy) if char not in counts: return False retu...
3.515625
4
GamePlay.py
maxm897/pentagoAI
4
53447
#GamePlay.py #<NAME>, <NAME>, <NAME> """This module contains the functions needed to support pentago gameplay. A pentago gameboard is represented by a 6x6 2D array. Each location on the board is initialized to "" and is set to 0 or 1 when the player or the AI respectively places a marble on that location. Each ar...
3.859375
4
archived/silbiocomp/Practicals/Code/oaks_test.py
mathemage/TheMulQuaBio
1
53448
<reponame>mathemage/TheMulQuaBio #Define function def is_an_oak(name): """ Returns True if name is starts with 'quercus' >>> is_an_oak('<NAME>') False >>> is_an_oak('<NAME>') True # A typo >>> is_an_oak('Quercuss') False """ return name.lower().startswith('quercus ') print(is...
3.109375
3
python/__init__.py
MSFPT/JsonBase
1
53449
<filename>python/__init__.py<gh_stars>1-10 # https://github.com/MSFPT/JsonBase import json class JsonBase(): def __init__(self,file_db: str) : try: self.file = open(file_db,'r+') except FileNotFoundError as ferr : with open(file_db,'w+')as f:f.close() self.file = open(file_db,'r+') ...
3.21875
3
hello.py
PowerSnail/cs3240-labdemo-hj5fb
0
53450
from helper import * # add a comment greeting('jin')
1.34375
1
data_exploration/explore.py
billylegota/ECE-380L-Term-Project
0
53451
import h5py import matplotlib.pyplot as plt import numpy as np import scipy.io import scipy.stats import complex_pca def plot_pca_variance_curve(x: np.ndarray, title: str = 'PCA -- Variance Explained Curve') -> None: pca = complex_pca.ComplexPCA(n_components=x.shape[1]) pca.fit(x) plt.figure() plt.p...
2.671875
3
setup.py
MiCHiLU/watchlion
1
53452
<reponame>MiCHiLU/watchlion #!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages setup(name="watchlion", version="0.3", description="Filesystem events monitoring", long_description=open('README.rst').read(), author="<NAME>", license="MIT", url="...
1.046875
1
utils/eval_utils.py
alon-albalak/XOR-COVID
1
53453
import sys import re import string from collections import Counter import pickle def normalize_answer(s): def remove_articles(text): return re.sub(r'\b(a|an|the)\b', ' ', text) def white_space_fix(text): return ' '.join(text.split()) def remove_punc(text): exclude = set(string....
2.71875
3
core/snippets.py
admariner/madewithwagtail
0
53454
from django.db import models from django.utils.encoding import python_2_unicode_compatible from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel, MultiFieldPanel, PageChooserPanel from wagtail.wagtailcore.mode...
1.953125
2
Hl7_Parser.py
AnaniSkywalker/HL7_Parser
1
53455
## Author: <NAME> import json import io import os import re from hl7apy.parser import parse_message from hl7apy.exceptions import UnsupportedVersion #receives the name of the file and reads the messages in the file def readMessageFile(filename): #read the file message = open(filename, 'r').read() print("St...
2.9375
3
cloud/blog/tests.py
XINGYANGSOFT/HuaZhang-Data-Engine
0
53456
# -*- coding:utf-8 -*- import urllib import urllib.request import json import django.utils.http from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from operator import itemgetter # 排序 import time from django.core.paginator import Paginator servers = ['127.0.0.1:8100', '127.0....
2.15625
2
top50.py
liyongyue/dnsspider
0
53457
from dnsget import dnsget from analyse_dependency import a_d f=open("targetd2") line=f.readline().strip('\n') o=open("targetd2r",'w') target=[] name="top50" while (line): target.append(line) line=f.readline().strip('\n') r=dnsget(target,name) a_d(name) f.close() o.close()
2.6875
3
compmech/conecyl/imperfections/imperfections.py
mrosemeier/compmech
4
53458
import os from random import sample import numpy as np from numpy import cos from scipy.linalg import lstsq from compmech.constants import CMHOME from compmech.logger import * def load_c0(name, funcnum, m0, n0): path = os.path.join(CMHOME, 'conecyl', 'imperfections', 'c0', 'c0_{0}_f{1}_m{2:03d}_n{3:0...
2.125
2
habanero/habanero_utils.py
Maocx/habanero
0
53459
<filename>habanero/habanero_utils.py import re import requests from . import __version__ from .response import Works from .noworks import NoWorks # helpers ---------- def converter(x): if(x.__class__.__name__ == 'str'): return [x] else: return x def sub_str(x, n = 3): if(x.__class__.__name__ == 'No...
2.3125
2
search/serialize/__init__.py
ID2797370/arxiv-search
35
53460
<filename>search/serialize/__init__.py """Provides serialization functions for API responses.""" __all__ = ["JSONSerializer", "as_json", "AtomXMLSerializer", "as_atom"] from search.serialize.json import JSONSerializer, as_json from search.serialize.atom import AtomXMLSerializer, as_atom
1.703125
2
boj/1439.py
JeongHoLim/practice
1
53461
<gh_stars>1-10 def func(s): one = 0 zero = 0 for i in range(len(s)): if i > 0 and s[i] == s[i-1] : continue if s[i] == "1": one += 1 else : zero += 1 return min(one,zero) s = input() print(func(s))
3.0625
3
cs294/hw4/controllers.py
Rolight/Mooc-Assignments
0
53462
import numpy as np from cost_functions import trajectory_cost_fn import time class Controller(): def __init__(self): pass # Get the appropriate action(s) for this state(s) def get_action(self, state): pass class RandomController(Controller): def __init__(self, env): """ YOUR...
3.453125
3
modeling/localization_ACRM.py
tanghaoyu258/ACRM-for-moment-retrieval
18
53463
import torch import numpy as np from torch import nn from torch.nn import functional as F # from modeling.dynamic_filters.multiheadatt import TransformerBlock from modeling.dynamic_filters.build import DynamicFilter,ACRM_query,ACRM_video from utils import loss as L from utils.rnns import feed_forward_rnn import utils.p...
2.34375
2
gridGrab.py
KaiLangen/Dual_Sudoku_Solver
0
53464
<gh_stars>0 import cv2 import numpy as np import matplotlib.pyplot as plt def preprocessing(img): # gaussian blur image and convert to grayscale blur = cv2.GaussianBlur(img, (5,5), 0) gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY) # perform a close operation kernel = cv2.getStructuringElement(cv2.M...
2.734375
3
src/topological_navigation/scripts/topological_map.py
LCAS/spqrel_navigation
28
53465
<gh_stars>10-100 import yaml from topological_node import TopologicalNode class TopologicalMap(object): def __init__(self, filename=None): if filename: lnodes = self._load_map(filename) self.nodes = self._get_nodes(lnodes) else: self.nodes = [] def _get_no...
2.765625
3
AlgorithmProblems/0348. Design Tic-Tac-Toe/348. Design Tic-Tac-Toe.py
lynnli92/leetcode-group-solution
4
53466
<gh_stars>1-10 """ We use row status, col status and diagonal status to track each row, column, diagonal in board. For example, in row status, the ith element [a, b] means player1 has filled n-a positions in current row and player2 filled n-b positions. Once this value reaches 0, that means all positions in current ro...
3.859375
4
mutations/__init__.py
tomergt45/Geneticflow
0
53467
<reponame>tomergt45/Geneticflow #!/usr/bin/env python # coding: utf-8 # In[1]: import os, sys sys.path.append(os.path.realpath('..')) import tensorflow as tf import numpy as np import string import utils # In[6]: def get(name): """ Returns a mutation by name, this can be a function or a class name, in ...
3.421875
3
tests/resource_tests.py
cgalleguillosm/accasim
3
53468
import os import sys import json accasim = os.path.abspath(os.path.join('../../accasim')) sys.path.insert(0, accasim) import unittest from accasim.base.resource_manager_class import Resources class ResourcesTests(unittest.TestCase): def load_sys_config(self): fp = 'data/system_def.con...
2.59375
3
src/models/layers.py
voreille/plc_seg
0
53469
<reponame>voreille/plc_seg<filename>src/models/layers.py import tensorflow as tf class ResidualLayer2D(tf.keras.layers.Layer): def __init__(self, *args, activation='relu', **kwargs): super().__init__() self.filters = args[0] self.conv = tf.keras.layers.Conv2D(*args, ...
2.53125
3
redditnfl/rnfltools/vet.py
redditnfl/rnfl-tools
0
53470
#!/usr/bin/env python3 import traceback from progressbar import ProgressBar, ETA, FormatLabel, Bar import csv import requests from bs4 import BeautifulSoup from datetime import datetime from praw import Reddit from redditnfl.reddittools.reddittoken import ensure_scopes import sys import pytz EST = pytz.timezone('Amer...
2.703125
3
experimental/blender/spheres.py
mcarlen/libbiarc
0
53471
""" Use this script to generate a *thick* wireframe with spheres as joints. The input file (currently /tmp/wire.txt) is the output file from the tool pkf2mesh! Adjust SRadius for the cylinder size. The sphere size is 6*SRadius, change it as well if needed. """ from Blender import * from Blender.Mathutils im...
2.953125
3
generateKeys.py
jeremywgleeson/Corec-AutoSchedule-Avail
1
53472
import random import string import json import os KEYS_FILE = os.path.join(os.path.dirname(os.path.realpath(__file__)), "project", "keys_file.json") def get_random_alphanumeric_string(length): letters_and_digits = string.ascii_letters + string.digits result_str = ''.join((random.choice(letters_and_digits) for...
3.28125
3
scripts/random-time.py
epochblue/annoy-a-tron
63
53473
#!/usr/bin/env python import random import subprocess HOURS = range(1, 13) MINUTES = ["o'clock"] + ["o %s" % x for x in range(1, 10)] + range(10, 60) AM_PM = ['a.m.', 'p.m.'] TIME = 'it is now {} {} {}'.format(random.choice(HOURS), random.choice(MINUTES), ...
2.546875
3
snippets/frame2lines.py
district10/snippet-manager
7
53474
# n points def lerp_line(pt0, pt1, n): pts = [] for i in range(n + 1): t = i / float(n) pt = pt0 * t + pt1 * (1.0 - t) pts.append(pt) return pts def pole_to_lines(pt0, pt1, color=[0, 255, 0], n=20): lines = [] pts = lerp_line(pt0, pt1, n) for pt in pts: lines.ap...
2.234375
2
flapison/querystring.py
Leechael/flapison
13
53475
# -*- coding: utf-8 -*- """Helper to deal with querystring parameters according to jsonapi specification""" import json from flask import current_app from flapison.exceptions import ( BadRequest, InvalidFilters, InvalidSort, InvalidField, InvalidInclude, ) from flapison.schema import get_model_f...
2.796875
3
src/_Image_Env/MetaData.py
krisHans3n/ifd_standardised_api_prod
0
53476
<reponame>krisHans3n/ifd_standardised_api_prod class MetaData: ''' convert to dynamically adding attributes by passing in **kwargs and setting each key value pair attention will need to be given for when this class is used in other processes to make sure they know the attributes that exists with ea...
2.4375
2
dsat/request.py
uba/DSAT-cli
0
53477
# Copyright (C) 2021-2022 INPE. # DSAT-Cli is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. __author__ = '<NAME>' __email__ = '<EMAIL>' from dsat import cache from dsat.config import Config from dsat.utils import computeImageSize, cre...
2.109375
2
Car_Pedestrian_tracker.py
zbaban/Car-and-Pedestrian-Tracking
0
53478
<gh_stars>0 import cv2 # Our Image img_file = "Car_Image.jpg" video = cv2.VideoCapture('NYC.mp4') # Our pre-trained car classifier vehichle_tracker_file = "vehichle_detector.xml" pedestrian_tracker_file = "pedestrian_detector.xml" #create car and pedestrains lassifier car_tracker = cv2.CascadeClassifier(vehichle_t...
3.265625
3
dtrace_ctypes/consumer.py
arichardson/l41-python-dtrace
1
53479
""" The implementation of the consumer. Created on Oct 10, 2011 @author: tmetsch """ from ctypes import cdll, CDLL, byref, c_int, c_char_p, CFUNCTYPE, c_void_p, \ POINTER, cast from dtrace_ctypes.dtrace_structs import dtrace_bufdata, dtrace_probedata, \ dtrace_aggdata, dtrace_recdesc from threading import Th...
2.734375
3
opennem/core/downloader.py
paulculmsee/opennem
0
53480
import logging from io import BytesIO from zipfile import ZipFile from opennem.utils.handlers import _handle_zip, chain_streams from opennem.utils.http import http from opennem.utils.mime import mime_from_content, mime_from_url logger = logging.getLogger("opennem.downloader") def url_downloader(url: str) -> bytes: ...
2.5625
3
Item.py
Luigimonbymus/Modern-Quest
1
53481
<reponame>Luigimonbymus/Modern-Quest<filename>Item.py class item(): def ___init___(self, name, desc, worth): self.name=name self.desc=desc self.worth=worth def _str_(self): return "{}\n=====\n{}\nWorth: {}\n".format(self.name, self.desc, self.worth) class money(item): def __...
3.390625
3
tools/faker_docs_utils/faker_markdown.py
abeyerpath/Snowfakery
81
53482
import re from functools import lru_cache from pathlib import Path import typing as T from yaml import dump as yaml_dump from faker import Faker from faker.config import AVAILABLE_LOCALES from tools.faker_docs_utils.format_samples import ( yaml_samples_for_docstring, snowfakery_output_for, ) from .summarize_fa...
2.265625
2
13/13.py
teagles/teagles-pc
0
53483
<reponame>teagles/teagles-pc #!/usr/bin/env python # http://huge:<EMAIL>@www.<EMAIL>.com/pc/return/disproportional.html import sys import xmlrpclib URL = 'http://www.pythonchallenge.com/pc/phonebook.php' # 13/13.py Bert def main(args=None): if args is None: args = sys.argv[1:] s = xmlrpclib.ServerPro...
2.09375
2
python/py-entrypoints/files/setup.py
svalgaard/macports-ports
1
53484
from distutils.core import setup setup( name='entrypoints', version='0.2.2', description='Discover and load entry points from installed packages.', author='<NAME>', author_email='<EMAIL>', url='https://github.com/takluyver/entrypoints', py_modules=['entrypoints'], )
1.195313
1
seamm_installer/__main__.py
molssi-seamm/seamm_installer
1
53485
# -*- coding: utf-8 -*- """The main module for running the SEAMM installer. """ import argparse import logging import sys import seamm_installer logger = logging.getLogger(__name__) def run(): """Run the installer. How the installer runs is controlled by command-line arguments. We need the installer ...
2.5625
3
psystem/create_stegotons/run_psystem.py
ranocha/Dispersive-wave-error-growth-notebooks
0
53486
#!/usr/bin/env python # encoding: utf-8 import sys import os sys.path.append('./../') from petsc4py import PETSc if __name__=="__main__": from psystem import * refn = 7 # goal 7 (1024 DoFs) outdir = './_output' rank = PETSc.COMM_WORLD.rank if rank==0: if not os.path.exists(outdir): os.mkdi...
2.015625
2
Jarvis/BadDataDetector/get_keywords.py
rafarrel/Jarvis
0
53487
<gh_stars>0 """ This file was used to generate the keywords used in the bad data detector. We manually edited/cleaned the generated keywords after to better reflect the data and remove fringe/minimally related keywords that don't convey any meaning. DO NOT RUN THIS FILE as it will overwrite our cleaned keywords. """ ...
2.671875
3
diffuse/diffuser/tests/base.py
asandeep/diffuse
1
53488
import os import time from concurrent import futures from contextlib import contextmanager from unittest import mock import pytest import diffuse from diffuse.diffuser.base import pool def target(msg): return f"hello {msg}" def target_exception(msg): raise ValueError("Test") def target_long_running(msg)...
2.15625
2
regmap/bin/regmap.py
stefanct/pulp-tools
0
53489
# # Copyright (C) 2018 ETH Zurich, University of Bologna # and GreenWaves Technologies # # 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 # # U...
1.898438
2
process.py
darthbatman/MachineryMonitor
0
53490
import h5py from os import listdir, getcwd from os.path import isfile, join def hdf_to_csv(): path = getcwd() + '/2020_Challenge_IOT_Analytics/competitionfiles' files = [f for f in listdir(path) if isfile(join(path, f))] for file in files: rf = h5py.File(path + '/' + file, 'r') chanIDs = r...
2.515625
3
gloop/clients/match.py
pitzer42/nano_tcg
1
53491
<gh_stars>1-10 from abc import ABC from gloop.entities.match import Match from gloop.entities.player import Player class MatchClient(ABC): async def wait_notification(self): raise NotImplementedError() async def notify_new_player_join(self, player: Player): raise NotImplementedError() ...
2.625
3
tests/messysoup_test.py
messysoup/messysoup
4
53492
<gh_stars>1-10 from messysoup.messysoup import * from messysoup.table.table import * import pytest def test_a(): assert a("test", href="test.domain") == "<a href=test.domain >test</a>\n" def test_abbreviation(): assert abbreviation("test") == "<abbr >test</abbr>\n" def test_address(): assert address('t...
2.296875
2
_build/jupyter_execute/contents/Python/Data Manipulation.py
svenaoki/dsinterviewqns
5
53493
<gh_stars>1-10 #!/usr/bin/env python # coding: utf-8 # ## Data Manipulation # ### Questions # ```{admonition} Problem: [GOOGLE] Score Bucketization # :class: dropdown, tip # # Let's say you're given a list of standardized test scores from high schoolers from grades $9$ to $12$. # # Given the dataset, write code in...
3.921875
4
read_comment_aloud.py
ArinoMiya/read-comment-aloud
0
53494
<filename>read_comment_aloud.py # coding: utf-8 import argparse import src.comment_reader as comment_reader SETUP_TYPE = ['channel', 'video', 'url'] def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-m', '--method', type=str, ...
3.296875
3
cord/http/utils.py
pritamsoni-hsr/cord-client-python
0
53495
import logging import magic import os.path import requests from tqdm import tqdm def read_in_chunks(file_path, blocksize=1024, chunks=-1): """ Splitting the file into chunks. """ with open(file_path, 'rb') as file_object: size = os.path.getsize(file_path) pbar = tqdm(total=100) curre...
2.578125
3
src/DNN_ref.py
somu15/Small_Pf_code
0
53496
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 14 09:15:33 2020 @author: dhulls """ # Imports import numpy as np np.random.seed(100) from tensorflow import random random.set_seed(100) import os import pathlib import matplotlib.pyplot as plt import pandas as pd import seaborn as sns os.chdir('/...
2.328125
2
cache.py
ivclab/Label_Reuse_Semisupervised
2
53497
import torch from torch import nn class Cache(nn.Module): def __init__(self, n_entries, entry_size): super(Cache, self).__init__() self.n_entries = n_entries self.entry_size = entry_size self.register_buffer( name='idx_sparse', tensor=torch.z...
2.9375
3
src/compute_results.py
sgk98/CRM-Better-Mistakes
4
53498
<filename>src/compute_results.py import argparse import os import json import shutil import numpy as np from distutils.util import strtobool as boolean import torch import torch.optim import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.utils.data import torch.utils.data.dis...
1.851563
2
src/kinesis_producer.py
jacobmas/docker-twitter-streamer
0
53499
# stdlib import os import sys import logging # addlib import boto3 log = logging.getLogger(__name__) class RecordAccumulator(object): def __init__(self, limit=20): self.limit = limit self.container = [] def empty(self): result, self.container = self.container, [] ...
2.34375
2