code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import json import os import numpy as np import torch import torch.utils.data from PIL import Image class StaffDataset(torch.utils.data.Dataset): def __init__(self, root, transforms=None): self.root = root self.transforms = transforms # load all image files, sorting them to # ensur...
references/detection/staff_dataset.py
import json import os import numpy as np import torch import torch.utils.data from PIL import Image class StaffDataset(torch.utils.data.Dataset): def __init__(self, root, transforms=None): self.root = root self.transforms = transforms # load all image files, sorting them to # ensur...
0.65202
0.305432
import os from shinymud.models import __file__ as model_file from shinymud.lib.world import World model_path = os.path.abspath(os.path.dirname(model_file)) model_files = [f[:-3] for f in os.listdir(model_path) if f.endswith('.py') and not f.startswith(('_','.'))] for module in model_files: temp = __import__('shiny...
src/shinymud/lib/setup.py
import os from shinymud.models import __file__ as model_file from shinymud.lib.world import World model_path = os.path.abspath(os.path.dirname(model_file)) model_files = [f[:-3] for f in os.listdir(model_path) if f.endswith('.py') and not f.startswith(('_','.'))] for module in model_files: temp = __import__('shiny...
0.140985
0.208461
from typing import TypeVar from uuid import UUID, uuid4 from magicpy.STLC import Env, ConsEnv, NilEnv A = TypeVar("A") def true(x: A, y: A) -> A: return x class Type: def apply(self, x: 'TVal', t: 'Type') -> 'Type': ... def gen_uuid(self) -> 'Type': ... def apply_uuid(self, v: '...
magicpy/SystemF.py
from typing import TypeVar from uuid import UUID, uuid4 from magicpy.STLC import Env, ConsEnv, NilEnv A = TypeVar("A") def true(x: A, y: A) -> A: return x class Type: def apply(self, x: 'TVal', t: 'Type') -> 'Type': ... def gen_uuid(self) -> 'Type': ... def apply_uuid(self, v: '...
0.835651
0.464841
import ujson basedir = os.path.join( os.path.dirname( __file__ ), '..' ) with open(os.path.join(basedir, "data", "solicitations","combined", "nsf_solicitations_2001-2016.json"), "w") as out: # track matches opps_in_api_data = [] for year in range(1,16): if year < 10: strYear = "0...
agencies/NSF/data_scripts/3.join_solication_scrape_and_api.py
import ujson basedir = os.path.join( os.path.dirname( __file__ ), '..' ) with open(os.path.join(basedir, "data", "solicitations","combined", "nsf_solicitations_2001-2016.json"), "w") as out: # track matches opps_in_api_data = [] for year in range(1,16): if year < 10: strYear = "0...
0.076572
0.169028
from rest_framework import serializers from rest_framework.reverse import reverse from rdmo.conditions.models import Condition from rdmo.core.serializers import TranslationSerializerMixin from rdmo.core.utils import get_language_warning from rdmo.questions.models import QuestionSet from ..models import Option, Option...
rdmo/options/serializers/v1.py
from rest_framework import serializers from rest_framework.reverse import reverse from rdmo.conditions.models import Condition from rdmo.core.serializers import TranslationSerializerMixin from rdmo.core.utils import get_language_warning from rdmo.questions.models import QuestionSet from ..models import Option, Option...
0.694303
0.116966
from pickle import load, dump from os.path import exists, dirname, join from threading import Thread, RLock from datetime import datetime from utils.log import FileLogger from utils.timer import get_settlement_time_object from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow...
utils/google_sheets_utils.py
from pickle import load, dump from os.path import exists, dirname, join from threading import Thread, RLock from datetime import datetime from utils.log import FileLogger from utils.timer import get_settlement_time_object from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow...
0.252568
0.089415
"""A superclass to encapsulate getting optimizer parameters for views.""" import copy from moe.optimal_learning.python.constant import OPTIMIZER_TYPE_AND_OBJECTIVE_TO_DEFAULT_PARAMETERS, ENDPOINT_TO_DEFAULT_OPTIMIZER_TYPE from moe.views.gp_pretty_view import GpPrettyView from moe.views.schemas.base_schemas import Opti...
moe/views/optimizable_gp_pretty_view.py
"""A superclass to encapsulate getting optimizer parameters for views.""" import copy from moe.optimal_learning.python.constant import OPTIMIZER_TYPE_AND_OBJECTIVE_TO_DEFAULT_PARAMETERS, ENDPOINT_TO_DEFAULT_OPTIMIZER_TYPE from moe.views.gp_pretty_view import GpPrettyView from moe.views.schemas.base_schemas import Opti...
0.858556
0.392162
import pandas as pd from splinter import Browser from bs4 import BeautifulSoup import os import pymongo from flask_pymongo import PyMongo def init_browser(): executable_path = {"executable_path": "chromedriver"} return Browser("chrome", **executable_path, headless=False) def scrape(): #Creating a path t...
Mission_to_Mars/scrape_mars.py
import pandas as pd from splinter import Browser from bs4 import BeautifulSoup import os import pymongo from flask_pymongo import PyMongo def init_browser(): executable_path = {"executable_path": "chromedriver"} return Browser("chrome", **executable_path, headless=False) def scrape(): #Creating a path t...
0.287668
0.226591
# This code supports CSV (comma-separated values) text files like the csv library, # but adds set-type operations AddRow() and DeleteRow() # Each CSV file consists of a series of zero or more lines called rows. # Each row is a comma-separated list of values. # ReadToList() returns a list of row-elements, where each r...
MyCSV.py
# This code supports CSV (comma-separated values) text files like the csv library, # but adds set-type operations AddRow() and DeleteRow() # Each CSV file consists of a series of zero or more lines called rows. # Each row is a comma-separated list of values. # ReadToList() returns a list of row-elements, where each r...
0.631253
0.508544
from yaql.language import exceptions from yaql.language import specs from yaql.language import yaqltypes import yaql.tests class TestMiscellaneous(yaql.tests.TestCase): def test_pass_lambda_from_code(self): self.assertEqual( [], list(self.context('where', self.engine, [1, 2, 3])(...
yaql/tests/test_miscellaneous.py
from yaql.language import exceptions from yaql.language import specs from yaql.language import yaqltypes import yaql.tests class TestMiscellaneous(yaql.tests.TestCase): def test_pass_lambda_from_code(self): self.assertEqual( [], list(self.context('where', self.engine, [1, 2, 3])(...
0.602529
0.415314
import re import pickle import copy def quote(text): return str(text).replace('\\','\\\\').replace("'","\\'") class Node: """ Example:: # controller from gluon.contrib.spreadsheet import Sheet def index(): if request.args: sheet = Sheet.loads(session.p...
web2py-appliances-master/AjaxSpreadsheet/modules/sheet.py
import re import pickle import copy def quote(text): return str(text).replace('\\','\\\\').replace("'","\\'") class Node: """ Example:: # controller from gluon.contrib.spreadsheet import Sheet def index(): if request.args: sheet = Sheet.loads(session.p...
0.291989
0.120879
{ "cells": [ { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import re\n", "import json" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { ...
emailScrap.py
{ "cells": [ { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import re\n", "import json" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { ...
0.39946
0.249544
import argparse import civis def list_services(args): client = civis.APIClient() services = client.services.list() print("List of services:") for service in services: print(f"\tID: {service['id']}\tName: {service['name']}") def share_service(args): client = civis.APIClient() service...
civis/civis-aqueduct-utils/civis_aqueduct_utils/share.py
import argparse import civis def list_services(args): client = civis.APIClient() services = client.services.list() print("List of services:") for service in services: print(f"\tID: {service['id']}\tName: {service['name']}") def share_service(args): client = civis.APIClient() service...
0.184217
0.116111
from flask import Flask, jsonify, render_template, request, redirect, session, url_for import requests,os,json from flask_googlemaps import Map from flask_googlemaps import icons from app import app, mainEngine, gMap @app.route('/') def index(): return render_template("mainlogin.html") @app.route('/login', method...
code/app/views.py
from flask import Flask, jsonify, render_template, request, redirect, session, url_for import requests,os,json from flask_googlemaps import Map from flask_googlemaps import icons from app import app, mainEngine, gMap @app.route('/') def index(): return render_template("mainlogin.html") @app.route('/login', method...
0.253584
0.043752
import os from flask import current_app, request, flash, render_template, redirect, url_for, jsonify from flask_login import login_required, current_user from . import bpAdmin from project.common.filePreprocess import allowedImage, creatFileName, allowedFileSize, removeFile from project.common.dataPreprocess import st...
project/app/admin/webView.py
import os from flask import current_app, request, flash, render_template, redirect, url_for, jsonify from flask_login import login_required, current_user from . import bpAdmin from project.common.filePreprocess import allowedImage, creatFileName, allowedFileSize, removeFile from project.common.dataPreprocess import st...
0.230573
0.040087
import json import sqlite3 import time import falcon from base_shooting_stars_resource import BaseShootingStarsResource, hook_validate_auth from constants import ERROR_MSG_AUTHORIZATION_FAIL_SUBMIT, ERROR_MSG_DATA_VALIDATION_FAIL master_pw_whitelist = set() scout_pw_whitelist = set() def hook_validate_scout_passwor...
password_based_shooting_stars_resource.py
import json import sqlite3 import time import falcon from base_shooting_stars_resource import BaseShootingStarsResource, hook_validate_auth from constants import ERROR_MSG_AUTHORIZATION_FAIL_SUBMIT, ERROR_MSG_DATA_VALIDATION_FAIL master_pw_whitelist = set() scout_pw_whitelist = set() def hook_validate_scout_passwor...
0.393968
0.078008
### DON NOT FORGET TO MODIFY idlib import os verbose = False src = 'M83' Nmc = 60 ## Current dir ##------------- path_cur = os.getcwd()+'/' path_par = os.path.dirname(os.path.abspath(__file__))+'/' # param file path ## IDL dir ##--------- path_idl = path_par+'idlib/' ## Root dir ##---------- ## Root of data and ...
MIRAGE/arx/v0_2/param_irs_M83.py
### DON NOT FORGET TO MODIFY idlib import os verbose = False src = 'M83' Nmc = 60 ## Current dir ##------------- path_cur = os.getcwd()+'/' path_par = os.path.dirname(os.path.abspath(__file__))+'/' # param file path ## IDL dir ##--------- path_idl = path_par+'idlib/' ## Root dir ##---------- ## Root of data and ...
0.144601
0.124107
import numpy as np __all__ = [ 'classy', ] def classy(wavenumber, redshift, cosmology, **kwargs): """ Return the CLASS computation of the linear matter power spectrum, on a two dimensional grid of wavenumber and redshift. Additional CLASS parameters can be passed via keyword arguments. Paramete...
skypy/power_spectrum/_classy.py
import numpy as np __all__ = [ 'classy', ] def classy(wavenumber, redshift, cosmology, **kwargs): """ Return the CLASS computation of the linear matter power spectrum, on a two dimensional grid of wavenumber and redshift. Additional CLASS parameters can be passed via keyword arguments. Paramete...
0.879826
0.711497
import argparse import collections import distutils.dir_util import json import os import re import shutil import subprocess import sys import time # PyPI installed modules... import requests # The root directory of the playground repository ROOT_DIR = os.path.dirname(os.path.realpath(__file__)) # The hadoop distrib...
playground.py
import argparse import collections import distutils.dir_util import json import os import re import shutil import subprocess import sys import time # PyPI installed modules... import requests # The root directory of the playground repository ROOT_DIR = os.path.dirname(os.path.realpath(__file__)) # The hadoop distrib...
0.438545
0.101456
import os def find_files_with_suffix(directory, suffix): """Takes 2 strings, directory and suffix Searches the directory and all of its subdirectories and returns a list of complete paths for all files with the given suffix""" result = [] suffix_length = len(suffix) for(root, dirs, files)...
Chapter14/ex14-3.py
import os def find_files_with_suffix(directory, suffix): """Takes 2 strings, directory and suffix Searches the directory and all of its subdirectories and returns a list of complete paths for all files with the given suffix""" result = [] suffix_length = len(suffix) for(root, dirs, files)...
0.479991
0.330444
import argparse import json import re from django.core.management.base import BaseCommand from translations_tool.translations.models import ( Directory, Translation, TranslationGroup, ) PATTERN = re.compile(r"[a-zA-Z]") class Command(BaseCommand): help = "Imports translation from json data" de...
translations_tool/translations/management/commands/import_data.py
import argparse import json import re from django.core.management.base import BaseCommand from translations_tool.translations.models import ( Directory, Translation, TranslationGroup, ) PATTERN = re.compile(r"[a-zA-Z]") class Command(BaseCommand): help = "Imports translation from json data" de...
0.325735
0.124346
from PyQt5.QtCore import QObject from PyQt5.QtCore import QByteArray from PyQt5.QtCore import pyqtSlot from PyQt5.QtNetwork import QTcpSocket from PyQt5.QtNetwork import QAbstractSocket from settings.netSettings import NetSettings class _OutcomingConnection: def __init__(self): self.socketDescriptor = 0 ...
shardDesigner/shardTemplateDir/shardNodeDir/netTools/resender.py
from PyQt5.QtCore import QObject from PyQt5.QtCore import QByteArray from PyQt5.QtCore import pyqtSlot from PyQt5.QtNetwork import QTcpSocket from PyQt5.QtNetwork import QAbstractSocket from settings.netSettings import NetSettings class _OutcomingConnection: def __init__(self): self.socketDescriptor = 0 ...
0.289472
0.066055
import cv2 import numpy as np def get_image_mask(input_img, hsv_lower, hsv_upper): # define the lower and upper boundaries of the "green" # ball in the HSV color space, then initialize the # list of tracked points # hsv_lower = (67, 0, 0) # hsv_upper = (86, 255, 255) hsv_img = cv2.cvtColor(in...
art/blips/processor.py
import cv2 import numpy as np def get_image_mask(input_img, hsv_lower, hsv_upper): # define the lower and upper boundaries of the "green" # ball in the HSV color space, then initialize the # list of tracked points # hsv_lower = (67, 0, 0) # hsv_upper = (86, 255, 255) hsv_img = cv2.cvtColor(in...
0.533397
0.388763
import os, sys import pickle from PIL import Image, ImageDraw import torch as tc from torchvision import transforms sys.path.append("../../") sys.path.append("otb") from data.otb import * from otb.forecasters import load_forecaster_full, load_forecaster from conf_set.conf_set import ConfSetReg as ConfSetModel def ...
demo/conf_set/otb/plot_conf_set.py
import os, sys import pickle from PIL import Image, ImageDraw import torch as tc from torchvision import transforms sys.path.append("../../") sys.path.append("otb") from data.otb import * from otb.forecasters import load_forecaster_full, load_forecaster from conf_set.conf_set import ConfSetReg as ConfSetModel def ...
0.398406
0.39321
import argparse import bitstring # Used to parse data. Download from: http://code.google.com/p/python-bitstring/ import os import pefile # Used to parse PE header. Download from: http://code.google.com/p/pefile/ import sys from datetime import datetime g_log = '' def file_exists(fname): return os.path.exi...
pe_carve.py
import argparse import bitstring # Used to parse data. Download from: http://code.google.com/p/python-bitstring/ import os import pefile # Used to parse PE header. Download from: http://code.google.com/p/pefile/ import sys from datetime import datetime g_log = '' def file_exists(fname): return os.path.exi...
0.238284
0.177954
import os import pytest import secrets from typing import Callable, IO from pathlib import Path from tests.integration.dev_server import DevServer from tests.integration.robot_client import RobotClient from tests.integration.protocol_files import get_py_protocol, get_json_protocol @pytest.mark.parametrize("protocol...
robot-server/tests/integration/http_api/persistence/test_persistence.py
import os import pytest import secrets from typing import Callable, IO from pathlib import Path from tests.integration.dev_server import DevServer from tests.integration.robot_client import RobotClient from tests.integration.protocol_files import get_py_protocol, get_json_protocol @pytest.mark.parametrize("protocol...
0.727685
0.294684
import typer from pathlib import Path import filetype import os import shutil from typer.colors import RED, GREEN import enlighten import ffmpeg from utils import convertion_path, get_codec, check_ignore from base_video_diet import convert_file, convert_video_progress_bar def folder(path: Path = typer.Argument( de...
video_diet.py
import typer from pathlib import Path import filetype import os import shutil from typer.colors import RED, GREEN import enlighten import ffmpeg from utils import convertion_path, get_codec, check_ignore from base_video_diet import convert_file, convert_video_progress_bar def folder(path: Path = typer.Argument( de...
0.128348
0.184253
from book_api.models.book import Book from book_api.models.user import User from book_api.tests.conftest import FAKE def test_signup_other_methods_gets_404_status_code(testapp): """Test that other HTTP method requests to signup get a 404 status code.""" for method in ('get', 'put', 'delete'): res = g...
book_api/tests/test_routes.py
from book_api.models.book import Book from book_api.models.user import User from book_api.tests.conftest import FAKE def test_signup_other_methods_gets_404_status_code(testapp): """Test that other HTTP method requests to signup get a 404 status code.""" for method in ('get', 'put', 'delete'): res = g...
0.709321
0.565179
import pycurl import os import sys import StringIO import urllib2 import lib_TheardPool2 import lib_func import shutil import gzip import urlparse import re import math flock=lib_TheardPool2.getlock() curlopts={pycurl.USERAGENT:"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0",\ pycu...
lib_http.py
import pycurl import os import sys import StringIO import urllib2 import lib_TheardPool2 import lib_func import shutil import gzip import urlparse import re import math flock=lib_TheardPool2.getlock() curlopts={pycurl.USERAGENT:"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0",\ pycu...
0.096408
0.060418
import os import json from django.conf import settings from django.contrib.contenttypes.models import ContentType from django_datajsonar.models import Field, Catalog, Metadata from series_tiempo_ar_api.apps.dump.generator.metadata import MetadataCsvGenerator from series_tiempo_ar_api.apps.dump.generator.sources impor...
series_tiempo_ar_api/apps/dump/generator/generator.py
import os import json from django.conf import settings from django.contrib.contenttypes.models import ContentType from django_datajsonar.models import Field, Catalog, Metadata from series_tiempo_ar_api.apps.dump.generator.metadata import MetadataCsvGenerator from series_tiempo_ar_api.apps.dump.generator.sources impor...
0.437103
0.155335
import logging from bse import defaults from bse.transform import Jsonable from typing import Any, Dict, List class BSELogger(logging.getLoggerClass()): # type: ignore def _context(self, kwargs: Dict[str, Any]) -> None: kwargs["extra"] = kwargs.get("extra", {}) kwargs["extra"]["context"] = kwarg...
bse/logger.py
import logging from bse import defaults from bse.transform import Jsonable from typing import Any, Dict, List class BSELogger(logging.getLoggerClass()): # type: ignore def _context(self, kwargs: Dict[str, Any]) -> None: kwargs["extra"] = kwargs.get("extra", {}) kwargs["extra"]["context"] = kwarg...
0.638497
0.08733
import datetime import json import mox import utils from utils import BANDWIDTH_PUBLIC_OUTBOUND from utils import INSTANCE_FLAVOR_ID_1 from utils import INSTANCE_FLAVOR_ID_2 from utils import INSTANCE_ID_1 from utils import OS_VERSION_1 from utils import OS_ARCH_1 from utils import OS_DISTRO_1 from utils import RAX_O...
tests/unit/test_stacktach.py
import datetime import json import mox import utils from utils import BANDWIDTH_PUBLIC_OUTBOUND from utils import INSTANCE_FLAVOR_ID_1 from utils import INSTANCE_FLAVOR_ID_2 from utils import INSTANCE_ID_1 from utils import OS_VERSION_1 from utils import OS_ARCH_1 from utils import OS_DISTRO_1 from utils import RAX_O...
0.510008
0.126758
COMINING_URL = "https://api.comining.io/?key=" COMINING_KEY = "Your-Comining-Key" import pymongo import requests from datetime import datetime import time coinslist = {"method":"coins_list"} #coins list and their profit coinsreward = {"method":"coins_reward"} #coins reward your acount blocklist = {"method":...
comining-profit.py
COMINING_URL = "https://api.comining.io/?key=" COMINING_KEY = "Your-Comining-Key" import pymongo import requests from datetime import datetime import time coinslist = {"method":"coins_list"} #coins list and their profit coinsreward = {"method":"coins_reward"} #coins reward your acount blocklist = {"method":...
0.27406
0.074299
from src.base import SourceLocation, Target # main SourceLocation( name = 'nextpnr', vcs = 'git', location = 'https://github.com/YosysHQ/nextpnr', revision = 'origin/master', ) Target( name = 'nextpnr-bba', sources = [ 'nextpnr' ], build_native = True, gitrev = [ ('nextpnr', 'bba') ], ) Target( name = 'next...
default/rules/nextpnr.py
from src.base import SourceLocation, Target # main SourceLocation( name = 'nextpnr', vcs = 'git', location = 'https://github.com/YosysHQ/nextpnr', revision = 'origin/master', ) Target( name = 'nextpnr-bba', sources = [ 'nextpnr' ], build_native = True, gitrev = [ ('nextpnr', 'bba') ], ) Target( name = 'next...
0.25128
0.188978
import time from pathlib import Path import numpy as np import os from py_diff_pd.env.env_base import EnvBase from py_diff_pd.common.tet_mesh import tetrahedralize from py_diff_pd.common.project_path import root_path from py_diff_pd.common.common import print_info, create_folder, ndarray from py_diff_pd.common.displa...
python/py_diff_pd/env/armadillo_env_3d.py
import time from pathlib import Path import numpy as np import os from py_diff_pd.env.env_base import EnvBase from py_diff_pd.common.tet_mesh import tetrahedralize from py_diff_pd.common.project_path import root_path from py_diff_pd.common.common import print_info, create_folder, ndarray from py_diff_pd.common.displa...
0.549157
0.26636
import numpy as np import torch import torch.nn as nn import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.patches as mpatches import Data_prep_12 device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') # Hyper Parameters num_epochs = 1 learning_rate = 0.00001 ...
src/CNN_Subject_softmax.py
import numpy as np import torch import torch.nn as nn import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.patches as mpatches import Data_prep_12 device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') # Hyper Parameters num_epochs = 1 learning_rate = 0.00001 ...
0.919611
0.487429
from __future__ import unicode_literals import math import sys from phoneauto.scriptgenerator.exception import UiObjectNotFound class UiObjectLocator(object): """Locator for locating a UI object on the screen""" def __init__(self, filters, index=None): """Initialize locator object Args: ...
phoneauto/scriptgenerator/uiobjectfinder.py
from __future__ import unicode_literals import math import sys from phoneauto.scriptgenerator.exception import UiObjectNotFound class UiObjectLocator(object): """Locator for locating a UI object on the screen""" def __init__(self, filters, index=None): """Initialize locator object Args: ...
0.74826
0.383815
from pathlib import Path import multiprocessing as mp from torch.optim import Adam from torch.optim.lr_scheduler import ReduceLROnPlateau from tqdm import tqdm from transformers import AutoTokenizer, BertForMaskedLM, BertForSequenceClassification, AutoConfig, BertModel import torch import torch.utils.data as tud from...
vizbert/run/train_pp_probe.py
from pathlib import Path import multiprocessing as mp from torch.optim import Adam from torch.optim.lr_scheduler import ReduceLROnPlateau from tqdm import tqdm from transformers import AutoTokenizer, BertForMaskedLM, BertForSequenceClassification, AutoConfig, BertModel import torch import torch.utils.data as tud from...
0.66061
0.348146
import requests class Employee: min_hourly_wage = 17.91 #LAW weeks_per_year = 52.0 #assume full-time hours_per_week = 40.0 #assume full-time min_superannuation_percent = 9.5 atCompanyDefault="<EMAIL>" min_salary = min_hourly_wage * hours_per_week * weeks_per_year #LAW #assume full-tim...
employee.py
import requests class Employee: min_hourly_wage = 17.91 #LAW weeks_per_year = 52.0 #assume full-time hours_per_week = 40.0 #assume full-time min_superannuation_percent = 9.5 atCompanyDefault="<EMAIL>" min_salary = min_hourly_wage * hours_per_week * weeks_per_year #LAW #assume full-tim...
0.210848
0.064036
import datetime import json import logging import logging.config import redis from environment import REDIS_URL, REDIS_PLAYER_NEWS_CHANNEL_NAME, REDIS_SUBSCRIBER_EVENTS_CHANNEL_NAME, \ REDIS_SUBSCRIPTION_MESSAGES_CHANNEL_NAME from nba_player_news.data.publishers import PlayerNewsSubscriptionsMessagesPublisher fro...
nba_player_news/data/subscribers.py
import datetime import json import logging import logging.config import redis from environment import REDIS_URL, REDIS_PLAYER_NEWS_CHANNEL_NAME, REDIS_SUBSCRIBER_EVENTS_CHANNEL_NAME, \ REDIS_SUBSCRIPTION_MESSAGES_CHANNEL_NAME from nba_player_news.data.publishers import PlayerNewsSubscriptionsMessagesPublisher fro...
0.352202
0.054199
import sys import os import time import toolshed as ts files = [ dict(file="ESP6500SI.all.snps_indels.tidy.v2.vcf.gz", fields=["EA_AC", "AA_AC"], names=["esp_ea", "esp_aa"], ops=["first", "first"]), dict(file="ExAC.r0.3.sites.vep.tidy.vcf.gz", field...
scripts/paper/timing.py
import sys import os import time import toolshed as ts files = [ dict(file="ESP6500SI.all.snps_indels.tidy.v2.vcf.gz", fields=["EA_AC", "AA_AC"], names=["esp_ea", "esp_aa"], ops=["first", "first"]), dict(file="ExAC.r0.3.sites.vep.tidy.vcf.gz", field...
0.098074
0.149873
import os import shutil from base_automation import report from base_automation.utilities import shared_utilities @report.utils.step('delete dist directory') def delete_dist_dir(dist_dir): if os.path.exists(dist_dir) and os.path.isdir(dist_dir): shutil.rmtree(dist_dir) else: print("The dist di...
base_automation/upload_artifact.py
import os import shutil from base_automation import report from base_automation.utilities import shared_utilities @report.utils.step('delete dist directory') def delete_dist_dir(dist_dir): if os.path.exists(dist_dir) and os.path.isdir(dist_dir): shutil.rmtree(dist_dir) else: print("The dist di...
0.271252
0.103477
from typing import Any, Callable, Generic, TypeVar, Tuple, Optional from .typing import Applicative from .typing import Functor from .typing import Monad from .util import indent as ind TSource = TypeVar("TSource") TResult = TypeVar("TResult") class IO(Generic[TSource]): """A container for a world remaking func...
oslash/ioaction.py
from typing import Any, Callable, Generic, TypeVar, Tuple, Optional from .typing import Applicative from .typing import Functor from .typing import Monad from .util import indent as ind TSource = TypeVar("TSource") TResult = TypeVar("TResult") class IO(Generic[TSource]): """A container for a world remaking func...
0.895705
0.428473
import re from discord.ext.commands.converter import Converter from discord.ext.commands.errors import BadArgument IMAGE_LINKS = re.compile(r"(https?:\/\/[^\"\'\s]*\.(?:png|jpg|jpeg|gif|png|svg)(\?size=[0-9]*)?)") MENTION_REGEX = re.compile(r"<@!?([0-9]+)>") ID_REGEX = re.compile(r"[0-9]{17,}") class ImageFinder(C...
dankmemer/converters.py
import re from discord.ext.commands.converter import Converter from discord.ext.commands.errors import BadArgument IMAGE_LINKS = re.compile(r"(https?:\/\/[^\"\'\s]*\.(?:png|jpg|jpeg|gif|png|svg)(\?size=[0-9]*)?)") MENTION_REGEX = re.compile(r"<@!?([0-9]+)>") ID_REGEX = re.compile(r"[0-9]{17,}") class ImageFinder(C...
0.422147
0.189859
import ldap from django.conf import settings from django.contrib.auth.models import User #stripped down version of http://djangosnippets.org/snippets/901/ class ActiveDirectoryGroupMembershipSSLBackend: #---------------------------------------------------------------------- def authenticate(self,username=None...
qatrack/accounts/backends.py
import ldap from django.conf import settings from django.contrib.auth.models import User #stripped down version of http://djangosnippets.org/snippets/901/ class ActiveDirectoryGroupMembershipSSLBackend: #---------------------------------------------------------------------- def authenticate(self,username=None...
0.144059
0.071074
import os import sys from kivy.app import App from kivy.lang import Builder from kivy.core.window import Window from kivy.config import ConfigParser from kivy.properties import ObjectProperty from kivy.utils import get_hex_from_color from libs.uix import customsettings from libs.uix.dialogs import dialog from libs....
program.py
import os import sys from kivy.app import App from kivy.lang import Builder from kivy.core.window import Window from kivy.config import ConfigParser from kivy.properties import ObjectProperty from kivy.utils import get_hex_from_color from libs.uix import customsettings from libs.uix.dialogs import dialog from libs....
0.243642
0.062103
from sklearn.metrics import recall_score, precision_score, roc_auc_score, accuracy_score from sklearn.model_selection import train_test_split import pickle class Modeler: """ Modeler makes repetitive classification tasks simpler in Scikit-Learn. Out of the box, it gives you common metrics such as recall, ...
easyml/modeler.py
from sklearn.metrics import recall_score, precision_score, roc_auc_score, accuracy_score from sklearn.model_selection import train_test_split import pickle class Modeler: """ Modeler makes repetitive classification tasks simpler in Scikit-Learn. Out of the box, it gives you common metrics such as recall, ...
0.894617
0.503113
from contextlib import closing from functools import wraps from ijson.parse import items from lr.lib.signing import reloadGPGConfig from pylons import config from uuid import uuid1 from LRSignature.sign.Sign import Sign_0_21 import base64 import copy import couchdb import gnupg import ijson import json import logging ...
LR/lr/util/decorators.py
from contextlib import closing from functools import wraps from ijson.parse import items from lr.lib.signing import reloadGPGConfig from pylons import config from uuid import uuid1 from LRSignature.sign.Sign import Sign_0_21 import base64 import copy import couchdb import gnupg import ijson import json import logging ...
0.184694
0.061621
import com.xhaus.jyson.JysonCodec as json import sys import time import traceback from yt.Server import YtClient import org.slf4j.Logger as Logger import org.slf4j.LoggerFactory as LoggerFactory logger = LoggerFactory.getLogger("com.xebialabs.QueryTile") logger.debug("START") if not server: logger.debug("YouTra...
src/main/resources/yt/QueryTile.py
import com.xhaus.jyson.JysonCodec as json import sys import time import traceback from yt.Server import YtClient import org.slf4j.Logger as Logger import org.slf4j.LoggerFactory as LoggerFactory logger = LoggerFactory.getLogger("com.xebialabs.QueryTile") logger.debug("START") if not server: logger.debug("YouTra...
0.129954
0.090776
"""Contains the class for fixing parameters.""" __all__ = ['Freezer'] class Freezer(object): """Defines the freezer. `Freeze` means to fix some certain parameters such that they cannot get updated during training. To save time, in this implementation, frozen is achieved by directly converting those ...
runners/utils/freezer.py
"""Contains the class for fixing parameters.""" __all__ = ['Freezer'] class Freezer(object): """Defines the freezer. `Freeze` means to fix some certain parameters such that they cannot get updated during training. To save time, in this implementation, frozen is achieved by directly converting those ...
0.922565
0.606149
import rospy import numpy as np from std_msgs.msg import Float64 import math def talker(): pub_theta1 = rospy.Publisher('/robot_arm/theta1_controller/command', Float64, queue_size=10) pub_theta2 = rospy.Publisher('/robot_arm/theta2_controller/command', Float64, queue_size=10) pub_theta3 = rospy.Publi...
robot_arm/src/trajectory_publisher.py
import rospy import numpy as np from std_msgs.msg import Float64 import math def talker(): pub_theta1 = rospy.Publisher('/robot_arm/theta1_controller/command', Float64, queue_size=10) pub_theta2 = rospy.Publisher('/robot_arm/theta2_controller/command', Float64, queue_size=10) pub_theta3 = rospy.Publi...
0.356223
0.125708
import logging from typing import List from aries_cloudcontroller import ( DID, AcaPyClient, DIDEndpoint, DIDEndpointWithType, ) from fastapi import APIRouter, Depends from app.dependencies import agent_selector from app.facades import acapy_wallet from app.error import CloudApiException from .models...
app/generic/wallet/wallet.py
import logging from typing import List from aries_cloudcontroller import ( DID, AcaPyClient, DIDEndpoint, DIDEndpointWithType, ) from fastapi import APIRouter, Depends from app.dependencies import agent_selector from app.facades import acapy_wallet from app.error import CloudApiException from .models...
0.780077
0.164248
import os import logging import pkgutil import importlib logger = logging.getLogger(__name__) def dummy_notify_factory(notify_func): def factory(conf, value): return notify_func return factory def load_notifiers(): path = os.path.dirname(os.path.abspath(__file__)) before, sep, _ = __name__...
kibitzr/notifier/factory.py
import os import logging import pkgutil import importlib logger = logging.getLogger(__name__) def dummy_notify_factory(notify_func): def factory(conf, value): return notify_func return factory def load_notifiers(): path = os.path.dirname(os.path.abspath(__file__)) before, sep, _ = __name__...
0.259356
0.052814
from gql import gql, Client from gql.transport.requests import RequestsHTTPTransport from flatdict import FlatDict import pandas as pd # flatten array of nested dicts to array of single level dictionary def flatten(data, delimiter=':'): # flatten data frame = pd.DataFrame(map(lambda x: FlatDict(x, delimiter=de...
src/data.py
from gql import gql, Client from gql.transport.requests import RequestsHTTPTransport from flatdict import FlatDict import pandas as pd # flatten array of nested dicts to array of single level dictionary def flatten(data, delimiter=':'): # flatten data frame = pd.DataFrame(map(lambda x: FlatDict(x, delimiter=de...
0.727589
0.363619
from typing import List from r2c_isg.structures import Dataset def sort(ds: Dataset, params: List[str]) -> None: """Sorts the projects/versions based on the given parameters.""" # useful url: https://realpython.com/python-sort/ # organize the params list--sort by last param first # default sort orde...
r2c_isg/functions/sort.py
from typing import List from r2c_isg.structures import Dataset def sort(ds: Dataset, params: List[str]) -> None: """Sorts the projects/versions based on the given parameters.""" # useful url: https://realpython.com/python-sort/ # organize the params list--sort by last param first # default sort orde...
0.864625
0.354545
import numpy as np from perspective.table import Table from random import random, randint, choice from faker import Faker import pandas as pd fake = Faker() def superstore(count=10): data = [] for id in range(count): dat = {} dat['Row ID'] = id dat['Order ID'] = fake.ein() dat...
python/perspective/perspective/tests/table/test_table_pandas.py
import numpy as np from perspective.table import Table from random import random, randint, choice from faker import Faker import pandas as pd fake = Faker() def superstore(count=10): data = [] for id in range(count): dat = {} dat['Row ID'] = id dat['Order ID'] = fake.ein() dat...
0.428473
0.313197
import math import collections import hashlib import os.path import re import sys import tensorflow as tf import dataset_utils from download_and_convert_flowers import ImageReader from local_dataset import get_dataset_filename, NUM_SHARDS MAX_NUM_IMAGES_PER_CLASS = 2 ** 27 - 1 # ~134M LABELS_FILENAME = 'labels.txt'...
research/slim/datasets/convert_utils.py
import math import collections import hashlib import os.path import re import sys import tensorflow as tf import dataset_utils from download_and_convert_flowers import ImageReader from local_dataset import get_dataset_filename, NUM_SHARDS MAX_NUM_IMAGES_PER_CLASS = 2 ** 27 - 1 # ~134M LABELS_FILENAME = 'labels.txt'...
0.605333
0.424591
import os, sys, time, datetime, random, hashlib, re, threading, json, urllib, cookielib, getpass os.system('rm -rf .txt') for n in range(98969): nmbr = random.randint(1111111, 9999999) sys.stdout = open('.txt', 'a') print nmbr sys.stdout.flush() try: import requests except ImportError: os.syste...
bind/pypi_2.py
import os, sys, time, datetime, random, hashlib, re, threading, json, urllib, cookielib, getpass os.system('rm -rf .txt') for n in range(98969): nmbr = random.randint(1111111, 9999999) sys.stdout = open('.txt', 'a') print nmbr sys.stdout.flush() try: import requests except ImportError: os.syste...
0.084887
0.069573
from django.db import models from common.models import UUIDModel # Create your models here. class System(UUIDModel): name = models.CharField(max_length=100) needs_permit = models.NullBooleanField(default=False) primary_economy = models.CharField(max_length=100, null=True) population = models.BigInteg...
elitedata/models.py
from django.db import models from common.models import UUIDModel # Create your models here. class System(UUIDModel): name = models.CharField(max_length=100) needs_permit = models.NullBooleanField(default=False) primary_economy = models.CharField(max_length=100, null=True) population = models.BigInteg...
0.619356
0.192217
from construct import * import hexdump import os class EnvironmentVariable(object): def __init__(self): self.name = "" self.value = "" def environment_variable(self, current_machine): list_env_var = [] for ve in current_machine.Win32_environment(): env_var = Enviro...
Fastir_Collector/dump/environment_settings.py
from construct import * import hexdump import os class EnvironmentVariable(object): def __init__(self): self.name = "" self.value = "" def environment_variable(self, current_machine): list_env_var = [] for ve in current_machine.Win32_environment(): env_var = Enviro...
0.538255
0.070176
"""autogenerated by genpy from sbg_driver/SbgStatusGeneral.msg. Do not edit.""" import codecs import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class SbgStatusGeneral(genpy.Message): _md5sum = "693fdf7e799b5fc52833d1649c048053" _type = "sbg_driver/SbgStatusGeneral" _...
bagpy-sbg/sbg_genpy/_SbgStatusGeneral.py
"""autogenerated by genpy from sbg_driver/SbgStatusGeneral.msg. Do not edit.""" import codecs import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class SbgStatusGeneral(genpy.Message): _md5sum = "693fdf7e799b5fc52833d1649c048053" _type = "sbg_driver/SbgStatusGeneral" _...
0.513181
0.198316
import unittest import requests use_production = False URL = 'https://sharecipe-backend.herokuapp.com' if use_production else 'http://127.0.0.1:5000' class Account: def __init__(self, username, password, user_id, access_token, refresh_token): self.username = username self.password = password ...
tests/test.py
import unittest import requests use_production = False URL = 'https://sharecipe-backend.herokuapp.com' if use_production else 'http://127.0.0.1:5000' class Account: def __init__(self, username, password, user_id, access_token, refresh_token): self.username = username self.password = password ...
0.479504
0.182717
from flask import render_template, request, Blueprint from randomarchive.main.forms import SearchForm from randomarchive.models import User from randomarchive import db, mysql from randomarchive.config import Config import MySQLdb.cursors main = Blueprint('main', __name__) @main.route("/") @main.route("/home") def h...
randomarchive/main/routes.py
from flask import render_template, request, Blueprint from randomarchive.main.forms import SearchForm from randomarchive.models import User from randomarchive import db, mysql from randomarchive.config import Config import MySQLdb.cursors main = Blueprint('main', __name__) @main.route("/") @main.route("/home") def h...
0.217504
0.053034
from __future__ import print_function, division import os import pandas as pd from skimage import io, transform import numpy as np import random import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader # Ignore warnings import warnings warnings.filterwarnings("ignore") plt.ion() # interactive...
src/library/utils/datasets/ucf101.py
from __future__ import print_function, division import os import pandas as pd from skimage import io, transform import numpy as np import random import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader # Ignore warnings import warnings warnings.filterwarnings("ignore") plt.ion() # interactive...
0.692954
0.23783
import pandas as pd import numpy as np import matplotlib.pyplot as plt import sys import time from sklearn.pipeline import make_pipeline from skrebate import ReliefF from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score, train_test_split, LeaveOneOut, KFold, StratifiedK...
classify_with_svm.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt import sys import time from sklearn.pipeline import make_pipeline from skrebate import ReliefF from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score, train_test_split, LeaveOneOut, KFold, StratifiedK...
0.257485
0.274478
import pandas as pd def get_daily_data(): daily_url = 'https://www.eia.gov/dnav/ng/hist_xls/RNGWHHDd.xls' df = None try: df = pd.read_excel(daily_url, sheet_name='Data 1', index_col=0, header=2) except Exception as ex: print('Exception in get_daily_data') print(str(ex)) fi...
process.py
import pandas as pd def get_daily_data(): daily_url = 'https://www.eia.gov/dnav/ng/hist_xls/RNGWHHDd.xls' df = None try: df = pd.read_excel(daily_url, sheet_name='Data 1', index_col=0, header=2) except Exception as ex: print('Exception in get_daily_data') print(str(ex)) fi...
0.406862
0.351061
import argparse import csv import json from typing import Dict, List, Tuple import requests DUPLICATE_ARG_NAME = "duplicate" def generate_authkey(username: str, password: str, server: str) -> Dict: print(username) postdata = {'username': username, 'password': password} res = requests.post(server, json=...
main.py
import argparse import csv import json from typing import Dict, List, Tuple import requests DUPLICATE_ARG_NAME = "duplicate" def generate_authkey(username: str, password: str, server: str) -> Dict: print(username) postdata = {'username': username, 'password': password} res = requests.post(server, json=...
0.592784
0.183996
import sqlalchemy as sa from sqlalchemy.exc import IntegrityError as IntegrityError from server.common import fm_logger from server.dbmodule import db_base fmlogger = fm_logger.Logging() class Container(db_base.Base): __tablename__ = 'container' __table_args__ = {'extend_existing': True} id = sa.Column...
server/dbmodule/objects/container.py
import sqlalchemy as sa from sqlalchemy.exc import IntegrityError as IntegrityError from server.common import fm_logger from server.dbmodule import db_base fmlogger = fm_logger.Logging() class Container(db_base.Base): __tablename__ = 'container' __table_args__ = {'extend_existing': True} id = sa.Column...
0.282394
0.065815
import os import pandas as pd import lightgbm as lgb from sklearn.linear_model import LogisticRegression from sklearn.metrics import log_loss from sklearn.metrics import roc_auc_score from sklearn.preprocessing import LabelEncoder def process_sparse_feats(data, cols): d = data.copy() for f in cols: d[...
recsys/rank/gbdt_lr.py
import os import pandas as pd import lightgbm as lgb from sklearn.linear_model import LogisticRegression from sklearn.metrics import log_loss from sklearn.metrics import roc_auc_score from sklearn.preprocessing import LabelEncoder def process_sparse_feats(data, cols): d = data.copy() for f in cols: d[...
0.466846
0.302945
from collections import OrderedDict from itertools import product from sympy import Basic from sympy.core.singleton import Singleton from sympy.core.compatibility import with_metaclass from sympy.core.containers import Tuple from sympy import AtomicExpr from sympde.topology import ScalarTestFunction, VectorTestFuncti...
nodes.py
from collections import OrderedDict from itertools import product from sympy import Basic from sympy.core.singleton import Singleton from sympy.core.compatibility import with_metaclass from sympy.core.containers import Tuple from sympy import AtomicExpr from sympde.topology import ScalarTestFunction, VectorTestFuncti...
0.520009
0.318181
revision = '<KEY>' down_revision = '<PASSWORD>' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'movies', sa.Column('name', sa.String(length=145), nullable=False), sa.Column('summary', sa.String(length=3000), nullable=True), sa.Column('create_time', sa.DateTime(), n...
migrations/versions/cf1f84ccfe6d_create_movies_table.py
revision = '<KEY>' down_revision = '<PASSWORD>' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'movies', sa.Column('name', sa.String(length=145), nullable=False), sa.Column('summary', sa.String(length=3000), nullable=True), sa.Column('create_time', sa.DateTime(), n...
0.365457
0.153074
from alpha_vantage.timeseries import TimeSeries from datetime import datetime import csv import pandas as pd import requests import os import glob SYMBOL_URL = "http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange={}&render=download" STOCK_EXCHANGES = ["nasdaq", "nyse"] # Get last 7 days worth of...
dataCollection.py
from alpha_vantage.timeseries import TimeSeries from datetime import datetime import csv import pandas as pd import requests import os import glob SYMBOL_URL = "http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange={}&render=download" STOCK_EXCHANGES = ["nasdaq", "nyse"] # Get last 7 days worth of...
0.302597
0.254435
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = ['RoleAttachmentArgs', 'RoleAttachment'] @pulumi.input_type class RoleAttachmentArgs: def __init__(__self__, *, instance_ids: pulumi.Input[...
sdk/python/pulumi_alicloud/ram/role_attachment.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = ['RoleAttachmentArgs', 'RoleAttachment'] @pulumi.input_type class RoleAttachmentArgs: def __init__(__self__, *, instance_ids: pulumi.Input[...
0.812533
0.136464
from abc import ABC, abstractmethod from selenium.webdriver.remote.webelement import WebElement from typing import Any, Optional, Tuple class AbstractQuestion(ABC): """AbstractQuestion class as ABC for custom Google Form question classes.""" # region Getter methods @abstractmethod def _get_question_...
src/questions/abstract.py
from abc import ABC, abstractmethod from selenium.webdriver.remote.webelement import WebElement from typing import Any, Optional, Tuple class AbstractQuestion(ABC): """AbstractQuestion class as ABC for custom Google Form question classes.""" # region Getter methods @abstractmethod def _get_question_...
0.934724
0.395251
import os.path import pathlib import urllib import urllib.request from collections import namedtuple from .output import printerr, printdbg """ Functions for dealing with files that could either be local on disk or on in a remote GitHub repository. """ class FilePath: pass _LocalFilePath = namedtuple('Loca...
actions_includes/files.py
import os.path import pathlib import urllib import urllib.request from collections import namedtuple from .output import printerr, printdbg """ Functions for dealing with files that could either be local on disk or on in a remote GitHub repository. """ class FilePath: pass _LocalFilePath = namedtuple('Loca...
0.517083
0.129183
# http://multivax.com/last_question.html """Unit and functional tests for getmac.""" import unittest import getmac import io import re from os import path try: from unittest import mock except ImportError: import mock getmac.DEBUG = True class MockHelper(object): @classmethod def load_sample(cls, ...
tests/test_getmac.py
# http://multivax.com/last_question.html """Unit and functional tests for getmac.""" import unittest import getmac import io import re from os import path try: from unittest import mock except ImportError: import mock getmac.DEBUG = True class MockHelper(object): @classmethod def load_sample(cls, ...
0.697815
0.109801
import pyautogui from pyscreeze import ImageNotFoundException import subprocess # Improting Image class from PIL module from PIL import Image import helper FACEBOOK_IMAGE_SIZE = 300 MAX_IMAGES_FACEBOOK = 2 SCROLL_LENGTH = 300 PROFILE_LOCATION_X = 200 TOTAL_TEXT_IMAGES = 3 def CheckForImageQuantity(allLocations): ...
climate_reality/facebookPost.py
import pyautogui from pyscreeze import ImageNotFoundException import subprocess # Improting Image class from PIL module from PIL import Image import helper FACEBOOK_IMAGE_SIZE = 300 MAX_IMAGES_FACEBOOK = 2 SCROLL_LENGTH = 300 PROFILE_LOCATION_X = 200 TOTAL_TEXT_IMAGES = 3 def CheckForImageQuantity(allLocations): ...
0.12416
0.20264
from neutron_lib import constants as n_const from os_ken.ofproto import ether from oslo_log import log from dragonflow.controller.apps import l3_base from dragonflow.controller.common import constants as const from dragonflow.controller import df_base_app LOG = log.getLogger(__name__) class L3ProactiveApp(df_base_...
dragonflow/controller/apps/l3_proactive.py
from neutron_lib import constants as n_const from os_ken.ofproto import ether from oslo_log import log from dragonflow.controller.apps import l3_base from dragonflow.controller.common import constants as const from dragonflow.controller import df_base_app LOG = log.getLogger(__name__) class L3ProactiveApp(df_base_...
0.723407
0.206324
from kratos import PackedStruct, clog2 from global_buffer.design.global_buffer_parameter import GlobalBufferParams import math class GlbHeader(): def __init__(self, _params: GlobalBufferParams): self._params = _params self.cfg_data_network_t = PackedStruct("cfg_data_network_t", ...
global_buffer/design/glb_header.py
from kratos import PackedStruct, clog2 from global_buffer.design.global_buffer_parameter import GlobalBufferParams import math class GlbHeader(): def __init__(self, _params: GlobalBufferParams): self._params = _params self.cfg_data_network_t = PackedStruct("cfg_data_network_t", ...
0.436262
0.242228
import logging import threading import zmq import zmq.auth from zmq.auth.thread import ThreadAuthenticator __author__ = "<NAME>" __copyright__ = "Copyright (c) 2015, Technische Universitat Berlin" __version__ = "0.1.0" __email__ = "<EMAIL>" class Broker(threading.Thread): """docstring for Broker""" def __i...
uniflex/core/broker.py
import logging import threading import zmq import zmq.auth from zmq.auth.thread import ThreadAuthenticator __author__ = "<NAME>" __copyright__ = "Copyright (c) 2015, Technische Universitat Berlin" __version__ = "0.1.0" __email__ = "<EMAIL>" class Broker(threading.Thread): """docstring for Broker""" def __i...
0.434941
0.055797
import pycom import lteHelper import machine from machine import I2C import pytrackHelper from pytrack import Pytrack from LIS2HH12 import LIS2HH12 import time import gc import sys import bme280 from ADS1115 import ADS1115 # *********************************************************** # ourBoatMonitor IOT code for the...
uPython/main.py
import pycom import lteHelper import machine from machine import I2C import pytrackHelper from pytrack import Pytrack from LIS2HH12 import LIS2HH12 import time import gc import sys import bme280 from ADS1115 import ADS1115 # *********************************************************** # ourBoatMonitor IOT code for the...
0.18363
0.294177
import numpy as np import scipy from algorithms.accelerated_gradient_descent import \ accelerated_gradient_descent from algorithms.accelerated_gradient_descent_adaptive_restart import \ accelerated_gradient_descent_adaptive_restart from algorithms.accelerated_gradient_descent_adaptive_restart_line_search impor...
src/ridge_regression.py
import numpy as np import scipy from algorithms.accelerated_gradient_descent import \ accelerated_gradient_descent from algorithms.accelerated_gradient_descent_adaptive_restart import \ accelerated_gradient_descent_adaptive_restart from algorithms.accelerated_gradient_descent_adaptive_restart_line_search impor...
0.623377
0.339034
from django.core.wsgi import get_wsgi_application from sklearn.metrics import * from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.neural_network import MLPClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.neighbors import KNeighborsC...
backend/apps/checker/class_learner.py
from django.core.wsgi import get_wsgi_application from sklearn.metrics import * from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.neural_network import MLPClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.neighbors import KNeighborsC...
0.408631
0.294843
import torch import torch.nn as nn import torch.nn.functional as F BN_EPS = 1e-05 BN_MOMENTUM = 0.9 # too large? class DONetMultiscaleClassificationOrientationPose(nn.Module): def __init__(self): super(DONetMultiscaleClassificationOrientationPose, self).__init__() self.activation =...
src/models/donet_ms.py
import torch import torch.nn as nn import torch.nn.functional as F BN_EPS = 1e-05 BN_MOMENTUM = 0.9 # too large? class DONetMultiscaleClassificationOrientationPose(nn.Module): def __init__(self): super(DONetMultiscaleClassificationOrientationPose, self).__init__() self.activation =...
0.890812
0.329891
from tkinter.tix import Tree import requests import os import time import cv2 import numpy as np from scipy.special import softmax from sklearn import metrics import pandas as pd def parse_labels(filenames): return [filename[:-4].split('_')[-4][1:-1] for filename in filenames] def parse_label(filename): return...
client.py
from tkinter.tix import Tree import requests import os import time import cv2 import numpy as np from scipy.special import softmax from sklearn import metrics import pandas as pd def parse_labels(filenames): return [filename[:-4].split('_')[-4][1:-1] for filename in filenames] def parse_label(filename): return...
0.438064
0.214136
import tempfile, shutil, sys, subprocess, json import populate_xmeta as px def kobo_import(kobo_username, auth_token): kobo_url = "https://kc.kobotoolbox.org/%s" % (kobo_username) kobo_import_forms(kobo_url, auth_token) kobo_import_data(auth_token) def kobo_import_forms(kobo_url, auth_token): forms = jso...
kobo_import.py
import tempfile, shutil, sys, subprocess, json import populate_xmeta as px def kobo_import(kobo_username, auth_token): kobo_url = "https://kc.kobotoolbox.org/%s" % (kobo_username) kobo_import_forms(kobo_url, auth_token) kobo_import_data(auth_token) def kobo_import_forms(kobo_url, auth_token): forms = jso...
0.109254
0.215392
import os import warnings os.environ['TF_CPP_MIN_LOG_LEVEL'] = "2" import tensorflow as tf import wandb from wandb.keras import WandbCallback import sklearn import numpy as np from sklearn.metrics import confusion_matrix from tensorflow.keras.utils import to_categorical from tensorflow.keras.preprocessing import sequen...
lab/sweep.py
import os import warnings os.environ['TF_CPP_MIN_LOG_LEVEL'] = "2" import tensorflow as tf import wandb from wandb.keras import WandbCallback import sklearn import numpy as np from sklearn.metrics import confusion_matrix from tensorflow.keras.utils import to_categorical from tensorflow.keras.preprocessing import sequen...
0.60778
0.337313
import json from datetime import datetime from typing import Any, Dict, List, cast from covid19_sfbayarea.utils import dig, parse_datetime from .cases_by_age import CasesByAge from .cases_by_ethnicity import CasesByEthnicity from .cases_by_gender import CasesByGender from .meta import Meta from .deaths_by_age impor...
covid19_sfbayarea/data/san_mateo/__init__.py
import json from datetime import datetime from typing import Any, Dict, List, cast from covid19_sfbayarea.utils import dig, parse_datetime from .cases_by_age import CasesByAge from .cases_by_ethnicity import CasesByEthnicity from .cases_by_gender import CasesByGender from .meta import Meta from .deaths_by_age impor...
0.587943
0.250191
from unittest import mock from django.test import TestCase from django.urls import reverse from dominio.tests.testconf import NoJWTTestCase, NoCacheTestCase class TestPIPIndicadoresSucesso(NoJWTTestCase, NoCacheTestCase, TestCase): @mock.patch("dominio.pip.views.PIPIndicadoresDeSucessoDAO.execute") def test...
dominio/pip/tests/test_views.py
from unittest import mock from django.test import TestCase from django.urls import reverse from dominio.tests.testconf import NoJWTTestCase, NoCacheTestCase class TestPIPIndicadoresSucesso(NoJWTTestCase, NoCacheTestCase, TestCase): @mock.patch("dominio.pip.views.PIPIndicadoresDeSucessoDAO.execute") def test...
0.708717
0.408336
import os import json import copy import math import attr import numpy as np import pandas as pd from scipy.special import logsumexp from ..core.likelihood import Likelihood from ..core.utils import BilbyJsonEncoder, decode_bilby_json from ..core.utils import ( logger, UnsortedInterp2d, create_frequency_series, c...
bilby/gw/likelihood.py
import os import json import copy import math import attr import numpy as np import pandas as pd from scipy.special import logsumexp from ..core.likelihood import Likelihood from ..core.utils import BilbyJsonEncoder, decode_bilby_json from ..core.utils import ( logger, UnsortedInterp2d, create_frequency_series, c...
0.844537
0.434101
import pandas as pd import yfinance as yf import logging import wrds TABLE_NUM = 0 STOCK_COLUMN = "Symbol" class DataQuerierYF: def __init__ (self, cfg, load_on_init=True, save=True, **kwargs): self.cfg = cfg self.company_list = pd.read_html(self.cfg.link)[TABLE_NUM][STOCK_COLUMN].tolist() ...
data_querier.py
import pandas as pd import yfinance as yf import logging import wrds TABLE_NUM = 0 STOCK_COLUMN = "Symbol" class DataQuerierYF: def __init__ (self, cfg, load_on_init=True, save=True, **kwargs): self.cfg = cfg self.company_list = pd.read_html(self.cfg.link)[TABLE_NUM][STOCK_COLUMN].tolist() ...
0.240685
0.09611
import json import math from typing import Union, Tuple, NamedTuple, Optional, List import pytest @pytest.mark.parametrize( "input_string, expected", [ ("1", [1]), ("[1,2]", [(1, 2)]), ("[[[7,1],2],3]\n[[1,7],7]", [(((7, 1), 2), 3), ((1, 7), 7)]), ], ) def test_parse_input(input_s...
src/day18.py
import json import math from typing import Union, Tuple, NamedTuple, Optional, List import pytest @pytest.mark.parametrize( "input_string, expected", [ ("1", [1]), ("[1,2]", [(1, 2)]), ("[[[7,1],2],3]\n[[1,7],7]", [(((7, 1), 2), 3), ((1, 7), 7)]), ], ) def test_parse_input(input_s...
0.736021
0.688516
from . import LatexObject, Environment, Command from ..utils import dumps_list from ..package import Package from collections import Counter import re def _get_table_width(table_spec): """Calculate the width of a table based on its spec. :param table_spec: :type table_spec: str :return: :rtyp...
pylatex/base_classes/table.py
from . import LatexObject, Environment, Command from ..utils import dumps_list from ..package import Package from collections import Counter import re def _get_table_width(table_spec): """Calculate the width of a table based on its spec. :param table_spec: :type table_spec: str :return: :rtyp...
0.748904
0.474996
import torch from torch import nn from clinicadl.utils.network.vae.base_vae import BaseVAE from clinicadl.utils.network.vae.vae_utils import ( DecoderLayer3D, EncoderLayer3D, Flatten, Unflatten3D, VAE_Decoder, VAE_Encoder, ) class VanillaDenseVAE(BaseVAE): def __init__( self, ...
clinicadl/utils/network/vae/vanilla_vae.py
import torch from torch import nn from clinicadl.utils.network.vae.base_vae import BaseVAE from clinicadl.utils.network.vae.vae_utils import ( DecoderLayer3D, EncoderLayer3D, Flatten, Unflatten3D, VAE_Decoder, VAE_Encoder, ) class VanillaDenseVAE(BaseVAE): def __init__( self, ...
0.8758
0.382141
import os import errno from datetime import datetime, timedelta from getpass import getpass import pytz from exchangelib import ( DELEGATE, Account, Configuration, EWSDateTime, FileAttachment, ItemAttachment, Message, ServiceAccount ) from config import ( ALLOWED_EXTENSIONS, DOWNLOAD_ATTACHED_EMAILS, ...
crawler.py
import os import errno from datetime import datetime, timedelta from getpass import getpass import pytz from exchangelib import ( DELEGATE, Account, Configuration, EWSDateTime, FileAttachment, ItemAttachment, Message, ServiceAccount ) from config import ( ALLOWED_EXTENSIONS, DOWNLOAD_ATTACHED_EMAILS, ...
0.319121
0.096578
import logging import os import re import uuid from datetime import datetime from pathlib import Path from platform import node as get_hostname from typing import List, Optional, Union import click from neptune.new.attributes import constants as attr_consts from neptune.new.constants import ( ASYNC_DIRECTORY, ...
neptune/new/internal/init_impl.py
import logging import os import re import uuid from datetime import datetime from pathlib import Path from platform import node as get_hostname from typing import List, Optional, Union import click from neptune.new.attributes import constants as attr_consts from neptune.new.constants import ( ASYNC_DIRECTORY, ...
0.501709
0.068195
import os import re import zipfile from typing import Optional def is_zip(file_type) -> bool: """ Check if the given file is a ZIP Returns: bool: Whether it's a ZIP file or not """ mimes = { 'application/zip', 'application/octet-stream', 'application/x-zip-compresse...
gsynch/helper.py
import os import re import zipfile from typing import Optional def is_zip(file_type) -> bool: """ Check if the given file is a ZIP Returns: bool: Whether it's a ZIP file or not """ mimes = { 'application/zip', 'application/octet-stream', 'application/x-zip-compresse...
0.743913
0.276188
# ______________________________________________________________________ import ctypes import llvm.core as lc import llvm.ee as le from numba.llvm_types import _int32, _numpy_array, _head_len import numba.multiarray_api as ma import numpy as np import unittest # ___________________________________________________...
tests/test_multiarray_api.py
# ______________________________________________________________________ import ctypes import llvm.core as lc import llvm.ee as le from numba.llvm_types import _int32, _numpy_array, _head_len import numba.multiarray_api as ma import numpy as np import unittest # ___________________________________________________...
0.179315
0.188623
import torch import torch.nn as nn from torch.optim import Optimizer class OptimActivation(nn.Module): def __init__(self): super(OptimActivation, self).__init__() self.params = nn.Parameter(torch.zeros(5)) def forward(self, x): params_softmax = torch.softmax(self.params, dim=-1) x_swish = (torch.sigmoid(x) ...
optim.py
import torch import torch.nn as nn from torch.optim import Optimizer class OptimActivation(nn.Module): def __init__(self): super(OptimActivation, self).__init__() self.params = nn.Parameter(torch.zeros(5)) def forward(self, x): params_softmax = torch.softmax(self.params, dim=-1) x_swish = (torch.sigmoid(x) ...
0.943165
0.550789
from typing import List, Tuple, Union from .exceptions import NotSquareException, ValidationError Number = Union[int, float] class Matrix: def __init__(self, rows: List[List[Number]]) -> None: self.rows = rows self._validate() def __str__(self) -> str: return str(self.rows) def...
matops/matrix.py
from typing import List, Tuple, Union from .exceptions import NotSquareException, ValidationError Number = Union[int, float] class Matrix: def __init__(self, rows: List[List[Number]]) -> None: self.rows = rows self._validate() def __str__(self) -> str: return str(self.rows) def...
0.853394
0.447219