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 |
|---|---|---|---|---|---|---|
nmrtools/__init__.py | bjrnfrdnnd/panel-test | 0 | 55400 | """
nmrtools
========
The nmrtools package provides tools for simulating nuclear magnetic resonance
(NMR) spectra.
The API is still in flux. Currently, it includes the following modules:
* dnmr: for modeling Dynamic NMR systems
* firstorder: for modeling first-order spectra
* math: core math routines for handling NM... | 2.078125 | 2 |
compile_break_level_ml.py | jwcalder/MachineLearningAnthro | 0 | 55401 | <filename>compile_break_level_ml.py<gh_stars>0
import numpy as np
import pickle
import matplotlib.pyplot as plt
import pandas as pd
from utils import arc_length, arc_angle, data_dir
from scipy import spatial
import sys
#Load angle data dictionary
with open('break_curve_data.pkl', 'rb') as f:
angledata = pickle.loa... | 2.15625 | 2 |
runtests.py | lukemerrett/SteamProgress | 2 | 55402 | import unittest
if __name__ == "__main__":
# Finds all tests in submodules ending in *tests.py and runs them
suite = unittest.TestLoader().discover('.', pattern = "*tests.py")
unittest.TextTestRunner().run(suite)
| 1.992188 | 2 |
swagger-4-es development/images/swagger/source/ingest_operations/__init__.py | swarmee/swagger-4-es | 3 | 55403 | <filename>swagger-4-es development/images/swagger/source/ingest_operations/__init__.py<gh_stars>1-10
from .ingest_operations import api as ingest_operations | 1.0625 | 1 |
foil/patterns.py | portfoliome/foil | 30 | 55404 | """
Pattern matching utilities.
"""
import re
from functools import wraps
from typing import Iterable
def match_subgroup(sequence, pattern):
"""Yield the sub-group element dictionary that match a regex pattern."""
for element in sequence:
match = re.match(pattern, element)
if match:
... | 3.78125 | 4 |
tests/unit/cirrus/quality_control_test.py | Maxsparrow/cirrus | 12 | 55405 | '''
qc command tests
'''
import mock
import unittest
from cirrus.quality_control import main, run_linters, build_parser
class QCCommandTests(unittest.TestCase):
"""
test coverage for qc command module
"""
def test_build_parser(self):
"""test build_parser call"""
args = [
... | 2.71875 | 3 |
python/runtime/local/submitter_test.py | ikingye/sqlflow | 4,742 | 55406 | <reponame>ikingye/sqlflow
# Copyright 2020 The SQLFlow Authors. 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 re... | 2.28125 | 2 |
python/ql/test/query-tests/Classes/incomplete-ordering/incomplete_ordering.py | vadi2/codeql | 4,036 | 55407 | <reponame>vadi2/codeql
#Incomplete ordering
class PartOrdered(object):
def __eq__(self, other):
return self is other
def __ne__(self, other):
return self is not other
def __hash__(self):
return id(self)
def __lt__(self, other):
return False
#Don't blame a sub-class f... | 2.59375 | 3 |
onedrive/cli_tool.py | timgates42/python-onedrive | 130 | 55408 | <reponame>timgates42/python-onedrive
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import itertools as it, operator as op, functools as ft
from os.path import dirname, basename, exists, isdir, join, abspath
from posixpath import join as ujoin, dirname as udirname... | 2.40625 | 2 |
t2t_bert/distributed_bin/tf_serving_api.py | yyht/bert | 34 | 55409 | # -*- coding: utf-8 -*-
import requests
import json
import tensorflow as tf
import sys,os
father_path = os.path.join(os.getcwd())
print(father_path, "==father path==")
def find_bert(father_path):
if father_path.split("/")[-1] == "BERT":
return father_path
output_path = ""
for fi in os.listdir(father_path):
i... | 2.53125 | 3 |
model/cgan.py | HyperAndy/GANPriv | 0 | 55410 | import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch
class Generator(nn.Module):
def __init__(self, configs, shape):
super(Generator, self).__init__()
self.label_emb = nn.Embedding(configs.n_classes, configs.n_classes)
self.shape = shape
def block(... | 2.484375 | 2 |
python/analysis_prepare.py | mz8i/ganplan | 0 | 55411 | <reponame>mz8i/ganplan
from analysis_util import *
def preprocess(data, name):
e_name = 'e_' + name
data[e_name] = get_embeddings(data, '../data/embeds/france_15_'+name+'_128_full')
for perplexity in [5, 30, 100]:
tsne_name = 'tsne' + str(perplexity) + '_' + name
data[tsne_name] = get_tsn... | 1.992188 | 2 |
bot coontrol/CollisionControl.py | aritrog/sarathi | 3 | 55412 | import BotDecidesPos
import numpy as np
class Collision_check:
def __init__(self):
self.m=0.0
self.n=0.0
def load_data(self,bot):
tgx,tgy=bot.getTarget()
mpx,mpy=bot.getPos()
spd=bot.getSpeed()
return spd,mpx,mpy,tgx,tgy
def checkCollisio... | 2.84375 | 3 |
try/process_num.py | pengjeck/xigua_crawler | 3 | 55413 | <filename>try/process_num.py
# coding: utf-8
import subprocess
import atexit
commands = [
'python',
'time_consume.py'
]
pids = []
def fun():
for p in pids:
p.kill()
atexit.register(fun)
for i in range(1000):
p = subprocess.Popen(commands)
pids.append(p)
print('stop')
a = input()
| 2.578125 | 3 |
tests/lit/lit/formats/__init__.py | junag/alive | 4 | 55414 | from __future__ import absolute_import
from lit.formats.base import TestFormat, FileBasedTest, OneCommandPerFileTest
from lit.formats.alivetest import AliveTest
| 1.0625 | 1 |
google_fanyi/fanyi.py | tangyazhou123/Spider | 0 | 55415 | <filename>google_fanyi/fanyi.py<gh_stars>0
from winreg import REG_QWORD
import requests
from fake_useragent import UserAgent
import random
import urllib.parse
import time
class GoogleFanyi():
def __init__(self, query):
form_data = f'[[["MkEWBc","[[\"{query}\",\"zh-CN\",\"en\",true],[null]]",null,"... | 2.359375 | 2 |
rsHRF/rsHRF_GUI/datatypes/misc/store.py | BIDS-Apps/rsHRF | 16 | 55416 | <filename>rsHRF/rsHRF_GUI/datatypes/misc/store.py
from . import subject
class Store():
"""
Stores all the subjects as a dictionary, with their keys as the index
"""
def __init__(self):
self.subjects = {}
# getters
def get_subjects(self):
""" Returns a tuple with the indices of ... | 2.71875 | 3 |
datasets/jfk_passengers/convert.py | jayschauer/TCPD | 70 | 55417 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Dataset conversion script
Author: <NAME>
"""
import json
import argparse
import clevercsv
def month2index(month):
return {
"Jan": "01",
"Feb": "02",
"Mar": "03",
"Apr": "04",
"May": "05",
"Jun": "06",
"Ju... | 3.609375 | 4 |
LTS/__init__.py | hecor/freeCTP | 8 | 55418 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
dirs = ['/tmp/CTP_L2data/', '/tmp/CTP_tradedata/']
for d in dirs:
if not os.path.isdir(d):
os.makedirs(d)
| 2.453125 | 2 |
web/pipeline/migrations/0054_auto_20200815_0728.py | stevenstuber/CIT | 10 | 55419 | # Generated by Django 2.2.13 on 2020-08-15 07:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pipeline', '0053_auto_20200813_0521'),
]
operations = [
migrations.AddField(
model_name='censussubdivision',
name='... | 1.734375 | 2 |
deep_learning/code/sigmoid_function.py | comet-syt/BAPS | 3 | 55420 | import numpy as np
import matplotlib.pyplot as plt
def sigmoid(x, w, b):
return 1/(1 + np.exp(-x*w+b))
x = np.arange(-5.0, 5.0, 0.1)
y1 = sigmoid(x, 0.5, 0)
y2 = sigmoid(x, 1, 0)
y3 = sigmoid(x, 2, 0)
plt.plot(x, y1, "r", linestyle='--')
plt.plot(x, y2, 'g')
plt.plot(x, y3, 'b', linestyle='--')
plt.plot([0, 0],... | 3.875 | 4 |
train.py | FayazRahman/EliteHyperOps | 1 | 55421 | import torch
from torch import nn
from torch.utils.data import DataLoader
from nn_model import NeuralNetwork, FrankWolfeDataset
train_dataset = FrankWolfeDataset("train_dataset")
test_dataset = FrankWolfeDataset("test_dataset")
train_dataloader = DataLoader(train_dataset, batch_size=128, shuffle=True)
test_dataloade... | 2.828125 | 3 |
setup.py | KamalDGRT/KamalSQL | 4 | 55422 | from setuptools import setup
# Read the README.md file
with open('README.md') as file_handle:
file_content = file_handle.read()
setup(
name='kamalsql',
packages=['kamalsql'],
version='1.0.0',
license='MIT',
description='A simple Python wrapper for your MySQL needs.',
long_description=file_... | 1.453125 | 1 |
bdt2cpp/PickleLoader.py | bixel/bdt2cpp | 3 | 55423 | import pickle
import tempfile
import os
from .XGBoostParser import parse_model as parse_model_xgb
def load_model(filename, feature_names=None):
with open(filename, 'rb') as f:
model = pickle.load(f)
_, tmp = tempfile.mkstemp(text=True)
model.get_booster().dump_model(tmp)
trees = parse_mod... | 2.5625 | 3 |
merge_sort/merge_sort_example.py | RafaSzl/Algorithms | 0 | 55424 | import random
# If the input list is empty or contains just one element, it is already sorted. Return it.
# If not, divide the list of numbers into two roughly equal parts.
# Sort each part recursively using the merge sort algorithm. You'll get back two sorted lists.
# Merge the two sorted lists to get a single sorted... | 4.03125 | 4 |
estruturas/lista.py | italoaalves/projeto-ed | 0 | 55425 | from typing import Union
from estruturas.excecoes import EstruturaException
from estruturas.no import Node
class ListaEncadeada:
def __init__(self) -> None:
self.__head = None
self.__tamanho = 0
@property
def head(self) -> object:
return self.__head
@head.setter
def head(... | 3.515625 | 4 |
Tutorial/Simulations/00_Initial/conservative.py | BenPski/RodDynamics | 2 | 55426 | import numpy as np
from scipy.optimize import fsolve
from scipy.linalg import expm
import matplotlib.pyplot as plt
# Some utilities
# map a vector to a skew symmetric matrix
def skew(x):
return np.array([[0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]])
# map a twist to its adjoint form
def adjoint(x):
r... | 2.765625 | 3 |
app/api/topics.py | amikoj/web | 0 | 55427 | # !/usr/bin/env python
# -*-coding:utf-8-*-
from flask import jsonify,request,g,url_for,current_app
from .. import db
from ..models import ShareCategory,Topic
from . import api
from .errors import forbidden
@api.route('/getCategory')
def get_category():
u"""
获取主题信息,可以通过type确定返回为JsonArray还是Json.
:return:
... | 2.59375 | 3 |
main.py | Lizt1996/VariationalQuantumGeneralizedEigensolver | 0 | 55428 | import GradientBasedOptimization as gbopt
import openpyxl as pyxl
import time
from QAnsatz import *
from QSubspaceEigensolver import *
import k_nearest_data as k_data
from QMeasure import HadamardTest_Analytical
W_Hamiltonian = Hamiltonian_in_Pauli_String(qubits=3,
... | 1.804688 | 2 |
sample_config.py | naushadzaman/CoinBaseBot | 0 | 55429 | <reponame>naushadzaman/CoinBaseBot
config = {
"coinbase":{
"Key": "",
"Secret": ""
},
"twilio":{
"Key": "",
"Secret": "",
"from": "+12223334444",
"to_list": ["+12223334444"],
},
"bittrex":{
"Key" : "",
"Secret" : ""
}
}
| 1.164063 | 1 |
registry/views.py | gutma-org/droneregistry | 4 | 55430 | import datetime
import json
from datetime import datetime
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.template import loader
from django.utils import translation
from django.views.generic import Templat... | 1.875 | 2 |
raft/datastore/Idatastore.py | shrinivdeshmukh/simpleRAFT | 3 | 55431 | from abc import ABC, ABCMeta, abstractmethod
class IDatastore(ABC):
@abstractmethod
def put(self, key: str, value: str):
'''
Implement this function to insert data into database
'''
@abstractmethod
def get(self, key: str):
'''
Implement this function to retrie... | 3.78125 | 4 |
release/train_tests/horovod/train_horovod_multi_node_test.py | mgelbart/ray | 22 | 55432 | import json
import os
import time
import ray
from ray.train import Trainer
from ray.train.examples.horovod.horovod_example import (
train_func as horovod_torch_train_func,
)
if __name__ == "__main__":
ray.init(address=os.environ.get("RAY_ADDRESS", "auto"))
start_time = time.time()
num_workers = 8
... | 2.296875 | 2 |
app_bookmarks/views.py | kostyachum/django-admin-app-bookmark | 0 | 55433 | <filename>app_bookmarks/views.py
from django.core.handlers.wsgi import WSGIRequest
from django.db.models import F
from django.http import HttpResponseRedirect
from django.views import View
from .models import AppBookmark
class UpdateAppBookmarkView(View):
admin_site = None
def post(self, request: WSGIRequest... | 2.046875 | 2 |
utility/model_mixins.py | didoogan/cookiecutter | 0 | 55434 | from django.db import models
class Representable(models.Model):
def __str__(self):
attrs = ((k, self.__dict__[k]) for k in self.__dict__ if not k.startswith('_'))
return '{} = > {}'.format(self.__class__, str(list(attrs)))
class Meta:
abstract = True
| 2.734375 | 3 |
MIS SCRIPTS/CALIBRACION.py | ctm1098/umucv | 0 | 55435 | <filename>MIS SCRIPTS/CALIBRACION.py<gh_stars>0
#!/usr/bin/env python
import argparse
import cv2 as cv
import numpy as np
from umucv.util import putText
from collections import deque
from umucv.util import Help
from math import pi
parser = argparse.ArgumentParser(description='Mide la d... | 2.53125 | 3 |
tests/test_debugging.py | butsuri43/hepdata_maker | 0 | 55436 | <reponame>butsuri43/hepdata_maker
import pytest
from hepdata_maker.Submission import Table
from hepdata_maker.Submission import Variable
from hepdata_maker.Submission import Uncertainty
from hepdata_maker.Submission import add_rich_error_tree_from_var
from hepdata_maker.Submission import add_rich_var_tree_from_table
fr... | 2.21875 | 2 |
record_inputs/record_low_level_sensor.py | AnfieldQi/SARA | 1 | 55437 | <filename>record_inputs/record_low_level_sensor.py<gh_stars>1-10
# coding=utf8
from . import record_utils as ru
SENSOR_MANAGER_TAG = '[SensorManager]'
SENSOR_LISTENER_TAG = '[SensorListener]'
"""
Record low-level sensor inputs, e.g., Gravity, Accelerometer, Gyroscope, Light
Details:
1. Instrument the method `registe... | 2.828125 | 3 |
tests/utils/test_image_utils.py | swershrimpy/gtsfm | 122 | 55438 | import numpy as np
from gtsam import SfmTrack
from gtsfm.common.image import Image
import gtsfm.utils.images as image_utils
def test_get_average_point_color():
""" Ensure 3d point color is computed as mean of RGB per 2d measurement."""
# random point; 2d measurements below are dummy locations (not actual pro... | 2.421875 | 2 |
sublemon/subprocess.py | welchbj/sublemon | 10 | 55439 | <reponame>welchbj/sublemon<gh_stars>1-10
"""Models for interacting with subprocesses."""
import asyncio
import uuid
from datetime import datetime
from typing import (
AsyncGenerator,
Optional,
TYPE_CHECKING)
from sublemon.errors import SublemonLifetimeError
if TYPE_CHECKING:
from sublemon.runtime im... | 2.4375 | 2 |
setup.py | rebeccaframework/rebecca.menu | 0 | 55440 | from setuptools import setup, find_packages
import os
version = '0.0'
requires = [
"setuptools>=0.7",
"pyramid",
]
tests_require = [
"pytest",
"testfixtures",
"webtest",
]
long_description = (
open('README.rst').read()
+ '\n' +
'Contributors\n'
'============\n'
+ '\n' +
o... | 1.460938 | 1 |
2021/day5.py | tangarts/advent-of-code | 0 | 55441 |
from collections import defaultdict
from advent_of_code.core import parse_input, mapt
test_input = """0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2"""
def count(iterable, predicate=bool):
return sum(1 for item in iterable if predicate(item))
def ... | 3.625 | 4 |
igf_data/igfdb/fileadaptor.py | imperial-genomics-facility/data-management-python | 7 | 55442 | import os
import pandas as pd
from sqlalchemy.sql import column
from igf_data.igfdb.baseadaptor import BaseAdaptor
from igf_data.igfdb.igfTables import File, File_attribute
class FileAdaptor(BaseAdaptor):
'''
An adaptor class for File tables
'''
def store_file_and_attribute_data(self,data,autosave=True):
'... | 2.984375 | 3 |
Python/1 - Easy/nthFibonacci.py | AntonioMM8506/AlgoExpert | 0 | 55443 | <reponame>AntonioMM8506/AlgoExpert
def getNthFib(n):
if(n==1):
return 0
elif (n==2):
return 1
else:
return getNthFib(n-1) + getNthFib(n-2)
#End of getNthFib
if __name__ == '__main__':
print(getNthFib(6))#5
print(getNthFib(7))#8
print(getNthFib(1))#0
print(getNthFib(... | 3.859375 | 4 |
ShotWrapper/shot_extractor.py | oronnir/CAST | 8 | 55444 | import os
import subprocess
from E2E.configuration_loader import Configuration
config = Configuration().get_configuration()
EXE_FOLDER, EXE_NAME = os.path.split(config['shotExtractor'])
SHOTS_OUTPUT_SUFFIX = '_shot_scene.txt'
KEYFRAMES_DIR = 'Keyframes'
class Keyframe:
def __init__(self, keyframe_name):
... | 2.671875 | 3 |
lib/viscoelasticity.py | mforstenhaeusler/AFMviscoelastic | 2 | 55445 | <gh_stars>1-10
"""
Created on Wed Jun 10th 2020
@author: <NAME>
Description: This library contains core algorithms to analyse and fit viscoelstic models to different AFM data.
"""
import numpy as np
from lmfit import Parameters, minimize, report_fit
def G_storage(omega, Ge, G, tau):
"""
Description:
The... | 2.5625 | 3 |
src/utilities.py | Mulugruntz/deep_3d_photo | 7 | 55446 | <reponame>Mulugruntz/deep_3d_photo
from __future__ import annotations
import os
from pathlib import Path
from typing import List, Optional, Callable
from inspect import currentframe
import requests
from kivy.clock import Clock
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from kv_classes import ComplexProgre... | 2.171875 | 2 |
aos_sw_api/tacacs_profile/_tacacs_profile.py | KennethSoelberg/AOS-Switch | 0 | 55447 | from typing import Union
import httpx
from aos_sw_api.validate import validate_200
from ._model import TacacsProfileModel
class TacacsProfile:
def __new__(cls, session: Union[httpx.Client, httpx.AsyncClient], **kwargs):
if isinstance(session, httpx.Client):
return TacacsProfileSync(session=... | 2.296875 | 2 |
train.py | TunnelTechnologies/dmrg-exact | 10 | 55448 | <reponame>TunnelTechnologies/dmrg-exact
import argparse
from config import read_config
from run_dmrg import run_dmrg
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='location of config file, for example ./config/parity.yaml')
args = parser.parse_args()
... | 2.09375 | 2 |
src/topoAddDGscore.py | ElofssonLab/TMplot | 0 | 55449 | <filename>src/topoAddDGscore.py
#!/usr/bin/env python
# better to be called by the master script "getDGvalueTMOfTopo.sh"
# add DG scores to the topology file,
# output two files:
# one is the topology file adding with one line with DG scores under each TM
# segment
# Another is a list
# ID TMsegment(aa) DGsc... | 2.3125 | 2 |
mass/__init__.py | shervinazadi/MASS | 0 | 55450 | <reponame>shervinazadi/MASS
from .MASS import environment, agent
from . import utilities | 1.070313 | 1 |
ssm/simulation/sim_modules/noise.py | sflis/SSM-analysis | 0 | 55451 | <reponame>sflis/SSM-analysis<filename>ssm/simulation/sim_modules/noise.py
from ssm.core.pchain import ProcessingModule
import numpy as np
class Noise(ProcessingModule):
def __init__(self, resp_key="response", name="Noise"):
super().__init__(name)
self.resp_key = resp_key
def configure(self, c... | 2.296875 | 2 |
post_setup.py | ExoWorldsSpies/hops | 5 | 55452 |
import os
import glob
import platform
import sys
sys.path = sys.path[1:]
from hops import __get_abspath__ as hops__get_abspath__
name = 'hops'
here = os.path.abspath(os.path.dirname(__file__))
shortcut = open(os.path.join(here, 'shortcut.txt')).read()
shortcut = shortcut.replace('{{x}}', hops__get_abspath__())
# c... | 2.546875 | 3 |
OfficeQts/OfficeApp/urls.py | jvillarreal7/TheOfficeQuotes | 0 | 55453 | <reponame>jvillarreal7/TheOfficeQuotes
from django.urls import path
from .views import *
from . import views
urlpatterns = [
path('', views.Home),
path('login-dashboard/', views.LoginAdmin),
path('dashboard/', views.Dashboard),
path('logout/', views.LogoutAdmin),
]
| 1.289063 | 1 |
src/ase2sprkkr/potentials/definitions/sections/reference_system.py | ase2sprkkr/ase2sprkkr | 1 | 55454 | <filename>src/ase2sprkkr/potentials/definitions/sections/reference_system.py
from ...potential_definitions import PotSectionDefinition, \
PotValueDefinition
from ...potential_sections import UniqueListSection
from ....common.grammar_types import Table
from ....sprkkr.reference_system... | 2.140625 | 2 |
stobu/core/outliner.py | NovelLab/storybuilder | 0 | 55455 | """Build outline module."""
# Official Libraries
# My Modules
from stobu.formats.outline import format_outlines_data
from stobu.syss import messages as msg
from stobu.tools.elmchecker import is_enable_the_elm
from stobu.tools.storydatareader import elm_outline_of, elm_title_of
from stobu.tools.translater import tran... | 2.265625 | 2 |
examples/educational/dipoles_and_loops.py | prisae/empymod | 31 | 55456 | r"""
Difference between magnetic dipole and loop sources
===================================================
In this example we look at the differences between an electric loop loop, which
results in a magnetic source, and a magnetic dipole source.
The derivation of the electromagnetic field in Hunziker et al. (2015)... | 3.140625 | 3 |
getData.py | expo7/stockBot123 | 0 | 55457 | import csv
from binance.client import Client
import pandas as pd
KEY ='<KEY>'
SECRET='<KEY>'
client = Client(KEY, SECRET)
candlesticks = client.get_historical_klines("BTCUSDT", Client.KLINE_INTERVAL_1DAY, "1 Jan, 2020", "12 Feb, 2020")
print(candlesticks)
time=[]
open=[]
high=[]
low=[]
close=[]
cols=['time', 'open', '... | 2.84375 | 3 |
Tests/test_tictactoe.py | Eberhofer/TicTacToe | 0 | 55458 | <reponame>Eberhofer/TicTacToe<filename>Tests/test_tictactoe.py<gh_stars>0
# import pyytest
from TicTacToe.tictactoe import winners, check_win, winning_combinations
from TicTacToe.tictactoe import reduce_winners
winning_set = winners()
class TestWinningSet:
def test_winners(self):
testwinners = [{1, 2, 3}... | 2.75 | 3 |
src/mav.py | yusufalptigin/StockMarketSaaSWebsite | 0 | 55459 | <reponame>yusufalptigin/StockMarketSaaSWebsite
import numpy as np
import csv
import os
from pathlib import Path
from datetime import datetime
def movingAverages(csvString):
listOfData = list(csv.DictReader(open(str(Path(__file__).resolve().parent) + "/../All Csv Data/" + csvString, mode='r')))
mavList =... | 2.75 | 3 |
tests/clickhouse.py | guoshuai2016/clickhouse-operator | 0 | 55460 | from kubectl import *
def clickhouse_query(chi_name, query, with_error = False, host = "127.0.0.1", port = "9000", user = "default", pwd = "", ns="test"):
pod_name = kube_get_pod_names(chi_name, ns)[0]
if (pwd != ""):
pwd_str = f"--password={<PASSWORD>}"
else:
pwd_str = ""
if (with_er... | 2.1875 | 2 |
account/serializer.py | k-koech/projects_review | 0 | 55461 | from django.contrib.auth import authenticate
from rest_framework import exceptions, serializers
from .models import Projects, Users
class MerchSerializer(serializers.ModelSerializer):
class Meta:
model = Projects
fields = ('title', 'description', 'image','link','date_posted','user')
class MerchUse... | 2.484375 | 2 |
tests/sentry/api/endpoints/test_project_user_reports.py | kl07/sentry | 20 | 55462 | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.testutils import APITestCase
from sentry.models import UserReport
class ProjectUserReportsTest(APITestCase):
def test_simple(self):
self.login_as(user=self.user)
project = self.create_project()
... | 2.25 | 2 |
Code_Challenges/string_rearrangement2.py | mvkumar14/Practice | 0 | 55463 | <reponame>mvkumar14/Practice<filename>Code_Challenges/string_rearrangement2.py
import itertools
def stringsRearrangement(inputArray):
compare = inputArray[0]
distances = []
for i in itertools.permutations(inputArray):
if sequence(i):
return True
return False
def distance(a,b):... | 4 | 4 |
scripts/vis_urdf.py | lianghongzhuo/urdfpy | 122 | 55464 | """
Script for visualizing a robot from a URDF.
Author: <NAME>
"""
import argparse
import urdfpy
if __name__ == '__main__':
# Parse Args
parser = argparse.ArgumentParser(
description='Visualize a robot from a URDF file'
)
parser.add_argument('urdf', type=str,
help='Pat... | 3.421875 | 3 |
MemberShip/web/test/test_header.py | zzragida/PythonExamples | 0 | 55465 | # -*- coding:utf-8 -*-
import os
import sys
sys.path.insert(0, '../')
import unittest
import membership_pb2
import utils
import models
class HeaderTest(utils.TestCase):
SERVICE_PLATFORM = models.service_platform()
PROTOCOL_VERSION = models.protocol_version()
def setUp(self):
app = models.app(app_id=1)
... | 2.40625 | 2 |
collectors/PDChaos.py | gfek/Lepus | 218 | 55466 | import requests
from json import loads
from termcolor import colored
from configparser import RawConfigParser
def init(domain):
PDCH = []
print(colored("[*]-Searching Project Discovery Chaos...", "yellow"))
parser = RawConfigParser()
parser.read("config.ini")
CHAOS_KEY = parser.get("PDChaos", "CHAOS_API_KEY")
... | 2.796875 | 3 |
src/config.py | vms10/meli-data-challenge-2021 | 22 | 55467 | from pathlib import Path
def absolute_path(path):
src_path = str(Path(__file__).parent.resolve())
return src_path + "/" + path
# Paths
DATASET_DIRECTORY = absolute_path("../dataset")
CLEAN_DATA_PATH = absolute_path("clean_data")
TIME_SERIES_PATH = absolute_path("clean_data/series.npy")
TRAINED_MODELS_PATH =... | 2.328125 | 2 |
Lib/Lib_Kafka.py | charles-hsiao/robotframework-kafka | 6 | 55468 | from pykafka import KafkaClient, exceptions
import logging, time
from robot.api import logger
import re
logging.basicConfig()
# RobotFramework.logger: http://robot-framework.readthedocs.org/en/2.9.2/_modules/robot/api/logger.html
# Print message to RobotFramework console & python output
def msg_print(msg):
print... | 2.296875 | 2 |
env/Lib/site-packages/OpenGL/GLES2/ANGLE/program_binary.py | 5gconnectedbike/Navio2 | 210 | 55469 | '''OpenGL extension ANGLE.program_binary
This module customises the behaviour of the
OpenGL.raw.GLES2.ANGLE.program_binary to provide a more
Python-friendly API
Overview (from the spec)
This extension makes available a program binary format,
PROGRAM_BINARY_ANGLE. It enables retrieving and loading of pre-linked
... | 2.3125 | 2 |
data.py | parasdahal/infersent | 1 | 55470 | <filename>data.py
import os
import torch
from torchtext.data import Field, Iterator
from torchtext.datasets import SNLI
import spacy
spacy_en = spacy.load('en_core_web_sm')
class SNLIData():
def __init__(self, batch_size):
self.text = Field(
lower=True,
tokenize=lambda x: [tok.text for tok i... | 2.53125 | 3 |
fowd/cli.py | dionhaefner/FOWD | 3 | 55471 | <filename>fowd/cli.py
"""
cli.py
Entry point for CLI.
"""
import os
import sys
import math
import logging
import datetime
import tempfile
import click
import tqdm
from . import __version__
@click.group('fowd', invoke_without_command=True)
@click.version_option(version=__version__)
@click.pass_context
def cli(ctx)... | 2.234375 | 2 |
git_info.py | ryanzav/birdseye | 41 | 55472 | import subprocess
import os
def getBlame(f):
folder = os.path.split(f)[0]
cwd = os.getcwd()
os.chdir(folder)
cmd = "git blame --abbrev=0 -e \"" + f + "\""
try:
sub = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
response, err = sub.comm... | 2.609375 | 3 |
nevergrad/functions/ac/ac.py | mathuvu/nevergrad | 0 | 55473 | <reponame>mathuvu/nevergrad
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Optimization of the FAO crop management model.
Based on
https://colab.research.google.com/github/thomasdkel... | 2.265625 | 2 |
datasets.py | aseldawy/deep-spatial-join | 0 | 55474 | import numpy as np
import pandas as pd
from sklearn import preprocessing
import math
def load_datasets_feature(filename):
features_df = pd.read_csv(filename, delimiter='\\s*,\\s*', header=0)
return features_df
def load_join_data3(features_df, result_file, histograms_path, num_rows, num_columns):
cols = ... | 3.21875 | 3 |
__init__.py | JarbasAl/fallback-node-red | 16 | 55475 | from mycroft.messagebus.message import Message, dig_for_message
from mycroft.skills.core import FallbackSkill, intent_file_handler, intent_handler
from adapt.intent import IntentBuilder
from jarbas_hive_mind_red import get_listener
from jarbas_hive_mind.settings import CERTS_PATH
from jarbas_hive_mind.database import C... | 1.679688 | 2 |
backend/apps/question/serializers/category.py | xingxingzaixian/django-vue3.2-online-exam | 3 | 55476 | from rest_framework import serializers
from question.models import TblQuestionCategory
class QuestionCategorySerializer(serializers.ModelSerializer):
class Meta:
model = TblQuestionCategory
fields = '__all__' | 1.96875 | 2 |
chapter_12/07_recursive_power_method.py | SergeHall/Tony-Gaddis-Python-4th | 2 | 55477 | # recursive power method
# 7. Рекурсивный метод возведения в степень. Разработайте функцию, в
# которой рекурсия применяется для возведения числа в степень. Данная
# функция должна принимать два аргумента: число, которое будет возведено в
# степень, и показатель степени. Исходите из того, что показатель степени
# ... | 4.25 | 4 |
setup.py | YOCKOW/PythonGitHubActionsWorkflowRepresentation | 0 | 55478 | from setuptools import setup, find_packages
setup(
name='GitHub Actions Workflow Representation',
version='0.9.2',
description='Workflow representation for GitHub Actions.',
long_description='See README.md',
author='YOCKOW',
url='https://github.com/YOCKOW/PythonGitHubActionsWorkflowRepresentati... | 1.210938 | 1 |
apps/baliza/apps.py | wisrovi/Server-Hospital-Smart-Bracelet | 0 | 55479 | <reponame>wisrovi/Server-Hospital-Smart-Bracelet
from django.apps import AppConfig
class BalizaConfig(AppConfig):
name = 'baliza'
| 1.34375 | 1 |
liv_learn/legacy/study/solubility.py | neilswainston/synbiochem-learn | 0 | 55480 | <reponame>neilswainston/synbiochem-learn
'''
(c) University of Liverpool 2019
All rights reserved.
@author: neilswainston
'''
# pylint: disable=invalid-name
# pylint: disable=wrong-import-order
from rdkit.Chem import MolFromSmiles
from liv_learn.keras import k_folds_nn
from liv_learn.utils.biochem_utils import get_t... | 2.34375 | 2 |
src/ctc/protocols/uniswap_v3_utils/contracts/quoter.py | fei-protocol/checkthechain | 94 | 55481 | <reponame>fei-protocol/checkthechain
from __future__ import annotations
from ctc import rpc
from ctc import spec
from .. import uniswap_v3_spec
async def async_quote_exact_input_single(
token_in: spec.Address,
token_out: spec.Address,
fee: int,
amount_in: int,
sqrt_price_limit_x96: int = 0,
... | 1.976563 | 2 |
app/helpers/exceptions.py | ONSdigital/sdx-downstream-ctp | 0 | 55482 | <reponame>ONSdigital/sdx-downstream-ctp
class BadMessageError(Exception):
# A bad message is broken in some way that will never be accepted by
# the endpoing and as such should be rejected (it will still be logged
# and stored so no data is lost)
pass
class RetryableError(Exception):
# A retryable... | 2.03125 | 2 |
_ipf_api.py | jamieparks/IPFabric | 1 | 55483 | <reponame>jamieparks/IPFabric<gh_stars>1-10
import requests,sys
# Suppressing SSL certificate warnings if needed
requests.packages.urllib3.disable_warnings()
def api_auth(username, password, base_url):
authEndpoint = base_url + 'auth/login'
authData = { 'username': username, 'password' : password }
... | 2.6875 | 3 |
utils.py | Yuexiaoxi10/Key-Frame-Proposal-Network-for-Efficient-Pose-Estimation-in-Videos | 46 | 55484 | import os
import numpy as np
import random
from math import isclose
import torch
import matplotlib.pyplot as plt
from modelZoo.DyanOF import OFModel, fista
from torch.autograd import Variable
import torch.nn
def gridRing(N):
# epsilon_low = 0.25
# epsilon_high = 0.15
# rmin = (1 - epsilon_low)
# rmax ... | 2.3125 | 2 |
bot.py | ali-moments/system-controler | 0 | 55485 | from telegram.ext import Updater,CommandHandler
import subprocess
updater = Updater("TOKEN",use_context = True)
def start_method(update,context):
context.bot.sendMessage(update.message.chat_id,"Connected !")
def run_command(update,context):
command = ""
for i in context.args:
command += i+" "
... | 2.5 | 2 |
server.py | simondevries/Snake-neural-network | 4 | 55486 | import socket
import select
import time
import datetime
import random
from collections import deque, namedtuple
BOARD_LENGTH = 32
OFFSET = 16
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
DIRECTIONS = namedtuple('DIRECTIONS',
['Up', 'Down', 'Left', 'Right'])(0, 1, 2, 3)
SNAKE... | 2.953125 | 3 |
alpha/app/__init__.py | SonneSun/edu | 0 | 55487 | from flask import Flask
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from config import config
bootstrap = Bootstrap()
moment = Moment()
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name]... | 2.3125 | 2 |
hatloads/payloads/__init__.py | YurinDoctrine/HatLoads | 1 | 55488 | #!/usr/bin/env python3
#
# MIT License
#
# Copyright (c) 2020-2022 EntySec
#
# 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... | 1.828125 | 2 |
format_world_bank.py | hoddy3190/wb_data_downloader | 0 | 55489 | import pandas as pd
import glob
# alpha3Codeをindexに設定して読み込む
country_data = pd.read_csv('../../country.csv', keep_default_na=False, index_col=0)
# 空行を除いて3行目からデータがスタートする(適宜要調整)
# 2列目の「Country Code」をindexに設定する。country.csvと同じ値が入るカラムをindexに指定する必要がある(適宜要調整)
raw_csv = glob.glob('API*.csv')[0]
data = pd.read_csv(raw_csv, hea... | 3 | 3 |
utils/money.py | Pythonian/bsawf | 1 | 55490 | <reponame>Pythonian/bsawf
def cents_to_dollars(cents):
"""
Convert cents to dollars.
:param cents: Amount in cents
:type cents: int
:return: float
"""
return round(cents / 100.0, 2)
def dollars_to_cents(dollars):
"""
Convert dollars to cents.
:param dollars: Amount in dollars... | 3.5 | 4 |
ncg/optimization/setup.py | LaudateCorpus1/ml-ncg | 10 | 55491 | <reponame>LaudateCorpus1/ml-ncg
from setuptools import setup
NAME = 'optimization'
DESCRIPTION = ' NCG optimization library'
URL = 'https://arxiv.org/abs/1812.02886'
EMAIL = '<EMAIL>','<EMAIL>'
AUTHOR = '<NAME>', '<NAME>'
VERSION = 0.1
REQUIRED=['tensorflow-gpu>=1.4, <=1.8',\
'horovod==0.13.3']
def find_pac... | 1.4375 | 1 |
accounts/migrations/0008_userprofile_private.py | mohsenamoon1160417237/Social_app | 0 | 55492 | # Generated by Django 2.2 on 2020-09-18 06:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0007_contact'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='private',
... | 1.703125 | 2 |
rrunner/common/handle_path.py | jigangc/rrunner | 0 | 55493 | import os
# 获取当前文件目录的根目录
DIR = os.path.dirname(os.path.dirname(__file__))
# 定义测试数据的存放目录
DATA_DIR = os.path.join(DIR, 'data')
# 定义用例存放的根目录
CASE_DIR = os.path.join(os.getcwd(), "testcases")
# 定义报告存放的根目录
REPORT_DIR = os.path.join(os.getcwd(), 'reports')
# 定义配置文件存放的根目录
CONFIG_DIR = os.path.join(DIR, 'config')
# 测试文件目录
TES... | 2.421875 | 2 |
wavepal/ridges/blocknum.py | metegenez/WAVEPAL | 22 | 55494 | <reponame>metegenez/WAVEPAL<gh_stars>10-100
import numpy as np
def blocknum(x):
"""BLOCKNUM Numbers the contiguous blocks of an array.
Suppose X is a column vector which contains blocks of identical
values, e.g. X=[0 0 0 1 1 3 2 2 2]
N, A, B=BLOCKNUM(X) gives each contiguous block of identical values a
... | 3.640625 | 4 |
QUANTAXIS/QAUtil/QASetting.py | 5267/QUANTAXIS | 5 | 55495 | from QUANTAXIS.QAUtil import QA_util_log_info,QA_util_sql_mongo_setting
from QUANTAXIS.QASU.user import QA_user_sign_in,QA_user_sign_up
class QA_Setting():
QA_util_sql_mongo_ip='127.0.0.1'
QA_util_sql_mongo_port='27017'
client=QA_util_sql_mongo_setting(QA_util_sql_mongo_ip,QA_util_sql_mongo_port)
... | 2.5 | 2 |
allcode.py | keiikegami/midtermtest | 0 | 55496 | <gh_stars>0
# import packages
% matplotlib inline
from scipy.stats import invgamma
from scipy.stats import norm
from multiprocessing import Pool
from datetime import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# setting
pine = pd.read_table("pine.txt", delim_whitespace = True)
p = ... | 2.28125 | 2 |
Classifier/PoseEmbedder.py | RandomForestGump/ProFitness | 1 | 55497 | import tqdm
import mediapipe
import requests
import cv2
import numpy as np
import matplotlib
class FullBodyPoseEmbedder(object):
"""Converts 3D pose landmarks into 3D embedding."""
def __init__(self, torso_size_multiplier=2.5):
# Multiplier to apply to the torso to get minimal body size.
se... | 2.65625 | 3 |
tests/conftest.py | bharathjinka09/flask-pytest-registration | 0 | 55498 | import pytest
from project import create_app, db
from project.models import User
@pytest.fixture(scope='module')
def new_user():
user = User('<EMAIL>', '<PASSWORD>')
return user
@pytest.fixture(scope='module')
def test_client():
flask_app = create_app('flask_test.cfg')
# Create a test client using ... | 2.453125 | 2 |
minimal_user/__init__.py | ionata/django-minimal-user | 0 | 55499 | <gh_stars>0
from pkg_resources import get_distribution
__version__ = get_distribution('django-minimal-user').version
| 1.164063 | 1 |