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 |
|---|---|---|---|---|---|---|
stograde/specs/file_options.py | StoDevX/stograde | 7 | 12774551 | <gh_stars>1-10
from dataclasses import dataclass
@dataclass
class FileOptions:
"""Represents options available for files in specs"""
compile_optional: bool = False
hide_contents: bool = False
optional: bool = False
timeout: int = 4
truncate_contents: int = 10000
truncate_output: int = 1000... | 2.484375 | 2 |
tflitehub/manual_test.py | rsuderman/iree-samples | 12 | 12774552 | import absl.flags
import absl.testing
import test_util
absl.flags.DEFINE_string('model', None, 'model path to execute')
class ManualTest(test_util.TFLiteModelTest):
def __init__(self, *args, **kwargs):
super(ManualTest, self).__init__(absl.flags.FLAGS.model, *args, **kwargs)
def compare_results(self, iree_re... | 2.296875 | 2 |
app1/app/api/v1/hello/hello.py | hzjsea/fastapi-admin | 0 | 12774553 | <gh_stars>0
#!/usr/bin/env python3
# encoding: utf-8
"""
@author: hzjsea
@file: hello.py
@time: 2021/11/19 10:34 上午
"""
from fastapi import APIRouter
from app1.app.utils.xhr import response_ok, response_error
router = APIRouter()
@router.get("/hello", summary="hello get请求格式")
async def hello():
data = {
... | 2.578125 | 3 |
Profile/migrations/0002_rename_name_profile.py | higornobrega/Cadastrar-formulario-sem-refrash | 0 | 12774554 | <gh_stars>0
# Generated by Django 3.2.4 on 2021-07-16 19:53
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Profile', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_name='Name',
new_name='Profile',
... | 1.6875 | 2 |
tests/google_analytics/test_google_analytics.py | T-FitAndFat/toucan-connectors | 0 | 12774555 | import json
import pytest
from toucan_connectors.google_analytics.google_analytics_connector import (
GoogleAnalyticsConnector, GoogleAnalyticsDataSource)
def test_google_analytics(mocker):
gac = GoogleAnalyticsConnector(
type="GoogleAnalytics",
name="Test",
credentials={
... | 2.09375 | 2 |
python_ne/core/ga/matplotlib_logger.py | MatheusZickuhr/python-neat | 1 | 12774556 | <gh_stars>1-10
from python_ne.utils.observer import Observer
import matplotlib.pyplot as plt
import numpy as np
import os
class MatplotlibLogger(Observer):
def __init__(self):
self.logged_data = []
def notify(self, *args, **kwargs):
data = {
'generation': kwargs['current_generati... | 2.625 | 3 |
hardware-check.py | thysia-zosa/hardware-check | 0 | 12774557 | #! /usr/bin/env python3
#
# Authors: <NAME>, <NAME>, <NAME>
# (c) 2021
from pathlib import Path
from datetime import datetime
import os.path
import requests
import yaml
import json
from pyspectator.processor import Cpu
from crontab import CronTab
import sys
# constants
CONFIG_FILE = 'config.yaml'
MAX_CPU_TEMP = 'maxC... | 2.25 | 2 |
src/slippinj/cli/scripts/basic_script.py | scm-spain/slippin-jimmy | 7 | 12774558 | class BasicScript(object):
def __init__(self, parser):
"""
Initialize the class
:param parser: ArgumentParser
"""
super(BasicScript, self).__init__()
self._parser = parser
def get_arguments(self):
"""
Get the arguments to configure current script,... | 3.0625 | 3 |
lib/kube_objs/volumes.py | olx-global/rubiks | 60 | 12774559 | <filename>lib/kube_objs/volumes.py
# (c) Copyright 2017-2018 OLX
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import OrderedDict
from kube_obj import KubeSubObj, KubeObj
from kube_types import *
im... | 2.03125 | 2 |
services/exchangeservice.py | kimi0230/gogopowerkimibot | 4 | 12774560 |
from bs4 import BeautifulSoup
# fix: InsecureRequestWarning: Unverified HTTPS request is being made to host
import requests.packages.urllib3
# 測試table
# import prettytable as pt
url = "https://rate.bot.com.tw/xrt?Lang=zh-TW"
herders = {
'User-Agent': 'Mozilla/5.0 (Macintosh Intel Mac OS X 10_15_7) AppleWebKit... | 2.8125 | 3 |
applications/CoSimulationApplication/mpi_extension/MPIExtension.py | clazaro/Kratos | 778 | 12774561 | import KratosMultiphysics.mpi # importing the MPI-Core, since the MPIExtension directly links to it
from KratosCoSimulationMPIExtension import *
| 1.039063 | 1 |
cadise-blender/core/__init__.py | xh5a5n6k6/cadise-blender | 1 | 12774562 | <gh_stars>1-10
from . import (
exporter,
renderer
)
import bpy
class CadiseAddonPreferences(bpy.types.AddonPreferences):
# Reference to T.C. Chang's work, this must match add-on's name
# https://github.com/TzuChieh/Photon-v2/blob/develop/BlenderAddon/PhotonBlend/bmodule/__init__.py
bl_idname = __p... | 1.640625 | 2 |
summary/__init__.py | svven/summary | 12 | 12774563 | <filename>summary/__init__.py
"""
Summary class improves extraction.Extracted by providing
incremental load mechanism, and especially image validation.
But the main difference is that it performs the requests.
Extraction is performed gradually by parsing the HTML <head>
tag first, applying specific head extraction te... | 3.140625 | 3 |
Fluid/io/fluid-cloudnative/module/data_load_spec.py | Rui-Tang/fluid-client-python | 1 | 12774564 | # coding: utf-8
"""
fluid
client for fluid # noqa: E501
OpenAPI spec version: v0.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from Fluid.io.fluid-cloudnative.module.target_dataset import TargetDataset # noqa: F401,E... | 1.984375 | 2 |
run.py | mrprogrammer2938/Translate | 0 | 12774565 | <reponame>mrprogrammer2938/Translate
#!/usr/bin/python3
# This Programm write by Mr.nope
# Version 1.3.0
from os import system as command
import sys
try:
from deep_translator import GoogleTranslator
except ImportError:
os.system("pip3 install deep_translator")
from platform import uname
try:
from... | 2.546875 | 3 |
examples/using_steem_offline.py | creativechain/crea-python-lib | 0 | 12774566 | from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
from datetime import datetime, timedelta
import time
import io
import logging
from crea.blockchain import Blockchain
from crea.block import Block
from crea.account import Account
from crea.amount im... | 1.890625 | 2 |
python/pyclaw/evolve/__init__.py | geoflows/geoclaw-4.x | 2 | 12774567 | <filename>python/pyclaw/evolve/__init__.py
#!/usr/bin/env python
# encoding: utf-8
"""
__init__.py
Created by <NAME> on 2008-08-21.
Copyright (c) 2008 University of Washington. All rights reserved.
"""
# This __init__ script only imports common utilities, most of the import
# should be done depending on the solver n... | 1.46875 | 1 |
process.py | nrc/rustc-timing-scripts | 2 | 12774568 | <reponame>nrc/rustc-timing-scripts<gh_stars>1-10
import json
import os
import re
import sys
VERBOSE = False
LL_RATIO = False
re_commit = re.compile("commit (.*)")
re_date = re.compile("Date: (.*)")
re_rustc = re.compile("rustc: .*/([\w\-_\.]*)")
re_time_and_mem = re.compile("( *)time: ([0-9\.]*); rss: ([0-9]*)MB\s*... | 2.1875 | 2 |
setup.py | pjdelport/django-timezone-utils | 1 | 12774569 | <filename>setup.py
# coding: utf-8
from setuptools import setup
import os
version = __import__('timezone_utils').VERSION
setup(
name='django-timezone-utils',
version=version,
description='Time Zone Utilities for Django Models',
long_description=open(
os.path.join(
os.path.dirname(... | 1.3125 | 1 |
hbaselines/base_policies/actor_critic.py | jesbu1/h-baselines | 0 | 12774570 | """Script containing the abstract policy class."""
import numpy as np
import tensorflow as tf
from hbaselines.utils.tf_util import get_trainable_vars
from hbaselines.utils.tf_util import get_target_updates
class ActorCriticPolicy(object):
"""Base Actor Critic Policy.
Attributes
----------
sess : tf.... | 2.609375 | 3 |
demo4.py | SysOptLab/Problems | 0 | 12774571 | import numpy as np
import opt_prob
import scipy.optimize
# -- problem setup
name = '2.4 GOLDPR'
problem = opt_prob.Cons(name)
def cns(x):
g = -1.0*np.array(problem.cns(x))
return g.tolist()
# -- start optimization
x0 = ((np.array(problem.lb) + np.array(problem.ub)) / 2.0).tolist()
bounds = []
for lb_i, ub... | 2.796875 | 3 |
create_number_text.py | sp1007/ViTacotron2 | 0 | 12774572 | from tacotron2.text.vi_number_and_units import normalize_vi
from random import randrange
print("Start generate vietnamese number strings")
with open("training_data/vietnamese_number.txt", 'w', encoding='utf-8') as f:
for i in range(20000):
n = randrange(1000000000, 2000000000)
f.write(normalize_... | 2.796875 | 3 |
hello_world.py | albertonietos/git-project | 0 | 12774573 | print("Hello world!")
print("Hello darkness my old friend")
print("I've come to talk with you again")
| 2.328125 | 2 |
ozpcenter/api/subscription/views.py | emosher/ozp-backend | 1 | 12774574 | <filename>ozpcenter/api/subscription/views.py
"""
Subscription Views
"""
import logging
from django.shortcuts import get_object_or_404
from rest_framework import filters
from rest_framework import status
from rest_framework import viewsets
from rest_framework.response import Response
from ozpcenter import errors
from... | 2.109375 | 2 |
src/ling_409/tests/test_join.py | seanbethard/corpuswork | 0 | 12774575 | <reponame>seanbethard/corpuswork
import nltk
grammar = nltk.data.load('file:agree_join.fcfg',cache=False)
parser = nltk.parse.FeatureChartParser(grammar)
agreement_test_sentences = ['Mary sang and danced',
'Mary and John danced',
'Mary and John',
... | 2.84375 | 3 |
sanitise/sanitise.py | wapdat/ppi-sanistise | 4 | 12774576 | import re
import nltk
debug = False
list = ''
def tokenise(doc):
tokenized_doc = nltk.word_tokenize(doc)
tagged_sentences = nltk.pos_tag(tokenized_doc)
ne_chunked_sents = nltk.ne_chunk(tagged_sentences)
named_entities = []
for tagged_tree in ne_chunked_sents:
if hasattr(tagged_tree, 'label... | 2.75 | 3 |
01-intro/bow-simple-pytorch.py | bastings/nn4nlp2017-code-pytorch | 82 | 12774577 | <filename>01-intro/bow-simple-pytorch.py
# coding: utf-8
"""
BOW (simple version)
Based on <NAME>'s DyNet code examples:
https://github.com/neubig/nn4nlp2017-code
http://phontron.com/class/nn4nlp2017/
"""
from collections import defaultdict
import time
import random
import torch
from torch.autograd import Varia... | 3.140625 | 3 |
docs/usage-reference/parser/parser_omegaconf.py | Mbompr/fromconfig | 19 | 12774578 | """OmegaConfParser example."""
import fromconfig
import random
def random_hex() -> str:
return hex(hash(random.random()))
if __name__ == "__main__":
config = {
"host": "localhost",
"port": "8008",
"url": "${host}:${port}",
"path": "models/${now:}/${random_hex:}", # Use def... | 3.125 | 3 |
exercises/chapter01/test_01_07.py | deep-diver/fastai-course | 0 | 12774579 | def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the messag... | 2.265625 | 2 |
ship_class.py | BTCallahan/super-ds9 | 0 | 12774580 | <reponame>BTCallahan/super-ds9<filename>ship_class.py
from dataclasses import dataclass
from functools import lru_cache
from posixpath import split
from random import choice
import re
from string import digits
from typing import Dict, Final, Optional, Tuple, List
from frozendict import frozendict
from energy_weapon imp... | 2.296875 | 2 |
lightning.py | entn-at/Online-Speech-Recognition | 0 | 12774581 | <reponame>entn-at/Online-Speech-Recognition<filename>lightning.py<gh_stars>0
import os, sys
import jiwer
import torch
import numpy as np
import torch.optim as optim
from absl import app
from apex import amp
from tqdm import trange, tqdm
from torch.utils.data import DataLoader
from tensorboardX import SummaryWriter
fro... | 1.84375 | 2 |
exberry_adapter/setup.py | gaborh-da/da-marketplace | 0 | 12774582 | <reponame>gaborh-da/da-marketplace<filename>exberry_adapter/setup.py<gh_stars>0
from setuptools import setup
setup(name='marketplace-exchange-adapter',
version='0.1.18',
description='Daml Marketplace Exchange Adapter',
author='<NAME>',
url='daml.com',
license='Apache2',
install_requ... | 1.335938 | 1 |
jwql/instrument_monitors/nirspec_monitors/data_trending/utils/process_data.py | falkben/jwql | 1 | 12774583 | """This module holds functions for miri data trending
All functions in this module are tailored for the miri datatrending application.
Detailed descriptions are given for every function individually.
-------
- <NAME>
Use
---
Dependencies
------------
MIRI_trend_requestsDRAFT1900201.docx
Referenc... | 2.46875 | 2 |
src/database/create_db.py | johnnychiuchiu/Music-Recommender | 0 | 12774584 | <reponame>johnnychiuchiu/Music-Recommender<gh_stars>0
from schema import db
# from schema.db_models import *
if __name__=='__main__':
# create a new table scheme as defined in the schema script
db.create_all()
| 1.429688 | 1 |
adobe_analytics/exceptions.py | nickolasgryga/adobe_analytics | 1 | 12774585 | class ApiError(Exception):
"""
Exception raised when user does not have appropriate credentials
Used for 301 & 401 HTTP Status codes
"""
def __init__(self, response):
if 'error_description' in response:
self.message = response['error_description']
else:
... | 2.984375 | 3 |
tools/ete/ete_gene_cnv.py | anilthanki/tgac-galaxytools | 8 | 12774586 | from __future__ import print_function
import argparse
import collections
from ete3 import PhyloTree
def printTSV(myDict, colList=None):
""" Pretty print a list of dictionaries (myDict) as a dynamically sized table.
If column names (colList) aren't specified, they will show in random order.
Author: <NAME... | 3.296875 | 3 |
gtp_monitor.py | decastromonteiro/GTPv1-Monitoring | 0 | 12774587 | <reponame>decastromonteiro/GTPv1-Monitoring<gh_stars>0
from scapy.all import *
from scapy.contrib import gtp
import random
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-l","--loop", help="Loop the script for x times", type=int)
parser.add_argument("-G", "--GGSN", help="Choose which GGSN to m... | 2.53125 | 3 |
day04/d4.py | basoares/advent-of-code-2018 | 0 | 12774588 | '''
Advent of Code - 2018
--- Day 4: Repose Record ---
Released under the MIT License <http://opensource.org/licenses/mit-license.php>
'''
import os
from collections import defaultdict
from datetime import datetime
import re
def sleep_pattern(events):
sleep = defaultdict(lambda: [0 for i in range(60)])
f... | 2.90625 | 3 |
trpgcreator/ui/dialogs/function.py | jacobcheatley/trpg-creator | 0 | 12774589 | <reponame>jacobcheatley/trpg-creator
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_files/dialogs/function.ui'
#
# Created by: PyQt5 UI code generator 5.7
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_FunctionDialog(obje... | 1.71875 | 2 |
src/probnum/diffeq/odefiltsmooth/initialize.py | jzenn/probnum | 1 | 12774590 | """Initialisation procedures."""
# pylint: disable=import-outside-toplevel
import numpy as np
import scipy.integrate as sci
import probnum.filtsmooth as pnfs
import probnum.statespace as pnss
from probnum import randvars
# In the initialisation-via-RK function below, this value is added to the marginal stds of the ... | 3.171875 | 3 |
cogs/utils/april_fool.py | HypixelBot/bot | 10 | 12774591 | <gh_stars>1-10
from random import random
hieroglyphics = {'a': 'ᔑ','b': 'ʖ','c': 'ᓵ','d': '↸','e': 'ᒷ','f': '⎓','g': '⊣','h': '⍑','i': '╎','j': '⋮','k': 'ꖌ','l': 'ꖎ','m': 'ᒲ','n': 'リ','o': '𝙹','p': '!¡','q': 'ᑑ','r': '∷','s': 'ᓭ','t': 'ℸ̣','u': '⚍','v': '⍊', 'w': '∴', 'x': '̇/', 'y': '||', 'z': '⨅'}
def magik(text):... | 2.9375 | 3 |
model/__init__.py | KentWangYQ/mongo2es | 5 | 12774592 | <gh_stars>1-10
# -*- coding: utf-8 -*-
from pymongo import MongoClient
from config import settings
client = MongoClient(settings.MONGO.get('uri'))
models = client.get_database()
from .base import BaseModel
# Brand
brand = models.brands
brand.__class__ = BaseModel
# car_product
car_product = models.carproducts
car... | 1.914063 | 2 |
pan15_compliant/temp/quick_read.py | ivan-bilan/author-profiling-pan-2016 | 6 | 12774593 | <reponame>ivan-bilan/author-profiling-pan-2016
import glob
import ntpath
import re
import codecs
from nltk.tokenize import word_tokenize, sent_tokenize
from unidecode import unidecode
import pickle
import cPickle
from time import sleep
from xml.dom import minidom
from nltk.stem.porter import *
import treetaggerwrapper... | 2.4375 | 2 |
bin/__init__.py | eurica/splunk_app_pagerduty | 2 | 12774594 | <reponame>eurica/splunk_app_pagerduty
#!/usr/bin/env python
"""Splunk App for Pagerduty."""
__author__ = '<NAME> <<EMAIL>>'
__copyright__ = 'Copyright 2014 OnBeep, Inc.'
__license__ = 'Apache License, Version 2.0'
from .pagerduty import (PagerDutyException, PagerDuty, extract_events, # NOQA
trigger_pagerduty, g... | 1.132813 | 1 |
arp_spoof_detector.py | goodoldie/Stalker | 0 | 12774595 | <reponame>goodoldie/Stalker
import scapy.all as scapy
import os
import sys
import netifaces
def become_root():
euid = os.geteuid()
if euid != 0:
print("Script not started as root. Running sudo..")
args = ['sudo', sys.executable] + sys.argv + [os.environ]
os.execlpe('sudo', *args)
... | 2.46875 | 2 |
list_ec2_publicly_accessible/check-ec2-publicly-exposed.py | trackit/audit-tools | 0 | 12774596 | import boto3
import botocore
import csv
import pprint
import argparse
import ConfigParser
import os
import re
def get_ec2_name(tags):
for tag in tags:
if tag['Key'] == 'Name':
return tag['Value']
return 'NA'
def get_ec2_sg(sgs):
res = []
for sg in sgs:
res.append(sg['GroupI... | 2.609375 | 3 |
scripts.py | guindosaros/tutotravis | 0 | 12774597 | import os
import platform
import subprocess
# # Creation de l'environnement virtual Venv et activation
version = subprocess.run(["python", "--version"], capture_output=True, text=True)
if "python 3" in version.stdout.lower():
python = "python"
else:
python = "python3"
createvenv = os.system... | 2.390625 | 2 |
RIT33PYT/Codigo_1/Guide/13_Funciones_genericas_1.py | Sbastdia/Ejercicios-probables-examen | 0 | 12774598 | """
Ejercicio: hacer un juego "Guess The number"
PARTE 1: Pedir al usuario que introduzca un número entre 0 y 100
PARTE 2: Adivinar el número por parte del usuario
Usar una función para capitalizar el código común
"""
MIN = 0
MAX = 99
def solicitar_introducir_numero(invite):
# Completar la entrada:
invite ... | 3.953125 | 4 |
IOProgram/pickling.py | zhaoyu69/python3-learning | 1 | 12774599 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 序列化
# import pickle
# d = dict(name='Bob', age=20, score=88)
# print(pickle.dumps(d))
# f = open('dump.txt', 'wb')
# pickle.dump(d, f)
# f.close()
# f = open('dump.txt', 'rb')
# d = pickle.load(f)
# f.close()
# print(d)
# JSON
# import json
# d = dict(name='Bob', age=2... | 3.84375 | 4 |
py/py_0134_prime_pair_connection.py | lcsm29/project-euler | 0 | 12774600 | # Solution of;
# Project Euler Problem 134: Prime pair connection
# https://projecteuler.net/problem=134
#
# Consider the consecutive primes p1 = 19 and p2 = 23. It can be verified that
# 1219 is the smallest number such that the last digits are formed by p1
# whilst also being divisible by p2. In fact, with the exc... | 3.171875 | 3 |
projects/gmc705/week1/demo_simple_pendulum_multiple_controller_options.py | echoix/pyro | 0 | 12774601 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 16 12:05:08 2018
@author: Alexandre
"""
###############################################################################
import numpy as np
###############################################################################
from pyro.dynamic import pendulum
from pyro.control ... | 2.625 | 3 |
ofb/datasource.py | openfoodbroker/pynutrition | 3 | 12774602 | """Abstract datasource for recipes"""
from os import path
import json
class Datasource:
"""foo"""
def __init__(self, data):
self.name = data["name"]
self.text = data["text"]
self.url = data["url"]
self.local = data["local"]
def validate(self):
"""Prove that data ... | 3.328125 | 3 |
main.py | justinhchae/gis_project | 0 | 12774603 | import geoplot as gplt
import geopandas as gpd
import matplotlib.pyplot as plt
import pandas as pd
from src import constants
# data from cook county open data and us census
township_boundaries = gpd.read_file(constants.TOWNSHIP_POLYGONS_GEOJSON)
zip_code_data = gpd.read_file(constants.TOWNSHIP_POINTS_GEOJSON)
# call... | 3.1875 | 3 |
util/utility.py | Isaac-Li-cn/certify_robustness | 0 | 12774604 | <reponame>Isaac-Li-cn/certify_robustness
import torch
import torch.nn as nn
import numpy as np
def reduced_m_bm(m1, m2):
'''
>>> merge a new constant transformation with a batch transformation
>>> m1: tensor of shape [dim1, dim2]
>>> m2: tensor of shape [batch_size, dim2] or [batch_size, dim2, dim3]
... | 2.9375 | 3 |
src/mlflow_turing_scoring_server/scoring_server/wsgi.py | jose-turintech/mlflow-turing-scoring-server | 0 | 12774605 | import os
from mlflow_turing_scoring_server import scoring_server
from mlflow.pyfunc import load_model
app = scoring_server.init(load_model(os.environ[scoring_server._SERVER_MODEL_PATH]))
| 1.492188 | 1 |
data_processing/eccv2020-sharp-workshop/setup.py | jchibane/if-net_texture | 42 | 12774606 | import setuptools
with open("readme.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="sharpcvi2",
version="1.0.0",
author="CVI2: Computer Vision, Imaging and Machine Intelligence Research Group",
author_email="<EMAIL>",
description="Routines for the SHARP Challenge, ECCV 20... | 1.367188 | 1 |
ImageTracker/ImageTrackerTest.py | Engin-Boot/transfer-images-s1b13 | 0 | 12774607 | <reponame>Engin-Boot/transfer-images-s1b13<gh_stars>0
import unittest
import ImageTracker
class TestImageTracker(unittest.TestCase):
def test_when_client_calls_with_valid_csv_then_print_CSV_data(self):
testsamplefilename = 'temp-samples-test.csv'
with open(testsamplefilename, 'w') as samplefile:... | 2.625 | 3 |
data/data_stage3.py | wswdx/C2F-FWN | 39 | 12774608 | <filename>data/data_stage3.py
import os.path
import torchvision.transforms as transforms
import torch
from PIL import Image
import numpy as np
from data.base_dataset import BaseDataset, get_img_params, get_transform, get_transform_fixed, get_video_params, concat_frame
from data.image_folder import make_grouped_dataset... | 2.21875 | 2 |
ABC/176/a.py | fumiyanll23/AtCoder | 0 | 12774609 | <reponame>fumiyanll23/AtCoder<gh_stars>0
N, X, T = map(int, input().split())
time = N // X
if(N%X == 0):
print(time * T)
else:
print((time+1) * T) | 2.765625 | 3 |
PyTorch Exercises/My_CNN_Sample.py | FredAmouzgar/46_Simple_python_Exercise | 0 | 12774610 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import torch
from torch import nn
import torch.nn.functional as F
class ConvNet(nn.Module):
def __init__(self, input_shape=(1,3,28,28)):
super(ConvNet, self).__init__()
self.cnn = nn.Sequential(nn.Conv2d(in_channels=3,... | 3.046875 | 3 |
viz_one_image.py | AdidasSuperstar/detr | 0 | 12774611 | <reponame>AdidasSuperstar/detr
import torch
import pandas as pd
import cv2
###CREATE DATASET
DIR_TRAIN = "C:\\Users\\Eva.Locusteanu\\PycharmProjects\\detr\\models\\train" #3423 images
class WheatDataset(Dataset):
def __init__(self, image_ids, dataframe, transforms=None):
self.image_ids = image_ids
... | 2.78125 | 3 |
storytracker/toolbox.py | pastpages/storytracker | 24 | 12774612 | <filename>storytracker/toolbox.py
#!/usr/bin/env python
from __future__ import print_function
import six
import re
import math
import operator
from functools import reduce
try:
import cStringIO as io
except:
import io
class UnicodeMixin(object):
"""
Mixin class to handle defining the proper __str__/__... | 3.140625 | 3 |
angel-ps/python/pyangel/ml/client/angel_client_factory.py | weien8899/angel | 1 | 12774613 | <reponame>weien8899/angel
#
# Tencent is pleased to support the open source community by making Angel available.
#
# Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in
# compliance with the License.... | 1.585938 | 2 |
src/tn_scraper.py | erik1066/covid-web-scraper | 3 | 12774614 | <filename>src/tn_scraper.py
import requests, openpyxl, io, csv, datetime, os, pathlib
import county_report, state_report
STATE_ABBR = 'TN'
STATE = 'Tennessee'
URL = 'https://www.tn.gov/content/dam/tn/health/documents/cedep/novel-coronavirus/datasets/Public-Dataset-County-New.XLSX'
def scraper():
# make an HTTP we... | 3.234375 | 3 |
lz_assoc_viewer/minimum_solution.py | atomai/lz-viewer | 1 | 12774615 | import gzip
import Data_reader
##REQUIRES filename is a tabix file, names is the header of the file
##MODIFIES nothing
##EFFECTS finds the position of the minimum pvalue
def find_min_pvals(filename, filetype, num_minimums, region_buffer):
#create a file reader from the file
file_reader = Data_reader.Data_reade... | 3.234375 | 3 |
src/amaping.py | Devdevdavid/Amaping | 1 | 12774616 | <filename>src/amaping.py
#!/usr/bin/python
# Author : <NAME>
# Desc : See APP_DESC :)
# File : Amaping.py
# Date : July 4th, 2021
# Version : 1.0.0
import time
import signal, os
import traceback # For debugging unhandled exceptions
import argparse ... | 2.359375 | 2 |
nbp/tests/tools.py | machism0/non-bonded-periodic | 0 | 12774617 | <reponame>machism0/non-bonded-periodic<gh_stars>0
import nbp
import numpy as np
def make_system(characteristic_length=10,
sigma=None, epsilon_lj=None, particle_charges=None, positions=None, particle_count=None,
lj=True, ewald=True, use_neighbours=False):
if particle_count is None:
... | 2.484375 | 2 |
reflex/reflex_runner.py | ankur-gos/RE-Flex | 3 | 12774618 | """
Classes for running lm inference
"""
import os
import torch
from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,
TensorDataset)
from reflex.models.reflex import Reflex
from dataclasses import dataclass
from reflex.utils import load_file, to_list
from reflex.struc... | 2.390625 | 2 |
emmet/css_abbreviation/tokenizer/tokens.py | jingyuexing/py-emmet | 29 | 12774619 | class Token:
__slots__ = ('start', 'end')
def __init__(self, start: int=None, end: int=None):
self.start = start
self.end = end
@property
def type(self):
"Type of current token"
return self.__class__.__name__
def to_json(self):
return dict([(k, self.__getat... | 2.578125 | 3 |
backend/app/models/client_model.py | juniorosorio47/client-order | 0 | 12774620 | <filename>backend/app/models/client_model.py
from django.contrib.auth import get_user_model
from django.db import models
User = get_user_model()
# Client model
class Client(models.Model):
name = models.CharField(max_length=120)
def _str_(self):
return self.name | 2.140625 | 2 |
apps/Tests/algs/TestAlg.py | erinzm/NEXT-chemistry | 155 | 12774621 | <filename>apps/Tests/algs/TestAlg.py
from apps.Tests.tests.test_api import set_and_get_alg, get_alg, get_exp
class MyAlg:
def initExp(self, butler, dummy):
get_exp(butler)
set_and_get_alg(butler)
return "return_init_exp"
def getQuery(self, butler):
get_alg(butler)
retu... | 2.0625 | 2 |
pinterest.py | raphaottoni/pinterest-crawler | 9 | 12774622 | <reponame>raphaottoni/pinterest-crawler
import urllib2
import time
import random
import socket
import MySQLdb
from config import *
import os,re
class Pinterest:
#------inicializacao -------#
def __init__(self, verbose=0):
self.db = MySQLdb.connect(host,user,password,database)
self.cursor = self.db.cursor()... | 2.828125 | 3 |
ciphers/zazcipher.py | zdhoward/practice | 0 | 12774623 | <reponame>zdhoward/practice
literals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.?/:;{[]}-=_+~!@#$%^&*()"
#obfuscated
literals = "tJ;EM mKrFzQ_SOT?]B[U@$yqec~fhd{=is&alxPIbnuRkC%Z(jDw#G:/)L,*.V!pov+HNYA^g-}WX"
key = 7
def shuffle(plaintext):
shuffled = ""
# shuffle plaintext
for i in range(in... | 3.078125 | 3 |
testsqlite.py | UncleEngineer/UncleVocab | 0 | 12774624 | # testsqlite.py
import sqlite3
conn = sqlite3.connect('vocab.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS vocab (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
vocab text,
meaning text,
score int)""")
def insert_vocab(vocab,meaning):
ID = None
score = 0
with c... | 3.59375 | 4 |
09_binarytree/binary_tree_xrh.py | Xinrihui/Data-Structure-and-Algrithms | 1 | 12774625 | from collections import deque
class TreeNode(object):
def __init__(self,item):
self.val=item
self.left=None
self.right=None
# self.height=None
# Codec
class DFS_Serialize:
"""
基于 DFS 的 二叉树 的序列化 和 反序列化
递归实现
ref:
https://blog.csdn.net/Shenpibaipao/article/det... | 3.328125 | 3 |
apis_v1/documentation_source/organization_suggestion_tasks_doc.py | ranadeepmitra21/WeVoteServer_Ranadeep | 44 | 12774626 | # apis_v1/documentation_source/organization_suggestion_tasks_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_suggestion_tasks_doc_template_values(url_root):
"""
Show documentation about organizationSuggestionTask
"""
required_query_parameter_list = [
{
... | 1.664063 | 2 |
tests/integration/conftest.py | tonybaloney/django-xss-fuzzer | 32 | 12774627 | import pytest
@pytest.fixture(scope='session')
def session_capabilities(session_capabilities):
session_capabilities['loggingPrefs'] = {'browser': 'ALL'}
session_capabilities['goog:loggingPrefs'] = {'browser': 'ALL'}
return session_capabilities
@pytest.fixture
def chrome_options(chrome_options):
chr... | 1.828125 | 2 |
ws-python/ex043.py | DerickSilva/Python | 0 | 12774628 | peso = float(input('Qual é seu peso? '))
altura = float(input('Qual é sua altura? '))
imc = peso / (altura * altura)
if imc < 18.5:
print(f'IMC {imc:.1f} Abaixo do Peso')
elif imc < 25:
print(f'IMC {imc:.1f} Peso Ideal')
elif imc < 30:
print(f'IMC {imc:.1f} Sobrepeso')
elif imc < 40:
print(f'IMC {imc... | 3.71875 | 4 |
examples/demo_a2c.py | antoine-moulin/rlberry | 0 | 12774629 | from rlberry.agents import A2CAgent
from rlberry.envs.classic_control import MountainCar
from rlberry.envs.benchmarks.ball_exploration import PBall2D
from rlberry.seeding import seeding
render = True
seeding.set_global_seed(1223)
for env, n_episodes, horizon in zip([PBall2D(), MountainCar()],
... | 2.28125 | 2 |
autogoal/datasets/movie_reviews.py | gmijenes/autogoal | 0 | 12774630 | <filename>autogoal/datasets/movie_reviews.py
import random
from autogoal.datasets import download, datapath
def load(max_examples=None):
try:
download("movie_reviews")
except:
print(
"Error loading data. This may be caused due to bad connection. Please delete badly downl... | 3.109375 | 3 |
h2o-py/tests/testdir_apis/Data_Manipulation/pyunit_h2oH2OFrame_countmatches.py | vishalbelsare/h2o-3 | 6,098 | 12774631 | <reponame>vishalbelsare/h2o-3<gh_stars>1000+
from __future__ import print_function
import sys
sys.path.insert(1,"../../../")
from tests import pyunit_utils
import h2o
from h2o.utils.typechecks import assert_is_type
from h2o.frame import H2OFrame
def h2o_H2OFrame_countmatches():
"""
Python API test: h2o.frame.... | 2.40625 | 2 |
mechlib/amech_io/parser/mech.py | keceli/mechdriver | 0 | 12774632 | """ Parses the `mechanism.dat` input file for MechDriver that contains
all of the reactions of mechanism. The format of this file corresponds
to some user-specified format.
"""
import mechanalyzer.parser.pes
def pes_dictionary(mech_str, mech_type, spc_dct, printlog=True):
""" Calls mechanalyzer to do the... | 3.09375 | 3 |
ml_code/GunshotDetection/eval_nolabel.py | ankitshah009/Daisy_Shooter_Localization | 18 | 12774633 | <reponame>ankitshah009/Daisy_Shooter_Localization
# coding=utf-8
# given downloaded annotation file from videoAnno(rename the filename first), the test file is filename+score+label, then compute the AP and precision and recall
# annotation will be transform first based on over-half overlapping of each filename(start an... | 2.75 | 3 |
September 2020/03-Multidimensional-Lists/Exercises/05-Snake-Moves.py | eclipse-ib/Software-University-Professional-Advanced-Module | 0 | 12774634 | from collections import deque
rows, cols = [int(_) for _ in input().split()]
string = input()
matrix = [[0 for j in range(cols)] for i in range(rows)]
# matrix = []
#
# for i in range(rows):
# matrix.append([])
# for j in range(cols):
# matrix[i].append(0)
key_word = deque(string)
count = 0
for i in ... | 3.34375 | 3 |
setup.py | bao-eng/oscc-check | 4 | 12774635 | <gh_stars>1-10
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
long_description = open('README.md', 'r').read()
class PyTest(TestCommand):
user_options = [("pytest-args=", "a", "Arguments to pass to pytest")]
def initialize_options(self):
... | 1.796875 | 2 |
src/utils/setup_django.py | mrts/foodbank-campaign | 1 | 12774636 | import os
import sys
import django
PROJDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, PROJDIR)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "foodbank.settings")
django.setup()
| 1.546875 | 2 |
plenum/test/run_continuously.py | andkononykhin/plenum | 148 | 12774637 | import traceback
import pytest
from plenum.test.testing_utils import setupTestLogging
setupTestLogging()
def run(test, stopOnFail=True, maxTimes=None):
count = 0
passes = 0
fails = 0
while maxTimes is None or count < maxTimes:
exitcode = pytest.main(test)
count += 1
if exitc... | 2.53125 | 3 |
bsmetadata/experiments/sample.py | chkla/metadata | 13 | 12774638 | from dataclasses import dataclass
from datasets import load_dataset
from torch.utils.data import DataLoader
from transformers import PreTrainedTokenizerBase
from bsmetadata.input_pipeline import DataConfig
@dataclass
class DataCollatorForCLM:
tokenizer: PreTrainedTokenizerBase
pad_to_multiple_of: int = 16
... | 2.46875 | 2 |
admin/migrations/0007_auto_20180304_2342.py | rodlukas/UP-admin | 4 | 12774639 | <gh_stars>1-10
# Generated by Django 2.0.2 on 2018-03-04 22:42
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("admin", "0006_auto_20180304_2334")]
operations = [
migrations.RenameField(
model_name="attendance", old_name="attendancestate", new_na... | 1.679688 | 2 |
methods/smoking-behavior.py | wdempsey/sense2stop-lvm | 1 | 12774640 | <gh_stars>1-10
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %% [markdown]
# # Summary
#
# * ADD LATER
# * ADD LATER
# * ADD LATER
# %% [markdown]
# # Estimation
# %%
import pymc3 as pm
import arviz as az
import pandas as pd
import numpy as np
from datetime import datetime
im... | 2.28125 | 2 |
data_construction/neg_mask_regen/detect_relation_ne_document_summary.py | launchnlp/cliff_summ | 14 | 12774641 | import argparse
from tqdm import tqdm
from spacy.tokens import DocBin
import spacy_stanza
nlp = spacy_stanza.load_pipeline("en", use_gpu=True)
def swap_one(document, summary):
try:
source_doc = nlp(document)
except RecursionError:
source_doc = nlp(document[:2000])
summary_doc = nlp(summ... | 2.609375 | 3 |
glue/qt/widgets/histogram_widget.py | aak65/glue | 0 | 12774642 | from __future__ import absolute_import, division, print_function
from functools import partial
from ...external.qt import QtGui
from ...external.qt.QtCore import Qt
from ...core import message as msg
from ...clients.histogram_client import HistogramClient
from ..widget_properties import (connect_int_spin, ButtonProp... | 1.914063 | 2 |
worlds_worst_operator/action_sets/text_adventure_actions.py | nigelmathes/worlds-worst-operator | 0 | 12774643 | <reponame>nigelmathes/worlds-worst-operator<filename>worlds_worst_operator/action_sets/text_adventure_actions.py
import json
from dataclasses import asdict
from typing import Dict, Tuple, List
import boto3
try:
from player_data import Player
from arns import TEXT_ADVENTURE_ARN
from action_sets.common_act... | 2.65625 | 3 |
common/datetime_helper.py | wuxh123/my_bottle | 3 | 12774644 | <gh_stars>1-10
#!/usr/bin/env python
# coding=utf-8
import time
import datetime
def to_date(dt):
"""将时间格式化为日期字符串"""
if isinstance(dt, datetime.datetime):
return dt.strftime('%Y-%m-%d')
elif isinstance(dt, datetime.date):
return dt.strftime('%Y-%m-%d')
else:
raise Exception("日期... | 3.265625 | 3 |
rec_to_nwb/test/processing/test_fileSorter.py | jihyunbak/rec_to_nwb | 8 | 12774645 | from unittest import TestCase
from rec_to_nwb.processing.tools.file_sorter import FileSorter
class TestFilenameSorter(TestCase):
def setUp(self):
self.strings_to_sort = ['name01', 'name11', 'name10', 'name02', 'name21']
self.correct_order_of_strings = ['name01', 'name02', 'name10', 'name11', 'nam... | 2.765625 | 3 |
t01primeshcflcm_primekth.py | CherryNoddles/y1math | 1 | 12774646 | # What is the kth prime number?
| 1.039063 | 1 |
Puzzles/Easy/EquivalentResistanceCircuitBuilding.py | Naheuldark/Codingame | 0 | 12774647 | import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
n = int(input())
resdict = {}
for i in range(n):
inputs = input().split()
name = inputs[0]
r = int(inputs[1])
resdict[name] = r
circuit = input().split(' ')
print(circu... | 3.4375 | 3 |
sqlalchemy/sqlalchemy-0.3.6+codebay/examples/collections/large_collection.py | nakedible/vpnease-l2tp | 5 | 12774648 | """illlustrates techniques for dealing with very large collections"""
from sqlalchemy import *
meta = BoundMetaData('sqlite://', echo=True)
org_table = Table('organizations', meta,
Column('org_id', Integer, primary_key=True),
Column('org_name', String(50), nullable=False, key='name'),
mysql_engine='InnoD... | 2.9375 | 3 |
scripts/artifacts/imoHD_Chat.py | isoft123/iLEAPP | 1 | 12774649 | import sqlite3
import io
import json
import os
import shutil
import nska_deserialize as nd
import scripts.artifacts.artGlobals
from packaging import version
from scripts.artifact_report import ArtifactHtmlReport
from scripts.ilapfuncs import logfunc, logdevinfo, timeline, kmlgen, tsv, is_platform_windows, op... | 2 | 2 |
amurlevel_model/model/model.py | RaevskyDN/aij2020-amur-noflood-public | 7 | 12774650 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import tensorflow as tf
import tensorflow.keras.layers as L
import tensorflow.keras.backend as K
from .metrics import rmse,mae,mae_inference
from ..config_features import NUMERICAL_FEATURES,CATEGORICAL_FEATURES,CAT_MAP
from ..config import DAYS_FORECAST,ALL_STATIONS
def lstm_l... | 2.515625 | 3 |