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
tests/test_adjacency.py
jpmaterial/trimesh
1,882
43700
try: from . import generic as g except BaseException: import generic as g class AdjacencyTest(g.unittest.TestCase): def test_radius(self): for radius in [0.1, 1.0, 3.1459, 29.20]: m = g.trimesh.creation.cylinder( radius=radius, height=radius * 10) # remov...
2.5
2
app/models/registration.py
bmstu-iu8-g1-2019-project/lingvo-subtitles
0
43701
<reponame>bmstu-iu8-g1-2019-project/lingvo-subtitles<gh_stars>0 from collections import Counter from werkzeug.security import generate_password_hash from app import db def register_user(email, username, password): db.auth.drop() if db.auth.find_one({"username": username}) is not None: return -1 i...
2.421875
2
cgi/io/logger.py
wedddy0707/categorial_grammar_induction_of_emergent_language
0
43702
<reponame>wedddy0707/categorial_grammar_induction_of_emergent_language from logging import Logger, getLogger, StreamHandler, Formatter, DEBUG logger_count = -1 def make_logger(name: str) -> Logger: global logger_count logger_count += 1 logger = getLogger(name + f'_{logger_count}') handler = StreamH...
2.75
3
main.py
twfce/hetzner-dns-ip-updater
0
43703
#! /usr/bin/python3 import os import json from datetime import datetime from colored import fg, attr import paho.mqtt.client as mqtt from hdns import hdns def updateDNSRecords(ip): api = hdns(hdnsToken) print ("{color}{timestamp} | [*] Requesting all zones{reset}".format(color=fg(3), timestamp=datetime.now(),...
2.671875
3
mmdet/datasets/coco_caption.py
wusize/mmdetection
0
43704
<gh_stars>0 from .api_wrappers import COCO from .builder import DATASETS from .custom import CustomDataset @DATASETS.register_module() class CocoCaptionDataset(CustomDataset): def load_annotations(self, ann_file): """Load annotation from COCO style annotation file. Args: ann_file (str...
2.34375
2
flow/flows/abstract_flow_on_demand.py
tomoya-sforzando/etude-Prefect
0
43705
import os from abc import ABC, abstractmethod from typing import List from prefect import Client, Flow, Task from prefect.executors import LocalDaskExecutor from prefect.run_configs import UniversalRun from prefect.storage import Local from flows.abstract_settings import AbstractDemands, AbstractTasks PROJECT_NAME =...
2.359375
2
examples/courseware/shapes.py
LettError/drawbot
2
43706
# draw a rectangle # rect(x, y, width, height) rect(20, 50, 100, 200) rect(130, 50, 100, 200) oval(240, 50, 100, 200) oval(20, 250, 100, 100) oval(130, 250, 100, 100) rect(240, 250, 100, 100) for x in range(20, 300, 50): rect(x, 370, 40, 40) for x in range(20, 300, 50): if random() > 0.5: rect(x,...
3.640625
4
PyObjCTest/test_nsdecimalnumber.py
linuxfood/pyobjc-framework-Cocoa-test
0
43707
import Foundation from PyObjCTools.TestSupport import TestCase import objc class Behaviour(Foundation.NSObject): def scale(self): return 1 def roundingMode(self): return 1 def exceptionDuringOperation_error_leftOperand_rightOperand_(self, exc, err, l, r): pass class TestNSDecim...
2.4375
2
clastic/tests/test_obj_browser.py
mahmoud/clastic
140
43708
# -*- coding: utf-8 -*- from __future__ import unicode_literals import sys import pytest from clastic.contrib.obj_browser import create_app _IS_PYPY = '__pypy__' in sys.builtin_module_names @pytest.mark.skipif(_IS_PYPY, reason='pypy gc cannot support obj browsing') def test_flaw_basic(): app = create_app() ...
2.109375
2
bam_readlength_profile_by_bed.py
The-Mosher-Lab/grover_sirens_paper
2
43709
#!/usr/bin/env python3 # Author: <NAME> # Purpose: Profile the read lengths which map to regions in a bed file # Created: 2019-08-14 # Depends: pysam, samtools, python >= 3.6 import pysam import gzip from os.path import exists from argparse import ArgumentParser from sys import exit def magic_open(input_file): ...
2.984375
3
exercicios2/ex050.py
LuanGermano/Mundo-2-Curso-em-Video-Python
0
43710
# Desenvolva um programa que leia seis numeros inteiros e mostre a soma apenas daqueles que forem PARES. # Se o valor digitado for IMPAR, desconsidere-o soma = 0 cont = 0 for n in range(1, 7): n = int(input('Digite um Valor inteiro: ')) if n % 2 == 0: soma = soma + n cont = cont + 1 print(f'A so...
3.890625
4
tests/rororo/test_openapi.py
fajfer/rororo
105
43711
import datetime import io import json import zipfile from pathlib import Path import pyrsistent import pytest import yaml from aiohttp import web from openapi_core.shortcuts import create_spec from yarl import URL from rororo import ( BaseSettings, get_openapi_context, get_openapi_schema, get_openapi_...
1.945313
2
python/sandbox/__init__.py
geometer/sandbox
6
43712
<reponame>geometer/sandbox from .scene import Scene from .placement import iterative_placement
1.054688
1
mcsim/monte_carlo.py
msse-2020-bootcamp/team1-project
0
43713
<filename>mcsim/monte_carlo.py<gh_stars>0 """ Functions for running Monte Carlo Simulation """ import math import os import random import matplotlib.pyplot as plt def calculate_LJ(r_ij): """ The LJ interaction energy between two particles. Computes the pairwise Lennard jones interaction energy base...
3.359375
3
training/train_word2vec.py
jodaiber/semantic_compound_splitting
17
43714
import gensim import sys import glob import codecs from nltk.tokenize import RegexpTokenizer import glob import sys class CorpusReader(): """ Reads corpus from gzip file. """ def __init__(self, files): if isinstance(files, str): self.files = [files] else: self...
3.125
3
gchaos/gae/datastore/latency.py
RealKinetic/echoes
0
43715
<gh_stars>0 # MIT License # Copyright (c) 2017 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, me...
2.046875
2
test/unit/mongo_class/server_disconnect.py
deepcoder42/mongo-lib
0
43716
#!/usr/bin/python # Classification (U) """Program: server_disconnect.py Description: Unit testing of Server.disconnect in mongo_class.py. Usage: test/unit/mongo_class/server_disconnect.py Arguments: """ # Libraries and Global Variables # Standard import sys import os if sys.version_info < ...
3.171875
3
projeto_contratacoes/ferramentas/validaDado.py
JhonatasMenezes/Projetos_Python
3
43717
<filename>projeto_contratacoes/ferramentas/validaDado.py # Importando uma função que muda cor de textos no terminal, criada em outro arquivo from ferramentas.create_db import Vagas from .utilidades import textoCor """ Módulo de funções para validação de alguns dados como Nomes, CPFs e Datas de nascimento. NOTA: Todas...
3.6875
4
possible-new-sites/web.py
purrcat259/thargoid-search-tools
1
43718
import argparse from flask import Flask, render_template, redirect, jsonify from data import DataRetriever from flask import request from gevent.pywsgi import WSGIServer app = Flask(__name__) data_retriever = DataRetriever() def parse_distance(amount): return round(float(amount), 2) @app.route('/') def index...
2.828125
3
apps/auth/forms.py
capy-pl/nccu-grade-system
2
43719
from django import forms from django.contrib.auth.password_validation import CommonPasswordValidator class ChangePasswordForm(forms.Form): password = forms.CharField(label='密碼', max_length=50, widget=forms.PasswordInput) def clean_password(self): password = self.cleaned_data['password'] valida...
2.484375
2
main.py
aub-cp-training/Discord-Bot
0
43720
# ------------------ [ Authors: ] ------------------ # # <NAME> # <NAME> # <NAME> import os, json, inspect, discord, asyncio, importlib, sys, keep_alive from helper.cLog import elog from helper.cEmbed import denied_msg, greeting_msg from helper.User import User from helper.Algorithm import Algorithm from c...
1.921875
2
HW1/main.py
mapa17/LearningFromData
0
43721
<filename>HW1/main.py # -*- coding: utf-8 -*- """ Created on Fri Nov 20 18:28:50 2015 @author: <NAME> , <EMAIL> Homework Assignment from https://work.caltech.edu/telecourse.html Simple Perceptron Learning Model Algorithm """ import sys import errno import random def main(argv): if len(argv) < 2: print(...
3.34375
3
multichaindb/backend/localarangodb/schema.py
mamaeo/multichaindb
0
43722
import logging from arango.exceptions import ( CollectionCreateError ) from multichaindb import backend from multichaindb.backend.localarangodb.connection import LocalArangoDBConnection from multichaindb.backend.utils import module_dispatch_registrar logger = logging.getLogger(__name__) register_schema = module...
1.914063
2
home/admin.py
StoneMasons4106/clay-cabinet
0
43723
<reponame>StoneMasons4106/clay-cabinet from django.contrib import admin from .models import HomePagePicture, Testimonial, Content class HomePagePictureAdmin(admin.ModelAdmin): list_display = ( 'name', 'title', 'description', ) fields = ( 'name', 'image', 'ti...
2.09375
2
pastetron/pagination.py
kgaughan/pastetron
1
43724
""" Pagination support code. """ BUFFER = 5 def paginator(page_num, max_page, buffer_size=BUFFER): """ Pagination generator. Generates a sequence of page numbers, giving the pages at the beginning and end, and around the current page, with a number of buffer pages on each side of both. Omitted ...
3.953125
4
armi/materials/inconel600.py
celikten/armi
162
43725
# Copyright 2019 TerraPower, 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
1.796875
2
statuschecker_queues.py
chrisguitarguy/Python-Threading-Examples
18
43726
# -*- coding: utf-8 -*- """ An example url status checker implementation consumes urls from a queue. """ import threading import queue import requests class StatusChecker(threading.Thread): """ The thread that will check HTTP statuses. """ #: The queue of urls url_queue = None #: The queue o...
3.59375
4
hubspot/crm/products/api/__init__.py
fakepop/hubspot-api-python
117
43727
<reponame>fakepop/hubspot-api-python from __future__ import absolute_import # flake8: noqa # import apis into api package from hubspot.crm.products.api.associations_api import AssociationsApi from hubspot.crm.products.api.basic_api import BasicApi from hubspot.crm.products.api.batch_api import BatchApi from hubspot.c...
1.203125
1
src/matador/cli/utils.py
meatballs/python_utils
0
43728
from logging import getLogger import shutil from configparser import ConfigParser from pathlib import Path import yaml from dulwich.errors import NotGitRepository from dulwich.repo import Repo from matador import git logger = getLogger(__name__) def deployment_repository(project_folder): project = Path(project...
2.171875
2
robot/autonomous/replay.py
frc1418/2018-robot
1
43729
<reponame>frc1418/2018-robot<filename>robot/autonomous/replay.py from magicbot.state_machine import state, AutonomousStateMachine from magicbot import tunable from networktables.util import ntproperty from components import drive, arm import json class Replay(AutonomousStateMachine): """ Replay recorded contr...
2.71875
3
util/common.py
alexjercan/mesh-pose-reconstruction
1
43730
<reponame>alexjercan/mesh-pose-reconstruction # -*- coding: utf-8 -*- # # Developed by <NAME> <<EMAIL>> # # References: # import glob import os from pathlib import Path import cv2 import pickle import matplotlib.pyplot as plt import matplotlib.patches as mpatches from matplotlib import cm import numpy as np import t...
2.125
2
app/projects/migrations/0003_auto_20201214_1344.py
JoaoAPS/BugTracker
0
43731
# Generated by Django 3.1.4 on 2020-12-14 13:44 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('projects', '0002_auto_20201202_1826'), ] operati...
1.625
2
test_scripts/track_edges_tests/track_edges_collect_results.py
bknueven/FindAlmostSymmetry
0
43732
#!/usr/bin/python3 import pandas as pd import csv runs = [ ('games120.col',7), ('miles250.col',5), ('miles500.col',5), ('miles750.col',5), ('miles1000.col',5), ('miles1500.col',3), ('le450_5b.col',18), ('le450_15b.col',15), ('le450_25b.c...
2.6875
3
tests/test_cars.py
remi2257/little-car-ai
2
43733
from src.objects.Track import Track from src.usesful_func import start_pygame_headless start_pygame_headless() track = Track("tracks/tiny.tra") def test_car_human(): from src.cars.CarHuman import CarHuman car = CarHuman(track) assert car def test_car_ai(): from src.cars.CarAI import CarAI fr...
2.1875
2
wordle.py
mineshpatel1/wordle
0
43734
import functools import os import math import random from utils import log, multi_process from typing import Optional MAX_GUESSES = 6 NUM_PROCESSES = 5 INITIAL_GUESSES = ['CRANE'] EXPLORATION_THRESHOLD = 4 # Number of possible remaining answers to force a guess BASE_DIR = os.path.dirname(__file__) WORD_LIST_DIR = os....
3
3
api_advertisements/migrations/0001_initial.py
alex-fullstack/goods
0
43735
<gh_stars>0 # Generated by Django 3.1.2 on 2020-11-03 11:01 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Photo', fields...
1.835938
2
app.py
sztanyoo/K2010-envvars
0
43736
<reponame>sztanyoo/K2010-envvars from flask import Flask from flask import render_template import socket import os app = Flask(__name__) TARGET = os.environ.get('TARGET') @app.route("/") def main(): return render_template('target.html', name=socket.gethostname(), target=TARGET) if __name__ == "__main__": a...
2.3125
2
system/functions/date.py
u-n-i-c-o-rn/jimi
1
43737
<reponame>u-n-i-c-o-rn/jimi import time import datetime def now(milliseconds=False): if milliseconds: return time.time() * 1000 return time.time() def day(): return datetime.datetime.now().strftime('%A') def year(): return int(datetime.datetime.now().strftime('%Y')) def month(): return i...
3.1875
3
outerJoin.py
eyalsus/python-fun
0
43738
import pandas as pd def leftOuterJoin(left_df, right_df, key): right_df['tmp'] = '@' join_df = left_df.merge(right_df[['tmp', key]], how='left', on=key) join_df = join_df[pd.isnull(join_df['tmp'])] join_df.drop('tmp', axis=1, inplace=True) right_df.drop('tmp', axis=1, inplace=True) return join_...
3.171875
3
python/GMatElastoPlasticQPot3d/Cartesian3d.py
tdegeus/ElastoPlasticQPot3d
0
43739
<filename>python/GMatElastoPlasticQPot3d/Cartesian3d.py from ._GMatElastoPlasticQPot3d.Cartesian3d import *
1.132813
1
src/grammar_test.py
adrianogil/nanogenmo17
0
43740
from grammar import SimpleGrammar sg = SimpleGrammar() sg.add_tag("story", ["#story_beginning# #story_problem# #story_climax# #story_ending#"]) sg.add_tag("story_beginning", ["Once upon a time there was a valiant #animal#"]) sg.add_tag("story_problem", ["that never #difficulty_verb#.", \ "that one day hear...
3.390625
3
ipintel.py
Godod/utils
0
43741
import requests import json from decimal import Decimal as D from typing import Iterable, Any, Dict from django.core.exceptions import ValidationError from django.core.validators import validate_email, validate_ipv46_address IPINTEL_URL = 'https://check.getipintel.net/check.php' VALID_FLAGS = ['m', 'b', 'f', None] P...
2.671875
3
cogs/hypixel.py
matcool/schezo-bot
1
43742
<gh_stars>1-10 from discord.ext import commands from discord.ext.commands.cooldowns import BucketType from .utils.misc import safe_div from typing import Dict import discord import asyncio import aiohttp import json import datetime class Hypixel(commands.Cog): __slots__ = 'bot', 'api_key', 'overwrite_name' def...
2.578125
3
cppumockify/prototype.py
spoorcc/CppUMockify
0
43743
<reponame>spoorcc/CppUMockify #!/usr/bin/env python3 # Copyright (c) 2015, <NAME>. # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE I...
2.265625
2
transform/gmb.py
lievcin/ner_tagger
0
43744
import os import csv from utils import check_dir, make_sentences import numpy as np import pandas as pd def transform(source_path): rows = [] sentence_count = 1 new_sentence=True for root, __subFolders, files in os.walk(source_path): for file in files: if file.endswith('.tags'): ...
2.796875
3
src/DanceCV.py
Adilmar/DancePython
0
43745
#!/usr/bin/env python # -*- coding: utf-8 -*- from Resource import Resource from Audio import Audio from Scene import Scene from Song import Song, Note, loadSong from Input import Input import pygame from pygame.locals import * import sys import getopt import Constants #import cProfile as profile class DanceCV(): ...
2.921875
3
day9/grading.py
kendopunk/udemy-python
0
43746
<gh_stars>0 scores = { "John": 81.5, "Fred": 100, "Chad": 50, "Wopper": 30, "Katie": 73 } def calc_grade(score): if score >= 91: return "Outstanding" elif score >= 81: return "Exceeds Expectations" elif score >= 71: return "Acceptable" elif score >= 61: ...
3.640625
4
Star Identification/cascade_test19.py
raspberrystars/CV-Star-Sensor
31
43747
<reponame>raspberrystars/CV-Star-Sensor #Imports required libraries. import cv2 import numpy as np import os, os.path #Creates variables for position and RA/Dec coordinate for two detections. d1x, d1y, d1ra, d1dec, d2x, d2y, d2ra, d2dec = (0,)*8 #Loads an input test image (which has had fiducial markers appli...
2.859375
3
codenerix/migrations/0021_auto_20171218_1039.py
centrologic/django-codenerix
28
43748
# Generated by Django 2.0 on 2017-12-18 09:39 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('codenerix', '0020_remotelog'), ] operations = [ migrations.AddField( ...
1.703125
2
notebook/algorithm/template.py
qixiuai/BCGHeart
0
43749
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np def find_template(signal, rr): return signal[200:400] def conv(signal, template): scores = [] template_length = len(template) signal_length = len(signal) for ind in ...
2.421875
2
Graph_VAE/eval_utils.py
xiangsheng1325/Graph_VAE
0
43750
# eval utils def statistics_degrees(A_in): """ Compute min, max, mean degree Parameters ---------- A_in: sparse matrix or np.array The input adjacency matrix. Returns ------- d_max. d_min, d_mean """ degrees = A_in.sum(axis=0) return np.max(degrees), np.min(degree...
3.359375
3
bin/test_release.py
tfheen/k8s
0
43751
from __future__ import unicode_literals import argparse import mock import pytest from git import Repo, TagObject, Commit, GitCommandError from git.util import hex_to_bin import release PREVIOUS_TAG = "v1.2.2" CURRENT_TAG = "v1.2.3" def _h2b(prefix): return hex_to_bin(_pad(prefix)) def _pad(prefix): ret...
2.0625
2
setup.py
BSalita/endplay
4
43752
<gh_stars>1-10 #!/usr/bin/env python3 import os import pathlib from setuptools import setup, Extension from setuptools.command.build_ext import build_ext class CMakeExtension(Extension): """ Stub class to distinguish between default extensions and CMake extensions (which contain no sources as these are listed in ...
2.109375
2
tests/test_superelasticsearch.py
wingify/superelasticsearch
69
43753
<filename>tests/test_superelasticsearch.py import functools import json import logging import os import time from copy import deepcopy from datadiff.tools import assert_equal as assertDictEquals from elasticsearch import Elasticsearch, ElasticsearchException, TransportError from mock import Mock from random import ran...
2.359375
2
Encryptions/Rail_Fence (Zig-Zag).py
Ramin-RX7/DramaX
14
43754
''' Case Sensetive. Support Numbers and Symbols. Key Must be an Integer Lower Than Word Length and Higher than 1. ''' def encryptRailFence(text, key): rail = [['\n' for i in range(len(text))] for j in range(key)] dir_down = False row, col = 0, 0 for i in range(len(text)): ...
3.859375
4
app/facial-keypoint-detection/models.py
sourhub226/Computer-Vision-Facial-Key-Point-Detection
4
43755
<filename>app/facial-keypoint-detection/models.py ## TODO: define the convolutional neural network architecture import torch import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I class Net(nn.Module): de...
3.265625
3
Desafios/exerc39.py
pedronb/Exercicios-Python
0
43756
<gh_stars>0 # Exercício Python 39: Crie um programa que leia o nome e o preço de vários produtos. O programa deverá perguntar se o usuário vai continuar ou não. No final, mostre: #A) qual é o total gasto na compra. #B) quantos produtos custam mais de R$1000. #C) qual é o nome do produto mais barato. print('~'*30) prin...
4.03125
4
apps/base/urls/product_category_uom.py
youssriaboelseod/pyerp
115
43757
<reponame>youssriaboelseod/pyerp """The store routes """ # Django Library from django.urls import path # Localfolder Library from ..views.product_category_uom import ( ProductCategoryUOMCreateView, ProductCategoryUOMDeleteView, ProductCategoryUOMDetailView, ProductCategoryUOMListView, ProductCategoryUOMUpd...
2.0625
2
db_interfacer/interfacer.py
VenkatSubramaniam/SDI
0
43758
<reponame>VenkatSubramaniam/SDI #!/usr/bin/env python # coding: utf-8 from typing import Dict import psycopg2 as pg class DBInterfacer: def __init__(self, uname: str, pword: str, db: str, port: str) -> None: self.connection, self.cursor = self._establish_postgres_connection(uname, pword, db, port) ...
3.40625
3
QENSmodels/chudley_elliot_diffusion.py
celinedurniak/test_nbsphinx
0
43759
from __future__ import print_function import numpy as np try: import QENSmodels except ImportError: print('Module QENSmodels not found') def hwhmChudleyElliotDiffusion(q, D=0.23, L=1.0): """ Returns some characteristics of `ChudleyElliotDiffusion` as functions of the momentum transfer `q`: the ha...
2.53125
3
Working CNN Boi v2.py
hlal1/Bebop-Autonomous-Control
2
43760
# coding: utf-8 # In[2]: import os import numpy as np import pylab import imageio from matplotlib import pyplot as plt import cv2 import time from os.path import isfile, join from keras.applications import mobilenet from keras.models import load_model from scipy.ndimage.measurements import label from scipy.ndimage....
2.125
2
setup.py
flavuer/flavuer
0
43761
#!/usr/bin/env python3 import os from setuptools import setup, find_packages PKG_NAME = "flavuer" def package_files(directory): paths = [] for root, _, files in os.walk(directory): root_strip = root.lstrip(f"{PKG_NAME}/") for filename in files: paths.append(os.path.join(root_stri...
1.828125
2
simpa/utils/libraries/structure_library/CircularTubularStructure.py
IMSY-DKFZ/simpa
3
43762
# SPDX-FileCopyrightText: 2021 Division of Intelligent Medical Systems, DKFZ # SPDX-FileCopyrightText: 2021 <NAME> # SPDX-License-Identifier: MIT import numpy as np from simpa.utils import Tags from simpa.utils.libraries.molecule_library import MolecularComposition from simpa.utils.libraries.structure_library.Structur...
2.375
2
delox.py
onexploit/onexploit
0
43763
<gh_stars>0 import random from requests import get import socket import os , win32gui , win32con import getpass import time from init import banner from init.color import Color def ClearCSR(): os.system('clear') os.system('cls') def username(): getpass.getuser() def ip_local(): get...
2.578125
3
train.py
Yukariin/NatSR_pytorch
18
43764
<filename>train.py import argparse import os from tensorboardX import SummaryWriter import torch import torch.nn as nn from torch.utils import data from torchvision import transforms from torchvision.utils import make_grid from tqdm import tqdm from data import SQLDataset, InfiniteSampler from model import * parser...
2.171875
2
src/pysonata/sonata/tests/circuit/conftest.py
AllenInstitute/project7
35
43765
<filename>src/pysonata/sonata/tests/circuit/conftest.py import os import pytest from six import string_types from sonata.circuit.file import File def _append_fdir(files): fdir = os.path.dirname(os.path.realpath(__file__)) if isinstance(files, string_types): return os.path.join(fdir, files) else: ...
2.203125
2
src/zc/sourcefactory/mapping.py
zopefoundation/zc.sourcefactory
1
43766
<filename>src/zc/sourcefactory/mapping.py<gh_stars>1-10 ############################################################################## # # Copyright (c) 2006-2007 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A ...
1.898438
2
texar/torch/data/tokenizers/sentencepiece_tokenizer_test.py
wwt17/texar-pytorch
19
43767
""" Unit tests for SentencePiece tokenizer. """ import unittest import os import pickle import tempfile from texar.torch.data.data_utils import maybe_download from texar.torch.data.tokenizers.sentencepiece_tokenizer import \ SentencePieceTokenizer class SentencePieceTokenizerTest(unittest.TestCase): def s...
2.640625
3
images2h5.py
prlz77/LSTM-on-CNN
11
43768
# -*- coding: utf-8 -*- """ Generates the outputs of an arbitrary CNN layer. """ __author__ = "<NAME>, ISELAB, CVC-UAB" __email__ = "<EMAIL>" import argparse import h5py import cv2 import os import numpy as np parser = argparse.ArgumentParser(description="Reads a list of images, labels and sequences and outputs it i...
3.015625
3
import_plotting_nmr.py
DrSPE/NMRscipts
0
43769
<reponame>DrSPE/NMRscipts<gh_stars>0 # -*- coding: utf-8 -*- """ Created on Fri Mar 10 12:19:15 2017 @author: se359 """ # Imports import numpy as np import matplotlib.pyplot as plt #data import n, I, f, delta = np.loadtxt('nmr.txt', skiprows=1, delimiter=',', unpack=True) # Create a new figure of size...
2.375
2
cq_cam/operations/base_operation.py
voneiden/cq-cam
7
43770
from abc import ABC, abstractmethod from dataclasses import dataclass, field from typing import List, Union, Optional, Tuple from OCP.BRepFeat import BRepFeat from OCP.TopAbs import TopAbs_FACE from OCP.TopExp import TopExp_Explorer from cadquery import cq from cq_cam.commands.base_command import Command from cq_cam....
2.265625
2
lec28_model_load_save/3_save_checkpoint.py
xfsm1912/DeepAI_Pytorch_camp
0
43771
# -*- coding: utf-8 -*- """ # @file name : 3_save_checkpoint.py # @author : <NAME> # @date : 20210403 # @brief : simulate the accident break """ import os import random import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader import torchvision.transforms as transfor...
2.3125
2
muddery/server/statements/statement_func_set.py
dongwudanci/muddery
127
43772
<gh_stars>100-1000 """ A statement function set holds a set of statement functions that can be used in statements. """ class BaseStatementFuncSet(object): """ A statement function set holds a set of statement functions that can be used in statements. """ def __init__(self): self.funcs = {} ...
3.515625
4
resources/src/mythbox/pool.py
bopopescu/ServerStatus
0
43773
# # MythBox for XBMC - http://mythbox.googlecode.com # Copyright (C) 2010 <EMAIL> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) ...
2.359375
2
src/code/static_network/globals.py
dvaruas/minority_recommendations
0
43774
<gh_stars>0 import os PARAMETERS_PATH = os.path.join(os.path.dirname(__file__), os.pardir, "common", "parameters.ini") STATIC_DATA_PATH = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, "data", "synthetic", "static")
1.632813
2
wordhit_crawler/spiders/wordhit_spider.py
holandajunior/wordhit-crawler
1
43775
<reponame>holandajunior/wordhit-crawler import scrapy from scrapy.selector import Selector from wordhit_crawler.items import WordhitItem class WordHitSpider(scrapy.Spider): name = 'wordhitSpider' allowed_domains = ["www.google.com"] custom_settings = { 'DOWNLOAD_DELAY': 6, 'CONCURRENT_REQUESTS': 1...
2.78125
3
Validation/CustomerValidate.py
gabrielmonzato20/testePython
0
43776
<reponame>gabrielmonzato20/testePython<gh_stars>0 import re class CustomerValidate(): def __init__(self,data): self.data = data def cpfValidate(self): cpf=self.data['cpf'] if not isinstance(cpf, str): raise Exception("Invalid cpf") # Remove some unwanted chara...
3.828125
4
pyof/v0x04/controller2switch/__init__.py
josemauro/python-openflow
48
43777
"""Controller to Switch and Switch to Controller Messages."""
1.070313
1
api.py
sVialaret/SCmon2000EP
1
43778
<reponame>sVialaret/SCmon2000EP # -*- coding: utf-8 -*- import requests from datetime import datetime import hashlib import urllib import base64 import random as rd allocine_secret_key = '29d185d98c984a359e6e6f26a0474269' allocine_partner = '100043982026' formatUrl = 'json' def init_connect(): ### Initialisation ...
2.015625
2
sapcai/apis/build/dialog_response.py
SAPConversationalAI/SDK-python
9
43779
# coding: utf-8 from .dialog_message import DialogMessage from .dialog_conversation import DialogConversation from ..request.models import Response as NLPResponse class DialogResponse(object): def __init__(self, messages, conversation, nlp, logs): if type(messages) is not list: raise ValueError('Invalid...
2.265625
2
DAA_Assi.py
scorpion-11/2D_array_clustering
0
43780
<gh_stars>0 # -*- coding: utf-8 -*- """ Created on Tue Sep 3 14:53:06 2019 @author: ISHA """ arr = [ [ 'XYZ', 1, 88, 56, 45], [ 'ABC', 2, 45, 86, 52], [ 'LMN', 3, 87, 39, 40], [ 'QWS', 4, 96, 86, 85], [ 'TRE', 5, 76, 56, 53], [ 'UTH', 6, 35, 79, 48],...
2.71875
3
text/color/__init__.py
jedhsu/text
0
43781
""" *graphical color* Spectral color measures. """ # from ._color import Color # from ._rgb import Rgba # from ._hsv import Hsba __all__ = [ "Color", "Rgba", "Hsba", ]
1.4375
1
rapikan_unduhan.py
rafiyqw/script
0
43782
#!/usr/bin/env python3 import os import re import shutil import subprocess def matchFilm(s): ''' Given string s, Return true if s match conventional film name ''' film = re.fullmatch(r'(.*?)(19|20)\d{2}(.*?)(.mp4|.mkv|.rar|.zip)$', s) psarips = re.fullmatch(r'(.*?)(\d\d\d\d)(.*?)(\.x265\.HEVC\...
2.78125
3
multiqc_uphl/modules/roary/roary.py
Ikkik/MultiQC_UPHL
2
43783
#!/usr/bin/env python """ MultiQC submodule to parse output from Roary """ import logging import statistics from multiqc.modules.base_module import BaseMultiqcModule from multiqc import config from multiqc.plots import bargraph, heatmap, linegraph log = logging.getLogger('multiqc') class MultiqcModule(BaseMultiqcMo...
2.578125
3
xen/xen-4.2.2/tools/python/xen/xend/XendDPCI.py
zhiming-shen/Xen-Blanket-NG
1
43784
<filename>xen/xen-4.2.2/tools/python/xen/xend/XendDPCI.py #============================================================================ # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software ...
1.242188
1
crypto/cipher/cipher-py/cipher.py
JohnBSmith/misc
0
43785
#!/usr/bin/python3 # Usage: # Encipher: python3 cipher.py -e input-file output-file # Decipher: python3 cipher.py -d input-file output-file import os, hashlib, struct from sys import argv, exit # ChaCha20 cipher def keystream(key, iv, position=0): assert isinstance(key,bytes) and len(key) == 32 assert isinst...
3.703125
4
studio/nuke/init.py
astips/tk-astips-app-url-resolver
0
43786
<filename>studio/nuke/init.py # -*- coding: utf-8 -*- ########################################################################################### # # Author: astips - (animator.well) # # Date: 2017.03 # # Url: https://github.com/astips # # Description: nuke url resolver # ##############################################...
1.8125
2
tests/behavioural/features/steps/status_code.py
ONSdigital/ras-secure-message
6
43787
<filename>tests/behavioural/features/steps/status_code.py<gh_stars>1-10 import nose.tools from behave import then @then("a success status code 200 is returned") def step_impl_200_success_returned(context): """validate that the status code was 200""" nose.tools.assert_equal(context.response.status_code, 200) ...
2.40625
2
model/trl_NEW.py
Evangeline98/Traffic-Automation-System-Reinforcement-Learning
0
43788
<reponame>Evangeline98/Traffic-Automation-System-Reinforcement-Learning import numpy as np import pandas as pd from strategies import return_strategy_space, strategy2idx from parameters import speed_matrix, transition_matrix from crossroads_helper import Y2detailY class Traffic: def __init__(self): self.T...
3.328125
3
magnifier/base.py
koreander2001/magnifier
0
43789
from abc import ABCMeta, abstractmethod from sklearn.base import ( BaseEstimator, ClassifierMixin, RegressorMixin, TransformerMixin, ) class BaseClassifier(BaseEstimator, ClassifierMixin, metaclass=ABCMeta): @abstractmethod def fit(self, X, y, **fit_params) -> "BaseClassifier": raise ...
3.0625
3
spydrnet/parsers/verilog/tokenizer.py
ganeshgore/spydrnet
34
43790
<reponame>ganeshgore/spydrnet # Copyright 2021 please see the license # Author <NAME> from functools import partial import re import zipfile import io import os import spydrnet.parsers.verilog.verilog_tokens as vt from spydrnet.parsers.verilog.verilog_token_factory import TokenFactory class VerilogTokenizer: @st...
2.46875
2
duplicate_titles.py
tomaszpasternak94/OpenX_task
0
43791
import titles from titles import titlesAll def duplicatesF(): duplicates=[] counter = 0 for i in titlesAll: if i in titlesAll[counter+1:]: duplicates.append(i) else: pass counter += 1 print('\nlista duplikatów:') return print(list(set(duplicates)),'\n...
3.53125
4
jira_analysis/defect_rate/chart/defect.py
arrwhidev/jira-analysis
10
43792
from bokeh.models.sources import ColumnDataSource from bokeh.transform import cumsum from functools import partial from typing import List, Type from jira_analysis.chart.base import Axis, IChart, Chart from jira_analysis.defect_rate.issue import Issue from .plot.donut import DefectRateDonut def generate_defect_chart...
2.328125
2
sevdesk/client/models/email_model.py
HpLightcorner/SevDesk-Python-Client
0
43793
import datetime from typing import Any, Dict, List, Type, TypeVar, Union import attr from dateutil.parser import isoparse from ..models.email_model_object import EmailModelObject from ..models.email_model_sev_client import EmailModelSevClient from ..types import UNSET, Unset T = TypeVar("T", bound="EmailModel") @a...
2.703125
3
selsearch/search.py
jeertmans/selsearch
8
43794
<filename>selsearch/search.py import urllib.parse import webbrowser def search_text(where, text): urlsafe = urllib.parse.quote(text) browser = webbrowser.get() browser.open(f"{where}{urlsafe}")
2.890625
3
myblog/posts/serializer.py
daxia07/fancyBlog
1
43795
<filename>myblog/posts/serializer.py from django.contrib.auth.models import User from rest_framework import serializers from .models import Post class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') class PostSerializer(serializers.Model...
2.234375
2
tests/test_automechanic/test_mol_graph.py
avcopan/automechanic-history-save
0
43796
<filename>tests/test_automechanic/test_mol_graph.py """ test the automechanc.mol.graph module """ import numpy from automechanic.mol import graph C8H13O_CGR = ( {0: ('C', 3, None), 1: ('C', 3, None), 2: ('C', 1, None), 3: ('C', 1, None), 4: ('C', 1, None), 5: ('C', 1, None), 6: ('C', 2, None), 7: ('C', ...
2.171875
2
CodeWars/2019/AnagramFinder-5k.py
JLJTECH/TutorialTesting
0
43797
<gh_stars>0 #!/usr/bin/env python3 ''' Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. ''' def anagrams(word, words): analis = [] for item in...
4.09375
4
solo/losses/swav.py
Evgeneus/solo-learn
0
43798
import numpy as np import torch def swav_loss_func(preds, assignments, temperature): losses = [] for v1 in range(len(preds)): for v2 in np.delete(np.arange(len(preds)), v1): a = assignments[v1] p = preds[v2] / temperature loss = -torch.mean(torch.sum(a * torch.log_s...
2.25
2
bol/inference/wav2vec2_fairseq/_wav2vec2_infer_single.py
harveenchadha/bol
10
43799
import soundfile as sf import torch import torch.nn.functional as F from fairseq.data import Dictionary from bol.utils.helper_functions import move_to_cuda def get_feature(filepath): def postprocess(feats, sample_rate): if feats.dim == 2: feats = feats.mean(-1) assert feats.dim() == ...
2.359375
2