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_db.py | heptaliane/RankingAnnotator | 1 | 12796051 | # -*- coding: utf-8 -*-
import os
from unittest import TestCase
import tempfile
from server import db
def use_temp_db(filename):
def _use_temp_db(fn):
def wrapper(obj):
with tempfile.TemporaryDirectory() as dirname:
fn(obj, os.path.join(dirname, filename))
return wrapp... | 2.953125 | 3 |
acousticsim/analysis/formants/lpc.py | JoFrhwld/python-acoustic-similarity | 5 | 12796052 | <filename>acousticsim/analysis/formants/lpc.py
import librosa
import numpy as np
import scipy as sp
from scipy.signal import lfilter
from scipy.fftpack import fft,ifft
from scipy.signal import gaussian
from ..helper import fix_time_points, nextpow2
def lpc_ref(signal, order):
"""Compute the Linear Prediction Co... | 2.359375 | 2 |
src/pyqp/__main__.py | MMSB-MOBI/pyqp | 0 | 12796053 | """Quantitative Proteomic Service
Usage:
pyqp api
pyqp cli <proteomicTSV> <proteomeXML> [--field=<quantity_column>] [--adress=<apiAdress>] [--port=<apiPort>] [--verbose] [--topScore=<pathway_number>]
Options:
-h --help Show this screen.
--field=<quantity column> csv column header featuring signal
... | 2.1875 | 2 |
phase3/consumer-new-customer.py | amanda-wink/Kafka3-Data | 0 | 12796054 | from kafka import KafkaConsumer, TopicPartition
from json import loads
from sqlalchemy import create_engine, Table, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
import os
user = os.getenv('MYSQL_user')
pw = os.getenv('MYSQL')
str_sql = 'mysql+mysqlconnector://' + user + ':' + pw + '@... | 2.78125 | 3 |
Server/diarization_service.py | mmlabox/TeamAudio | 0 | 12796055 | import os
from google.cloud import speech_v1p1beta1 as speech
import io
#Set env variable, because it resets every shell session
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/home/robin_jf_andersson/mbox_speaker_diarization/mbox1-28508a73fde1.json"
def speaker_diarization(audio_file, channels, sample_rate, nbr_of_... | 2.984375 | 3 |
Parabola/prop1_probs.py | pdcxs/ManimProjects | 29 | 12796056 | from manimlib.imports import *
from ManimProjects.utils.Parabola import Parabola
from ManimProjects.utils.geometry import CText
class Prob1(Parabola):
CONFIG = {
'x_min' : -5
}
def construct(self):
self.adjust_x_range()
graph = self.get_graph(color=LIGHT_BROWN)
directrix = s... | 2.515625 | 3 |
pyfuseki/rdf/rdf_prefix.py | yubinCloud/pyfuseki | 21 | 12796057 | <reponame>yubinCloud/pyfuseki
"""
@Time: 2021/9/18 13:04
@Author:
@File: rf_prefix.py
"""
import rdflib
from pyfuseki import config
import uuid
name_to_uri = dict()
class NameSpace(rdflib.Namespace):
"""
继承 rdflib 的 Namespace 并扩充其他相关的功能
"""
def __getitem__(self, key) -> rdflib.URIRef:
retur... | 2.390625 | 2 |
Python 3 - Curso completo/exercicio067.py | PedroMunizdeMatos/Estudos-e-Projetos | 0 | 12796058 | '''faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado
pelo usuário. O programa será interrompido quando o valor solicitado for negativo.'''
from time import sleep
n = 0
cont = 0
while n >= 0:
print('--' * 15)
print('\033[33mPara cancelar, digite um número negativo.... | 3.9375 | 4 |
src/core.py | foutoucour/nepo | 1 | 12796059 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import os
from contextlib import contextmanager
import click
import crayons
def open_url(url):
click.echo("Opening {}.".format(crayons.white(url, bold=True)))
click.launch(url)
def get_config_file_path():
home = os.path.expanduser("~")
retur... | 3.125 | 3 |
src/tanuki/database/adapter/query/query_compiler.py | M-J-Murray/tanuki | 0 | 12796060 | <gh_stars>0
from __future__ import annotations
from typing import Any, Generic, TYPE_CHECKING, TypeVar, Union
T = TypeVar("T")
from tanuki.data_store.query import Query
if TYPE_CHECKING:
from tanuki.data_store.query import (
AndGroupQuery,
AndQuery,
EqualsQuery,
GreaterEqualQuery... | 2.359375 | 2 |
trade_fetcher.py | jianwang0212/napoli_gang | 1 | 12796061 | import json
import requests
import ccxt
import time
import os
import pandas as pd
from datetime import datetime, timedelta
import operator
import csv
import cfg
liquid = ccxt.liquid(cfg.liquid_misc_credential)
exchange = liquid
since = exchange.milliseconds() - 86400000 # -1 day from now
def save_and_get_str():
... | 2.484375 | 2 |
mytb/datetime.py | quentinql/mytb | 0 | 12796062 | import re
from datetime import datetime
from datetime import timedelta
import dateutil.parser
import pytz
import tzlocal
# datetime objct for beginning of epoch
T_EPOCH = datetime(1970, 1, 1, tzinfo=pytz.utc)
DEFAULT = object() # singleton, for args with default values
class DateTimeError(Exception):
""" custo... | 2.96875 | 3 |
izzy.py | imre-kerr/better-ea | 0 | 12796063 | from __future__ import division
from ea import float_gtype
from ea import adult_selection
from ea import parent_selection
from ea import reproduction
from ea import main
from ea.ea_globals import *
import pylab
import sys
import copy
import multiprocessing as mp
def spiketrain(a, b, c, d, k,):
'''Compute a spike t... | 2.703125 | 3 |
contrib/python/CUBRIDdb/connections.py | eido5/cubrid | 253 | 12796064 | """
This module implements connections for CUBRIDdb. Presently there is
only one class: Connection. Others are unlikely. However, you might
want to make your own subclasses. In most cases, you will probably
override Connection.default_cursor with a non-standard Cursor class.
"""
from CUBRIDdb.cursors import *
import t... | 3.234375 | 3 |
client.py | pereztjacob/http-server | 0 | 12796065 | <reponame>pereztjacob/http-server
import sys
import socket
def client(message):
s = socket.socket()
host = socket.gethostname()
res = socket.gethostbyaddr("127.0.0.1")
host = res[0]
try:
s.connect((host, 12345))
except:
print("connection failed")
else:
s.send(str.en... | 2.90625 | 3 |
Python/math/sum_of_digits.py | TechSpiritSS/NeoAlgo | 897 | 12796066 | # Python program to Find the Sum of Digits of a Number
def sum_of_digits(num):
# Extracting Each digits
# and compute thier sum in 's'
s = 0
while num != 0:
s = s + (num % 10)
num = num // 10
return s
if __name__ == '__main__':
# Input the number And
# Call the function
... | 4.28125 | 4 |
as2t.py | minitech/as2t | 1 | 12796067 | <gh_stars>1-10
import json
import tarfile
from typing import NamedTuple
_UINT32_SIZE = b'\x04\x00\x00\x00'
class FileRecord(NamedTuple):
path: str
offset: int
size: int
executable: bool
def _read_exact(f, count):
result = f.read(count)
if len(result) != count:
raise ValueError('Un... | 2.4375 | 2 |
coole/settings.py | ahDDD/jwt-template | 1 | 12796068 | """
Django settings for coole project.
Generated by 'django-admin startproject' using Django 1.11.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
i... | 1.820313 | 2 |
sparse/repos/pyomeca/tutorials/setup.py | yuvipanda/mybinder.org-analytics | 1 | 12796069 | from setuptools import setup
setup(name='tutorials',
version='POC',
url='https://github.com/pyomeca/tutorials.git',
author='pyomeca',
packages=['src'],
zip_safe=False)
| 1.007813 | 1 |
troposphere/cassandra.py | compose-x/troposphere | 0 | 12796070 | <filename>troposphere/cassandra.py
# Copyright (c) 2012-2022, <NAME> <<EMAIL>>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
from . import AWSObject, AWSProperty, PropsDictType, Tags
from .validators import boolean, integer
from .validators.cassan... | 1.929688 | 2 |
app/utils/game_logic.py | lik33v3n/Tower-of-God | 3 | 12796071 | import random
import json
import math
async def battle_attack(x, y, u, e, call):
if x == y:
await call.answer("❗ Противник увернулся от удара", show_alert=True)
return e.health, e.defence
else:
if e.defence <= 0:
e.health -= u.damage
return e.health, e.defence
... | 2.859375 | 3 |
app/components/menu.py | TechPriestJon/ChessPython | 0 | 12796072 | <gh_stars>0
import pyglet
from .button import Button
from .border import Border
class Menu:
def __init__(self, x, y, background):
self.__x = x
self.__y = y
#self.__image = pyglet.image.load(background)
#self.__sprite = pyglet.sprite.Sprite(self.__image, x, y - self.__image.height)
... | 2.890625 | 3 |
packages/news_classifier/news_classifier/utils/load_data.py | marco-cardoso/ML-News-article-classification-architecture | 0 | 12796073 | import pandas as pd
from news_classifier.database import db
def load_data(projection: dict) -> pd.DataFrame:
"""
Load the data from the Mongo collection and transform
into a pandas dataframe
:projection: A dictionary with the fields to load from database
:return: A pandas dataframe with the data
... | 3.234375 | 3 |
pvlib/clearsky.py | dpete2008/Sandia | 0 | 12796074 | <gh_stars>0
"""
The ``clearsky`` module contains several methods
to calculate clear sky GHI, DNI, and DHI.
"""
from __future__ import division
import os
from collections import OrderedDict
import numpy as np
import pandas as pd
from pvlib import tools
def ineichen(apparent_zenith, airmass_absolute, linke_turbidit... | 2.34375 | 2 |
utils/utils.py | toandaominh1997/ProductDetectionShopee | 0 | 12796075 | import torch
def get_state_dict(model):
if type(model) == torch.nn.DataParallel:
state_dict = model.module.state_dict()
else:
state_dict = model.state_dict()
return state_dict
| 2.5 | 2 |
pylaprof/scripts/merge.py | glumia/pylaprof | 14 | 12796076 | #!/usr/bin/env python
import argparse
import sys
from collections import defaultdict
DEFAULT_OUT = "stackcollapse-merged.txt"
def merge(files, dst):
data = defaultdict(lambda: 0)
for file in files:
with open(file, "r") as fp:
for line in fp.readlines():
stack, hits = lin... | 3 | 3 |
src/imable_backend/app.py | AlinMH/imable-backend | 0 | 12796077 | import os
from fastapi import Depends, FastAPI, Response, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi_users import FastAPIUsers
from fastapi_users.authentication import JWTAuthentication
from sqlalchemy.orm import Session
from .database.session import database, user_db
from .deps import db_... | 2.078125 | 2 |
api/tf_auth/migrations/0003_populate_email_preferences.py | prattl/teamfinder-web | 9 | 12796078 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-04-15 17:10
from __future__ import unicode_literals
from django.db import migrations
class EmailTag:
ALL = 0
UPDATES = 1
PLAYER_NOTIFICATIONS = 2
TEAM_NOTIFICATIONS = 3
CHOICES = (
(ALL, 'All'),
(UPDATES, ... | 1.953125 | 2 |
edgify/functional/linear.py | scale-lab/BitTrain | 3 | 12796079 | <gh_stars>1-10
import torch
class Linear(torch.autograd.Function):
@staticmethod
def forward(ctx, input, weight, bias=None):
ctx.save_for_backward(input.to_sparse(), weight.to_sparse(), bias.to_sparse() if bias else None)
output = input.mm(weight.t())
if bias is not None:
... | 2.390625 | 2 |
tests/test_rate.py | kalaspuff/stockholm | 15 | 12796080 | <gh_stars>10-100
import json
import pytest
import stockholm
from stockholm import ConversionError, ExchangeRate, Money, Rate
def test_rate():
assert Rate(100) == 100
assert Rate("100.50551") == ExchangeRate("100.50551")
assert str(Rate("4711.1338")) == "4711.1338"
assert Rate(100).currency is None
... | 2.84375 | 3 |
GLM/source/plugins/minimal_plugin.py | tomsimonart/LMPM | 1 | 12796081 | <reponame>tomsimonart/LMPM
from ..libs.pluginbase import PluginBase
class Plugin(PluginBase):
def __init__(self, start, *args):
super().__init__(start, *args)
def _plugin_info(self):
"""Required informations about the plugin
"""
self.version = "0.11.0"
self.data_dir = "... | 2.34375 | 2 |
singlecell/util.py | johannesnicolaus/singlecell | 0 | 12796082 | """Utility functions."""
import subprocess
import logging
import os
import shutil
import stat
import itertools
from collections import OrderedDict
from pkg_resources import resource_string
import pandas as pd
from genometools.expression import ExpGeneTable
from genometools import gtf
import singlecell
_LOGGER = lo... | 2.609375 | 3 |
app.py | maguowei/aweme-sign | 2 | 12796083 | import os
import frida
from flask import Flask, jsonify, request
from hook import start_hook
REMOTE_DEVICE = os.getenv('REMOTE_DEVICE', '')
app = Flask(__name__)
api = start_hook(REMOTE_DEVICE)
@app.route('/sign')
def sign():
global api
url = request.args.get('url', '')
headers = dict(request.headers)... | 2.328125 | 2 |
aserializer/fields/time_fields.py | orderbird/aserializer | 0 | 12796084 | <reponame>orderbird/aserializer<filename>aserializer/fields/time_fields.py<gh_stars>0
# -*- coding: utf-8 -*-
from datetime import datetime, date, time
from aserializer.utils import py2to3
from aserializer.fields.base import BaseSerializerField, SerializerFieldValueError
from aserializer.fields import validators as v... | 2.40625 | 2 |
_scripts/objecteditor/controller/newproduction.py | Son-Guhun/Titan-Land-Lands-of-Plenty | 12 | 12796085 | import PySimpleGUI as sg
from ..model.objectdata import ObjectData
from ..model.search import SearchableList
from ..view import newproduction
from . import get_string_unit, RACES, filter_listbox
from myconfigparser import Section
def open_window(data):
options = SearchableList()
for u in data:
unit = ... | 2.453125 | 2 |
DallasPlayers/soft_grudger_player.py | fras2560/Competition | 0 | 12796086 | '''
@author: <NAME>
@id: 20652186
@class: CS686
@date: 2016-02-13
@note: contains a player using an soft grudge strategy
'''
from DallasPlayers.player import COOPERATE, Player, DEFECT
import unittest
class SoftGrudgerPlayer(Player):
"""
Soft Grudger Player - Co-operates until the opponent defects,
... | 3.390625 | 3 |
beats/migrations/0003_auto_20210809_1938.py | cybrvybe/FactorBeats-Platform | 0 | 12796087 | # Generated by Django 3.2.3 on 2021-08-10 02:38
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('artists', '0002_artist_bio'),
('beats', '0002_instrumental_img_file'),
]
operations = [
... | 1.523438 | 2 |
autodiscover/util/helper.py | macbryc/IX-DiscoveryTools | 3 | 12796088 | <reponame>macbryc/IX-DiscoveryTools
#Copyright 2021, Battelle Energy Alliance, LLC
from uuid import uuid4
from stix2.datastore import Filter, FilterSet
from stix2 import Software, Process, IPv4Address, Infrastructure, Relationship, CustomExtension, properties
import logging
import re
def gen_uuid(string):
return ... | 2.015625 | 2 |
examples/dataPipe.py | kirillovmr/python-pipeline | 2 | 12796089 | import os
import sys
sys.path.append(os.path.join(sys.path[0], '../'))
from smart_pipeline import Pipeline
data = [1,2,3,4,5]
# Define a data function
def onlyOdd(item):
return False if item%2==0 else True
pl = Pipeline()
# Adds function into pipeline
pl.addDataPipe(onlyOdd)
res = pl(data)
for item in res:
... | 2.734375 | 3 |
y2_test_feed_tensor.py | ZhengDeQuan/AAA | 0 | 12796090 | import tensorflow as tf
batch_size = 4
feature_num = 3
csv1 = [
"harden|james|curry",
"wrestbrook|harden|durant",
"paul|towns",
]
csv2 = [
"curry",
"wrestbrook|harden|durant",
"paul|towns",
]
csv3 = [
"harden|james|curry",
"durant",
"paul|towns",
]
csv4 = [
"wrestbrook|harden|durant",
"wrestbrook|harden|... | 2.421875 | 2 |
products/migrations/0008_auto_20201019_1155.py | akshaynot/farmedorganic | 0 | 12796091 | <reponame>akshaynot/farmedorganic
# Generated by Django 3.1.2 on 2020-10-19 11:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0007_product_detail'),
]
operations = [
migrations.RemoveField(
model_name='produc... | 1.554688 | 2 |
python/experiments/feedback/bcipy_psd_explore.py | oken-cognitive-neuroscience-lab/scripts | 0 | 12796092 | <filename>python/experiments/feedback/bcipy_psd_explore.py
import csv
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
from bcipy.helpers.load import read_data_csv
from bcipy.signal.process.filter import bandpass, notch, downsample
from bcipy.helpers.task import trial_reshaper
f... | 2.390625 | 2 |
src/lightmlrestapi/testing/__init__.py | sdpython/lightmlrestapi | 0 | 12796093 | """
@file
@brief Shortcuts to *testing*.
"""
from .dummy_applications import dummy_application, dummy_application_image
from .dummy_applications import dummy_application_fct, dummy_application_neighbors, dummy_application_neighbors_image
from .dummy_applications import dummy_application_auth, dummy_mlstorage
| 1.070313 | 1 |
mnotes/cmd_index.py | mattj23/m-notes | 0 | 12796094 | """
Commands for index operations
"""
import os
import re
import sys
import time
from typing import List
from zipfile import ZipFile, ZIP_DEFLATED
from datetime import datetime as DateTime
import click
from mnotes.environment import MnoteEnvironment, pass_env, echo_line, save_global_index_data
from mnotes.notes.in... | 2.96875 | 3 |
src/evaluate_attn_maps.py | MkuuWaUjinga/leopart | 0 | 12796095 | import numpy as np
import os
import torch
import torch.nn as nn
import pytorch_lightning as pl
from data.VOCdevkit.vocdata import VOCDataset
from torch.utils.data import DataLoader
from torchvision.transforms import Compose, Resize, ToTensor, Normalize, GaussianBlur
from torchvision.transforms.functional import Interp... | 2.078125 | 2 |
students/K33402/Karatetskaya_Maria/lab1/4/server.py | marysadness/ITMO_ICT_WebDevelopment_2021-2022 | 0 | 12796096 | import socket, threading
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 9090
server.bind((host, port))
server.listen(5)
clients = list()
end = list()
def get():
while True:
client, addr = server.accept()
clients.append(client)
print(f'сервер подключе... | 3.125 | 3 |
src/deep_autoencoder.py | Cc618/PyTorch-Collections | 0 | 12796097 | # Autoencoder using convolutional layers
# Dataset : MNIST
# Requires : PIL, matplotlib
# Inspired by https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html
# To compress data : net.encode(data)
# To decompress data : net.decode(data)
# To mutate data : net(data)
import os
import numpy as np
import matplot... | 3.203125 | 3 |
src/main/python/monocyte/handler/ec2.py | claytonbrown/aws-monocyte | 20 | 12796098 | # Monocyte - Search and Destroy unwanted AWS Resources relentlessly.
# Copyright 2015 Immobilien Scout GmbH
#
# 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/licens... | 2.015625 | 2 |
vendas/forms.py | Moisestuli/karrata | 0 | 12796099 | <gh_stars>0
from django import forms
from vendas.models import Venda
class VendaAdminForm(forms.ModelForm):
class Meta:
model = Venda
fields = ('nome_client','telefone','cidade','email','produto','deu',) | 1.84375 | 2 |
deck_code.py | BenWiederhake/solitaire_aide | 0 | 12796100 | #!/usr/bin/env python3
import common
import os
import sys
def run_encode(base):
x = 0
for i in range(base)
b = sys.stdin.buffer.read(1)
if b == b'':
break
def run_decode(base):
raise NotImplementedError()
def usage(progname):
print('USAGE: {} {{encode | decode}} [<BASE... | 3.359375 | 3 |
twitch-chat-reader/acapyla.py | Evshaddock/scripts | 11 | 12796101 | from pathlib import Path
import requests
import string
import urllib
import random
import json
import sys
def acapyla(quote, voicename="willfromafar"):
try:
voiceid = "enu_" + voicename + "_22k_ns.bvcu"
except IndexError:
voiceid = "enu_willfromafar_22k_ns.bvcu"
letters = string.ascii_lower... | 2.71875 | 3 |
getFeed.py | kjohn01/fbexample | 0 | 12796102 | <gh_stars>0
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import json
import datetime
import pandas as pd
from dateutil.parser import parse
def handleDate(x):
if isinstance(x, datetime.date):
return "{}-{}-{}".format(x.year, x.month, x.day)
token = '<KEY>'
group = {'689157281218904':'台北技能交換'}... | 2.75 | 3 |
agnes/algos/configs/a2c_config.py | rotinov/CITUS | 24 | 12796103 | <gh_stars>10-100
from typing import Dict, Tuple
def atari_config() -> Dict:
return dict(
timesteps=10e6,
nsteps=32,
nminibatches=1,
gamma=0.99,
lam=0.95,
noptepochs=1,
max_grad_norm=0.5,
learning_rate=lambda x: 7e-4*x,
vf_coef=0.5,
en... | 2.484375 | 2 |
cottonformation/res/batch.py | MacHu-GWU/cottonformation-project | 5 | 12796104 | # -*- coding: utf-8 -*-
"""
This module
"""
import attr
import typing
from ..core.model import (
Property, Resource, Tag, GetAtt, TypeHint, TypeCheck,
)
from ..core.constant import AttrMeta
#--- Property declaration ---
@attr.s
class PropJobDefinitionAuthorizationConfig(Property):
"""
AWS Object Type =... | 1.953125 | 2 |
monitor/utils/mail.py | laozhudetui/wam | 227 | 12796105 | #!/usr/bin/env python
# coding: utf-8
# __buildin__ modules
import smtplib
from email.mime.text import MIMEText
from monitor.utils.settings import EMAIL_SERVER
from monitor.utils.settings import EMAIL_PORT
from monitor.utils.settings import EMAIL_USER
from monitor.utils.settings import EMAIL_PASS
from monitor.utils.s... | 2.25 | 2 |
py_kiwoom/kiwoom_evol.py | ijhan21/hackathon_kiwoom | 0 | 12796106 | <gh_stars>0
import os
import pickle
import sys
from PyQt5.QAxContainer import *
from PyQt5.QtCore import *
from config.errorCode import *
from PyQt5.QtTest import *
from config.kiwoomType import *
# from config.slack import *
import logging
from PyQt5.QtWidgets import *
STOP_LOSS_RATE = 0.03
STOP_PROFIT_RATE = 0.03
#... | 2.0625 | 2 |
ibsng/handler/session/__init__.py | ParspooyeshFanavar/pyibsng | 6 | 12796107 | """Session library."""
| 1.007813 | 1 |
src/runner.py | jayantik/AiCorExample | 0 | 12796108 | <filename>src/runner.py
import collections
import torch
# Train
# Validate
# On given arguments, data
def run(model, criterion, optimizer, dataset, is_training: bool, **metrics):
model.train(is_training)
dictionary = collections.defaultdict(int)
counter = 0
with torch.set_grad_enabled(is_training)... | 2.890625 | 3 |
pl_bolts/callbacks/ssl_online.py | Aayush-Jain01/lightning-bolts | 504 | 12796109 | <filename>pl_bolts/callbacks/ssl_online.py
from contextlib import contextmanager
from typing import Any, Dict, Optional, Sequence, Tuple, Union
import torch
from pytorch_lightning import Callback, LightningModule, Trainer
from pytorch_lightning.utilities import rank_zero_warn
from torch import Tensor, nn
from torch.nn... | 2.265625 | 2 |
math/stochastic_modeling/program.py | spideynolove/Other-repo | 0 | 12796110 | <reponame>spideynolove/Other-repo
import numpy as np
print("Hello stochastic_modeling!") | 1.273438 | 1 |
tests/regressions/python/530_augmented_assignment_indexed_lhs.py | frzfrsfra4/phylanx | 83 | 12796111 | # Copyright (c) 2018 <NAME>
# Copyright (c) 2018 <NAME>
#
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
from phylanx import Phylanx
import numpy as np
@Phylanx
def foo():
local_a = np.array((2, 1))
lo... | 1.9375 | 2 |
test/test-cases/conftest.py | vkuma82/DASH | 0 | 12796112 | import importlib
import json
import os
import sys
from pprint import pprint as pp
import pytest
import utils as util
from ixload import IxLoadTestSettings as TestSettings
from ixload import IxLoadUtils as IxLoadUtils
from ixload import IxRestUtils as IxRestUtils
from ixnetwork_restpy import SessionAssistant
from ixnet... | 1.859375 | 2 |
Array/MaxProductOfTwoElements.py | haaris272k/Problem-Solving-Collection | 1 | 12796113 | <filename>Array/MaxProductOfTwoElements.py
"""Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).
Example 1:
Input: nums = [3,4,5,2]
Output: 12
Explanation: If you choose the indices i=1 and j=2 (indexed from 0),... | 4.25 | 4 |
tests/test_attributes.py | uilianries/bintray-python | 4 | 12796114 | <filename>tests/test_attributes.py
import pytest
from bintray.bintray import Bintray
@pytest.fixture()
def create_attributes():
bintray = Bintray()
attributes = [{"name": "att1", "values": ["val1"], "type": "string"}]
return bintray.set_attributes("uilianries", "generic", "statistics", "test", attributes)... | 2.125 | 2 |
floodsystem/plot.py | vuquach99/1a-flood-warning-system | 0 | 12796115 | import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import datetime
from dateutil.tz import tzutc
def plot_water_levels(station, dates, levels):
"""Task 2E: Plots water level against time"""
#Assign variables
range_high = [station.typical_range[1]]*len(dates)
range_low = [station.ty... | 3.8125 | 4 |
sp_pipe.py | icanswim/seneca | 0 | 12796116 | <gh_stars>0
# Author: <NAME>
from __future__ import unicode_literals
import spacy
import numpy as np
class SpPipe():
def __init__(self):
self.nlp = spacy.load('en_core_web_md', disable=['ner','parser','tagger','textcat'])
def __call__(self, texts, labels, steps=10):
print 'tokenizing with spacy...'
... | 2.828125 | 3 |
app/api_tools.py | AndreyAD1/forum | 0 | 12796117 | from app import database
def get_single_json_entity(entity_query):
query_result_proxy = database.session.execute(entity_query)
database.session.commit()
row_proxies = [r for r in query_result_proxy]
if len(row_proxies) == 1:
json_entity = {k: v for k, v in row_proxies[0].items()}
else:
... | 2.40625 | 2 |
test.py | rykumar13/news-scrapper-backend | 0 | 12796118 | <filename>test.py
import requests
def main():
# url = "http://127.0.0.1:5000/"
url = "http://localhost:8080/"
raw_response = requests.get(url=url, auth=('api_username', 'api_password'))
if raw_response.status_code == 200:
result = raw_response.json()
print(result)
else:... | 2.984375 | 3 |
test/formats/test_mrea.py | randovania/retro-data-structures | 0 | 12796119 | <filename>test/formats/test_mrea.py
from pathlib import Path
import pytest
from retro_data_structures.base_resource import AssetId
from retro_data_structures.formats import Mlvl
from retro_data_structures.formats.mrea import MREA, Mrea
from retro_data_structures.game_check import Game
from test import test_lib
_mrea... | 2.234375 | 2 |
build/tools/build_resource_to_bytecode.py | openharmony-gitee-mirror/ace_ace_engine | 0 | 12796120 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Huawei Device Co., Ltd.
# 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
#
#... | 2.484375 | 2 |
config.py | nowindxdw/flask_base | 0 | 12796121 | <filename>config.py
#!/usr/bin/env python
# encoding: utf-8
import os
basedir = os.path.abspath(os.path.dirname(__file__))
BASEDIR = basedir
DEBUG = False
SECRET_KEY = 'This is a secret key forexample'
# not end with else throw AttributeError: 'tuple' object has no attribute 'drivername'
SQLALCHEMY_DATABASE_URI = "my... | 2.0625 | 2 |
examples/miniapps/engines_cars/example/cars.py | kinow/python-dependency-injector | 0 | 12796122 | """Dependency injection example, cars module."""
class Car:
"""Example car."""
def __init__(self, engine):
"""Initialize instance."""
self._engine = engine # Engine is injected
| 2.8125 | 3 |
GCC-paddle/gcc/models/emb/from_numpy.py | S-HuaBomb/Contrib | 243 | 12796123 | <reponame>S-HuaBomb/Contrib
import random
import networkx as nx
import numpy as np
class Zero(object):
def __init__(self, hidden_size, **kwargs):
self.hidden_size = hidden_size
def train(self, G):
return np.zeros((G.number_of_nodes(), self.hidden_size))
class FromNumpy(object):
def __i... | 2.3125 | 2 |
tests/__init__.py | robinsax/canvas | 4 | 12796124 | # coding: utf-8
'''
Unit tests on the canvas framework.
'''
from . import exceptions, utils, json, views, controller_service, assets, \
model, service
| 1.132813 | 1 |
files/042 - coded triangle numbers.py | farukara/Project-Euler-problems | 0 | 12796125 | <filename>files/042 - coded triangle numbers.py<gh_stars>0
#!python3
# coding: utf-8
# The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# By converting each letter in a word to a number corresponding to its alph... | 3.828125 | 4 |
nucleus/__init__.py | ciex/souma | 5 | 12796126 | <filename>nucleus/__init__.py
import logging
import blinker
from web_ui import db, app
from sqlalchemy.orm import sessionmaker
ERROR = {
"MISSING_MESSAGE_TYPE": (1, "No message type found."),
"MISSING_PAYLOAD": (2, "No data payload found."),
"OBJECT_NOT_FOUND": lambda name: (3, "Object does not exist: ".... | 2.28125 | 2 |
2018/day2/part2.py | MartinPetkov/AdventOfCode | 0 | 12796127 | <reponame>MartinPetkov/AdventOfCode
#!/usr/bin/env python
import argparse
def part2(input):
# Track all strings with each letter missing.
# If seen, exit early.
seen = {}
for box_id in input:
for i in range(len(box_id) - 1):
if i not in seen:
seen[i] = set()
s = box_id[:i] + box_id[i... | 3.5 | 4 |
analysis.py | cangokceaslanx/2D-Scattering | 1 | 12796128 | <reponame>cangokceaslanx/2D-Scattering
from scipy.stats import linregress
import matplotlib.pyplot as mt
import math
import numpy as np
import statistics as st
datax = [20,40,60,80,100,120,140,160,180,200,220,240,260,280,300,320,340]
data = [43,23,25,32,46,55,55,72,73,92,73,56,37,54,33,26,16]
datax_symmetric = [20,40,6... | 2.5 | 2 |
Python-LoopControlBreak.py | H2oPtic/Codecademy-Education | 0 | 12796129 | <gh_stars>0
dog_breeds_available_for_adoption = ["french_bulldog", "dalmatian", "shihtzu", "poodle", "collie"]
dog_breed_I_want = "collie"
for dog_breed in dog_breeds_available_for_adoption:
print(dog_breed)
if dog_breed == dog_breed_I_want:
print("They have the dog I want!")
break
| 3.5625 | 4 |
calibration/python/bolopropertiesutils.py | tskisner/spt3g_software | 6 | 12796130 | <reponame>tskisner/spt3g_software<gh_stars>1-10
from spt3g.calibration import BolometerProperties
from spt3g import core
import math
__all__ = ['SplitByProperty', 'SplitByBand', 'SplitTimestreamsByBand',
'SplitByWafer', 'SplitByPixelType']
@core.indexmod
class SplitByProperty(object):
'''
Take an i... | 2.609375 | 3 |
controle_financeiro/lancamentos/migrations/0001_initial.py | douglaspands/controle-financeiro | 0 | 12796131 | <reponame>douglaspands/controle-financeiro
# Generated by Django 3.2 on 2021-04-27 02:00
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('carteiras', '0001_initial'),
... | 1.882813 | 2 |
test_time_log_window.py | sphericalpm/jira-quick-reporter | 1 | 12796132 | <filename>test_time_log_window.py
from jiraclient import JiraClient
import unittest
from types import SimpleNamespace as sn
class Test(unittest.TestCase):
def test_get_remaining_estimate_empty(self):
issue = sn(
fields=sn(
timetracking=sn(
raw={}
... | 2.421875 | 2 |
test_old.py | knightman/skybitz-gatewaydemo | 0 | 12796133 | import gateway
import soapreqs
import time
from datetime import datetime
#Imports currently used for testing only
# import pprint
# import json
# --------------------------------------------------------- #
''' EARLY TEST SCENARIOS '''
# --------------------------------------------------------- #
# invalrmlist = d['so... | 2.28125 | 2 |
setup.py | vspaz/pclient | 1 | 12796134 | <reponame>vspaz/pclient
import os
import setuptools
def _build_path(file_path, base=os.path.abspath(os.path.dirname(__file__))):
return os.path.join(base, file_path)
def _get_dependencies():
with open(_build_path(file_path='requirements/prod.txt')) as fh:
return [line.strip() for line in fh.readlin... | 1.921875 | 2 |
performance_curves/__init__.py | erp12/performance-curves | 0 | 12796135 | <gh_stars>0
"""Hello world!
A brief overview of the package should go here.
"""
| 1.179688 | 1 |
tcs.py | DeViL3998/hackerrankChallenges | 0 | 12796136 | n, m = list(map(int, input().split(" ")))
arr = [ ]
count = count2 = 0
for i in range(n, m+1):
for j in range(1, i//2 + 1):
if i%j == 0:
count += 1
if count == 1:
arr.append(i)
count = 0
for i in arr:
if i + 6 in arr:
count2 += 1
print(count2) | 3.046875 | 3 |
basicts/data/transforms.py | zezhishao/GuanCang_BasicTS | 3 | 12796137 | from basicts.utils.registry import SCALER_REGISTRY
"""
data normalization and re-normalization
"""
# ====================================== re-normalizations ====================================== #
@SCALER_REGISTRY.register()
def re_max_min_normalization(x, **kwargs):
_min, _max = kwargs['min'], kwargs['max']
... | 2.84375 | 3 |
ex009.py | vinisantos7/PythonExercicios | 2 | 12796138 | print("Bem-Vindo a Tabuada v1.0!")
num = (int(input("Digite um número para a tabuada: ")))
print('-'*12)
print(f"{num} x {1:2} = {num * 1}")
print(f"{num} x {2:2} = {num * 2}")
print(f"{num} x {3:2} = {num * 3}")
print(f"{num} x {4:2} = {num * 4}")
print(f"{num} x {5:2} = {num * 5}")
print(f"{num} x {6:2} = {num * 6}... | 4.25 | 4 |
python-pattern-matching/stdlib_ast.py | oilshell/blog-code | 54 | 12796139 | <reponame>oilshell/blog-code
#!/usr/bin/env python3
"""
demo.py
Run with Python 3.10
"""
from __future__ import print_function
import sys
import ast
from ast import BinOp, UnaryOp, Constant, Add, Sub, USub
# https://gvanrossum.github.io/docs/PyPatternMatching.pdf
def fact(arg):
match arg:
case 0 | 1:
f... | 2.546875 | 3 |
swaty/classes/subbasin.py | changliao1025/pyswat | 2 | 12796140 | <filename>swaty/classes/subbasin.py
import os,stat
import sys
import glob
import shutil
import numpy as np
from pathlib import Path
import tarfile
import subprocess
from shutil import copyfile
from abc import ABCMeta, abstractmethod
import datetime
from shutil import copy2
import json
from json import JSONEncoder
from... | 2.234375 | 2 |
Ch1-Arrays-and-Strings/04_palindrome_permutation.py | fatima-rizvi/CtCI-Solutions-6th-Edition | 0 | 12796141 | <filename>Ch1-Arrays-and-Strings/04_palindrome_permutation.py<gh_stars>0
# Given a string, write a function to check if it is a permutation of a palindrome
def palindrome_permutation(str1):
str1 = str1.replace(" ", "")
count = {}
for char in str1:
if count.get(char):
count[char] += 1
else:
c... | 3.96875 | 4 |
instructors/need-rework/24_curses/cu0.py | mgadagin/PythonClass | 46 | 12796142 | import curses
def main(stdscr):
""" Curses is controlled from here.
This might be called 'the loop' in a game.
game loop: http://gameprogrammingpatterns.com/game-loop.html
"""
curses.textpad.rectangle(stdscr,0,0,10,10)
keypress = int()
# 113 is the lowercase 'q' key.
while ke... | 3.9375 | 4 |
treecompare/__init__.py | mx-pycoder/treecompare | 0 | 12796143 | # API
from ._treecompare import namecomp
from ._treecompare import treedups
from ._treecompare import treepurge
from ._treecompare import duplicate
| 1.046875 | 1 |
kite-python/metrics/kite_metrics/loader.py | kiteco/kiteco-public | 17 | 12796144 | from jinja2 import Environment, PackageLoader, select_autoescape
import yaml
import json
import pkg_resources
import os
env = Environment(
loader=PackageLoader('kite_metrics', 'schemas'),
)
cache = {}
def _schema_exists(filename):
return pkg_resources.resource_exists('kite_metrics', 'schemas/{}'.format(file... | 2.265625 | 2 |
scan/link_finders/find_links_for_disks.py | korenlev/calipso-cvim | 0 | 12796145 | ###############################################################################
# Copyright (c) 2017-2020 <NAME> (Cisco Systems), #
# <NAME> (Cisco Systems), <NAME> (Cisco Systems) and others #
# #
# All rights r... | 1.835938 | 2 |
gws_volume_scanner/scanner/util.py | cedadev/gws-scanner | 0 | 12796146 | <filename>gws_volume_scanner/scanner/util.py<gh_stars>0
import multiprocessing as mp
import queue as queue_
from . import config, elastic, models, scanner
class ElasticQueueWorker:
"""Create and manage a worker for sending files to es."""
def __init__(self, config_: config.ScannerSchema):
# Used to... | 2.5 | 2 |
src/Plot.py | ComicSphinx/TimeTracker | 1 | 12796147 | <gh_stars>1-10
# @Author: <NAME> (@ComicSphinx)
from database.DatabaseUtilities import DatabaseUtilities as dbu
from datetime import datetime as dt
class Plot():
str_sleeping = "Sleeping"
str_unknown = "?"
int_maxMinutes = 1440
int_sleep = 480
def addData(self, minutes):
select = dbu.buil... | 2.828125 | 3 |
bluebottle/time_based/migrations/0020_auto_20201102_1230.py | terrameijar/bluebottle | 10 | 12796148 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.17 on 2020-11-02 11:30
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('activities', '0027_contributionvalue'),
('time_bas... | 1.679688 | 2 |
amulet/world_interface/chunk/interfaces/leveldb/leveldb_15/interface.py | architectdrone/Amulet-Core | 0 | 12796149 | from __future__ import annotations
from amulet.world_interface.chunk.interfaces.leveldb.leveldb_14.interface import (
LevelDB14Interface,
)
class LevelDB15Interface(LevelDB14Interface):
def __init__(self):
LevelDB14Interface.__init__(self)
self.features["chunk_version"] = 15
INTERFACE_CLAS... | 1.5625 | 2 |
main.py | knishioka/arxiv-bot | 0 | 12796150 | <reponame>knishioka/arxiv-bot
import datetime
from arxiv_bot.arxiv_scraper import ArxivScraper
from arxiv_bot.translator import translate
def main():
"""List updated articles."""
today = datetime.date.today()
start_date = today - datetime.timedelta(days=2)
end_date = today - datetime.timedelta(days=1... | 2.640625 | 3 |