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 |
|---|---|---|---|---|---|---|
snowballs.py | GYosifov88/Python-Fundamentals | 0 | 33700 | import sys
number_of_snowballs = int(input())
highest_value = -sys.maxsize
highest_quality = -sys.maxsize
highest_weight = -sys.maxsize
highest_time = -sys.maxsize
for i in range (number_of_snowballs):
weight_of_snowball = int(input())
time_of_reaching = int(input())
quality_of_snowball = int(input())
... | 3.375 | 3 |
altperf-server/apps/start-api.py | ynakaoku/altperf | 0 | 33701 | # -*- coding: utf-8 -*-
from flask import Flask, jsonify, request, Markup, abort, make_response
# import peewee
# import json
api = Flask(__name__)
@api.route('/')
def index():
html = '''
<form action="/iperf3test">
<p><label>iperf3 test: </label></p>
Test Name: <input type="text" name="TestNa... | 2.578125 | 3 |
ESAN.py | wnxbwyc/ESAN | 0 | 33702 | <reponame>wnxbwyc/ESAN
import functools
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def make_model(level):
return ESAN(level = level)
def initialize_weights(net_l, scale=1):
if not isinstance(net_l, list):
net_l = [net_l]
for net in net_l:
for m in n... | 2.4375 | 2 |
problems/tsptw/problem_tsptw.py | cem0963/dpdp | 0 | 33703 | import math
import numpy as np
from scipy.spatial.distance import cdist
from torch.utils.data import Dataset
import torch
import os
import pickle
from problems.tsptw.state_tsptw import StateTSPTWInt
from utils.functions import accurate_cdist
class TSPTW(object):
NAME = 'tsptw' # TSP with Time Windows
@stati... | 2.03125 | 2 |
thespian/test/__init__.py | dendron2000/Thespian | 210 | 33704 | """Defines various classes and definitions that provide assistance for
unit testing Actors in an ActorSystem."""
import unittest
import pytest
import logging
import time
from thespian.actors import ActorSystem
def simpleActorTestLogging():
"""This function returns a logging dictionary that can be passed as
... | 2.875 | 3 |
main.py | JeffSpies/nonwordlist | 0 | 33705 | <filename>main.py
from process import wordlist
import itertools
import time
import os
import re
ALPHABET = '23456789abcdefghjkmnpqrstuvwxyz'
def main():
blacklist_all = wordlist.dict_by_length()
blacklist = blacklist_all[3].union(blacklist_all[4]).union(blacklist_all[5])
combinations = get_combinations(3)... | 3.046875 | 3 |
src/PPO.py | thurbridi/mo436-project-1 | 0 | 33706 | <filename>src/PPO.py
import numpy as np
import random
import gym
import time
import itertools
from numpy.random.mtrand import gamma
import torch
from torch import nn
from torch._C import dtype
from torch.optim import Adam
from torch.distributions import Categorical
class ExperienceBuffer:
def __init__(self, buffe... | 2.09375 | 2 |
python/macRC.pyw | drs251/MacRC | 0 | 33707 | <filename>python/macRC.pyw<gh_stars>0
from subprocess import Popen, PIPE
from distutils.util import strtobool
import serial
import sys
import time
import glob
import serial.tools.list_ports_posix
def run_applescript(scpt, args=()):
p = Popen(['osascript', '-'] + list(args), stdin=PIPE, stdout=PIPE)
stdout, st... | 2.328125 | 2 |
tryopenapi.py | fakegit/eave | 0 | 33708 | <gh_stars>0
import json
import yaml
import dnode
from eave import *
openapi_yaml = open('openapi.yaml').read()
openapi_json = open('openapi.json').read()
yaml_data = yaml.safe_load(openapi_yaml)
json_data = json.loads(openapi_json)
assert yaml_data == json_data
class DNode(dnode.DNode):
def __getattr__(s... | 2.3125 | 2 |
memory.py | Matioz/World-Models | 9 | 33709 | import logging as log
import numpy as np
import h5py
import humblerl as hrl
from humblerl import Callback, Interpreter
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Normal
from torch.utils.data import Dataset
from common_utils import get_model_path_if_exists
from third... | 2.25 | 2 |
wagtailrelated/utils.py | torchbox/wagtail-related | 2 | 33710 | <reponame>torchbox/wagtail-related<gh_stars>1-10
from bs4 import BeautifulSoup
from wagtail.core.fields import StreamField
def extract_text(obj):
"""Extracts data, concatenates and removes html tags
from fields listed in a obj.related_source_fields list.
"""
related_source_fields = getattr(obj._meta.m... | 2.796875 | 3 |
codes/globo_videos_cuts/core/tests/models/programs_model_test_case.py | lariodiniz/teste_meta | 0 | 33711 | # coding: utf-8
__author__ = "<NAME>"
from django.test import TestCase
from model_mommy import mommy
from core.models import Programs
class ProgramsModelTestCase(TestCase):
"""Class Testing Model Pogramas """
def setUp(self):
"""
Initial Test Settings
"""
self.program = ... | 2.84375 | 3 |
figures/plot_occurrence.py | wdlynch/symbolic_experiments | 0 | 33712 |
import os
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib import rcParams
params = {
# 'text.latex.preamble': ['\\usepackage{gensymb}'],
# 'text.usetex': True,
'font.family': 'Helvetica',
'lines.solid_capstyle'... | 2.5 | 2 |
Chapter04/apriori.py | PacktPublishing/Mastering-Machine-Learning-Algorithms-Second-Edition | 40 | 33713 | <filename>Chapter04/apriori.py<gh_stars>10-100
import numpy as np
# Install the library using: pip install -U efficient-apriori
from efficient_apriori import apriori
# Set random seed for reproducibility
np.random.seed(1000)
nb_users = 100
nb_products = 100
if __name__ == "__main__":
# Create the dataset
... | 2.90625 | 3 |
graph_nn-master/utils.py | allisontam/graph_coattention | 0 | 33714 | import numpy as np
def split_ids(args, ids, folds=10):
if args.dataset == 'COLORS-3':
assert folds == 1, 'this dataset has train, val and test splits'
train_ids = [np.arange(500)]
val_ids = [np.arange(500, 3000)]
test_ids = [np.arange(3000, 10500)]
elif args.dataset == 'TRIANGL... | 2.421875 | 2 |
dingus/block.py | ricott1/dingus | 0 | 33715 | import dingus.codec
import utils
import transaction
class BlockHeader(object):
VERSION = 0
def __init__(
self,
) -> None:
raise NotImplementedError
class Block(object):
VERSION = 0
def __init__(
self,
header: BlockHeader,
payload: list[transaction.Trans... | 2.28125 | 2 |
sigpy/block.py | EfratShimron/sigpy | 0 | 33716 | <filename>sigpy/block.py
# -*- coding: utf-8 -*-
"""Block reshape functions.
"""
import numpy as np
import numba as nb
from sigpy import backend, config, util
__all__ = ['array_to_blocks', 'blocks_to_array']
def array_to_blocks(input, blk_shape, blk_strides):
"""Extract blocks from an array in a sliding windo... | 3.140625 | 3 |
awscdk/app.py | jaliste/mi_coop | 54 | 33717 | #!/usr/bin/env python3
import os
from aws_cdk import core
from awscdk.app_stack import ApplicationStack
# naming conventions, also used for ACM certs, DNS Records, resource naming
# Dynamically generated resource names created in CDK are used in GitLab CI
# such as cluster name, task definitions, etc.
environment_na... | 2.1875 | 2 |
test_phase_equilibrium.py | khuston/interfacial_transport | 1 | 33718 | <filename>test_phase_equilibrium.py
import numpy as np
import logging
from interfacial_transport import compute_one_phase_equilibrium, compute_mass_balance_one_phase
from interfacial_transport import compute_two_phase_equilibrium, compute_mass_balance_two_phase
from numpy.testing import assert_almost_equal
logger = lo... | 2.359375 | 2 |
testbed1/scratchnet_single_switch_test.py | Benny93/SDNMininetScripts | 0 | 33719 | <filename>testbed1/scratchnet_single_switch_test.py
#!/usr/bin/python
"""
Build a simple network from scratch, using mininet primitives.
This is more complicated than using the higher-level classes,
but it exposes the configuration details and allows customization.
For most tasks, the higher-level API will be prefera... | 2.78125 | 3 |
teampy/__init__.py | arcward/teampy | 0 | 33720 | from teampy.client import APIClient
__version__ = '0.1'
__author__ = '<NAME>'
__all__ = ['APIClient'] | 1.15625 | 1 |
app/housekeeping.py | openpeoria/covid-19-il-data-scraper | 2 | 33721 | <reponame>openpeoria/covid-19-il-data-scraper
# -*- coding: utf-8 -*-
"""
app.housekeeping
~~~~~~~~~~~~~~~~
Provides additional housekeeping endpoints
"""
from flask import Blueprint, redirect, request
from werkzeug.exceptions import HTTPException
from app.helpers import exception_hook
from app.utils impo... | 2.03125 | 2 |
game.py | MisterL2/WarzoneAI | 0 | 33722 | from aiplayer import *
from player import *
from gameclasses import *
def setup(countries, countryMap):
print("Setup started!")
#Initialise boni
NA.countries = countries[0:9]
SA.countries = countries[9:13]
AF.countries = countries[13:19]
EU.countries = countries[19:26]
AU.countries = countr... | 3.03125 | 3 |
src/pretix/plugins/stripe/views.py | abrock/pretix | 1 | 33723 | import json
import logging
import stripe
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from pretix.base.models import Event, Order
from pretix.plugins.stripe.payment import Stripe
logger = logging.getLogger('pretix.plug... | 1.953125 | 2 |
meerkat_backend_interface/logger.py | rubyvanrooyen/meerkat-backend-interface | 0 | 33724 | <filename>meerkat_backend_interface/logger.py
import logging
def get_logger():
"""Get the logger."""
return logging.getLogger("BLUSE.interface")
log = get_logger()
def set_logger(log_level=logging.DEBUG):
"""Set up logging."""
FORMAT = "[ %(levelname)s - %(asctime)s - %(filename)s:%(lineno)s] %(me... | 2.359375 | 2 |
alipay/aop/api/domain/AlipayUserApplepayMerchantauthtokenGetModel.py | antopen/alipay-sdk-python-all | 213 | 33725 | <reponame>antopen/alipay-sdk-python-all<gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.OpenApiAppleRequestHeader import OpenApiAppleRequestHeader
class AlipayUserApplepayMerchantauthtokenGetModel(object):
... | 1.789063 | 2 |
sloth/lexer.py | TueHaulund/SLOTH | 0 | 33726 | import re
from sloth.grammar import LexicalGrammar
from sloth.token import Token
class LexerError(Exception):
def __init__(self, pos):
self.pos = pos
self.description = 'LexerError at Line {}, Column {}'.format(
self.pos[0], self.pos[1]
)
def __str__(self):
return... | 3.09375 | 3 |
test/hlt/pytest/python/com/huawei/iotplatform/client/dto/QueryDeviceCmdCancelTaskOutDTO.py | yuanyi-thu/AIOT- | 128 | 33727 | from com.huawei.iotplatform.client.dto.DeviceCommandCancelTaskRespV4 import DeviceCommandCancelTaskRespV4
from com.huawei.iotplatform.client.dto.Pagination import Pagination
class QueryDeviceCmdCancelTaskOutDTO(object):
pagination = Pagination()
data = DeviceCommandCancelTaskRespV4()
def __init__(self):
... | 2.328125 | 2 |
utils/file_utils.py | hardore007/FeedSDK-Python | 27 | 33728 | <gh_stars>10-100
# **************************************************************************
# Copyright 2018-2019 eBay Inc.
# Author/Developers: --
# 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 Licen... | 2.21875 | 2 |
tests/licenses/test_tasks.py | GitKlip/python-common | 0 | 33729 | import os
import subprocess
class TestTasks:
""" Test that the tasks work with invoke. """
CMD_KWARGS = dict(
capture_output=True,
encoding="utf-8",
shell=True,
env=os.environ.copy(),
)
def test_unapproved_licenses(self):
""" Should emit table of unapproved lic... | 2.390625 | 2 |
src/config.py | raywu60kg/credit-card-fraud-detection | 4 | 33730 | <filename>src/config.py
import os
from ray import tune
package_dir = os.path.dirname(os.path.abspath(__file__))
identity_dir = os.path.join(package_dir, "..", "data/train_identity.csv")
transaction_dir = os.path.join(package_dir, "..", "data/train_transaction.csv")
data_primary_key = "TransactionID"
label_name = ["isF... | 1.828125 | 2 |
app/chat/__init__.py | B-T-S/Build | 1 | 33731 | <gh_stars>1-10
from . import guest
from . import pusherauth
from . import admin | 1.125 | 1 |
dataloader/statetransformer_Guidance.py | proroklab/magat_pathplanning | 40 | 33732 | <filename>dataloader/statetransformer_Guidance.py
import numpy as np
import torch
from offlineExpert.a_star import PathPlanner
class AgentState:
def __init__(self, config):
# self.config = config
# self.num_agents = self.config.num_agents
self.config = config
self.num_agents = sel... | 2.359375 | 2 |
Algorithms/0212_Word_Search_II/Python/Word_Search_II_Solution_1.py | lht19900714/Leetcode_Python | 0 | 33733 |
# Space: O(n)
# Time: O(n)
import collections
class Solution():
def findWords(self, board, words):
column = len(board)
if column == 0: return []
row = len(board[0])
if row == 0: return []
target_word = set()
res = set()
# build a trie, this will be used... | 3.796875 | 4 |
training/pl_logger.py | stdiff/emo-classifier | 0 | 33734 | <reponame>stdiff/emo-classifier
from typing import Dict, Any, Optional
import pandas as pd
from pytorch_lightning.loggers import LightningLoggerBase
from pytorch_lightning.loggers.base import rank_zero_experiment
from pytorch_lightning.utilities import rank_zero_only
class SimpleLogger(LightningLoggerBase):
def ... | 2.703125 | 3 |
exec/tests/unit/runners/test_evaluators.py | AndersonReyes/klio | 705 | 33735 | <filename>exec/tests/unit/runners/test_evaluators.py
# Copyright 2021 Spotify AB
#
# 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 r... | 1.796875 | 2 |
tests/test_test.py | pthomson88/drug_design | 1 | 33736 | <reponame>pthomson88/drug_design
import pytest
def test_test():
hello_world = "Hello World"
assert hello_world == "Hello World"
def test_always_passes():
assert True
#This test will always fail
def test_always_fails():
assert False
| 2.6875 | 3 |
tic-tac-toe.py | aaditkapoor/tic-tac-toe-ml-project | 4 | 33737 |
# coding: utf-8
# - We are creating a very simple machine learning model.<br>
# - Using dataset: tic-tac-toe.data.txt with user-defined columns.<br>
# - We are treating this problem as a supervised learning problem.<br>
# In[74]:
# This the rough sketch of the processing that happened in my brain while creating the... | 3.875 | 4 |
murel/models/networks/control.py | gokcengokceoglu/murel.bootstrap.pytorch | 1 | 33738 | <reponame>gokcengokceoglu/murel.bootstrap.pytorch
import torch.nn as nn
import torch
class ControlModule(nn.Module):
def __init__(self, input_size, hidden_size):
super(ControlModule, self).__init__()
self.rnncell = nn.RNNCell(input_size=input_size, hidden_size=hidden_size, nonlinearity='tanh')
... | 2.875 | 3 |
uim/model/helpers/__init__.py | Wacom-Developer/universal-ink-library | 5 | 33739 | # -*- coding: utf-8 -*-
"""
Helpers
=======
The helpers are simple functions to support with:
- Catmull-Rom splines
- Extracting text and named entities from Ink Model
- Iterate over the Ink Tree
"""
__all__ = ['spline', 'text_extractor', 'treeiterator', 'policy']
from uim.model.helpers import ... | 2.125 | 2 |
matrix_traversal/get_matrix.py | SiberiaMan/Avitotech | 0 | 33740 | import aiohttp
from matrix_traversal.utils import (
traverse_matrix_counterclockwise,
get_formatted_matrix,
check_url)
from typing import List
from aiohttp import ClientError
from asyncio.exceptions import TimeoutError
async def send_request(url: str) -> List[List[int]]:
"""
This function sends a ... | 3.140625 | 3 |
wildlifecompliance/migrations/0431_merge_20200218_1801.py | preranaandure/wildlifecompliance | 1 | 33741 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2020-02-18 10:01
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wildlifecompliance', '0430_briefofevidencedocument'),
('wildlifecompliance', ... | 1.1875 | 1 |
python/testData/copyPaste/LineToPrev.after.py | jnthn/intellij-community | 2 | 33742 | print
print 21
print 3
| 1.632813 | 2 |
pdfencrypter.py | kamimura/pdfendecrypter | 0 | 33743 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import PyPDF2
length = len(sys.argv)
if length >= 2:
PASSWORD = sys.argv[1]
else:
print('usage: cmd password [path]')
sys.exit(1)
if length == 3:
PATH = sys.argv[2]
else:
PATH = os.curdir
for folder_name, _, filenames in os.walk... | 3.421875 | 3 |
Term2/15-5-square-for-input.py | theseana/apondaone | 0 | 33744 | import turtle as t
zel = float(input("What is your Zel: "))
for i in range(4):
t.fd(zel)
t.lt(90)
t.done()
| 3.109375 | 3 |
src/ashley/urls.py | openfun/ashley | 6 | 33745 | """
Ashley URLs (that includes django machina urls)
"""
from django.urls import include, path, re_path
from machina import urls as machina_urls
from ashley.api import urls as api_urls
from ashley.views import ChangeUsernameView, ForumLTIView, ManageModeratorsView
API_PREFIX = "v1.0"
urlpatterns = [
path("lti/fo... | 2.234375 | 2 |
schemes/mkcap.py | gold2718/ccpp-framework | 0 | 33746 | <gh_stars>0
#!/usr/bin/env python
#
# Script to generate a cap module and subroutines
# from a scheme xml file.
#
from __future__ import print_function
import os
import sys
import getopt
import xml.etree.ElementTree as ET
#################### Main program routine
def main():
args = parse_args()
data = parse_s... | 2.671875 | 3 |
setup.py | CertiFire/certifire | 0 | 33747 | #!/usr/bin/env python
import certifire
import certifire.plugins.acme
import certifire.plugins.dns_providers
from codecs import open
from setuptools import setup, find_packages
import sys
try:
# for pip >= 10
from pip._internal.req import parse_requirements
except ImportError:
# for pip <= 9.0.3
print(... | 2.125 | 2 |
kanka/utils.py | rbtnx/python-kanka | 3 | 33748 | """
:mod: `kanka.utils` - Helper functions
"""
from datetime import datetime
from requests_toolbelt.sessions import BaseUrlSession
from dacite import from_dict, Config
from .exceptions import KankaAPIError
API_BASE_ENDPOINT = 'https://kanka.io/api/1.0/'
class KankaSession(BaseUrlSession):
""" Store session data.... | 2.546875 | 3 |
day2/exercises/Jamila/pi_estimate/plots.py | lavjams/BI-Demo | 0 | 33749 | <gh_stars>0
######
###BACKGROUND
#Below Section: Imports necessary functions
import numpy as np
import matplotlib.pyplot as graph
import random as rand
import time as watch
import sims
pi = np.pi
######
###PLOTS
#FUNCTION: drawdarts
#PURPOSE: This function is meant to draw the darts for a given simulation within the ... | 3.15625 | 3 |
scripts/animate_demo.py | wjchen84/rapprentice | 23 | 33750 | #!/usr/bin/env python
"""
Animate demonstration trajectory
"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("h5file")
parser.add_argument("--seg")
parser.add_argument("--nopause", action="store_true")
args = parser.parse_args()
import h5py, openravepy,trajoptpy
from rapprentice import ani... | 2.15625 | 2 |
rsp2/src/python/rsp2/io/structure_dir.py | colin-daniels/agnr-ml | 0 | 33751 | import json
import os
from pymatgen.io.vasp import Poscar
def from_path(path):
# TODO: should maybe support .tar.gz or .tar.xz
return StructureDir.from_dir(path)
class StructureDir:
def __init__(self, *, layers, masses, layer_sc_matrices, structure):
self.layers = layers
self.masses = mass... | 2.40625 | 2 |
scripts/generate_mapping_summary.py | BleekerLab/snakemake_rnaseq | 4 | 33752 | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
import os
from functools import reduce
import sys
directory_with_mapping_reports = sys.argv[1]
mapping_summary = sys.argv[2]
############################################################
# Reads each file. Add sample name in the column with values
###########... | 2.875 | 3 |
Chapter2_Python/fStrings.py | dependencyInversion/UdemyML | 0 | 33753 | my_name = "Jan"
my_age = 23
print(f"Age: { my_age }, Name: { my_name }")
| 2.828125 | 3 |
src/models/predict_text_model.py | eyosyaswd/disaster-response | 0 | 33754 | <filename>src/models/predict_text_model.py
from ast import literal_eval
from performance_metrics import get_performance_metrics
from tensorflow.keras.models import load_model
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1' # Ignore tf info messages
import pandas as pd
if __name__ == "__main__":
TASK = "hum... | 2.546875 | 3 |
pygsti/tools/lindbladtools.py | pyGSTi-Developers/pyGSTi | 0 | 33755 | <filename>pygsti/tools/lindbladtools.py
"""
Utility functions relevant to Lindblad forms and projections
"""
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms o... | 1.78125 | 2 |
quality_dataset.py | Phoenix-Chen/butterflies | 45 | 33756 | <filename>quality_dataset.py
import torch
from torch.utils.data import Dataset
import numpy as np
import csv
import random
from config import *
import itertools
import torch
from skimage import io
import os
class QualityDataset(Dataset):
def __init__(self, return_hashes=False):
self.label_count = 3
... | 2.75 | 3 |
tests/components/geofency/__init__.py | domwillcode/home-assistant | 30,023 | 33757 | <filename>tests/components/geofency/__init__.py
"""Tests for the Geofency component."""
| 1.125 | 1 |
examples/nn_opt.py | jjakimoto/BBoptimizer | 1 | 33758 | <filename>examples/nn_opt.py<gh_stars>1-10
from sklearn.preprocessing import OneHotEncoder
import numpy as np
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, BatchNormalization, Dropout
from keras.layers import Activation, Reshape
from keras.optimizers import Adam, Adadelta, ... | 2.5 | 2 |
tests/library/register_expansion_test.py | Walon1998/dace | 1 | 33759 | # Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
import dace
import dace.library
from dace.transformation import transformation as xf
import pytest
@dace.library.node
class MyLibNode(dace.nodes.LibraryNode):
implementations = {}
default_implementation = 'pure'
def __init__(self... | 1.929688 | 2 |
utils/db_manipulate.py | DSSG-EUROPE/wef_oceans | 3 | 33760 | """
Functions to manipulate data from PostgreSQL database includes a
parallelise dataframe that runs a function on a pandas data frame
in parallel, as well as a loop_chunks function. This reads a chunk
from the database performs an operation and uploads to a new
table in the database.
"""
import numpy as np
import pa... | 3.453125 | 3 |
dialogue-engine/test/programytest/mappings/test_properties.py | cotobadesign/cotoba-agent-oss | 104 | 33761 | <reponame>cotobadesign/cotoba-agent-oss
"""
Copyright (c) 2020 COTOBA DESIGN, Inc.
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 u... | 1.632813 | 2 |
arango/mixins.py | joymax/arango-python | 6 | 33762 | <filename>arango/mixins.py<gh_stars>1-10
__all__ = ("ComparsionMixin", "LazyLoadMixin")
class ComparsionMixin(object):
"""
Mixin to help compare two instances
"""
def __eq__(self, other):
"""
Compare two items
"""
if not issubclass(type(other), self.__class__):
... | 2.40625 | 2 |
gherkin_to_markdown/expressions/second_header_expression.py | LeandreArseneault/gherkin_to_markdown | 6 | 33763 | from gherkin_to_markdown.expressions.expression import Expression
class SecondHeaderExpression(Expression):
def to_markdown(self, statement: str):
return f"##{statement.strip().replace(':', '', 1)[len(self.keyword):]}\n\n"
| 2.5 | 2 |
deephub/resources/__init__.py | deeplab-ai/deephub | 8 | 33764 | <gh_stars>1-10
from __future__ import unicode_literals
from __future__ import absolute_import
import os
from pathlib import Path
class ResourceNotFound(OSError):
pass
DEFAULT_USER_RESOURCES_DIRECTORY = 'runtime_resources'
_default_package_dir = Path(__file__).resolve().parent / 'blobs'
_user_resources_dir = ... | 2.78125 | 3 |
kaggle-lung-cancer-approach2/modules/ImagePreprocessing3d.py | flaviostutz/datascience-snippets | 2 | 33765 | <filename>kaggle-lung-cancer-approach2/modules/ImagePreprocessing3d.py
from tflearn.data_preprocessing import DataPreprocessing
import numpy as np
import random
class ImagePreprocessing3d(DataPreprocessing):
""" Image Preprocessing.
Base class for applying real-time image related pre-processing.
This class... | 2.6875 | 3 |
rpicamera/usepygame.py | terasakisatoshi/pythonCodes | 0 | 33766 | import pygame
import pygame.camera
#from pygame.locals import *
pygame.init()
pygame.camera.init()
screen = pygame.display.set_mode((640, 480), 0)
def main():
camlist = pygame.camera.list_cameras()
if camlist:
print('camera {} is detected'.format(camlist[0]))
cam = pygame.camera.Camera(camlis... | 3.1875 | 3 |
AI502/ScAI/lstm.py | sungnyun/AI-assignments | 0 | 33767 | <gh_stars>0
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import torch.nn as nn
class SimpleRNN(nn.Module):
def __init__(self, num_features, name='LSTM', seq_length=100, hidden_size=128):
super(SimpleRNN, self).__init__()
self.num_features = num_features
self.seq_length = seq_length
... | 2.984375 | 3 |
dracoon/public_models.py | Quirinwierer/dracoon-python-api | 3 | 33768 | from dataclasses import dataclass
from typing import List
@dataclass
class SystemInfo:
languageDefault: str
hideLoginPinputFields: bool
s3Hosts: List[str]
s3EnforceDirectUpload: bool
useS3Storage: bool
@dataclass
class ActiveDirectoryInfoItem:
id: int
alias: str
isGlobalAvailable: bool... | 2.203125 | 2 |
col_validation.py | scouvreur/pyspark-rdd-csv-parser | 0 | 33769 | import csv
import codecs
import StringIO
import cStringIO
import sys
import time
import argparse
from pyspark import SparkContext
parser = argparse.ArgumentParser(description='Count columns and lines existing in file')
parser.add_argument('-df','--DATAFILE', dest="DATAFILE", type=str,
help='the pat... | 3.3125 | 3 |
Fibonacci.py | Eziowrf/project555 | 1 | 33770 | # <NAME> 10423172
def Fibonacci(n):
if n == 1:
return 1
elif n == 2:
return 1
else:
return Fibonacci(n - 1) + Fibonacci(n - 2)
# arr = [1,2,3,4,5,6,7,8,9,10]
# for i in arr:
# print(Fibonacci(i))
| 3.78125 | 4 |
seek/dbtable_content_blobs.py | BMCBCC/NExtSEEK | 0 | 33771 | '''
Created on July 12, 2016
@author: <NAME>
Email: <EMAIL>
Description:
This script is implemented for the Content_blobs database/table.
Input: No typical input to define.
Output: No typical output to define.
Example command line:
Log of changes:
'''
#!/usr/bin/env python
import os
im... | 2.171875 | 2 |
netbox_secretstore/__init__.py | motad333/netbox-secretstore | 0 | 33772 | from extras.plugins import PluginConfig
from django.utils.translation import gettext_lazy as _
class NetBoxSecretStore(PluginConfig):
name = 'netbox_secretstore'
verbose_name = _('Netbox Secret Store')
description = _('A Secret Storage for NetBox')
version = '1.0.8'
author = 'NetBox Maintainers'
... | 1.664063 | 2 |
functions/load_respiratory_disease_data.py | rlbarter/covid19-severity-prediction | 2 | 33773 | <reponame>rlbarter/covid19-severity-prediction<gh_stars>1-10
import pandas as pd
def loadRespDiseaseSheet(sheet_name):
filepath = "data/respiratory_disease/IHME_USA_COUNTY_RESP_DISEASE_MORTALITY_1980_2014_NATIONAL_Y2017M09D26.XLSX"
orig_data = pd.read_excel(filepath,
sheet_name = ... | 2.625 | 3 |
src/flows.py | act65/mri-reconstruction | 8 | 33774 | import os
import numpy as np
import urllib
from absl import flags
import tensorflow as tf
import tensorflow_probability as tfp
tfb = tfp.bijectors
tfd = tfp.distributions
flags.DEFINE_float(
"learning_rate", default=0.001, help="Initial learning rate.")
flags.DEFINE_integer(
"epochs", default=100, help="Numb... | 2.25 | 2 |
src/utils/url_path.py | FP-DataSolutions/DeltaWarehouse | 6 | 33775 | <filename>src/utils/url_path.py<gh_stars>1-10
class UrlPath:
@staticmethod
def combine(*args):
result = ''
for path in args:
result += path if path.endswith('/') else '{}/'.format(path)
#result = result[:-1]
return result | 2.90625 | 3 |
data/model.py | depowered/mndot-bid-abstracts | 0 | 33776 | from sqlalchemy import Column, Integer, String, Float, ForeignKey
from sqlalchemy.engine.create import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
CONNECTION_STRING = "sqlite+pysqlite:///data/db.sqlite"
engine = create_engine(CONNECTION_STRING)
Sess... | 2.921875 | 3 |
guess_number_bo/guess_number.py | scumabo/Number-Guessing-Game | 0 | 33777 | <filename>guess_number_bo/guess_number.py<gh_stars>0
import random
from enum import Enum, auto
class Result(Enum):
BINGO = auto()
HIGH = auto()
LOW = auto()
class GuessNumber:
"""The class randomly chooses an integer
and then tells a human player if a guess is higher or lower than the number
... | 3.984375 | 4 |
attic/concurrency/timer2.py | matteoshen/example-code | 5,651 | 33778 | <gh_stars>1000+
import asyncio
import sys
import contextlib
@asyncio.coroutine
def show_remaining(dots_task):
remaining = 5
while remaining:
print('Remaining: ', remaining)
sys.stdout.flush()
yield from asyncio.sleep(1)
remaining -= 1
dots_task.cancel()
print()
@asyncio... | 3.109375 | 3 |
nexpose_rest/nexpose_policy.py | Patralos/nexpose-rest | 0 | 33779 | <gh_stars>0
from nexpose_rest.nexpose import _GET
def getPolicies(config, filter=None, scannedOnly=None):
getParameters=[]
if filter is not None:
getParameters.append('filter=' + filter)
if scannedOnly is not None:
getParameters.append('scannedOnly=' + scannedOnly)
code, data = _GET('/... | 2.03125 | 2 |
cybld/cybld_command_stats.py | dcvetko/cybld | 0 | 33780 | #!/usr/bin/python
# --------------------------------------------------------------------------
#
# MIT License
#
# --------------------------------------------------------------------------
from cybld import cybld_helpers
# --------------------------------------------------------------------------
class CyBldComma... | 2.625 | 3 |
core/src/zeit/content/article/edit/browser/interfaces.py | rickdg/vivi | 5 | 33781 | import zope.interface
class IFoldable(zope.interface.Interface):
"""Marker interface for a block which can be callapsed."""
| 1.875 | 2 |
{{cookiecutter.repo_name}}/{{cookiecutter.project_name}}/utils/context_processor.py | abahnihi/kn-django-cookiecutter | 2 | 33782 | from django.conf import settings
def google_analytics(request):
return {'GOOGLE_ANALYTICS': settings.GOOGLE_ANALYTICS}
def debug_state(request):
return {'DEBUG': settings.DEBUG}
| 1.578125 | 2 |
src/search/src/search-service/app.py | Young-ook/retail-demo-store | 1 | 33783 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.ext.flask.middleware import XRayMiddleware
from aws_xray_sdk.core import patch_all
patch_all()
from flask import Flask
from flask import request
from fla... | 1.859375 | 2 |
utils/iou.py | taimur1871/cutter_detect_app | 0 | 33784 | <reponame>taimur1871/cutter_detect_app
# check for duplicate detections
import numpy as np
def iou(box1, box2):
# determine the (x, y)-coordinates of the intersection rectangle
xA = max(box1[0], box2[0])
yA = max(box1[1], box2[1])
xB = min(box1[2], box2[2])
yB = min(box1[3], box2[3])
# compute... | 2.84375 | 3 |
tests/i18n/patterns/urls/path_unused.py | webjunkie/django | 790 | 33785 | from django.conf.urls import url
from django.conf.urls import patterns
from django.views.generic import TemplateView
view = TemplateView.as_view(template_name='dummy.html')
urlpatterns = patterns('',
url(r'^nl/foo/', view, name='not-translated'),
)
| 1.882813 | 2 |
backend/profiles/serializers.py | stevethompsonstar/django-react-blog | 592 | 33786 | from rest_framework import serializers
from .models import Subscriber
class SubscriberSerializer(serializers.ModelSerializer):
class Meta:
model = Subscriber
fields = (
'email',
)
| 1.96875 | 2 |
src/opendr/perception/activity_recognition/datasets/utils/transforms.py | makistsantekidis/opendr | 3 | 33787 | <filename>src/opendr/perception/activity_recognition/datasets/utils/transforms.py
# Copyright 2020-2021 OpenDR Project
#
# 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.apach... | 1.96875 | 2 |
coinbase/models/util.py | EU-institution/coinbase_python | 53 | 33788 | import collections
try:
stringtype = basestring # python 2
except:
stringtype = str # python 3
def coerce_to_list(x):
if isinstance(x, stringtype):
return x.replace(',', ' ').split()
return x or []
def namedtuple(name, args=None, optional=None):
args = coerce_to_list(args)
optiona... | 3.078125 | 3 |
main.py | Spain-AI/dark_helper | 0 | 33789 | <filename>main.py
from capture_monitor import CaptureMonitor
from face_lib import FaceSystem
from visualizer import Visualizer #MainWindow
#from PyQt5 import QtCore, QtGui, QtWidgets
import os
monitor = CaptureMonitor(bb=(0, 0, 600, 480))
face_system = FaceSystem(os.path.abspath("./bio/bio.json"))
def thread_process(... | 2.140625 | 2 |
tests/mixins.py | armstrong/armstrong.apps.embeds | 1 | 33790 | import fudge
from armstrong.apps.embeds.mixins import TemplatesByEmbedTypeMixin
from .support.models import Parent, Child, TypeModel
from ._utils import TestCase
class TemplateCompareTestMixin(object):
def path_opts(self, obj, use_fallback=False, use_type=False):
return dict(
base=obj.base_la... | 2.0625 | 2 |
app/api/__init__.py | correaleyval/Telezon-S3 | 12 | 33791 | <gh_stars>10-100
from fastapi import APIRouter
from app.api.auth import router as auth
from app.api.v1 import router as v1
router = APIRouter(prefix='/api')
router.include_router(auth)
router.include_router(v1)
| 1.820313 | 2 |
TestData/Soccer/ImageDownloader.py | hundyoung/yolo3_keras | 0 | 33792 | <reponame>hundyoung/yolo3_keras<filename>TestData/Soccer/ImageDownloader.py
import requests
import urllib
import os
import re
from bs4 import BeautifulSoup
import json
# save_path = "./foul/"
save_path = "./non_foul/"
url="https://images.api.press.net/api/v2/search/?category=A,S,E&ck=public&cond=not&crhPriority=1&fie... | 2.609375 | 3 |
twitchchatbot/lib/commands/addcom.py | Amperture/twitch-sbc-integration | 10 | 33793 | from twitchchatbot.lib.commands.parsing import commands
import json
def addcom(user, args):
# Concatenate a list of strings down to a single, space delimited string.
queueEvent = {}
if len(args) < 2:
queueEvent['msg'] = "Proper usage: !addcom <cmd> <Text to send>"
else:
commandHead = ... | 2.875 | 3 |
fog/fog-client/setup.py | breakEval13/tor_dev | 1 | 33794 | from distutils.core import setup
import py2exe
# if py2exe complains "can't find P", try one of the following workarounds:
#
# a. py2exe doesn't support zipped eggs - http://www.py2exe.org/index.cgi/ExeWithEggs
# You should give the --always-unzip option to easy_install, or you can use setup.py directly
# $ python s... | 1.921875 | 2 |
generate_imagery.py | AnthonyLapadula/pytorch-GANs | 278 | 33795 | import os
import shutil
import argparse
import torch
from torch import nn
from torchvision.utils import save_image, make_grid
import matplotlib.pyplot as plt
import numpy as np
import cv2 as cv
import utils.utils as utils
from utils.constants import *
class GenerationMode(enum.Enum):
SINGLE_IMAGE = 0,
INT... | 2.671875 | 3 |
toontown/dmenu/DMenuDisclaimer.py | LittleNed/toontown-stride | 1 | 33796 | from direct.gui.DirectGui import OnscreenText, DirectButton
from panda3d.core import *
from direct.interval.IntervalGlobal import *
from direct.showbase.DirectObject import DirectObject
from toontown.toonbase import ToontownGlobals
class DMenuDisclaimer(DirectObject):
notify = directNotify.newCategory('DisclaimerS... | 2.140625 | 2 |
geomloss/sinkhorn_images.py | ismedina/geomloss | 0 | 33797 | <gh_stars>0
import torch
from .utils import log_dens, pyramid, upsample, softmin_grid
from .sinkhorn_divergence import epsilon_schedule, scaling_parameters
from .sinkhorn_divergence import sinkhorn_cost, sinkhorn_loop
def extrapolate(f_ba, g_ab, eps, damping, C_xy, b_log, C_xy_fine):
return upsample(f_ba)
def k... | 1.6875 | 2 |
time_trials/indexedvalues_timetrials.py | eric-s-s/share-with-z | 5 | 33798 | """a module solely for finding how add_a_list and add_tuple_list compare.
it's effectively the empirical proof for how LongIntTable.add() chooses
the fastest method with it's get_fastest_method() function."""
from __future__ import print_function
from math import log10
import time
import random
from os import getcwd
... | 3.203125 | 3 |
orangecontrib/wonder/widgets/wonder/ow_lorentz_polarization.py | WONDER-project/OASYS1-WONDER | 0 | 33799 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# #########################################################################
# Copyright (c) 2020, UChicago Argonne, LLC. All rights reserved. #
# #
# Copyright 2020. UChicago Argonne, LLC. This ... | 1.148438 | 1 |