max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111
values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
examples/operator_v1.py | dciangot/pymesos | 177 | 6622851 | #!/usr/bin/env python2.7
from __future__ import print_function
import sys
from pymesos import MesosOperatorMasterDriver, OperatorMaster
class MinimalOperator(OperatorMaster):
def __init__(self):
pass
def taskAdded(self, task_info):
logging.debug('Task added')
logging.debug(task_info... | #!/usr/bin/env python2.7
from __future__ import print_function
import sys
from pymesos import MesosOperatorMasterDriver, OperatorMaster
class MinimalOperator(OperatorMaster):
def __init__(self):
pass
def taskAdded(self, task_info):
logging.debug('Task added')
logging.debug(task_info... | ru | 0.174408 | #!/usr/bin/env python2.7 | 2.245847 | 2 |
tests/plugins/twitter.py | alfie-max/Publish | 1 | 6622852 | <filename>tests/plugins/twitter.py
class Twitter(object):
def __init__(self):
self.__fields__ = ['Message']
def VerifyCredentials(self):
return False
def Authorize(self):
pass
def VerifyFields(self, fields):
return True
def SendMsg(self, msg):
return {'':''}
... | <filename>tests/plugins/twitter.py
class Twitter(object):
def __init__(self):
self.__fields__ = ['Message']
def VerifyCredentials(self):
return False
def Authorize(self):
pass
def VerifyFields(self, fields):
return True
def SendMsg(self, msg):
return {'':''}
... | none | 1 | 2.210048 | 2 | |
handyrep/plugins/multi_pgbouncer.py | ubiquitousthey/handyrep | 0 | 6622853 | <reponame>ubiquitousthey/handyrep
# plugin method for failing over connections
# using pgbouncer
# rewrites the list of databases
# plugin for users running multiple pgbouncer servers
# requires that each pgbouncer server be in the servers dictionary
# as role "pgbouncer" and enabled.
# further, this plugin requires ... | # plugin method for failing over connections
# using pgbouncer
# rewrites the list of databases
# plugin for users running multiple pgbouncer servers
# requires that each pgbouncer server be in the servers dictionary
# as role "pgbouncer" and enabled.
# further, this plugin requires that the handyrep user, DB and pas... | en | 0.867269 | # plugin method for failing over connections # using pgbouncer # rewrites the list of databases # plugin for users running multiple pgbouncer servers # requires that each pgbouncer server be in the servers dictionary # as role "pgbouncer" and enabled. # further, this plugin requires that the handyrep user, DB and passw... | 2.541012 | 3 |
script/lib/get_next_obs.py | cyberphantom/Selfie-Drone-Stick | 2 | 6622854 | # ROS import
import future
import rospy
import rospkg
from geometry_msgs.msg import Twist, Vector3Stamped, Pose, PoseWithCovarianceStamped
def nextObs():
next_st = None
n_s = []
while next_st is None:
next_st = rospy.wait_for_message('/obs/pos', Pose, timeout=1)
if next_st.orientation.x == ... | # ROS import
import future
import rospy
import rospkg
from geometry_msgs.msg import Twist, Vector3Stamped, Pose, PoseWithCovarianceStamped
def nextObs():
next_st = None
n_s = []
while next_st is None:
next_st = rospy.wait_for_message('/obs/pos', Pose, timeout=1)
if next_st.orientation.x == ... | es | 0.271199 | # ROS import | 2.302258 | 2 |
Lander/Timer.py | IrvKalb/pygwidgetsExamples | 1 | 6622855 | # CountDownTimer class
# <NAME> 4/16
import time
class CountUpTimer(object):
def __init__(self):
self.running = False
self.savedSecondsElapsed = 0
def mStart(self):
self.secondsStart = time.time() # get the current seconds, and save it away
#print 'time start:', self... | # CountDownTimer class
# <NAME> 4/16
import time
class CountUpTimer(object):
def __init__(self):
self.running = False
self.savedSecondsElapsed = 0
def mStart(self):
self.secondsStart = time.time() # get the current seconds, and save it away
#print 'time start:', self... | de | 0.206928 | # CountDownTimer class # <NAME> 4/16 # get the current seconds, and save it away #print 'time start:', self.secondsStart ############################################# | 3.531291 | 4 |
tests/test_output.py | sander76/consoler | 0 | 6622856 | import logging
import pytest
from pyconsoler.output import print_waiting_countdown, prt
_LOGGER = logging.getLogger(__name__)
@pytest.mark.asyncio
async def test_print_waiting_countdown():
await print_waiting_countdown(4)
@pytest.mark.parametrize("_input", [1, False, None, "test", {"test": 10}])
def test_prt... | import logging
import pytest
from pyconsoler.output import print_waiting_countdown, prt
_LOGGER = logging.getLogger(__name__)
@pytest.mark.asyncio
async def test_print_waiting_countdown():
await print_waiting_countdown(4)
@pytest.mark.parametrize("_input", [1, False, None, "test", {"test": 10}])
def test_prt... | none | 1 | 2.560927 | 3 | |
genetic_algo/individual.py | TheRun98/genetic-algo | 3 | 6622857 | import random
SEX_PARAM = [0.25, 0.5, .9]
class Individual:
""" Class that represents an individual
Attributes:
genes(array): array of 16 floats representing the individual's characteristics
fit_func(func): function used to assess fitness of the individual
fitness(float): a float ... | import random
SEX_PARAM = [0.25, 0.5, .9]
class Individual:
""" Class that represents an individual
Attributes:
genes(array): array of 16 floats representing the individual's characteristics
fit_func(func): function used to assess fitness of the individual
fitness(float): a float ... | en | 0.786134 | Class that represents an individual Attributes: genes(array): array of 16 floats representing the individual's characteristics fit_func(func): function used to assess fitness of the individual fitness(float): a float representing the individual's fitness, stored so it doesn't have to b... | 3.632895 | 4 |
sdk/python/pulumi_google_native/dialogflow/v2/get_participant.py | AaronFriel/pulumi-google-native | 44 | 6622858 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__... | en | 0.816806 | # coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** Optional. Key-value filters on the metadata of documents returned by article suggestion. If specified, article suggestion only returns suggested documen... | 1.61694 | 2 |
lintcode/Depth First Search & Backtracking/1353. Sum Root to Leaf Numbers.py | yanshengjia/algorithm | 23 | 6622859 | """
Description:
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Example:
Input: {1,2,3}
1
/ \
2 3
Output: 25
Explanation:
The... | """
Description:
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Example:
Input: {1,2,3}
1
/ \
2 3
Output: 25
Explanation:
The... | en | 0.704434 | Description: Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. Example: Input: {1,2,3} 1 / \ 2 3 Output: 25 Explanation: The roo... | 4.035043 | 4 |
freshdesk/python-connectors/freshdesk-users-simple/connector.py | gbetegon88/dataiku-contrib | 93 | 6622860 | from dataiku.connector import Connector
from freshdesk_utils import FreshdeskConnector
class FreshDeskUsersConnector(FreshdeskConnector, Connector):
def __init__(self, config, plugin_config):
Connector.__init__(self, config, plugin_config)
FreshdeskConnector.__init__(self, config, plugin_config)
... | from dataiku.connector import Connector
from freshdesk_utils import FreshdeskConnector
class FreshDeskUsersConnector(FreshdeskConnector, Connector):
def __init__(self, config, plugin_config):
Connector.__init__(self, config, plugin_config)
FreshdeskConnector.__init__(self, config, plugin_config)
... | none | 1 | 2.142267 | 2 | |
asist_nsf_2018/process_level1.py | sustain-lab/asist-nsf-2018 | 1 | 6622861 | """
process_level1.py
"""
from asist.irgason import read_irgason_from_toa5
from asist.hotfilm import read_hotfilm_from_lvm
from asist.pressure import read_pressure_from_toa5
from asist.pitot import pitot_velocity
from asist_nsf_2018.experiments import experiments
from datetime import datetime, timedelta
import glob
fro... | """
process_level1.py
"""
from asist.irgason import read_irgason_from_toa5
from asist.hotfilm import read_hotfilm_from_lvm
from asist.pressure import read_pressure_from_toa5
from asist.pitot import pitot_velocity
from asist_nsf_2018.experiments import experiments
from datetime import datetime, timedelta
import glob
fro... | en | 0.770355 | process_level1.py Gets the data path from the env variable. Returns time and data slice between experiment start and end times. Processes pressure gradient into a NetCDF file. # remove offset from pressure # fan frequency # distance between air pressure ports # 14 panels, 0.77 m each, minus 2 cm on each end Proces... | 2.243066 | 2 |
generate.py | mankadronit/Spotify-Playlist-Generator | 0 | 6622862 | import base64
from bs4 import BeautifulSoup
import datetime
import json
from os.path import isfile, getsize
import re
import requests
import six
import sqlite3
import urllib
import webbrowser
from constants import *
def authenticate_client():
""" Spotify's Auth Flow, a three steps process """
auth_code = get... | import base64
from bs4 import BeautifulSoup
import datetime
import json
from os.path import isfile, getsize
import re
import requests
import six
import sqlite3
import urllib
import webbrowser
from constants import *
def authenticate_client():
""" Spotify's Auth Flow, a three steps process """
auth_code = get... | en | 0.897803 | Spotify's Auth Flow, a three steps process 1st Step of Auth Process 2nd Step of Auth Process Fetches Access Token from Spotify API Fetches a new access token using refresh token Fetches Auth code by making a request to Spotify OAUTH URL Saves auth code to the disk Asks the user to paste the redirect URL through any inp... | 2.919765 | 3 |
src/tagger_from_scratch/data.py | soldni/tagger-from-scratch | 0 | 6622863 | from typing import Sequence, Dict, Tuple
import dataclasses
import torch
from tagger_from_scratch.config import Config
@dataclasses.dataclass
class ConllCourpusSample:
tokens: list = dataclasses.field(default_factory=lambda: [])
pos: list = dataclasses.field(default_factory=lambda: [])
con: list = datac... | from typing import Sequence, Dict, Tuple
import dataclasses
import torch
from tagger_from_scratch.config import Config
@dataclasses.dataclass
class ConllCourpusSample:
tokens: list = dataclasses.field(default_factory=lambda: [])
pos: list = dataclasses.field(default_factory=lambda: [])
con: list = datac... | en | 0.970676 | # only append a new sample if the previous sample # was filled up or it's the first sample # skip first line, only has shape info about dim # and size of vocab | 2.417305 | 2 |
PSO2LogReader.pyw | yumimint/PSO2LogReader | 0 | 6622864 | import os
import pathlib
from app.gmain import main
os.chdir(pathlib.Path(__file__).parent)
main()
| import os
import pathlib
from app.gmain import main
os.chdir(pathlib.Path(__file__).parent)
main()
| none | 1 | 1.439104 | 1 | |
code/mcmc.py | mjvakili/alpha-forecast | 0 | 6622865 | from linear_bias import linear_model, shear_extractor
import os
import sys
import numpy as np
import emcee
from numpy.linalg import solve
import h5py
def lnPost(theta, **kwargs):
def lnprior(theta, **kwargs):
'''log prior
'''
obs = kwargs['data']
obs_cov = kwargs['data_cov']
... | from linear_bias import linear_model, shear_extractor
import os
import sys
import numpy as np
import emcee
from numpy.linalg import solve
import h5py
def lnPost(theta, **kwargs):
def lnprior(theta, **kwargs):
'''log prior
'''
obs = kwargs['data']
obs_cov = kwargs['data_cov']
... | en | 0.566646 | log prior log likelihood # Likelihood #print("neg_chi_tot" , neg_chisq*2./len(res)) Parameters ----------- - Nwalker : Number of walkers - Nchains : Number of MCMC chains #initializing the positions of the walkers #setting up the data kwargs to be passed to log-likelihood #setting up the M... | 1.979949 | 2 |
hexrd/ui/calibration/auto/powder_runner.py | HEXRD/hexrdgui | 13 | 6622866 | import traceback
import numpy as np
from PySide2.QtCore import QObject, QTimer, Qt, Signal
from PySide2.QtWidgets import QCheckBox, QMessageBox
from hexrd.ui.async_runner import AsyncRunner
from hexrd.ui.create_hedm_instrument import create_hedm_instrument
from hexrd.ui.constants import OverlayType
from hexrd.ui.hex... | import traceback
import numpy as np
from PySide2.QtCore import QObject, QTimer, Qt, Signal
from PySide2.QtWidgets import QCheckBox, QMessageBox
from hexrd.ui.async_runner import AsyncRunner
from hexrd.ui.create_hedm_instrument import create_hedm_instrument
from hexrd.ui.constants import OverlayType
from hexrd.ui.hex... | en | 0.826788 | # Remove the box if it is still there... # First, have the user pick some options # User canceled... # The options they chose are saved here # Assume there is only one image in each image series for now... # FIXME: currently coded to handle only a single material # so grabbing first (only) element # Add a checkb... | 1.837643 | 2 |
pip_services_runtime/build/DefaultFactory.py | pip-services-archive/pip-services-runtime-python | 0 | 6622867 | # -*- coding: utf-8 -*-
"""
pip_services_runtime.build.DefaultFactory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Default component factory implementation
:copyright: Digital Living Software Corp. 2015-2016, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
from... | # -*- coding: utf-8 -*-
"""
pip_services_runtime.build.DefaultFactory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Default component factory implementation
:copyright: Digital Living Software Corp. 2015-2016, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
from... | en | 0.723415 | # -*- coding: utf-8 -*- pip_services_runtime.build.DefaultFactory ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Default component factory implementation :copyright: Digital Living Software Corp. 2015-2016, see AUTHORS for more details. :license: MIT, see LICENSE for more details. Component factory... | 2.203776 | 2 |
src/Tuple/unpackTuple.py | mikeludemann/helperFunctions_Python | 0 | 6622868 | x = 4, 17, 31
print(x)
numberOne, numberTwo, numberThree = x
print(numberOne + numberTwo + numberThree) | x = 4, 17, 31
print(x)
numberOne, numberTwo, numberThree = x
print(numberOne + numberTwo + numberThree) | none | 1 | 2.949842 | 3 | |
Desafios/Desafio102.py | julianascimentosantos/cursoemvideo-python3 | 0 | 6622869 | def fatorial(num, show=False):
"""
-> Calcula o Fatorial de um número.
:param num: O numero a ser calculado.
:param show: (opcional) Mostrar ou não a conta
:return: O valor do fatorial de um numero num.
"""
f = 1
for n in range(num, 0, -1):
f *= n
if show:
pri... | def fatorial(num, show=False):
"""
-> Calcula o Fatorial de um número.
:param num: O numero a ser calculado.
:param show: (opcional) Mostrar ou não a conta
:return: O valor do fatorial de um numero num.
"""
f = 1
for n in range(num, 0, -1):
f *= n
if show:
pri... | pt | 0.92676 | -> Calcula o Fatorial de um número. :param num: O numero a ser calculado. :param show: (opcional) Mostrar ou não a conta :return: O valor do fatorial de um numero num. #Programa Principal | 3.745573 | 4 |
serial_temp/serial_temp.py | nathanwiens/sdk-samples | 44 | 6622870 | import time
import serial
import paho.mqtt.client as mqtt
import json
from csclient import EventingCSClient
cp = EventingCSClient('serial_temp')
broker_address = '127.0.0.01'
port = '/dev/ttyUSB0'
speed = 9600
my_sim = 'mdm-e152d8b2' # Change to your SIM slot UID
class Timeout(Exception):
pass
def has_t1t2(chu... | import time
import serial
import paho.mqtt.client as mqtt
import json
from csclient import EventingCSClient
cp = EventingCSClient('serial_temp')
broker_address = '127.0.0.01'
port = '/dev/ttyUSB0'
speed = 9600
my_sim = 'mdm-e152d8b2' # Change to your SIM slot UID
class Timeout(Exception):
pass
def has_t1t2(chu... | en | 0.841226 | # Change to your SIM slot UID # Blocking call that will wait until a given state is shown as the modem's status # TODO add checking for error states # create new instance # connect to broker | 2.750875 | 3 |
Tools/Jinja2/Jinja2-2.5/build.py | rtobar/askapsoft | 1 | 6622871 | from askapdev.rbuild.builders import Setuptools as Builder
builder = Builder()
builder.remote_archive = "Jinja2-2.5.tar.gz"
builder.build()
| from askapdev.rbuild.builders import Setuptools as Builder
builder = Builder()
builder.remote_archive = "Jinja2-2.5.tar.gz"
builder.build()
| none | 1 | 1.334567 | 1 | |
scripts/data_manipulation/build_datasets.py | GuyBaele/sars-cov-2-belgium | 0 | 6622872 | <gh_stars>0
"""build_datasets.py
"""
from __future__ import print_function
import datetime as dt
import json
# import multiprocessing as mp
import os
import random
import subprocess
import sys
import numpy as np
import pandas as pd
from argh import dispatch_command # type: ignore
from Bio import SeqIO # type: igno... | """build_datasets.py
"""
from __future__ import print_function
import datetime as dt
import json
# import multiprocessing as mp
import os
import random
import subprocess
import sys
import numpy as np
import pandas as pd
from argh import dispatch_command # type: ignore
from Bio import SeqIO # type: ignore
from redi... | en | 0.890006 | build_datasets.py # import multiprocessing as mp # type: ignore # type: ignore # type: ignore # type: ignore The main process to follow for incorporating metadata files # There should be two files that come from GISAID: # 1) A dated metadata tsv # 2) A dated sequences fasta # These files can be found throught: # GI... | 2.265099 | 2 |
point_registration/compare_results.py | MarvinGravert/utils-computation | 0 | 6622873 |
from typing import Tuple
import numpy as np
from loguru import logger
from config.config import RANSAC_THRESHOLD, RANSAC_CONFIDENCE
from utils.check_cost_function import check_cost_function
from client import run_with_config
from modules.optimization import optimize
def show_Matrix(R, t):
# logger.inf... |
from typing import Tuple
import numpy as np
from loguru import logger
from config.config import RANSAC_THRESHOLD, RANSAC_CONFIDENCE
from utils.check_cost_function import check_cost_function
from client import run_with_config
from modules.optimization import optimize
def show_Matrix(R, t):
# logger.inf... | en | 0.393734 | # logger.info(f""" # Rotationmatrix: # {R[0,:]} # {R[1,:]} # {R[2,:]} # Translationvektor: # {t[0]} # {t[1]} # {t[2]} # """) # logger.info(f"\n {R.as_matrix()}") # return len(first), len(second) # t = np.loadtxt(filename, skiprows=1, delimiter=",") #boolean, False #[threshold, confidence]list of floats IMPORT DATA ## d... | 2.509197 | 3 |
map/models.py | gadkaridarshan/ShpTest | 0 | 6622874 | from django.db import models
class Coordinate(models.Model):
Unique_ID = models.CharField(max_length=128,null=True, blank=True)
Address = models.CharField(max_length=500,null=True, blank=True)
Latitude = models.CharField(max_length=32,null=True, blank=True)
Longitude = models.CharField(max_length=32,null=True, bla... | from django.db import models
class Coordinate(models.Model):
Unique_ID = models.CharField(max_length=128,null=True, blank=True)
Address = models.CharField(max_length=500,null=True, blank=True)
Latitude = models.CharField(max_length=32,null=True, blank=True)
Longitude = models.CharField(max_length=32,null=True, bla... | none | 1 | 2.392008 | 2 | |
test/api_test.py | LLK/fastly-py | 4 | 6622875 | import unittest
import fastly
class APITest(unittest.TestCase):
def setUp(self):
self.api = fastly.API()
def test_purge(self):
self.assertTrue(self.api.purge_url('test.com', '/'))
def test_purge_by_key(self):
self.api.deauthenticate()
self.api.authenticate_by_key('TESTA... | import unittest
import fastly
class APITest(unittest.TestCase):
def setUp(self):
self.api = fastly.API()
def test_purge(self):
self.assertTrue(self.api.purge_url('test.com', '/'))
def test_purge_by_key(self):
self.api.deauthenticate()
self.api.authenticate_by_key('TESTA... | none | 1 | 2.611288 | 3 | |
fit/utils.py | rembish/f | 10 | 6622876 | <reponame>rembish/f<gh_stars>1-10
from importlib import import_module
from inspect import getmembers, isclass
from pkgutil import iter_modules
def get_known(name, base_cls, key="type"):
main = import_module(name)
known = {}
for _, module_name, _ in iter_modules(main.__path__, "%s." % name):
modul... | from importlib import import_module
from inspect import getmembers, isclass
from pkgutil import iter_modules
def get_known(name, base_cls, key="type"):
main = import_module(name)
known = {}
for _, module_name, _ in iter_modules(main.__path__, "%s." % name):
module = import_module(module_name)
... | none | 1 | 2.476661 | 2 | |
src/accounts/serializers.py | NamHDT/Django-HDT | 0 | 6622877 | <filename>src/accounts/serializers.py
from rest_framework import serializers
from .models import Accounts
from django.contrib.auth.models import User
class AccountsSerializer(serializers.ModelSerializer):
class Meta:
model = Accounts
fields = '__all__' | <filename>src/accounts/serializers.py
from rest_framework import serializers
from .models import Accounts
from django.contrib.auth.models import User
class AccountsSerializer(serializers.ModelSerializer):
class Meta:
model = Accounts
fields = '__all__' | none | 1 | 1.692505 | 2 | |
src_pkg/generate.py | KaiyanD/Data_Generator | 0 | 6622878 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 23 14:39:42 2017
@author: kading
"""
# Import all dependencies.
import csv
import itertools
import json
from src_pkg.core import *
import config
rootpath = os.path.dirname(setup.path()) + "\\testdatageneration\\"
class Generate_Main:
def run(self,schema,bottle... | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 23 14:39:42 2017
@author: kading
"""
# Import all dependencies.
import csv
import itertools
import json
from src_pkg.core import *
import config
rootpath = os.path.dirname(setup.path()) + "\\testdatageneration\\"
class Generate_Main:
def run(self,schema,bottle... | en | 0.51477 | # -*- coding: utf-8 -*- Created on Mon Oct 23 14:39:42 2017 @author: kading # Import all dependencies. # Create the generator object. # Create data frame to store fake data and metadata # Provide the number of rows # Read table title and table columns # Read through the columns dictionary # Read column name # Read thr... | 2.863192 | 3 |
src/perlin_test.py | jkunimune15/kodi-analysis | 0 | 6622879 | <reponame>jkunimune15/kodi-analysis
import matplotlib.pyplot as plt
import numpy as np
import perlin
r = np.sqrt(np.random.random(1000000))
t = 2*np.pi*np.random.random(1000000)
x, y = r*np.cos(t), r*np.sin(t)
dx, dy = np.zeros(x.shape), np.zeros(y.shape)
for n in range(0, 3):
dx += perlin.perlin(x, y, 2**(-n), 0.1... | import matplotlib.pyplot as plt
import numpy as np
import perlin
r = np.sqrt(np.random.random(1000000))
t = 2*np.pi*np.random.random(1000000)
x, y = r*np.cos(t), r*np.sin(t)
dx, dy = np.zeros(x.shape), np.zeros(y.shape)
for n in range(0, 3):
dx += perlin.perlin(x, y, 2**(-n), 0.1*2**(-2*n))
dy += perlin.perlin(x, ... | none | 1 | 2.959404 | 3 | |
algorithms/greed/greed.py | emrysf/Algorithms | 2 | 6622880 | states_needed = set(['mt', 'wa', 'or', 'id', 'nv', 'ut', 'ca', 'az'])
stations = {}
stations['kone'] = set(['id', 'nv', 'ut'])
stations['ktwo'] = set(['wa', 'id', 'mt'])
stations['kthree'] = set(['or', 'nv', 'ca'])
stations['kfour'] = set(['nv', 'ut'])
stations['kfive'] = set(['ca', 'az'])
final_stations = set()
whil... | states_needed = set(['mt', 'wa', 'or', 'id', 'nv', 'ut', 'ca', 'az'])
stations = {}
stations['kone'] = set(['id', 'nv', 'ut'])
stations['ktwo'] = set(['wa', 'id', 'mt'])
stations['kthree'] = set(['or', 'nv', 'ca'])
stations['kfour'] = set(['nv', 'ut'])
stations['kfive'] = set(['ca', 'az'])
final_stations = set()
whil... | none | 1 | 3.387102 | 3 | |
5.py | prof-paradox/project-euler | 0 | 6622881 | <filename>5.py
# Calculates smallest positive number that is evenly divisible by all of the numbers from 1 to 20
''' Inefficient method - takes about 2.5 mins
---------------------------------------------
min_mult = None
num = 21
while(True):
for i in range(2, 21):
if num % i != 0:
bre... | <filename>5.py
# Calculates smallest positive number that is evenly divisible by all of the numbers from 1 to 20
''' Inefficient method - takes about 2.5 mins
---------------------------------------------
min_mult = None
num = 21
while(True):
for i in range(2, 21):
if num % i != 0:
bre... | en | 0.517029 | # Calculates smallest positive number that is evenly divisible by all of the numbers from 1 to 20 Inefficient method - takes about 2.5 mins
---------------------------------------------
min_mult = None
num = 21
while(True):
for i in range(2, 21):
if num % i != 0:
break
else:
... | 3.722107 | 4 |
control_panel/__init__.py | uzum/cran-orchestrator | 0 | 6622882 | <gh_stars>0
from .server import CPServer
| from .server import CPServer | none | 1 | 1.100991 | 1 | |
troupon/payment/api.py | andela/troupon | 14 | 6622883 | """Generic API configuration."""
from django.shortcuts import get_object_or_404
from rest_framework import generics
from rest_framework import permissions
from deals.models import Advertiser
from payment.models import Purchases
from payment.serializers import TransactionSerializer
class TransationsList(generics.List... | """Generic API configuration."""
from django.shortcuts import get_object_or_404
from rest_framework import generics
from rest_framework import permissions
from deals.models import Advertiser
from payment.models import Purchases
from payment.serializers import TransactionSerializer
class TransationsList(generics.List... | en | 0.865413 | Generic API configuration. A merchant can see a list of all transactions that contained items he/she is advertising on the site. Using a transaction ID, a merchant can see the details of a particular transaction. | 2.402708 | 2 |
examples/modules/object_tracker/opencv_object_tracker.py | jagin/dvg-utils | 7 | 6622884 | import cv2
from .centroid_tracker import CentroidTracker
class OpencvObjectTracker:
def __init__(self, max_disappeared=20, max_distance=80, tracker_type="kcf"):
# Initialize the frame dimensions (we'll set them as soon as we read the first frame from the video)
self.w = None
self.h = None... | import cv2
from .centroid_tracker import CentroidTracker
class OpencvObjectTracker:
def __init__(self, max_disappeared=20, max_distance=80, tracker_type="kcf"):
# Initialize the frame dimensions (we'll set them as soon as we read the first frame from the video)
self.w = None
self.h = None... | en | 0.797429 | # Initialize the frame dimensions (we'll set them as soon as we read the first frame from the video) # Initialize a dictionary that maps strings to their corresponding OpenCV object tracker implementations # Instantiate our centroid tracker, then initialize a list to store each of our OpenCV correlation trackers, # fol... | 3.007855 | 3 |
Examples/DebugBase.py | whitfija/ACTUAL_GAME | 0 | 6622885 | #Base Class
class MyP5t:
definitely __init__( name):
self.name = "Billy"
def pet():
print("Oh no, your pet " + name + " ran away!")
def meow(self):
print("Meow meow")
class MyCat:
def init(self, name, age): #Make this not override __init__
self.name = name
self.age = age
def ba... | #Base Class
class MyP5t:
definitely __init__( name):
self.name = "Billy"
def pet():
print("Oh no, your pet " + name + " ran away!")
def meow(self):
print("Meow meow")
class MyCat:
def init(self, name, age): #Make this not override __init__
self.name = name
self.age = age
def ba... | en | 0.565854 | #Base Class #Make this not override __init__ | 3.78419 | 4 |
play_with_interface.py | marshallmcdonnell/journals | 0 | 6622886 | #!/usr/bin/env python
import unittest
from journals.databases.icat.sns.interface import SnsICatInterface
if __name__=="__main__":
conn = SnsICatInterface()
#print(conn.get_instruments())
print(conn.get_experiments('NOM'))
#print(conn.get_experiments_meta('NOM'))
#print(conn.get_experiments_id_an... | #!/usr/bin/env python
import unittest
from journals.databases.icat.sns.interface import SnsICatInterface
if __name__=="__main__":
conn = SnsICatInterface()
#print(conn.get_instruments())
print(conn.get_experiments('NOM'))
#print(conn.get_experiments_meta('NOM'))
#print(conn.get_experiments_id_an... | ru | 0.193945 | #!/usr/bin/env python #print(conn.get_instruments()) #print(conn.get_experiments_meta('NOM')) #print(conn.get_experiments_id_and_title('NOM')) #print(conn.get_experiments_id_and_date('NOM')) #print(conn.get_runs_all('NOM','IPTS-17210')) #print(conn.get_runs('NOM','IPTS-17210')) #print(conn.get_runs_meta('NOM','IPTS-172... | 1.971396 | 2 |
tests/test_s3_filer.py | Zcowyzrg/tesk-core | 2 | 6622887 | import os
import pytest
import boto3
from tesk_core.filer_s3 import S3Transput
from tesk_core.extract_endpoint import extract_endpoint
from moto import mock_s3
from unittest.mock import patch, mock_open
@pytest.fixture()
def moto_boto():
with mock_s3():
client = boto3.resource('s3',endpoint_url="http://s3.... | import os
import pytest
import boto3
from tesk_core.filer_s3 import S3Transput
from tesk_core.extract_endpoint import extract_endpoint
from moto import mock_s3
from unittest.mock import patch, mock_open
@pytest.fixture()
def moto_boto():
with mock_s3():
client = boto3.resource('s3',endpoint_url="http://s3.... | en | 0.816234 | Check if the bucket name and path is extracted correctly for file and folders Check if the bucket exists # @patch('tesk_core.filer.os.makedirs') # @patch('builtins.open') # @patch('s3transfer.utils.OSUtils.rename_file') Checking for successful/failed file download from Object storage server test case to check directory... | 1.945114 | 2 |
remedy/scrapers/scraper.py | AllieDeford/radremedy | 0 | 6622888 | <gh_stars>0
"""
scraper.py
Scraper template used throughout the application.
"""
from radrecord import RadRecord
class Scraper(object):
"""
This class is a template or better said interface,
all scrapers should inherit from this class.
Currently it promises that all scrapers will have a source
... | """
scraper.py
Scraper template used throughout the application.
"""
from radrecord import RadRecord
class Scraper(object):
"""
This class is a template or better said interface,
all scrapers should inherit from this class.
Currently it promises that all scrapers will have a source
and a scrape... | en | 0.834586 | scraper.py Scraper template used throughout the application. This class is a template or better said interface, all scrapers should inherit from this class. Currently it promises that all scrapers will have a source and a scrape method. This is going to be used to automate the scraping of multiple we... | 3.437552 | 3 |
src/analytical_validation/validators/intermediate_precision_validator.py | abxsantos/analytical-validation-backend | 0 | 6622889 | import numpy
import pandas
from statsmodels.formula.api import ols
import statsmodels.api as statsmodels
from analytical_validation.exceptions import IncorrectIntermediatePrecisionData
class IntermediatePrecision(object):
"""
Example:
>>> analytical_data = [0.1, 0.11, 0.12, 0.1, 0.11, 0.12, 0.1, 0.11,... | import numpy
import pandas
from statsmodels.formula.api import ols
import statsmodels.api as statsmodels
from analytical_validation.exceptions import IncorrectIntermediatePrecisionData
class IntermediatePrecision(object):
"""
Example:
>>> analytical_data = [0.1, 0.11, 0.12, 0.1, 0.11, 0.12, 0.1, 0.11,... | en | 0.699843 | Example: >>> analytical_data = [0.1, 0.11, 0.12, 0.1, 0.11, 0.12, 0.1, 0.11, 0.12, 0.1, 0.11, 0.12,] >>> intercept = 0.0001 >>> slope = 20.2 >>> alpha = 0.05 >>> intermediate_precision = IntermediatePrecision(analytical_data, intercept, slope, alpha) >>> intermediate_prec... | 3.411063 | 3 |
easelenium/ui/generator/page_object_class.py | kirillstrelkov/easyselenium | 1 | 6622890 | <reponame>kirillstrelkov/easyselenium
# coding=utf8
import os
from easelenium.ui.file_utils import safe_create_path, save_file
from easelenium.utils import LINESEP, get_match
from selenium.webdriver.common.by import By
# TODO: move to f string and get rid of u strings
def get_by_as_code_str(by):
if by == By.LIN... | # coding=utf8
import os
from easelenium.ui.file_utils import safe_create_path, save_file
from easelenium.utils import LINESEP, get_match
from selenium.webdriver.common.by import By
# TODO: move to f string and get rid of u strings
def get_by_as_code_str(by):
if by == By.LINK_TEXT:
return "By.LINK_TEXT"
... | en | 0.517848 | # coding=utf8 # TODO: move to f string and get rid of u strings # coding=utf8 from selenium.webdriver.common.by import By from easelenium.base_page_object import BasePageObject class {name}(BasePageObject): # Please do NOT remove auto-generated comments # Url: {url} # Area: {area} # File path: {file_... | 2.471511 | 2 |
donkeycar/parts/serial_arduino.py | arigadget/donkeycar | 2 | 6622891 | import serial
import time
class Serial_sense():
'''
get sensor information from Arduino via serial USB interface
'''
def __init__(self, dev='/dev/ttyUSB0', baudrate=115200, poll_delay=0.03):
self.status = b'F'
self.dev = dev
self.baudrate = baudrate
self.serial_port = s... | import serial
import time
class Serial_sense():
'''
get sensor information from Arduino via serial USB interface
'''
def __init__(self, dev='/dev/ttyUSB0', baudrate=115200, poll_delay=0.03):
self.status = b'F'
self.dev = dev
self.baudrate = baudrate
self.serial_port = s... | en | 0.44846 | get sensor information from Arduino via serial USB interface #print(self.status) | 3.104156 | 3 |
import_export_open_civic_data/models.py | adborden/WeVoteBase | 0 | 6622892 | <reponame>adborden/WeVoteBase
# import_export_open_civic_data/models.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.db import models
# https://github.com/opencivicdata/python-opencivicdata-django
# There are models for the ocd data types
# Other Open Civic Data identifiers that refer t... | # import_export_open_civic_data/models.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.db import models
# https://github.com/opencivicdata/python-opencivicdata-django
# There are models for the ocd data types
# Other Open Civic Data identifiers that refer to the same division -- for exa... | en | 0.753975 | # import_export_open_civic_data/models.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- # https://github.com/opencivicdata/python-opencivicdata-django # There are models for the ocd data types # Other Open Civic Data identifiers that refer to the same division -- for example, those that refer to other #... | 2.076555 | 2 |
Visualization_Script/discriminator_attention_visual(Single).py | aesrgan/A-ESRGAN | 58 | 6622893 | from basicsr.utils.registry import ARCH_REGISTRY
from torch import nn as nn
from torch.nn import functional as F
from torch.nn.utils import spectral_norm
import torch
class add_attn(nn.Module):
def __init__(self, x_channels, g_channels=256):
super(add_attn, self).__init__()
self.W = nn.Sequential... | from basicsr.utils.registry import ARCH_REGISTRY
from torch import nn as nn
from torch.nn import functional as F
from torch.nn.utils import spectral_norm
import torch
class add_attn(nn.Module):
def __init__(self, x_channels, g_channels=256):
super(add_attn, self).__init__()
self.W = nn.Sequential... | en | 0.733094 | # Upsampling Defines a U-Net discriminator with spectral normalization (SN) # Center # attention Blocks # Cat # upsample # extra # Attention | 2.42933 | 2 |
MSquared/SElaser.py | mmsutula/hwserver | 0 | 6622894 | <gh_stars>0
from MSquared.msquared import *
init(__name__, \
solstis_addr = None, \
emm_addr = None)
# add solstis_addr and emm_addr as ('xxx.xxx.xxx.xxx',xxxxx), specifying the IP and port et in the web interface | from MSquared.msquared import *
init(__name__, \
solstis_addr = None, \
emm_addr = None)
# add solstis_addr and emm_addr as ('xxx.xxx.xxx.xxx',xxxxx), specifying the IP and port et in the web interface | en | 0.548707 | # add solstis_addr and emm_addr as ('xxx.xxx.xxx.xxx',xxxxx), specifying the IP and port et in the web interface | 1.447101 | 1 |
plot/figure_3.py | aneeshnaik/spam | 0 | 6622895 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created: 2018
Author: <NAME>
Description: Figure 3 in Naik et al., 2019.
"""
from matplotlib import rcParams
import matplotlib.pyplot as plt
import spam
import numpy as np
rcParams['text.usetex'] = True
rcParams['font.size'] = 8
green1 = '#EDF8E9'
green2 = '#BAE4B3'
g... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created: 2018
Author: <NAME>
Description: Figure 3 in Naik et al., 2019.
"""
from matplotlib import rcParams
import matplotlib.pyplot as plt
import spam
import numpy as np
rcParams['text.usetex'] = True
rcParams['font.size'] = 8
green1 = '#EDF8E9'
green2 = '#BAE4B3'
g... | en | 0.859012 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Created: 2018 Author: <NAME> Description: Figure 3 in Naik et al., 2019. Figure showing priors used. Two panels: Upper shows stellar mass / halo mass relation, while lower shows concentration / halo mass relation. 1 sigma and 2 sigma regions are shown as colou... | 2.243927 | 2 |
train.py | Yonder-OSS/ICLR-CV-Transfer-Learning | 0 | 6622896 | <filename>train.py
# This script can be used to train any deep learning model on the BigEarthNet.
#
# To run the code, you need to provide a json file for configurations of the training.
#
# Original Author: <NAME>, http://www.user.tu-berlin.de/gencersumbul/ <EMAIL>
# Usage: train.py [CONFIG_FILE_PATH]
from __future... | <filename>train.py
# This script can be used to train any deep learning model on the BigEarthNet.
#
# To run the code, you need to provide a json file for configurations of the training.
#
# Original Author: <NAME>, http://www.user.tu-berlin.de/gencersumbul/ <EMAIL>
# Usage: train.py [CONFIG_FILE_PATH]
from __future... | en | 0.589574 | # This script can be used to train any deep learning model on the BigEarthNet. # # To run the code, you need to provide a json file for configurations of the training. # # Original Author: <NAME>, http://www.user.tu-berlin.de/gencersumbul/ <EMAIL> # Usage: train.py [CONFIG_FILE_PATH] # TODO - allow randomness during ac... | 2.655203 | 3 |
build/lib/Tests/Validation/test_datadual.py | enjoyneer87/SciDataTool | 24 | 6622897 | <filename>build/lib/Tests/Validation/test_datadual.py
import pytest
from SciDataTool import (
DataTime,
Data1D,
DataLinspace,
DataFreq,
DataDual,
)
import numpy as np
from numpy.testing import assert_array_almost_equal
@pytest.mark.validation
def test_datadual():
f = 50
time = np.linspace(... | <filename>build/lib/Tests/Validation/test_datadual.py
import pytest
from SciDataTool import (
DataTime,
Data1D,
DataLinspace,
DataFreq,
DataDual,
)
import numpy as np
from numpy.testing import assert_array_almost_equal
@pytest.mark.validation
def test_datadual():
f = 50
time = np.linspace(... | pt | 0.58501 | # test to_datadual | 2.226044 | 2 |
converter/setup.py | thpts/tls-cbor-benchmark | 0 | 6622898 | <filename>converter/setup.py
from setuptools import setup
setup(
name='cbor_converter',
author='<NAME>',
author_email='<EMAIL>',
license='Apache 2',
packages=['cbor_converter'],
install_requires=[
'pyasn1',
'pyasn1-modules'
],
test_suite='test',
entry_points={
... | <filename>converter/setup.py
from setuptools import setup
setup(
name='cbor_converter',
author='<NAME>',
author_email='<EMAIL>',
license='Apache 2',
packages=['cbor_converter'],
install_requires=[
'pyasn1',
'pyasn1-modules'
],
test_suite='test',
entry_points={
... | none | 1 | 1.37359 | 1 | |
python/ml4ir/applications/ranking/model/scoring/pointwise_scoring.py | ducouloa/ml4ir | 70 | 6622899 | from ml4ir.base.model.scoring.scoring_base import ScoringBase
class PointwiseScoring(ScoringBase):
def get_scoring_fn(self, **kwargs):
"""
Define a pointwise ranking scoring function with specified architecture
"""
def _scoring_fn(features):
return self.architecture_op... | from ml4ir.base.model.scoring.scoring_base import ScoringBase
class PointwiseScoring(ScoringBase):
def get_scoring_fn(self, **kwargs):
"""
Define a pointwise ranking scoring function with specified architecture
"""
def _scoring_fn(features):
return self.architecture_op... | en | 0.624081 | Define a pointwise ranking scoring function with specified architecture | 2.396487 | 2 |
apps/plea/tests/test_forms.py | uk-gov-mirror/ministryofjustice.manchester_traffic_offences_pleas | 3 | 6622900 | <filename>apps/plea/tests/test_forms.py
import redgreenunittest as unittest
from ..forms import CompanyFinancesForm
class TestCompanyForm(unittest.TestCase):
def test_trading_period_not_specified_other_fields_not_required(self):
form = CompanyFinancesForm({})
form.is_valid()
self.asser... | <filename>apps/plea/tests/test_forms.py
import redgreenunittest as unittest
from ..forms import CompanyFinancesForm
class TestCompanyForm(unittest.TestCase):
def test_trading_period_not_specified_other_fields_not_required(self):
form = CompanyFinancesForm({})
form.is_valid()
self.asser... | none | 1 | 2.810515 | 3 | |
allure-pytest/test/steps/parameters/step_default_parameters_test.py | vdsbenoit/allure-python | 1 | 6622901 | import allure
@allure.step("First step")
def step_with_parameters(arg_param, kwarg_param=None):
pass
def test_defined_default_parameter():
"""
>>> from allure_commons.utils import represent
>>> allure_report = getfixture('allure_report')
>>> assert_that(allure_report,
... has_tes... | import allure
@allure.step("First step")
def step_with_parameters(arg_param, kwarg_param=None):
pass
def test_defined_default_parameter():
"""
>>> from allure_commons.utils import represent
>>> allure_report = getfixture('allure_report')
>>> assert_that(allure_report,
... has_tes... | en | 0.214895 | >>> from allure_commons.utils import represent >>> allure_report = getfixture('allure_report') >>> assert_that(allure_report, ... has_test_case('test_defined_default_parameter', ... has_step('First step', ... has_parameter('arg... | 2.484377 | 2 |
api/qmrandom.py | unhaltable/txti | 0 | 6622902 | <reponame>unhaltable/txti
import random
import requests
class qmrandom(random.Random):
def __init__(self):
self.nums = []
super(qmrandom, self).__init__()
def seed(self, x=None):
pass
def random(self):
if (len(self.nums) == 0):
self._getNums()
return i... | import random
import requests
class qmrandom(random.Random):
def __init__(self):
self.nums = []
super(qmrandom, self).__init__()
def seed(self, x=None):
pass
def random(self):
if (len(self.nums) == 0):
self._getNums()
return int(self.nums.pop(), 16) / ... | en | 0.797366 | # bits / 8 and rounded up | 3.098287 | 3 |
com/Leetcode/1344.AngleBetweenHandsofaClock.py | samkitsheth95/InterviewPrep | 0 | 6622903 | class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
am = minutes * 6
ah = ((hour * 30) + (minutes/60) * 30) % 360
if am > ah:
return min(am - ah, (360 - am) + ah)
else:
return min(ah - am, (360 - ah) + am)
def angleClockLeetcodeSol(se... | class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
am = minutes * 6
ah = ((hour * 30) + (minutes/60) * 30) % 360
if am > ah:
return min(am - ah, (360 - am) + ah)
else:
return min(ah - am, (360 - ah) + am)
def angleClockLeetcodeSol(se... | none | 1 | 3.668363 | 4 | |
examples/adh_Savannah/adh.py | jonghyunharrylee/PCGA | 16 | 6622904 | # Savannah
import os
import numpy as np
from shutil import copy2, rmtree
from time import time
from multiprocessing import Pool
import setup_savannah
'''
three operations
1. write inputs
2. run simul
3. read input
'''
class Model:
def __init__(self,params = None):
self.idx = 0
s... | # Savannah
import os
import numpy as np
from shutil import copy2, rmtree
from time import time
from multiprocessing import Pool
import setup_savannah
'''
three operations
1. write inputs
2. run simul
3. read input
'''
class Model:
def __init__(self,params = None):
self.idx = 0
s... | en | 0.508431 | # Savannah three operations
1. write inputs
2. run simul
3. read input # physcial cpu counts ##instantiate the class that describes the forward problem geometry, boundary conditions, initial conditions # inflow discharge and free surface elevation at the boundary # inflow discharge and free surface elevation at the ... | 2.382494 | 2 |
fast_tmp/utils/pydantic/__init__.py | Chise1/fastapi-cli | 5 | 6622905 | from fast_tmp.utils.pydantic.creator import pydantic_model_creator # noqa
from fast_tmp.utils.pydantic.creator import pydantic_queryset_creator # type: ignore
| from fast_tmp.utils.pydantic.creator import pydantic_model_creator # noqa
from fast_tmp.utils.pydantic.creator import pydantic_queryset_creator # type: ignore
| it | 0.280569 | # noqa # type: ignore | 1.121656 | 1 |
webdriver_manager/archive.py | mlouielu/webdriver_manager | 4 | 6622906 | import tarfile
import zipfile
class Archive(object):
def __init__(self, path: str):
self.file_path = path
def unpack(self, directory):
if self.file_path.endswith(".zip"):
return self.__extract_zip(directory)
elif self.file_path.endswith(".tar.gz"):
return self... | import tarfile
import zipfile
class Archive(object):
def __init__(self, path: str):
self.file_path = path
def unpack(self, directory):
if self.file_path.endswith(".zip"):
return self.__extract_zip(directory)
elif self.file_path.endswith(".tar.gz"):
return self... | none | 1 | 3.307179 | 3 | |
retinanet/predict_script.py | pk00095/retinanet | 0 | 6622907 | <gh_stars>0
"""Summary
"""
from tensorflow import keras
from tensorflow.keras.applications.resnet import preprocess_input as resnet_normalize_image
import numpy as np
import cv2
from PIL import Image, ImageDraw, ImageFont
font = ImageFont.load_default()
interpolation_options = {
'nearest':cv2.INTER_NEAREST,
... | """Summary
"""
from tensorflow import keras
from tensorflow.keras.applications.resnet import preprocess_input as resnet_normalize_image
import numpy as np
import cv2
from PIL import Image, ImageDraw, ImageFont
font = ImageFont.load_default()
interpolation_options = {
'nearest':cv2.INTER_NEAREST,
'linear':cv2... | en | 0.546029 | Summary Summary Args: checkpoint_path (string): path to prediction model checkpoint Returns: tf.keras.model.Model: The prediction model Summary Args: image (TYPE): Description height (TYPE): Description width (TYPE): Description scale (TYPE): De... | 2.130264 | 2 |
yt_ddl.py | Wecros/youtube_dash_dl | 0 | 6622908 | from requests import get, Session # requests
import sys #
from bs4 import BeautifulSoup # beautifulsoup4 / lxml
import urllib.parse #
import os #
from mpegdash.parser import MPEGDASHParser # mpegdash
from datetime import datetime, timezone
from tqdm import tqdm # tqdm
import platform
import shutil
import re
... | from requests import get, Session # requests
import sys #
from bs4 import BeautifulSoup # beautifulsoup4 / lxml
import urllib.parse #
import os #
from mpegdash.parser import MPEGDASHParser # mpegdash
from datetime import datetime, timezone
from tqdm import tqdm # tqdm
import platform
import shutil
import re
... | en | 0.850004 | # requests # # beautifulsoup4 / lxml # # # mpegdash # tqdm # make a temporary directory in the output file's directory # get video and audio segments asynchronously # merge video and audio segments each into its file | 2.504028 | 3 |
tree/tests/test_tree_ds.py | kylepclarkson/Tries | 0 | 6622909 | import unittest
from tree.Tree import Tree
class TestTree(unittest.TestCase):
def test_create_tree_0(self):
t = Tree(None)
self.assertEqual(t.root().element(), None)
def test_create_tree_1(self):
# A tree with only a root.
t = Tree()
self.assertEqual(len(t), 1)... | import unittest
from tree.Tree import Tree
class TestTree(unittest.TestCase):
def test_create_tree_0(self):
t = Tree(None)
self.assertEqual(t.root().element(), None)
def test_create_tree_1(self):
# A tree with only a root.
t = Tree()
self.assertEqual(len(t), 1)... | en | 0.913327 | # A tree with only a root. # A tree with root, three children. # Single child node of node a contains value 'aa' as element. | 3.663496 | 4 |
tf-benchmark/tf-keras-config/mlp.py | csruiliu/NSD-Project | 0 | 6622910 | <reponame>csruiliu/NSD-Project<gh_stars>0
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Input
def model_fn(input_shape, num_classes=10):
"""
tensorflow.keras sequential x
"""
x = inputs = Input(shape=input_shape)
x = Dense(512, activation='r... | import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Input
def model_fn(input_shape, num_classes=10):
"""
tensorflow.keras sequential x
"""
x = inputs = Input(shape=input_shape)
x = Dense(512, activation='relu')(x)
x = Dense(128, activation='relu'... | en | 0.556824 | tensorflow.keras sequential x | 3.424814 | 3 |
databases/working_ap/annotate_and_resquiggle_reads.py | mrubio-chavarria/project_2 | 0 | 6622911 | <filename>databases/working_ap/annotate_and_resquiggle_reads.py
#!/home/mario/anaconda3/envs/project2_venv/bin python
"""
DESCRIPTION:
This script tries to gather all the steps needed to
perform once the basecalls have been obtained.
"""
# Libraries
import os
import sys
from tombo import tombo_helper, tombo_stats, r... | <filename>databases/working_ap/annotate_and_resquiggle_reads.py
#!/home/mario/anaconda3/envs/project2_venv/bin python
"""
DESCRIPTION:
This script tries to gather all the steps needed to
perform once the basecalls have been obtained.
"""
# Libraries
import os
import sys
from tombo import tombo_helper, tombo_stats, r... | en | 0.63148 | #!/home/mario/anaconda3/envs/project2_venv/bin python DESCRIPTION: This script tries to gather all the steps needed to perform once the basecalls have been obtained. # Libraries # Functions DESCRIPTION: A function to filter the reads based on their q score. :param read_folders: [str] the route to folder with ... | 2.203601 | 2 |
data_collection.py | gopiraj15/tutorial-repo | 0 | 6622912 | <gh_stars>0
from bs4 import BeautifulSoup
import requests as req
base_url = "http://www.talkinghands.co.in"
open_pg = req.get(base_url+"/sentences").text
soup = BeautifulSoup(open_pg,"lxml")
vid_title_url={}
for i in soup.find("div",{"class":"span8"}).find_all("div",{"class":"views-field views-field-title"}):... | from bs4 import BeautifulSoup
import requests as req
base_url = "http://www.talkinghands.co.in"
open_pg = req.get(base_url+"/sentences").text
soup = BeautifulSoup(open_pg,"lxml")
vid_title_url={}
for i in soup.find("div",{"class":"span8"}).find_all("div",{"class":"views-field views-field-title"}):
vid_pg... | ja | 0.067828 | #yt.streams.filter('mp4').download(filename = 'data/' + i) | 2.996307 | 3 |
bookwyrm/tests/lists_stream/test_signals.py | mouse-reeve/fedireads | 270 | 6622913 | <reponame>mouse-reeve/fedireads
""" testing lists_stream """
from unittest.mock import patch
from django.test import TestCase
from bookwyrm import lists_stream, models
@patch("bookwyrm.models.activitypub_mixin.broadcast_task.apply_async")
class ListsStreamSignals(TestCase):
"""using redis to build activity stream... | """ testing lists_stream """
from unittest.mock import patch
from django.test import TestCase
from bookwyrm import lists_stream, models
@patch("bookwyrm.models.activitypub_mixin.broadcast_task.apply_async")
class ListsStreamSignals(TestCase):
"""using redis to build activity streams"""
def setUp(self):
... | en | 0.887199 | testing lists_stream using redis to build activity streams use a test csv a new lists has entered delete a list create streams for a user don't show lists from blocked users re-add lists on unblock dont' re-add lists on unblock if there's a block the other way | 2.400907 | 2 |
specs/matchers/built_in/have_property_spec.py | danibaena/expects | 189 | 6622914 | # -*- coding: utf-8 -*-
from expects import *
from expects.aliases import *
from expects.testing import failure
class Foo(object):
bar = 0
baz = 1
with describe('have_property'):
with before.each:
self.obj = Foo()
with it('should pass if object has property'):
expect(self.obj).to(h... | # -*- coding: utf-8 -*-
from expects import *
from expects.aliases import *
from expects.testing import failure
class Foo(object):
bar = 0
baz = 1
with describe('have_property'):
with before.each:
self.obj = Foo()
with it('should pass if object has property'):
expect(self.obj).to(h... | en | 0.769321 | # -*- coding: utf-8 -*- | 3.070924 | 3 |
typedjson/__init__.py | cosmin/python-typed-json | 0 | 6622915 | <filename>typedjson/__init__.py<gh_stars>0
from .basemodel import BaseModel
from .jsonencoder import ModelJsonEncoder
__all__ = [BaseModel, ModelJsonEncoder]
| <filename>typedjson/__init__.py<gh_stars>0
from .basemodel import BaseModel
from .jsonencoder import ModelJsonEncoder
__all__ = [BaseModel, ModelJsonEncoder]
| none | 1 | 1.356199 | 1 | |
home_platform/core.py | ml-lab/home-platform | 3 | 6622916 | <filename>home_platform/core.py<gh_stars>1-10
# Copyright (c) 2017, IGLU consortium
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above co... | <filename>home_platform/core.py<gh_stars>1-10
# Copyright (c) 2017, IGLU consortium
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above co... | en | 0.725259 | # Copyright (c) 2017, IGLU consortium # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # - Redistributions of source code must retain the above copyright notice, # this list of conditions and... | 1.615053 | 2 |
aql/util_types/aql_path_types.py | menify/aqualid | 1 | 6622917 | <gh_stars>1-10
#
# Copyright (c) 2011-2015 The developers of Aqualid project
#
# 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 t... | #
# Copyright (c) 2011-2015 The developers of Aqualid project
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, mo... | en | 0.567349 | # # Copyright (c) 2011-2015 The developers of Aqualid project # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, mo... | 2.197557 | 2 |
carson/endpoints.py | cyu/carson | 7 | 6622918 | <gh_stars>1-10
MAP_ATTR_TO_ENDPOINT = {
'STATUS': {
'TYPE': 'GET',
'URI': 'status',
'AUTH': False
},
'AUTHENTICATE': {
'TYPE': 'POST',
'URI': 'oauth/token',
'AUTH': False
},
'REVOKE_AUTH_TOKEN': {
'TYPE': 'POST',
'URI': 'oauth/revoke',
... | MAP_ATTR_TO_ENDPOINT = {
'STATUS': {
'TYPE': 'GET',
'URI': 'status',
'AUTH': False
},
'AUTHENTICATE': {
'TYPE': 'POST',
'URI': 'oauth/token',
'AUTH': False
},
'REVOKE_AUTH_TOKEN': {
'TYPE': 'POST',
'URI': 'oauth/revoke',
'AUTH':... | none | 1 | 1.520306 | 2 | |
tests/cc/test_array.py | lcp/bcc | 0 | 6622919 | #!/usr/bin/env python
# Copyright (c) PLUMgrid, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
from bcc import BPF
from ctypes import c_int, c_ulonglong
import random
import time
from unittest import main, TestCase
class TestArray(TestCase):
def test_simple(self):
b = BPF(text="""BP... | #!/usr/bin/env python
# Copyright (c) PLUMgrid, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
from bcc import BPF
from ctypes import c_int, c_ulonglong
import random
import time
from unittest import main, TestCase
class TestArray(TestCase):
def test_simple(self):
b = BPF(text="""BP... | en | 0.562793 | #!/usr/bin/env python # Copyright (c) PLUMgrid, Inc. # Licensed under the Apache License, Version 2.0 (the "License") BPF_TABLE("array", int, u64, table1, 128); | 2.575787 | 3 |
catalog/bindings/gmd/multi_solid.py | NIVANorge/s-enda-playground | 0 | 6622920 | from dataclasses import dataclass
from bindings.gmd.multi_solid_type import MultiSolidType
__NAMESPACE__ = "http://www.opengis.net/gml"
@dataclass
class MultiSolid(MultiSolidType):
"""A gml:MultiSolid is defined by one or more gml:AbstractSolids.
The members of the geometric aggregate may be specified eithe... | from dataclasses import dataclass
from bindings.gmd.multi_solid_type import MultiSolidType
__NAMESPACE__ = "http://www.opengis.net/gml"
@dataclass
class MultiSolid(MultiSolidType):
"""A gml:MultiSolid is defined by one or more gml:AbstractSolids.
The members of the geometric aggregate may be specified eithe... | en | 0.775486 | A gml:MultiSolid is defined by one or more gml:AbstractSolids. The members of the geometric aggregate may be specified either using the "standard" property (gml:solidMember) or the array property (gml:solidMembers). It is also valid to use both the "standard" and the array properties in the same collec... | 2.64051 | 3 |
landmarkerio/template.py | patricksnape/landmarkerio-server | 0 | 6622921 | <reponame>patricksnape/landmarkerio-server<filename>landmarkerio/template.py
import itertools
from collections import namedtuple
import os.path as p
from pathlib import Path
from flask import safe_join
import abc
import yaml
import os
from landmarkerio import TEMPLATE_DINAME, FileExt
Group = namedtuple('Group', ['la... | import itertools
from collections import namedtuple
import os.path as p
from pathlib import Path
from flask import safe_join
import abc
import yaml
import os
from landmarkerio import TEMPLATE_DINAME, FileExt
Group = namedtuple('Group', ['label', 'n', 'index'])
def parse_connectivity(index_lst, n):
index = []
... | en | 0.825273 | # User is providing a slice # Just a standard pair of numbers # Allow simple ordered groups # Should raise KeyError by design if missing # Couldn't parse connectivity, safe default # split on \n and strip left and right whitespace. Abstract definition of an adapter that can be passed to app_for_adapter in order to ... | 2.617095 | 3 |
tests/_test_requests.py | Zadigo/Zah | 0 | 6622922 | from zah.router import Router
from zah.server import BaseServer
from zah.urls import render, render_page
from werkzeug.test import create_environ
from zah.decorators._http import only_GET
from werkzeug.wrappers import Request
from zah.decorators._cache import cache_control, never_cache
environ = create_environ('/home'... | from zah.router import Router
from zah.server import BaseServer
from zah.urls import render, render_page
from werkzeug.test import create_environ
from zah.decorators._http import only_GET
from werkzeug.wrappers import Request
from zah.decorators._cache import cache_control, never_cache
environ = create_environ('/home'... | en | 0.408306 | # 1. Using render page # server.add_route('/home', render_page('home.html')) # 2. Using decorator # @server.as_route('/contact') # def contact(request, **kwargs): # return render(request, 'home.html') # 3. Using view function # @only_SAFE # def home(request, *args, **kwargs): # return render(request, 'home.html... | 2.113616 | 2 |
exercicios/038.py | daldantas/Curso-Python | 0 | 6622923 | <reponame>daldantas/Curso-Python
n1 = int(input("Digite um nº: "))
n2 = int(input("Digite outro nº: "))
if n1 > n2:
print(n1, "é maior que", n2)
elif n2 > n1:
print(n2, "é maior que", n1)
else:
print(n1, "e", n2, "São iguais") | n1 = int(input("Digite um nº: "))
n2 = int(input("Digite outro nº: "))
if n1 > n2:
print(n1, "é maior que", n2)
elif n2 > n1:
print(n2, "é maior que", n1)
else:
print(n1, "e", n2, "São iguais") | none | 1 | 3.90765 | 4 | |
Ex_Files_Python_Standard_Library_EssT/Exercise Files/Chapter 1/01_05/mathMyExample.py | steveayers124/PythonStandardLibraryEssentialTraining | 1 | 6622924 | <reponame>steveayers124/PythonStandardLibraryEssentialTraining
import math
# https://docs.python.org/3/library/math.html
print("ceiling of")
f1 = 4.0
print(f" math.ceil({f1}) = |{math.ceil(f1)}|")
f1 = 4.1
print(f" math.ceil({f1}) = |{math.ceil(f1)}|")
f1 = 4.5
print(f" math.ceil({f1}) = |{math.ceil(f1)}|")
f1 = 4... | import math
# https://docs.python.org/3/library/math.html
print("ceiling of")
f1 = 4.0
print(f" math.ceil({f1}) = |{math.ceil(f1)}|")
f1 = 4.1
print(f" math.ceil({f1}) = |{math.ceil(f1)}|")
f1 = 4.5
print(f" math.ceil({f1}) = |{math.ceil(f1)}|")
f1 = 4.9
print(f" math.ceil({f1}) = |{math.ceil(f1)}|")
i1 = 3
print... | en | 0.734199 | # https://docs.python.org/3/library/math.html # According to the documentation, platforms supporting signed zeros yield |-1.0|. # even though % may have identical result in many cases, # math.fmod(a, b) is preferred for floats, and # a % b is preferred for integers. # [see https://docs.python.org/3/library/math.html ::... | 3.519577 | 4 |
gait_analysis/gait_analysis/__init__.py | gait-analyzer/.github | 1 | 6622925 | from .subject import Subject
from .algorithms import *
| from .subject import Subject
from .algorithms import *
| none | 1 | 0.973302 | 1 | |
dock_r/main.py | aaronsteers/quickdock | 0 | 6622926 | """dock_r module, helps with dockerization."""
import datetime
import hashlib
import json
import time
import os
import docker
from logless import get_logger, logged, logged_block
import runnow
import uio
MAX_ECS_WAIT = 12 * 60 * 60 # max 12 hours wait
docker_client = docker.from_env()
logging = get... | """dock_r module, helps with dockerization."""
import datetime
import hashlib
import json
import time
import os
import docker
from logless import get_logger, logged, logged_block
import runnow
import uio
MAX_ECS_WAIT = 12 * 60 * 60 # max 12 hours wait
docker_client = docker.from_env()
logging = get... | en | 0.697735 | dock_r module, helps with dockerization. # max 12 hours wait Build an image. 'tag_as' can be a string or list of strings Tag an image. 'tag_as' can be a string or list of strings. # docker_client.images.push(image_name) Builds the dockerfile if needed but pulls it from the remote if possible. Returns list of tuples: [
... | 2.575673 | 3 |
tools/thumbnails.py | WebSVG/next-svg | 0 | 6622927 | <gh_stars>0
import os
import json
from PIL import Image
def load_json(fileName):
return json.load(open(fileName))
root_dir = "../public"
thumb_width = 300
def single_command(root_dir):
file_list = ""
for file in os.listdir(root_dir):
if file.endswith(".svg"):
file_list += " " +file
... | import os
import json
from PIL import Image
def load_json(fileName):
return json.load(open(fileName))
root_dir = "../public"
thumb_width = 300
def single_command(root_dir):
file_list = ""
for file in os.listdir(root_dir):
if file.endswith(".svg"):
file_list += " " +file
command =... | none | 1 | 2.862388 | 3 | |
src/w1therm2influx/core.py | rkschamer/w1therm2influx | 0 | 6622928 | from influxdb import InfluxDBClient
from w1thermsensor import W1ThermSensor
from w1thermsensor.errors import W1ThermSensorError
import logging
# in case this is used as library, prevent logging if the application
# does not define it
logging.getLogger('foo').addHandler(logging.NullHandler())
logger = logging.getLogger... | from influxdb import InfluxDBClient
from w1thermsensor import W1ThermSensor
from w1thermsensor.errors import W1ThermSensorError
import logging
# in case this is used as library, prevent logging if the application
# does not define it
logging.getLogger('foo').addHandler(logging.NullHandler())
logger = logging.getLogger... | en | 0.950401 | # in case this is used as library, prevent logging if the application # does not define it | 2.784947 | 3 |
sesarwslib/sesarwsclient.py | Adam-Brown/SESAR-Web-Services-Lib | 1 | 6622929 | <filename>sesarwslib/sesarwsclient.py
import urllib
import urllib2
import xml.etree.ElementTree as eTree
import StringIO
SAMPLE_REGISTRATION_SERVICE_URL = 'http://app.geosamples.org/webservices/uploadservice.php'
CREDENTIAL_SERVICE_URL = 'http://app.geosamples.org/webservices/credentials_service.php'
IGSN_LIST_SERVICE... | <filename>sesarwslib/sesarwsclient.py
import urllib
import urllib2
import xml.etree.ElementTree as eTree
import StringIO
SAMPLE_REGISTRATION_SERVICE_URL = 'http://app.geosamples.org/webservices/uploadservice.php'
CREDENTIAL_SERVICE_URL = 'http://app.geosamples.org/webservices/credentials_service.php'
IGSN_LIST_SERVICE... | en | 0.534949 | # 1. Sample registration web service # According to the v2 XSD the tag should be sampleType... I can't test it yet because I think SESAR need to update something. # I'm temporarily forcing this to use version 1 for the moment by rewriting these tags. # handler.getcode() # handler.headers.getheader('content-type') # <re... | 2.388019 | 2 |
threes/test_threes_util.py | davitf/puzzle-ai | 0 | 6622930 | import numpy as np
import pytest
from threes import threes_util
# A series of sample lines, with the results of moving them left or right.
SAMPLE_LINES_BOTH_DIRECTIONS = [
# Move spaces.
([0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]),
([1, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0]),
([0, 0, 0, 1], [0, 0, 1, 0]... | import numpy as np
import pytest
from threes import threes_util
# A series of sample lines, with the results of moving them left or right.
SAMPLE_LINES_BOTH_DIRECTIONS = [
# Move spaces.
([0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]),
([1, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0]),
([0, 0, 0, 1], [0, 0, 1, 0]... | en | 0.920206 | # A series of sample lines, with the results of moving them left or right. # Move spaces. # Merge 1s and 2s. # Merge two equal 3+ tiles. # Two 1s or 2s cannot be merged. # Non-contiguous tiles cannot be merged. # move_line only computes the result of moving a line to the left. For a # move to the right, we must invert ... | 2.529571 | 3 |
BlueSubdivision/perlinVoxel.py | DweebsUnited/CodeMonkey | 0 | 6622931 | <reponame>DweebsUnited/CodeMonkey
# On a grid, while a geometric true
from random import uniform
from noise import snoise2
from math import exp, pow
class Sigmoid:
s = 0.001
a = 0
b = 0
def __init__( self, s = 0.001 ):
self.config( s )
def config( self, s ):
self.s = s;
self.a = self.raw( 1 )... | # On a grid, while a geometric true
from random import uniform
from noise import snoise2
from math import exp, pow
class Sigmoid:
s = 0.001
a = 0
b = 0
def __init__( self, s = 0.001 ):
self.config( s )
def config( self, s ):
self.s = s;
self.a = self.raw( 1 );
self.b = self.raw( 0 );
... | en | 0.895781 | # On a grid, while a geometric true # If a neighbor is not filled, write out the face between them | 2.923528 | 3 |
src/ibl_tools/util.py | ekellbuch/ibl_tools | 0 | 6622932 | import numpy as np
def quantile_scaling(x, min_per=5, max_per=95):
"""
Scale data using max and min quantiles
"""
# see quantile_transform sklearn
x_min = np.nanpercentile(x, min_per)
x_max = np.nanpercentile(x, max_per)
xrmp = (x - x_min) / (x_max - x_min)
return xrmp, x_min, x_max
| import numpy as np
def quantile_scaling(x, min_per=5, max_per=95):
"""
Scale data using max and min quantiles
"""
# see quantile_transform sklearn
x_min = np.nanpercentile(x, min_per)
x_max = np.nanpercentile(x, max_per)
xrmp = (x - x_min) / (x_max - x_min)
return xrmp, x_min, x_max
| en | 0.434419 | Scale data using max and min quantiles # see quantile_transform sklearn | 3.382828 | 3 |
Alipay/AlipayNotify.py | Shellbye/django_Alipay | 10 | 6622933 | <reponame>Shellbye/django_Alipay
# -*- coding:utf-8 -*-
__author__ = '<EMAIL>'
import urllib2
from AlipayConfig import Config
from AlipayCore import Core
class Notify():
# HTTPS支付宝通知路径
Https_verify_url = "https://www.alipay.com/cooperate/gateway.do?service=notify_verify&"
# HTTP支付宝通知路径
Http_verify_ur... | # -*- coding:utf-8 -*-
__author__ = '<EMAIL>'
import urllib2
from AlipayConfig import Config
from AlipayCore import Core
class Notify():
# HTTPS支付宝通知路径
Https_verify_url = "https://www.alipay.com/cooperate/gateway.do?service=notify_verify&"
# HTTP支付宝通知路径
Http_verify_url = "http://notify.alipay.com/tra... | zh | 0.603563 | # -*- coding:utf-8 -*- # HTTPS支付宝通知路径 # HTTP支付宝通知路径 # 从配置文件中初始化变量 # <param name="inputPara">通知返回参数数组</param> # <param name="notify_id">通知验证ID</param> # 合作身份者ID # 交易安全校验码 # 签名方式 # 访问模式 # <summary> # 验证消息是否是支付宝发出的合法消息 # </summary> # <param name="inputPara">通知返回参数数组</param> # <returns>验证结果</returns> # 验证基本数据 # 获取返回回来的待签名... | 2.688833 | 3 |
src/comp_crawling/find_recent.py | barahana20/comp_announcement_crawling | 0 | 6622934 | from datetime import datetime
def find_recent(file_name, new_timestamp):
timestamp = file_name[file_name.rfind('_')+1:file_name.index('.md')]
timestamp = datetime.strptime(timestamp, "%Y-%m-%dT%H-%M")
new_timestamp = datetime.strptime(new_timestamp, "%Y-%m-%dT%H-%M")
if timestamp < new_timestamp:
... | from datetime import datetime
def find_recent(file_name, new_timestamp):
timestamp = file_name[file_name.rfind('_')+1:file_name.index('.md')]
timestamp = datetime.strptime(timestamp, "%Y-%m-%dT%H-%M")
new_timestamp = datetime.strptime(new_timestamp, "%Y-%m-%dT%H-%M")
if timestamp < new_timestamp:
... | none | 1 | 2.851377 | 3 | |
ppo_pytorch/__init__.py | SSS135/ppo-pytorch | 2 | 6622935 | from . import common
from . import ppo
from . import models
| from . import common
from . import ppo
from . import models
| none | 1 | 1.058359 | 1 | |
bot/utils/convert.py | AEnterprise/kanelbulle | 4 | 6622936 | from discord.ext import commands
class ApexPlatformConverter(commands.Converter):
async def convert(self, ctx, argument):
ValidPlatforms = {
"XBOX": {"value": "xbl", "name": "Xbox"},
"PS4": {"value": "psn", "name": "PSN"},
"PC": {"value": "origin", "name": "PC"}
... | from discord.ext import commands
class ApexPlatformConverter(commands.Converter):
async def convert(self, ctx, argument):
ValidPlatforms = {
"XBOX": {"value": "xbl", "name": "Xbox"},
"PS4": {"value": "psn", "name": "PSN"},
"PC": {"value": "origin", "name": "PC"}
... | none | 1 | 2.863571 | 3 | |
lib/utils/utils.py | Bazinga699/NCL | 32 | 6622937 | <reponame>Bazinga699/NCL
import logging
import time
import os
import torch
from utils.lr_scheduler import WarmupMultiStepLR
from net import multi_Network, multi_Network_MOCO
def create_logger(cfg, rank=0):
dataset = cfg.DATASET.DATASET
net_type = cfg.BACKBONE.TYPE
module_type = cfg.MODULE.TYPE
log_dir... | import logging
import time
import os
import torch
from utils.lr_scheduler import WarmupMultiStepLR
from net import multi_Network, multi_Network_MOCO
def create_logger(cfg, rank=0):
dataset = cfg.DATASET.DATASET
net_type = cfg.BACKBONE.TYPE
module_type = cfg.MODULE.TYPE
log_dir = os.path.join(cfg.OUTPU... | en | 0.489806 | # set up logger | 2.181174 | 2 |
aussiebb/const.py | yaleman/pyaussiebb | 0 | 6622938 | <reponame>yaleman/pyaussiebb
""" constants and utilities """
from typing import TypedDict
BASEURL = {
"api": "https://myaussie-api.aussiebroadband.com.au",
"login": "https://myaussie-auth.aussiebroadband.com.au/login",
}
DEFAULT_BACKOFF_DELAY = 90
DefaultHeaders = TypedDict(
"DefaultHeaders",
{
... | """ constants and utilities """
from typing import TypedDict
BASEURL = {
"api": "https://myaussie-api.aussiebroadband.com.au",
"login": "https://myaussie-auth.aussiebroadband.com.au/login",
}
DEFAULT_BACKOFF_DELAY = 90
DefaultHeaders = TypedDict(
"DefaultHeaders",
{
"Accept": str,
"... | en | 0.47466 | constants and utilities returns a default set of headers | 2.370382 | 2 |
transparentemail/services/Emails/emailException.py | fossabot/TransparentEmail | 5 | 6622939 | <reponame>fossabot/TransparentEmail<filename>transparentemail/services/Emails/emailException.py
class InvalidEmailException(Exception):
pass
| class InvalidEmailException(Exception):
pass | none | 1 | 1.147237 | 1 | |
setup.py | wesleyks/fine_sm | 2 | 6622940 | <gh_stars>1-10
from setuptools import setup
with open('README.md', 'r') as fh:
long_description = fh.read()
setup(
name='finesm',
version='1.0.0',
description='A fine state machine',
long_description=long_description,
long_description_content_type="text/markdown",
url='https://github.co... | from setuptools import setup
with open('README.md', 'r') as fh:
long_description = fh.read()
setup(
name='finesm',
version='1.0.0',
description='A fine state machine',
long_description=long_description,
long_description_content_type="text/markdown",
url='https://github.com/wesleyks/fine... | none | 1 | 1.319419 | 1 | |
video_detection.py | kihtov23/yolo_image_and_video_detection | 0 | 6622941 | from imageai.Detection import VideoObjectDetection
detector = VideoObjectDetection()
detector.setModelTypeAsYOLOv3()
detector.setModelPath('.\\yolo.h5')
detector.loadModel()
video_path = detector.detectObjectsFromVideo(
input_file_path='.\\input_data\cars.mp4',
output_file_path='.\\output_data\cars_detected',... | from imageai.Detection import VideoObjectDetection
detector = VideoObjectDetection()
detector.setModelTypeAsYOLOv3()
detector.setModelPath('.\\yolo.h5')
detector.loadModel()
video_path = detector.detectObjectsFromVideo(
input_file_path='.\\input_data\cars.mp4',
output_file_path='.\\output_data\cars_detected',... | none | 1 | 2.094755 | 2 | |
tests/model/test_calendar.py | gpresazzi/parrocchie-valmalenco-FM | 1 | 6622942 | import pytest
from parrocchie_valmalenco_fm.model.calendar import Calendar
from parrocchie_valmalenco_fm.model.mass import Mass
class TestCalendar:
def test_validate_ok(self):
calendar = Calendar()
mass1 = Mass("caspoggio", "27/10/2020", "18:00", "19:00")
calendar.mass_list.append(mass1... | import pytest
from parrocchie_valmalenco_fm.model.calendar import Calendar
from parrocchie_valmalenco_fm.model.mass import Mass
class TestCalendar:
def test_validate_ok(self):
calendar = Calendar()
mass1 = Mass("caspoggio", "27/10/2020", "18:00", "19:00")
calendar.mass_list.append(mass1... | none | 1 | 2.308159 | 2 | |
jasmin/protocols/cli/smppccm.py | pyghassen/jasmin | 0 | 6622943 | import pickle
from twisted.internet import defer
from jasmin.protocols.smpp.configs import SMPPClientConfig
from jasmin.protocols.cli.managers import Manager, Session
from jasmin.vendor.smpp.pdu.constants import (addr_npi_name_map, addr_ton_name_map,
replace_if_present_flap_name_m... | import pickle
from twisted.internet import defer
from jasmin.protocols.smpp.configs import SMPPClientConfig
from jasmin.protocols.cli.managers import Manager, Session
from jasmin.vendor.smpp.pdu.constants import (addr_npi_name_map, addr_ton_name_map,
replace_if_present_flap_name_m... | en | 0.798126 | # A config map between console-configuration keys and SMPPClientConfig keys. # When updating a key from RequireRestartKeys, the connector need restart for update to take effect # Empty line # Initiate JCliSMPPClientConfig with sessBuffer content # Hand the instance to fCallback # Unknown key # Cast to boolean # Buffer ... | 1.667145 | 2 |
server/src/api/routers/sessions/landmark.py | Mokumoku-Rin/client | 0 | 6622944 | from fastapi import APIRouter, Depends
from schemas.landmark import (
LandmarkVisitRequest, LandmarkVisitResponse,
LandmarkPostResponse, LandmarkPostRequest, LandmarkResponse)
from services.landmark import LandmarkService
from depends.auth import FirebaseToken
router = APIRouter()
@router.post("/visit/", res... | from fastapi import APIRouter, Depends
from schemas.landmark import (
LandmarkVisitRequest, LandmarkVisitResponse,
LandmarkPostResponse, LandmarkPostRequest, LandmarkResponse)
from services.landmark import LandmarkService
from depends.auth import FirebaseToken
router = APIRouter()
@router.post("/visit/", res... | ja | 0.998155 | # デバッグモードなら常にOKを返す | 2.359972 | 2 |
source/python/MonkeyWantingToBeAHorse.py | JoHyukJun/algorithm-analysis | 0 | 6622945 | '''
main.py
Created by <NAME> on 2021
Copyright © 2021 <NAME>. All rights reserved.
'''
import sys
from collections import deque
def bfs():
queue = deque([(0, 0, 0)])
while queue:
x, y, z = queue.popleft()
if x == h - 1 and y == w - 1:
return visited[x][y][z] - 1... | '''
main.py
Created by <NAME> on 2021
Copyright © 2021 <NAME>. All rights reserved.
'''
import sys
from collections import deque
def bfs():
queue = deque([(0, 0, 0)])
while queue:
x, y, z = queue.popleft()
if x == h - 1 and y == w - 1:
return visited[x][y][z] - 1... | en | 0.839279 | main.py Created by <NAME> on 2021 Copyright © 2021 <NAME>. All rights reserved. # monkey move # horse move | 3.203156 | 3 |
leetcode/1344_angle_between_hands_of_a_clock.py | jacquerie/leetcode | 3 | 6622946 | <gh_stars>1-10
# -*- coding: utf-8 -*-
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
minutes_angle = 6 * minutes
hour_angle = (30 * hour + minutes / 2) % 360
angle = abs(minutes_angle - hour_angle)
return angle if angle <= 180 else 360 - angle
if __name_... | # -*- coding: utf-8 -*-
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
minutes_angle = 6 * minutes
hour_angle = (30 * hour + minutes / 2) % 360
angle = abs(minutes_angle - hour_angle)
return angle if angle <= 180 else 360 - angle
if __name__ == '__main__'... | en | 0.769321 | # -*- coding: utf-8 -*- | 3.888895 | 4 |
objvar.py | git-ning/byte-of-python | 1 | 6622947 | <filename>objvar.py
#!/usr/bin/python
class Robot:
"""Represents a robot, with a name."""
# A calss variable, counting the number of robots
population = 0
def __init__(self, name):
"""Initialize the data."""
self.name = name
print('(Initialize {0})'.format(self.name))
... | <filename>objvar.py
#!/usr/bin/python
class Robot:
"""Represents a robot, with a name."""
# A calss variable, counting the number of robots
population = 0
def __init__(self, name):
"""Initialize the data."""
self.name = name
print('(Initialize {0})'.format(self.name))
... | en | 0.828799 | #!/usr/bin/python Represents a robot, with a name. # A calss variable, counting the number of robots Initialize the data. # When this person is created, the robot adds to population I am daying. Greeting by the robot. Yeah, they can do taht. Prints the current population. | 4.054466 | 4 |
CNN_by_Chong Feng/display_layers.py | shaw-wong/Malmo | 1 | 6622948 | import math
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from PIL import Image
# from tf_cnnvis import *
def weight(shape):
return tf.Variable(tf.truncated_normal(shape, stddev=0.1))
def bias(length):
return tf.Variable(tf.constant(0.1, shape=[length]))
def layer(input, num_i... | import math
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from PIL import Image
# from tf_cnnvis import *
def weight(shape):
return tf.Variable(tf.truncated_normal(shape, stddev=0.1))
def bias(length):
return tf.Variable(tf.constant(0.1, shape=[length]))
def layer(input, num_i... | en | 0.548977 | # from tf_cnnvis import * # image0 = image0.reshape(img_size_flat) # feed_dict = {x: [image0], keep_prob: 0.5} # layers = ["r", "p", "c"] # is_success = deconv_visualization(sess_graph_path=session, # value_feed_dict=feed_dict, # input_tensor=x_image, ... | 2.67925 | 3 |
Vocabulary/GBLxAPI_Json_Parser.py | gblxapi/UnityGBLxAPI | 14 | 6622949 | <filename>Vocabulary/GBLxAPI_Json_Parser.py
# -------------------------------------------------------------------------------------------------
# GBLxAPI_Json_Parser.py
# Project: GBLXAPI
# Created: 2018/07/21
# Copyright 2018 Dig-It! Games, LLC. All rights reserved.
# This code is licensed under the MIT License (See L... | <filename>Vocabulary/GBLxAPI_Json_Parser.py
# -------------------------------------------------------------------------------------------------
# GBLxAPI_Json_Parser.py
# Project: GBLXAPI
# Created: 2018/07/21
# Copyright 2018 Dig-It! Games, LLC. All rights reserved.
# This code is licensed under the MIT License (See L... | en | 0.723382 | # ------------------------------------------------------------------------------------------------- # GBLxAPI_Json_Parser.py # Project: GBLXAPI # Created: 2018/07/21 # Copyright 2018 Dig-It! Games, LLC. All rights reserved. # This code is licensed under the MIT License (See LICENSE.txt for details) # ------------------... | 2.608183 | 3 |
tests/test_models.py | nlessmann/rse-panimg | 5 | 6622950 | <reponame>nlessmann/rse-panimg
import logging
import pytest
from panimg.exceptions import ValidationError
from panimg.image_builders.metaio_utils import load_sitk_image
from panimg.models import EXTRA_METADATA, ExtraMetaData, SimpleITKImage
from tests import RESOURCE_PATH
@pytest.mark.parametrize(
"vr,valid,inv... | import logging
import pytest
from panimg.exceptions import ValidationError
from panimg.image_builders.metaio_utils import load_sitk_image
from panimg.models import EXTRA_METADATA, ExtraMetaData, SimpleITKImage
from tests import RESOURCE_PATH
@pytest.mark.parametrize(
"vr,valid,invalid",
(
(
... | none | 1 | 1.94752 | 2 |