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
tools/process_EUROSTAT_historic.py
WOIDMO/WoMo-FrontEnd-V1
0
51500
<reponame>WOIDMO/WoMo-FrontEnd-V1<filename>tools/process_EUROSTAT_historic.py # #EUROSTAT historic processing # import pandas as pd from datetime import date, timedelta import datetime #Dictionaries and stuff ccodes = ['AT', 'BE', 'BG', 'CH', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FR', 'HU', 'IS', 'IT', 'LI', 'LT', 'LU'...
2.1875
2
tests/factories.py
UNINETT/django-rtdb
0
51501
<gh_stars>0 from __future__ import unicode_literals import factory from faker import Factory as Faker from rtdb.models import Customfield from rtdb.models import Queue from rtdb.models import Ticket from rtdb.models import TicketCustomfieldValue __all__ = [ 'QueueFactory', 'TicketFactory', ] fake = Faker.c...
1.992188
2
omsignal/utils/transform/__init__.py
eeishaan/ift6759-block1
0
51502
#!/usr/bin/env python3 from abc import ABC, abstractmethod class OmTransform(ABC): ''' Abstract base class for custom transformers ''' @abstractmethod def __call__(self, x): pass def state(self): ''' This method should return the state of the transformer ''' ...
3.359375
3
src/example.py
siddhesh-singh/rule-generator
0
51503
#!/usr/bin/env python3 import rulegenerator from random import randint if __name__ == '__main__': generations = 500 width = 501 rule = randint(0, 255) init_config = randint(0, 32) init_config = bin(init_config)[2:] grid = rulegenerator.generate_rule_wrap(generations, init_config, rule, width) print("Wr...
2.765625
3
Documentation_generator/ivml_documentation_from_file.py
jegentile/IVML
8
51504
__author__ = 'jgentile' class IVMLDocumentationFromFile: def __init__(self,file_name): self.__file_name = file_name self.__file = open(file_name) print ' Document generator looking at ',file_name self.__ivml_object_documentation = '\0' self.__type = '' self.__ivm...
2.578125
3
tests/silhouette_test.py
JesusFreke/fscad
35
51505
<gh_stars>10-100 # Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
1.875
2
core/configs.py
firehose-dataset/congrad
9
51506
<reponame>firehose-dataset/congrad import os import time import argparse def get_basic_parser(): parser = argparse.ArgumentParser(description='Transformer Language Model', add_help=False) parser.add_argument('--gpu0_bsz', type=int, default=-1, help='batch size on gpu 0') par...
2.34375
2
src/conf.py
bcartwri96/sermon-skeleton
1
51507
import configparser as cfg import src.scripts.index as scripts import os try: cel_det = scripts.get_env_variable('REDIS_URL') # we want to use the heroku set add-on redis server if it's available, # but if we can't find it, then it isn't set and we must be running # the dev server, so we connect to it ...
2.328125
2
p3.py
joefinlon/Finlon_et_al_2021_DFR
0
51508
<gh_stars>0 ''' Contains routines to read and manipulate particle size distribution data from the 2D-S and HVPS optical array probes during the IMPACTS experiment. Creation of 1 Hz PSD data requires use of UIOOPS package (doi: 10.5281/zenodo.3976291). Some of the arguments in the routines require radar data matched to ...
1.898438
2
codeChef/practice/easy/muffins3.py
ferhatelmas/algo
25
51509
<reponame>ferhatelmas/algo import sys print "\n".join(str(int(i) / 2 + 1) for i in sys.stdin.readlines()[1:])
2.703125
3
Profile.roboFontExt/lib/roboFontProfile.py
LettError/profileRoboFontExtension
3
51510
<gh_stars>1-10 import AppKit import cProfile import os import tempfile from mojo.compile import executeCommand from mojo.UI import HelpWindow python = os.path.join(AppKit.NSBundle.mainBundle().bundlePath(), "Contents", "MacOS", "python") def ShowProfile(func, *args, **kwargs): """ +------------------------...
2.1875
2
src/ui/cli/input.py
FilaCo/upg
0
51511
import click from ui.cli.command import Command class Input(Command): def __init__(self, title: str, value=None): self.title = title self.value = value def render(self): click.echo("%s\t%s" % (self.title, self.value))
2.5625
3
database/apis/api_msql.py
JhonSaguay/Observatorioapi
0
51512
import requests import json import time import mysql.connector from mysql.connector import Error def saveindicador(conexion): cur=conexion.cursor() sqlconsulta="SELECT JSON_EXTRACT(datosjson,'$.internal_type') as internal_type,sum(JSON_EXTRACT(datosjson,'$.amount')) as total_amount FROM apidata group by JSON_E...
2.484375
2
test/unit/jobs/test_statuses.py
NHSDigital/list-reconciliation
4
51513
import pytest from jobs.statuses import JobStatus @pytest.mark.parametrize( "code,value", [ (JobStatus.SENT_TO_DPS, "SENT_TO_DPS"), (JobStatus.PROCESSED_BY_DPS, "PROCESSED_BY_DPS"), (JobStatus.COMPLETE, "COMPLETE"), (JobStatus.NOTIFIED_VALIDATION_FAILED, "NOTIFIED_VALIDATION_FA...
2.390625
2
mason/clients/engines/scheduler.py
kyprifog/mason
4
51514
from typing import Tuple, Optional, Union from abc import abstractmethod from mason.clients.base import Client from mason.engines.scheduler.models.dags.client_dag import ClientDag from mason.engines.scheduler.models.schedule import Schedule, InvalidSchedule from mason.clients.response import Response from mason.util.e...
2.40625
2
main.py
ragequitcc/Ragequit.FritzBoxStatus
0
51515
from os import environ from http.server import BaseHTTPRequestHandler, HTTPServer from fritzconnection.lib.fritzstatus import FritzStatus from fritzconnection import FritzConnection if "FritzBoxUri" not in environ: print("FritzBoxUri Missing") quit() if "FritzBoxUser" not in environ: print("Frit...
2.65625
3
email_signals/urls.py
Salaah01/django-email-signals
14
51516
from django.urls import path from . import views urlpatterns = [ path( "model-attrs/<int:content_type_id>/", views.model_attrs, name="django_signals_model_attrs", ), ]
1.53125
2
clients/python/tyckiting_client/ai/myai.py
HimanshuSingal/space_mission
0
51517
<reponame>HimanshuSingal/space_mission import random from tyckiting_client.ai import base from tyckiting_client import actions class Ai(base.BaseAi): a = 0 wait_list = [] def move(self, bots, events): """ Move the bot to a random legal positon. Args: bots: List of bo...
2.8125
3
status/get_status_from_s3_path.py
oslokommune/dataplatform-status-api
0
51518
import base64 import simplejson from aws_xray_sdk.core import patch_all, xray_recorder from botocore.exceptions import ClientError from okdata.aws.logging import ( logging_wrapper, log_add, log_exception, ) from okdata.resource_auth import ResourceAuthorizer from status.StatusData import StatusData from s...
1.890625
2
rtmlparse/elements/entry.py
thusser/rtml-parse
1
51519
<gh_stars>1-10 from lxml import etree from datetime import datetime from .baseelement import BaseElement from .misc import auto_attr_check @auto_attr_check class Entry(BaseElement): Agent = str Date = datetime Description = str Error = str Rejection = str Version = int def __init__(self,...
2.75
3
hammers/osrest/keystone.py
ChameleonCloud/bag-o-hammers
0
51520
""" Keystone API shims. Requires v3 API. See `Keystone HTTP API <https://developer.openstack.org/api-ref/identity/v3/>`_ """ from requests import HTTPError from hammers.osrest.base import BaseAPI API = BaseAPI('identity') def project(auth, id): """Retrieve project by ID""" response = API.get(auth, '/project...
2.328125
2
examples/LabMaster/View/ColormapEditorFrame.py
dowerner/QtModularUiPack
3
51521
<filename>examples/LabMaster/View/ColormapEditorFrame.py from ViewModel.ColormapEditorViewModel import ColormapEditorViewModel from Framework.Plotting.color_utils import ColorMapImage from Widgets import EmptyFrame, PlotMasterWidget from Widgets.QtExtensions import QRangeSlider from Widgets.VideoExtensions import Image...
2.140625
2
0901-1000/0931-Median of K Sorted Arrays/0931-Median of K Sorted Arrays.py
jiadaizhao/LintCode
77
51522
<reponame>jiadaizhao/LintCode import bisect class Solution: """ @param nums: the given k sorted arrays @return: the median of the given k sorted arrays """ def findMedian(self, nums): # write your code here n = sum(len(arr) for arr in nums) if n == 0: return 0 ...
3.515625
4
backend/dndapi/characters/admin.py
cyaconiello/dndapi
0
51523
<gh_stars>0 from django.contrib import admin from characters.models import Character # Register your models here. admin.site.register(Character)
1.28125
1
tests/test_pydent/test_utils/__init__.py
aquariumbio/trident
5
51524
<filename>tests/test_pydent/test_utils/__init__.py """Tests related to utilities."""
1.109375
1
sql4json/sql4json.py
bheni/sql4json
7
51525
import json from data_query_engine import DataQueryEngine class Sql4Json(object): def __init__(self, json_str, sql_str): self.data = json.loads(json_str, encoding="latin1") self.query_engine = DataQueryEngine(self.data, sql_str) def get_results(self): return self.query_engine.get_res...
2.734375
3
Lib/unittest/case.py
sireliah/polish-python
1
51526
<gh_stars>1-10 """Test case implementation""" zaimportuj sys zaimportuj functools zaimportuj difflib zaimportuj logging zaimportuj pprint zaimportuj re zaimportuj warnings zaimportuj collections zaimportuj contextlib zaimportuj traceback z . zaimportuj result z .util zaimportuj (strclass, safe_repr, _count_diff_all_p...
2.5625
3
test/core/derivatives/implementation/backpack.py
jabader97/backpack
395
51527
"""Contains derivative calculation with BackPACK.""" from test.core.derivatives.implementation.base import DerivativesImplementation from test.utils import chunk_sizes from typing import List from torch import Tensor, einsum, zeros from backpack.utils.subsampling import subsample class BackpackDerivatives(Derivativ...
2.6875
3
Beginner/1016.py
pedrodanieljardim/DesafiosURI-feitos-em-JAVA
1
51528
<reponame>pedrodanieljardim/DesafiosURI-feitos-em-JAVA km = int(input()) minutes = 2*km print("{} minutos".format(minutes))
3.421875
3
cloudsky_backend/common/common_serializers.py
minicloudsky/cloudsky_backend
0
51529
from rest_framework import serializers from rest_framework.serializers import raise_errors_on_nested_writes from rest_framework.utils import model_meta import logging logger = logging.getLogger(__file__) class BaseSerializer(serializers.ModelSerializer): def update(self, instance, validated_data): ...
2.453125
2
RabbitMQooz.py
khalilovcmd/sd-rabbitmqooz
1
51530
import json import urllib2 import base64 import json import logging import os import platform import sys import time class RabbitMQooz(object): def __init__(self, agent_config, checks_logger, raw_config): self.agent_config = agent_config self.checks_logger = checks_logger self.raw_config =...
2.625
3
tests/test_pytest_utils.py
UT-Covid/compartmental_model_case_studies
1
51531
import os import sys import pytest from . import pytest_utils HERE = os.path.dirname(os.path.abspath(__file__)) @pytest.mark.parametrize('o1,o2', [ (1, 2), (3, 3.), ({'inject_test': 'foo bar{{inject_me}}', 'inject_me': 'beezbooz'}, {'inject_test': 'foo barbeezbooz', 'inject_me': 'beezbooz'}), ]) def...
2.40625
2
annotation-tool/filter_annotations.py
robotika/subt-artf
1
51532
"""Filter and convert annotations""" import json import os import cv2 USED_ARTF_NAME = ["backpack", "phone", "survivor", "drill", "fire_extinguisher", "vent", "helmet", "rope", "breadcrumb", "robot", "cube", "nothing"] BLACKLIST = [ "../virtual/helmet/local_J01_000.jpg", "../virtual/helmet/local_J...
2.171875
2
django_mobile_app_distribution/migrations/0005_auto_20160118_1759.py
chingmeng/django-mobile-app-distribution
38
51533
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django_mobile_app_distribution.storage import django_mobile_app_distribution.models class Migration(migrations.Migration): dependencies = [ ('django_mobile_app_distribution', '0004_auto_201509...
1.671875
2
styn/tests/test_styn.py
ldmoray/styn
1
51534
<filename>styn/tests/test_styn.py import contextlib import imp import pytest import re import sys if sys.version.startswith("3."): from io import StringIO as SOut else: from StringIO import StringIO as SOut from os import path from styn import _styn, main def fpath(mod): return path.splitext(mod.__file_...
2.34375
2
app/dao/decorators.py
kentsanggds/api
1
51535
from flask import current_app from functools import wraps from app import db def transactional(func): @wraps(func) def commit_or_rollback(*args, **kwargs): try: res = func(*args, **kwargs) db.session.commit() return res except Exception as e: cu...
2.671875
3
Algorithm/Decrypt.py
prathamsingh90/Implementation-of-RC5-Algorithm
0
51536
<reponame>prathamsingh90/Implementation-of-RC5-Algorithm import lcshift import comply import add1 import char2bin def crypt(a,b,ky1,ro): ky = [0]*len(ky1) for x in range(len(ky)): ky[x]=comply.comp(ky1[x]) #print('ky',ky1[x],'x',x) for i in range(ro): #h = comply.comp(b) ...
3.421875
3
yayun.py
Gold-Sea/Poems
0
51537
def clarify_yayun(): with open("字表拼音.txt", "r", encoding="utf-8") as f: lines = f.readlines() zhengti = ["hi", "ri", "zi", "ci", "si"] # 整体认读音节的后两个字母 u_to_v = ["yu", "xu", "qu"] # 读作v写作u for line in lines: c = line[0] # _i指末尾i个字母组成的韵母 _1 ...
3.296875
3
knightbook/splitting.py
beninato8/selenium
0
51538
<reponame>beninato8/selenium<gh_stars>0 m = '<NAME>' a = m[:-6] b = m[-6:] print(b.title() + ": " + a) print('AsDf'.lower(), 'AsDf'.upper())
2.84375
3
pyckaxe/utils/cache/static_cache.py
Arcensoth/pyckaxe
3
51539
<filename>pyckaxe/utils/cache/static_cache.py<gh_stars>1-10 from typing import Dict, Iterator, Mapping, MutableMapping, Optional, TypeVar __all__ = ("StaticCache",) KT = TypeVar("KT") VT = TypeVar("VT") # @implements Cache class StaticCache(MutableMapping[KT, VT]): """ A cache with a pre-defined set of ent...
2.890625
3
analysisCodes/hotrgFlow.py
brucelyu/tensorRGflow
12
51540
<filename>analysisCodes/hotrgFlow.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 4 15:06:00 2020 Anlysis of the flow of 1) norm of the tensor, 2) singular value spectrum of the tensor, and 3) norm of the difference of the two tensors in adjacent RG step @author: brucelyu """ from HOTRG imp...
2.40625
2
ifelse.py
chidanandpujar/Python_scripts
0
51541
num=int(input("Enter number:")) if (num > 0): print(num,"is a positive number") else: print(num,"is not a positive number")
4.21875
4
src/lib/components/views/explorer/directory/tree.py
billyeatcookies/Biscuit
1
51542
import os, threading import tkinter.ttk as ttk import tkinter as tk class Tree(ttk.Treeview): def __init__(self, master, double_click=None, single_click=None, startpath=None, *args, **kwargs): super().__init__(master, *args, **kwargs) self.master = master self.base = master.base se...
2.65625
3
webup/content_type.py
cariad/webup
0
51543
<gh_stars>0 from typing import Dict from webup.suffix import normalize_suffix _content_types: Dict[str, str] = {} _default_content_type = "" def set_default_content_type(type: str = "application/octet-stream") -> None: """ Sets the default Content-Type header for file types not registered via `set_conte...
2.59375
3
commanderbot_lib/database/mixins/yaml_file_database_mixin.py
CommanderBot-Dev/commanderbot-lib
1
51544
from typing import IO import yaml class YamlFileDatabaseMixin: async def load_yaml(self, file: IO) -> dict: return yaml.safe_load(file) async def dump_yaml(self, data: dict, file: IO): return yaml.safe_dump(data, file)
2.40625
2
neoload/commands/login.py
adamleskis/neoload-cli
0
51545
<gh_stars>0 import sys import click from neoload_cli_lib import user_data @click.command() @click.option('--url', default="https://neoload-api.saas.neotys.com/", help="The URL of api ", metavar='URL') @click.option('--no-write', is_flag=True, help="don't save login on application data") @click.argument('token', requ...
2.640625
3
tests/datatypes/test_resolver_address.py
VIDA-NYU/openclean-pattern
4
51546
<filename>tests/datatypes/test_resolver_address.py # This file is part of the Pattern and Anomaly Detection Library (openclean_pattern). # # Copyright (C) 2021 New York University. # # openclean_pattern is released under the Revised BSD License. See file LICENSE for # full license details. """unit tests for address ty...
2.421875
2
Python/searching/linear/linear_search_rec.py
stanislav-kudriavtsev/Algorithms
1
51547
<filename>Python/searching/linear/linear_search_rec.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """Recursive linear search algorithm.""" __author__ = "<NAME>" from typing import Any, Optional, Sequence # Complexity: worst case # Time : O(n) # Space : O(n) def linear_search_rec(seq: Sequence, valu...
3.65625
4
scatterpie/plot.py
racng/scatterpie
1
51548
from typing import Union, Optional, Sequence, Any, Mapping, List, Tuple, Callable from collections.abc import Iterable import operator import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.axes import Axes def pie_marker( ratios: Sequence[float], res: int = 50, ...
3.265625
3
complaint_app/management/commands/populate_db.py
sriniArumalla/fullstack-coding-challenge
0
51549
from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from complaint_app.models import UserProfile, Complaint import os.path import json class Command(BaseCommand): help = "Seeds database with users, and complaints" def handle(self, *args, **options): BA...
2.25
2
examples/sub_commands_named.py
shicholas/glacier
86
51550
from glacier import glacier def f1(name: str, verbose: bool = False) -> None: pass def f2(name: str, verbose: bool = False) -> None: pass def f3(name: str, verbose: bool = False) -> None: pass if __name__ == '__main__': glacier({ 'run': f1, 'build': f2, 'test': f3, })...
1.734375
2
analyzer_project/source_parser/abstract_source_parser.py
Dakhnovskiy/linguistic_analyzer_projects
0
51551
<reponame>Dakhnovskiy/linguistic_analyzer_projects # -*- coding: utf-8 -*- __author__ = 'Dmitriy.Dakhnovskiy' import itertools from abc import ABCMeta, abstractmethod class AbstractSourceParser: __metaclass__ = ABCMeta def __init__(self, source): """ :param source: исходный код """ ...
2.453125
2
handlers/comment.py
byn9826/Thousand-Day
2
51552
#!/usr/bin/python # -*- coding: utf-8 -*- import mysql.connector import datetime #search 5 comment for a moment #return 0 for error def searchComment(momentId, startPoint, addPoint, cnx): commentQuery = 'SELECT * FROM moment_comment WHERE moment_id = %s ORDER BY comment_id DESC LIMIT %s, 5' pin = startPoint * ...
2.453125
2
utils/__init__.py
atlashugs/dqn_pytorch
0
51553
from .utils import set_requires_grad, create_exp_logfile, performance_avg
1
1
poplerGUI/ui_logic_sitechange.py
bibsian/lter
5
51554
from PyQt4 import QtGui from Views import ui_dialog_sitechange as uichange class TablePreview(QtGui.QDialog, uichange.Ui_Dialog): def __init__(self, parent=None): super().__init__(parent) self.setupUi(self)
1.90625
2
cloudseg/datasets/preprocessing.py
elrichgro/irccam-pmodwrc
1
51555
<reponame>elrichgro/irccam-pmodwrc<gh_stars>1-10 import cv2 import numpy as np from cloudseg.utils.constants import * from cloudseg.datasets.masking import apply_mask, apply_background_mask, full_mask def rotate_image(img, angle): """ Rotate image by given angle. Adapted from https://stackoverflow.com/a/2331...
2.8125
3
geo/analysis/data_paths.py
stefantaubert/life
2
51556
<reponame>stefantaubert/life<gh_stars>1-10 import os from geo.data_paths import get_suffix_pro from geo.data_paths import get_suffix_prote from geo.data_paths import get_suffix_o from geo.data_dir_config import root analysis_dir = root + "analysis/" heatmaps_dir = root + "analysis/Heatmaps/" most_common_values_best_...
2.34375
2
our_scripts/setup.py
shrivats-pu/Prescient
1
51557
<reponame>shrivats-pu/Prescient<gh_stars>1-10 from setuptools import setup setup(name='prescient_helpers', version='0.1', description='Use prescient helper functions', url='#', author='<NAME>', author_email='<EMAIL>', packages=['prescient_helpers'], zip_safe=False)
1.46875
1
models/__init__.py
kun-woo-park/Mobile_Stereo_Net_RealSense
76
51558
# Copyright (c) 2021. All rights reserved. from models.MSNet2D import MSNet2D from models.MSNet3D import MSNet3D from models.submodule import model_loss __models__ = { "MSNet2D": MSNet2D, "MSNet3D": MSNet3D }
1.507813
2
rlpyt/ul/experiments/rl_with_ul/configs/dmlab_ppo_with_ul.py
nirbhayjm/rlpyt
0
51559
<reponame>nirbhayjm/rlpyt<filename>rlpyt/ul/experiments/rl_with_ul/configs/dmlab_ppo_with_ul.py import copy configs = dict() config = dict( agent=dict( store_latent=False, # only if model stop_conv_grad=True ), algo=dict( discount=0.99, learning_rate=2.5e-4, value_loss_co...
1.710938
2
modelling/modelling_sample.py
PREDICTFORCE/Toolkit-for-Professional-Data-Science-Workflow-Example
0
51560
import argparse import pickle from pathlib import Path import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, confusion_matrix, classification_report from sklearn.model_selection import train_test_split parser = argparse.ArgumentParser(description='Process ...
2.5625
3
src/rotas/cidade_1a.py
giovanigiaqueto/APS-Games
0
51561
#!/usr/bin/env python # -*- coding: utf-8 -*- from .. import especial from ..narracao import narrador from ..base import Opcao, Escolhas def inicio(): narrador(\ """ Com o pensamento de que poderiam passar despercebidos pelos zumbis, você decide ir com a ideia de ir pelos esgotos. """, """ ...
3.421875
3
GameUtils/PronunciationUtils/recorder.py
SamSpaulding/speech-tapgame-aamas18
2
51562
import wave import pyaudio FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 16000 RECORD_SECONDS = 10 CHUNK = 16000 WAV_OUTPUT_FILENAME = "audioFile2.wav" EXTERNAL_MIC_NAME = 'USB audio CODEC: Audio (hw:1,0)' mic_index = None audio = pyaudio.PyAudio() info = audio.get_host_api_info_by_index(0) numdevices = info.get('dev...
2.9375
3
test/test_likelihood.py
nigeltrc72/cwinpy
5
51563
""" Test script for data.py classes. """ import os import numpy as np import pytest from bilby.core.prior import PriorDict, Uniform from cwinpy import HeterodynedData, MultiHeterodynedData, TargetedPulsarLikelihood class TestTargetedPulsarLikelhood(object): """ Tests for the TargetedPulsarLikelihood class. ...
2.375
2
turtle/static/game/level2/prompt2.py
ramimanna/turtle-playground
0
51564
<filename>turtle/static/game/level2/prompt2.py<gh_stars>0 #Level 2! def play_turn(p2):
1.851563
2
retriever_train/inference_utils.py
martiansideofthemoon/relic-retrieval
13
51565
import pickle import torch import numpy as np from transformers import RobertaModel, RobertaTokenizerFast from retriever_train.dataset_config import DATASET_CONFIG, BASE_CONFIG from retriever_train.data_utils import Instance from retriever_train.utils import init_parent_model class PrefixSuffixWrapper(object): ...
2.0625
2
spynoza/filtering/workflows.py
spinoza-centre/spynoza
7
51566
<gh_stars>1-10 from nipype.workflows.fmri.fsl.preprocess import create_susan_smooth import nipype.pipeline as pe import nipype.interfaces.fsl as fsl from nipype.interfaces.io import DataSink from nipype.interfaces.utility import IdentityInterface, Merge, Select """ Most of this code has been generously provided by nip...
2.21875
2
moveit_ros/moveit_servo/test/python_tests/msg_reception/test_servo_msg_reception.py
thomas-gale/moveit
0
51567
<reponame>thomas-gale/moveit #!/usr/bin/env python import time import pytest import rospy from geometry_msgs.msg import TwistStamped from control_msgs.msg import JointJog from trajectory_msgs.msg import JointTrajectory # Import common Python test utilities from os import sys, path sys.path.append(path.dirname(path.d...
2.3125
2
ranking_nlp4if/pointwise_transformer/train_pointwise.py
bekou/evidence_aware_nlp4if
0
51568
<filename>ranking_nlp4if/pointwise_transformer/train_pointwise.py<gh_stars>0 import random, os import argparse import numpy as np import torch import torch.optim as optim import torch.nn.functional as F from tqdm import tqdm from torch.autograd import Variable from pytorch_pretrained_bert.tokenization import whitespace...
2.09375
2
src/conformal_methods/utils.py
JosefNagelschmidt/conformal-inference
0
51569
<filename>src/conformal_methods/utils.py import numpy as np import pandas as pd from src.config import SRC from numba import jit from scipy.stats import norm from scipy.stats import skewnorm from sklearn.preprocessing import StandardScaler def init_scoring_object(method, quantile=0.9): def scoring_object(estim...
2.3125
2
pyos/os/shell.py
dgisolfi/PyOS
3
51570
<gh_stars>1-10 #!/usr/bin/env python3 # <NAME> from pyos.globals import _globals from pyos.os.commands import shell_commands from pyos.os.userCommand import UserCommand from pyos.os.shellCommand import ShellCommand import datetime import os import re class Shell: """ Main interaction with OS via CLI """ def __init_...
2.578125
3
sdk/python/pulumi_rancher2/get_project_role_template_binding.py
mitchellmaler/pulumi-rancher2
0
51571
<gh_stars>0 # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from typing import Union from . import utilities, tables c...
1.921875
2
main.py
DebNatkh/tinkoff-colloquium-bot
0
51572
#! /usr/bin/env python3 import os from random import choice import filetype from telegram.ext import Updater, CommandHandler from tinydb import TinyDB, where db = TinyDB('db.json') admins_table = db.table("admins") given_questions = db.table("given") quiet_categories = ['meme'] def register_admin(update, context):...
2.5
2
crop_type_mapping/ml_crop_cli/ml_crop/utils_data.py
developmentseed/servir-training-notebooks
8
51573
<filename>crop_type_mapping/ml_crop_cli/ml_crop/utils_data.py import geopandas as gpd import numpy as np import rasterio from rasterio.features import rasterize from rasterstats.io import bounds_window from sklearn.model_selection import train_test_split def crop_classes(train_geo): training_vectors = gpd.read_f...
2.96875
3
py/mockDensData.py
jobovy/apogee-maps
1
51574
############################################################################### # mockDensData.py: generate mock data following a given density ############################################################################### import os, os.path import pickle import multiprocessing from optparse import OptionParser import...
2.484375
2
src/static-vxlan-agent/evpn-proxy-agent.py
jbemmel/srl-evpn-proxy
8
51575
#!/usr/bin/env python # coding=utf-8 import eventlet # BGPSpeaker needs sockets patched -> breaks SRL registration if done too late # eventlet.monkey_patch( socket=True, select=True ) # adding only ( socket=True ) allows SRL, but then BGP doesn't work :( eventlet.monkey_patch() # need thread too # Google core librar...
1.71875
2
authors/apps/articles/migrations/0007_report.py
andela/ah-backend-summer
1
51576
<filename>authors/apps/articles/migrations/0007_report.py # Generated by Django 2.1.5 on 2019-02-19 13:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('profiles', '0003_merge_20190214_1334'), ('articles', '0006...
1.460938
1
test_recfile.py
shgalus/recfile
0
51577
<gh_stars>0 #!/usr/bin/python3 "Tests the module recfile." import unittest import io import os import filecmp from recfile import format_line from recfile import Recjar from recfile import Recset import recfile TEST_DIR = os.path.abspath(os.path.dirname(__file__)) LOCATION = os.path.join(TEST_DIR, 'testdata') class...
2.875
3
my_modules.py
jcjumley/FlightPathBuilder
0
51578
""" My commenly used Modules: (1) get_directory_name(caption) -- browses for directory name (2) get_file_name(caption) -- browses for a specific file (3) save_file_name(caption) -- saves named file to selected directory (4) get_exif(fn) -- gets inag exif data (5) get_gps_deg(exf) -- extracts GPS data from exi...
2.984375
3
gvsoc/gvsoc/tests/bench/top.py
knmcguire/gap_sdk
1
51579
<reponame>knmcguire/gap_sdk # # Copyright (C) 2018 ETH Zurich and University of Bologna # # 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 # # ...
1.820313
2
prosit/train_prosit.py
jmueller95/prosit
0
51580
import os import numpy as np import pandas as pd import yaml from . import model as model_lib from . import training, tensorize, io_local def main(): #Turn off warnings: os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" ###Load training data - Put the path to your own data here training_data_path = "/root/trai...
2.46875
2
securedrop_api/__init__.py
heartsucker/python-securedrop-api
0
51581
<reponame>heartsucker/python-securedrop-api __version__ = '0.0.0' API_V1 = 'api/v1/'
1.085938
1
draw2/_legacy/igorio.py
SanTelva/Crystal3D
0
51582
<filename>draw2/_legacy/igorio.py<gh_stars>0 from math import * def formatPC3D(inputFile): ''' Returns list, containing nodes. Each node is list [num, x, y, z, [bonds]] where: "num" is number of node (numeration starts from 1) "x", "y", "z" are coords of node, relative to primitive cell. Each bond ...
3.34375
3
SecML/src/secml/core/tests/test_attr_utils.py
dsolanno/Poisoning-Attacks-on-Algorithmic-Fairness
5
51583
from secml.testing import CUnitTest from secml.core.attr_utils import extract_attr class TestAttributeUtilities(CUnitTest): """Unit test for secml.core.attr_utils.""" def test_extract_attr(self): # Toy class for testing class Foo: def __init__(self): self.a = 5 ...
2.75
3
tools_box/safety_and_compliance/api.py
maisonarmani/Tools_Box
4
51584
<reponame>maisonarmani/Tools_Box # -*- coding: utf-8 -*- # Copyright (c) 2015, <EMAIL> and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.desk.reportview import get_match_cond @frappe.whitelist() def employee_query...
1.960938
2
src/py_moveit/scripts/line_cartesian_5DOF.py
ERP1234/5DOF_Robot_arm
0
51585
#!/usr/bin/env python import sys import copy import rospy import moveit_commander import moveit_msgs.msg import geometry_msgs.msg from math import pi from std_msgs.msg import String from moveit_commander.conversions import pose_to_list ## END_SUB_TUTORIAL def all_close(goal, actual, tolerance): all_equal = True ...
2.59375
3
hyparam.py
Shihab-Shahriar/500-miles
0
51586
from time import perf_counter import numpy as np from sklearn.model_selection import RepeatedStratifiedKFold from sklearn.metrics import * from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.decomposition import PCA from sklearn.manifold import TSNE import matplotlib.pyplot as pl...
2.40625
2
server/scripts/utils.py
smartscenes/multiscan
6
51587
import os import sys import shutil import re def print_m(msg): msg_color = '\033[0m' sys.stdout.write(f'{msg_color}{msg}{msg_color}\n') def print_w(warning): warn_color = '\033[93m' msg_color = '\033[0m' sys.stdout.write(f'{warn_color}Warning: {warning} {msg_color}\n') def print_e(error): ...
3.140625
3
web_app/routes/GET_PUT_API.py
AmyBeisel/BW_Med_Cabinet
0
51588
<filename>web_app/routes/GET_PUT_API.py # GET_PUT_API.py # This is the test version of the API, it can both GET and POST JSON data # An NLP model is imported as the recommend function, recommends strains and sends results #Imports import pandas as pd import requests import json from flask import Blueprint, reque...
2.890625
3
reviews/migrations/0003_auto_20180610_1456.py
UrbanBogger/horrorexplosion
0
51589
<reponame>UrbanBogger/horrorexplosion # -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-06-10 13:56 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('reviews', '0002_auto_20180610_1406'), ] opera...
1.976563
2
coinbasepro/auth.py
apfelnutzer/coinbasepro
46
51590
import time import base64 import hashlib import hmac from requests.auth import AuthBase class CoinbaseProAuth(AuthBase): """Request authorization. Provided by Coinbase Pro: https://docs.pro.coinbase.com/?python#signing-a-message """ def __init__(self, api_key, secret_key, passphrase): s...
2.9375
3
src/rbx2/rbx2_tasks/src/rbx2_tasks/clean_house_tasks_tree.py
fujy/ROS-Project
9
51591
<gh_stars>1-10 #!/usr/bin/env python """ clean_house_tasks_tree.py - Version 1.0 2013-12-20 Create a number of simulated cleaning tasks. Created for the Pi Robot Project: http://www.pirobot.org Copyright (c) 2013 <NAME>. All rights reserved. This program is free software; you can redistribute it an...
2.75
3
blog/models.py
alegume/furry-succotash
0
51592
from django.conf import settings from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField...
2.109375
2
ex036.py
MarcelleFranca/exercicios-python
0
51593
<reponame>MarcelleFranca/exercicios-python print('-=-' * 25) print('BEM-VINDO AO SEU EMPRÉSTIMO, PARA INICIAR SIGA AS INTRUÇÕES ABAIXO!') print('-=-' * 25) salario = float(input('Qual é o seu salario atual? R$')) casa = float(input('Qual é o valo do imóvel que pretende compar? R$')) anos = int(input('Em quantos anos pr...
3.84375
4
client.py
JulianRobin/servChat
0
51594
import socket import threading import sys import subprocess from colorama import init from colorama import Fore, Back, Style init() def sending(server): while True: user = subprocess.run(['whoami'], stdout=subprocess.PIPE).stdout.decode('utf-8').strip().split('\\')[-1] print(Fore.GREEN + user + ":...
3.125
3
Metaheuristic Optimization/tabu_search.py
bnjasim/algorithms
0
51595
#!/usr/bin/env python # coding: utf-8 import random import matplotlib.pyplot as plt cities = ['A', 'B', 'C', 'E', 'M', 'S'] # Represent the Graph as a dictionary of dictionaries A = {'A':0, 'B':10, 'C':15, 'E':14, 'M':11, 'S':10} B = {'A':10, 'B':0, 'C':8, 'E':13 ,'M':15 ,'S':9} C = {'A':15, 'B':8, 'C':0, 'E':11,'M'...
3.828125
4
PositionalList.py
xliiauo/leetcode
1
51596
<filename>PositionalList.py class _DoubleLinkedBase: class _Node: __slots__ = '_element', '_prev', '_next' def __init__(self, element, prev, next): self._element = element self._prev = prev self._next = next def __init__(self): self._header = self._N...
3.015625
3
src/textdatasetcleaner/processors/normalize_unicode.py
ameyuuno/TextDatasetCleaner
27
51597
<filename>src/textdatasetcleaner/processors/normalize_unicode.py from pathlib import Path from typing import Optional from textacy.preprocessing import normalize_unicode # type: ignore from textdatasetcleaner.exceptions import TDCValueError from textdatasetcleaner.processors.base import BaseProcessor class Normali...
2.4375
2
tests/test_base_repository.py
mamerisawesome/coeusfactory
1
51598
<reponame>mamerisawesome/coeusfactory def test_base_repository(): from coeusfactory.repositories.BaseRepository import BaseRepository br = BaseRepository(model="test", name=__name__) # return fails if no interface is created assert not br.get_all() assert not br.get_by_id(0) assert not br.get(...
2.171875
2
Module 03/DjangoDesignPatternsandBestPracticesSecondEdition_Code/src/sightings/admin.py
74gigi8/Learning-Path-Learn-Web-Development-with-Python
41
51599
from django.contrib import admin from . import models class SightingAdmin(admin.ModelAdmin): list_display = ('superhero', 'power', 'location', 'sighted_on') date_hierarchy = 'sighted_on' search_fields = ['superhero'] ordering = ['superhero'] admin.site.register(models.Origin) admin.site.register(mod...
1.53125
2