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
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.firefox.options import Options from time import time, sleep import re import requests import os impo...
pokedex_scraper.py
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.firefox.options import Options from time import time, sleep import re import requests import os impo...
0.247078
0.097777
import numpy as np import pandas as pd pd.options.mode.chained_assignment = None import time from sklearn.externals import joblib from sklearn.model_selection import StratifiedKFold, GridSearchCV, train_test_split from sklearn.metrics import roc_auc_score, average_precision_score, make_scorer from sklearn import linear...
model_selection.py
import numpy as np import pandas as pd pd.options.mode.chained_assignment = None import time from sklearn.externals import joblib from sklearn.model_selection import StratifiedKFold, GridSearchCV, train_test_split from sklearn.metrics import roc_auc_score, average_precision_score, make_scorer from sklearn import linear...
0.451568
0.259321
# %% import libraries import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB from sklearn.linear_m...
Project_Source_Code_Kutay_Erkan.py
# %% import libraries import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB from sklearn.linear_m...
0.61878
0.367753
import datetime import math import pytest import pytz from mer.constants import mars_year_0_start, sols_per_martian_year from mer.retimers import EarthDateTime, MarsYearSol, MarsYearSolarLongitude, \ datetime_to_earthdatetime, sols_after_mars_year_0, sols_between_datetimes, \ sols_since_datetime class TestEar...
mer/tests/test_retimers.py
import datetime import math import pytest import pytz from mer.constants import mars_year_0_start, sols_per_martian_year from mer.retimers import EarthDateTime, MarsYearSol, MarsYearSolarLongitude, \ datetime_to_earthdatetime, sols_after_mars_year_0, sols_between_datetimes, \ sols_since_datetime class TestEar...
0.668339
0.742655
import os import json from datetime import datetime import requests from .utils import execute STATUS_COPYRIGHTED = 0 STATUS_UNCOPYRIGHTED = 1 STATUS_UNDETECTED = 2 STATUS_WORKING = 3 OVERALL_WORKING = 3 OVERALL_HAS_COPYRIGHTED = 0 OVERALL_ALL_UNDETECTED = 2 OVERALL_UNDETECTED_UNCOPYRIGHTED = 1 # ===============...
common/services.py
import os import json from datetime import datetime import requests from .utils import execute STATUS_COPYRIGHTED = 0 STATUS_UNCOPYRIGHTED = 1 STATUS_UNDETECTED = 2 STATUS_WORKING = 3 OVERALL_WORKING = 3 OVERALL_HAS_COPYRIGHTED = 0 OVERALL_ALL_UNDETECTED = 2 OVERALL_UNDETECTED_UNCOPYRIGHTED = 1 # ===============...
0.314787
0.050377
"""jquery-autocomplete-light widget implementation module.""" from __future__ import unicode_literals from django import forms try: from django.urls import resolve except ImportError: from django.core.urlresolvers import resolve from django.template.loader import render_to_string from django.utils import safes...
src/dal_jal/widgets.py
"""jquery-autocomplete-light widget implementation module.""" from __future__ import unicode_literals from django import forms try: from django.urls import resolve except ImportError: from django.core.urlresolvers import resolve from django.template.loader import render_to_string from django.utils import safes...
0.776369
0.115961
from keras import Input, Model, Sequential from keras.layers import Flatten, Conv2D, Concatenate, Dense, Activation, concatenate from keras.optimizers import Adam, SGD from rl.agents import CEMAgent from rl.memory import SequentialMemory, EpisodeParameterMemory from hexagon_agent import * from random import shuffle fr...
ppo_centaur_ai_gym.py
from keras import Input, Model, Sequential from keras.layers import Flatten, Conv2D, Concatenate, Dense, Activation, concatenate from keras.optimizers import Adam, SGD from rl.agents import CEMAgent from rl.memory import SequentialMemory, EpisodeParameterMemory from hexagon_agent import * from random import shuffle fr...
0.737442
0.275687
__author__ = 'pieroit' from DatabaseHulk import DatabaseHulk import collections def parseLine(line): # take away newline and split by tab return line.rstrip('\r\n').split('\t') # make dictionary out of the list of names and their values # order must be the same def buildRecordObj(cols, vals): newObj = {}...
import2sql.py
__author__ = 'pieroit' from DatabaseHulk import DatabaseHulk import collections def parseLine(line): # take away newline and split by tab return line.rstrip('\r\n').split('\t') # make dictionary out of the list of names and their values # order must be the same def buildRecordObj(cols, vals): newObj = {}...
0.282097
0.130812
from sciibo.core.colors import * # Define our color pairs BACKGROUND = create_color(CYAN, BLUE) # Logos LOGO = create_color(CYAN, BLUE) LOGO_SHADOW = create_color(BLACK, BLUE) LOGO_TEXT = create_color(YELLOW, YELLOW) LOGO_TEXT_SLIDER = create_color(YELLOW, WHITE) # Menus MENU = create_color(CYAN, BLUE) MENU_TEXT =...
sciibo/graphics/colors.py
from sciibo.core.colors import * # Define our color pairs BACKGROUND = create_color(CYAN, BLUE) # Logos LOGO = create_color(CYAN, BLUE) LOGO_SHADOW = create_color(BLACK, BLUE) LOGO_TEXT = create_color(YELLOW, YELLOW) LOGO_TEXT_SLIDER = create_color(YELLOW, WHITE) # Menus MENU = create_color(CYAN, BLUE) MENU_TEXT =...
0.404625
0.097907
import optparse, os, shutil, subprocess, sys, tempfile def stop_err( msg ): sys.stderr.write( '%s\n' % msg ) sys.exit() def run_process ( cmd, name, tmp_dir, buffsize ): try: tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name tmp_stderr = open( tmp, 'wb' ) proc = subprocess.Pope...
DWGSIMSrc/scripts/galaxy/dwgsim_eval_wrapper.py
import optparse, os, shutil, subprocess, sys, tempfile def stop_err( msg ): sys.stderr.write( '%s\n' % msg ) sys.exit() def run_process ( cmd, name, tmp_dir, buffsize ): try: tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name tmp_stderr = open( tmp, 'wb' ) proc = subprocess.Pope...
0.134804
0.079854
import secrets, os, bcrypt, subprocess, json, math, shutil from decouple import config passwords_dir = 'web/.passwords' # Directory for display templates (not Flask templates) templates_dir = 'templates' services_config_path = 'cache/services.json' env_file = '.env' def generate_secret(): secret = secrets.toke...
web/utilities.py
import secrets, os, bcrypt, subprocess, json, math, shutil from decouple import config passwords_dir = 'web/.passwords' # Directory for display templates (not Flask templates) templates_dir = 'templates' services_config_path = 'cache/services.json' env_file = '.env' def generate_secret(): secret = secrets.toke...
0.424054
0.092811
from rest_framework import status from core.entity.user import User, UserSet from core.entity.entity_exceptions import EntityNotFoundException from core.entity.entry_points.authorizations import AuthorizationModule from ..base_view_test import BaseViewTest from .synchronization_client import SynchronizationClient c...
corefacility/core/test/views/synchronization_test/test_synchronization.py
from rest_framework import status from core.entity.user import User, UserSet from core.entity.entity_exceptions import EntityNotFoundException from core.entity.entry_points.authorizations import AuthorizationModule from ..base_view_test import BaseViewTest from .synchronization_client import SynchronizationClient c...
0.746416
0.162712
import os import sys base_dir = os.path.dirname(__file__) data_dir = os.path.join(base_dir, "resources") sys.path.extend([os.path.join(base_dir, '../..')]) import unittest import warnings import pandas as pd from enricher.enrich import regulon_utils, regulon_enrichment warnings.simplefilter("ignore", UserWarning) d...
enricher/tests/test_regulon.py
import os import sys base_dir = os.path.dirname(__file__) data_dir = os.path.join(base_dir, "resources") sys.path.extend([os.path.join(base_dir, '../..')]) import unittest import warnings import pandas as pd from enricher.enrich import regulon_utils, regulon_enrichment warnings.simplefilter("ignore", UserWarning) d...
0.233444
0.508849
from flask import Blueprint, redirect, url_for, render_template, request from data.models import Person, db from utils.csv2dict import convert from constants import attributes as attrs from datetime import datetime from os.path import join main = Blueprint('main', __name__) langs_dict = {} convert(langs_dict, csv...
main/controllers.py
from flask import Blueprint, redirect, url_for, render_template, request from data.models import Person, db from utils.csv2dict import convert from constants import attributes as attrs from datetime import datetime from os.path import join main = Blueprint('main', __name__) langs_dict = {} convert(langs_dict, csv...
0.234757
0.104021
from asyncio import sleep from logging import getLogger import aiologstash from aiologstash import create_tcp_handler from async_asgi_testclient import TestClient from pytest import mark, raises from yellowbox.extras.logstash import FakeLogstashService from heksher._version import __version__ from heksher.main import...
tests/blackbox/app/test_startup.py
from asyncio import sleep from logging import getLogger import aiologstash from aiologstash import create_tcp_handler from async_asgi_testclient import TestClient from pytest import mark, raises from yellowbox.extras.logstash import FakeLogstashService from heksher._version import __version__ from heksher.main import...
0.403332
0.111338
import asyncio import typing as t from dataclasses import asdict, dataclass, field from datetime import datetime, timedelta import discord from discord.ext import commands from bot import ModmailBot from core import checks from core.models import PermissionLevel, getLogger from core.thread import Thread from .utils i...
ping_manager/ping_manager.py
import asyncio import typing as t from dataclasses import asdict, dataclass, field from datetime import datetime, timedelta import discord from discord.ext import commands from bot import ModmailBot from core import checks from core.models import PermissionLevel, getLogger from core.thread import Thread from .utils i...
0.715424
0.15925
import FWCore.ParameterSet.Config as cms ecal_pulse_shape_templates = cms.PSet( EBPulseShapeTemplate = cms.vdouble ( 1.13979e-02, 7.58151e-01, 1.00000e+00, 8.87744e-01, 6.73548e-01, 4.74332e-01, 3.19561e-01, 2.15144e-01, 1.47464e-01, 1.01087e-01, 6.93181e-02, 4.75044e-02 ) , EEPulseShapeTemplat...
RecoLocalCalo/EcalRecProducers/python/ecalPulseShapeParameters_cff.py
import FWCore.ParameterSet.Config as cms ecal_pulse_shape_templates = cms.PSet( EBPulseShapeTemplate = cms.vdouble ( 1.13979e-02, 7.58151e-01, 1.00000e+00, 8.87744e-01, 6.73548e-01, 4.74332e-01, 3.19561e-01, 2.15144e-01, 1.47464e-01, 1.01087e-01, 6.93181e-02, 4.75044e-02 ) , EEPulseShapeTemplat...
0.169887
0.475544
import cv2 import time import numpy as np MODE = "BODY25" if MODE is "COCO": protoFile = "C:/Users/romanrosh/openpose-1.4.0-win64-gpu-binaries/models/pose/coco/pose_deploy_linevec.prototxt" weightsFile = "C:/Users/romanrosh/openpose-1.4.0-win64-gpu-binaries/models/pose/coco/pose_iter_440000.caffemodel" nP...
OpenPoseImage.py
import cv2 import time import numpy as np MODE = "BODY25" if MODE is "COCO": protoFile = "C:/Users/romanrosh/openpose-1.4.0-win64-gpu-binaries/models/pose/coco/pose_deploy_linevec.prototxt" weightsFile = "C:/Users/romanrosh/openpose-1.4.0-win64-gpu-binaries/models/pose/coco/pose_iter_440000.caffemodel" nP...
0.289472
0.335895
from .base_endpoint import BaseEndpoint # The base CheckIns endpoint class CheckInsEndpoint(BaseEndpoint): pass # All CheckIns endpoints class CheckIns(CheckInsEndpoint): """An attendance record for an event. If someone was checked out, `checked_out_at` will be present. You can scope check-ins in a few ways: ...
pypco/endpoints/check_ins.py
from .base_endpoint import BaseEndpoint # The base CheckIns endpoint class CheckInsEndpoint(BaseEndpoint): pass # All CheckIns endpoints class CheckIns(CheckInsEndpoint): """An attendance record for an event. If someone was checked out, `checked_out_at` will be present. You can scope check-ins in a few ways: ...
0.742328
0.480357
from __future__ import absolute_import, division import bcrypt import flask.ext.testing import functools import hashlib import inspect import os import shutil import tempfile from . import create_app from . import settings from .model import db from .site import Site def create_tempdir(): d = tempfile.mkdtemp(...
src/marv/marv/testing.py
from __future__ import absolute_import, division import bcrypt import flask.ext.testing import functools import hashlib import inspect import os import shutil import tempfile from . import create_app from . import settings from .model import db from .site import Site def create_tempdir(): d = tempfile.mkdtemp(...
0.466846
0.081082
from pyglet import event from pyglet.gl import glClearColor, GL_TRIANGLES from pyglet.window import key, Window from pyglet.shapes import Rectangle from pyglet.text import Label, caret from pyglet.text.document import FormattedDocument from pyglet.text.layout import IncrementalTextLayout, ScrollableTextLayout from sett...
gui.py
from pyglet import event from pyglet.gl import glClearColor, GL_TRIANGLES from pyglet.window import key, Window from pyglet.shapes import Rectangle from pyglet.text import Label, caret from pyglet.text.document import FormattedDocument from pyglet.text.layout import IncrementalTextLayout, ScrollableTextLayout from sett...
0.265785
0.155271
import os from math import exp from parsable import parsable import pomagma.util import util SPECS = {} SPECS['sk'] = { 'binary_probs': { 'APP': 0.374992, 'COMP': 0.198589, }, 'nullary_weights': { 'B': 1.0, 'C': 1.30428, 'CB': 1.35451, 'CI': 1.74145, ...
src/language/bootstrap.py
import os from math import exp from parsable import parsable import pomagma.util import util SPECS = {} SPECS['sk'] = { 'binary_probs': { 'APP': 0.374992, 'COMP': 0.198589, }, 'nullary_weights': { 'B': 1.0, 'C': 1.30428, 'CB': 1.35451, 'CI': 1.74145, ...
0.397354
0.25799
import pandas as pd def read_csv(path=str, sep=';'): """ Leer un archivo csv y los transforma a un dataframe :param path: dirección del archivo csv :param sep: separador del archvio :return: dataframe """ # Leemos el archivo con la funcioón read_csv() df = pd.read_csv(path, sep=sep) ...
discover/features/build_features.py
import pandas as pd def read_csv(path=str, sep=';'): """ Leer un archivo csv y los transforma a un dataframe :param path: dirección del archivo csv :param sep: separador del archvio :return: dataframe """ # Leemos el archivo con la funcioón read_csv() df = pd.read_csv(path, sep=sep) ...
0.561575
0.603435
import cherrypy import re, json from flask_restful import reqparse, abort, Api, Resource class OptionsController(Resource): def __init__(self): print("starting Options Controller") def OPTIONS(self, *args, **kargs): return "" class CardsController(Resource): def __init__(self, cdb...
server/controller.py
import cherrypy import re, json from flask_restful import reqparse, abort, Api, Resource class OptionsController(Resource): def __init__(self): print("starting Options Controller") def OPTIONS(self, *args, **kargs): return "" class CardsController(Resource): def __init__(self, cdb...
0.220678
0.067731
# Copyright (c) 2016-2020, <NAME> # 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 the fo...
src/sharp/functions/repeat.py
# Copyright (c) 2016-2020, <NAME> # 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 the fo...
0.661486
0.059757
import os import sys import copy import pytz import datetime import traceback import numpy as np from django.conf import settings from django.core import management from django.core.management.base import BaseCommand, CommandError from django.db.models import Q from dining_room import constants from dining_room.mod...
website/management/commands/sync_suggestions.py
import os import sys import copy import pytz import datetime import traceback import numpy as np from django.conf import settings from django.core import management from django.core.management.base import BaseCommand, CommandError from django.db.models import Q from dining_room import constants from dining_room.mod...
0.495361
0.282332
import discord class Bot(discord.Client): def __init__(self, guild_name, channel_id, logger=None, **kwargs): """ Bot for use with a single Discord Guild and Text Channel :param guild_name: The name of the Discord Guild to join :type guild_name: string :param channel_id: T...
chuckle_bot/single_channel_bot.py
import discord class Bot(discord.Client): def __init__(self, guild_name, channel_id, logger=None, **kwargs): """ Bot for use with a single Discord Guild and Text Channel :param guild_name: The name of the Discord Guild to join :type guild_name: string :param channel_id: T...
0.662251
0.093969
import argparse import os.path import sys sys.path.append(os.path.dirname(__file__)) from signing import notarize from signing.config import CodeSignConfig def main(): parser = argparse.ArgumentParser( description='Notarize and staple an application binary or archive.') parser.add_argument( ...
chrome/installer/mac/notarize_thing.py
import argparse import os.path import sys sys.path.append(os.path.dirname(__file__)) from signing import notarize from signing.config import CodeSignConfig def main(): parser = argparse.ArgumentParser( description='Notarize and staple an application binary or archive.') parser.add_argument( ...
0.466846
0.06666
import hashlib import json import numpy as np from .utils import FeatureData class CMSRecordTest0(FeatureData): def __init__(self, data: ('CMSDataPopularity', dict) = {}): super(CMSRecordTest0, self).__init__() self.__tot_wrap_cpu = 0.0 self.__tot_requests = 1 self.__num_next_w...
DataManager/collector/datafeatures/extractor.py
import hashlib import json import numpy as np from .utils import FeatureData class CMSRecordTest0(FeatureData): def __init__(self, data: ('CMSDataPopularity', dict) = {}): super(CMSRecordTest0, self).__init__() self.__tot_wrap_cpu = 0.0 self.__tot_requests = 1 self.__num_next_w...
0.532911
0.214434
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under th...
build.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under th...
0.870597
0.223091
class Stack(object): """Docstring for Stack """ def __init__(self): """@todo: to be defined1 """ self.items = [] def pushFromList(self, list): """Push the list in the stack :param list: a list """ for i in list[::-1]: self.push(i) def isE...
pymath/generic.py
class Stack(object): """Docstring for Stack """ def __init__(self): """@todo: to be defined1 """ self.items = [] def pushFromList(self, list): """Push the list in the stack :param list: a list """ for i in list[::-1]: self.push(i) def isE...
0.592549
0.499207
""" Main menu """ import sys import os import datetime import asyncio import curses import npyscreen from error_handler import error_handler from main_menu_list import MainMenuList from widgets.net_interfaces_widget import NetInterfacesWidget APP_NAME = "{} ASR".format(os.environ.get("APP_NAME", "Speechmatics")) # p...
main_menu.py
""" Main menu """ import sys import os import datetime import asyncio import curses import npyscreen from error_handler import error_handler from main_menu_list import MainMenuList from widgets.net_interfaces_widget import NetInterfacesWidget APP_NAME = "{} ASR".format(os.environ.get("APP_NAME", "Speechmatics")) # p...
0.393502
0.11129
from json import loads from logging import getLogger from os import environ, path from typing import Any, Callable, Dict, Final, List, Optional from fastapi import APIRouter, FastAPI from fastapi.middleware.cors import CORSMiddleware from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests imp...
stac_fastapi/api/stac_fastapi/api/middleware.py
from json import loads from logging import getLogger from os import environ, path from typing import Any, Callable, Dict, Final, List, Optional from fastapi import APIRouter, FastAPI from fastapi.middleware.cors import CORSMiddleware from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests imp...
0.876806
0.069827
import os from typing import Tuple, Union, Optional from PIL import Image from torchvision.datasets import VisionDataset from torchvision.datasets.folder import is_image_file from torchvision.transforms import RandomCrop, CenterCrop from torchvision.transforms.functional import resize _PIL_IMAGE_MODES_ = ('L', 'F', '...
isr/datasets/isr.py
import os from typing import Tuple, Union, Optional from PIL import Image from torchvision.datasets import VisionDataset from torchvision.datasets.folder import is_image_file from torchvision.transforms import RandomCrop, CenterCrop from torchvision.transforms.functional import resize _PIL_IMAGE_MODES_ = ('L', 'F', '...
0.907972
0.486149
import re import math from os import system import sys import traceback def inlst(lst, value, key=lambda x:x): for i in range(len(lst)): each = lst[i] if key(each) == value: return i return -1 recipes = {} def main(): global recipes ...
recipes_calc.py
import re import math from os import system import sys import traceback def inlst(lst, value, key=lambda x:x): for i in range(len(lst)): each = lst[i] if key(each) == value: return i return -1 recipes = {} def main(): global recipes ...
0.039909
0.152979
import pytest import mock # Django REST Framework from rest_framework import exceptions from rest_framework.generics import ListAPIView # Django from django.core.urlresolvers import RegexURLResolver, RegexURLPattern # AWX from awx.main.views import ApiErrorView from awx.api.views import JobList, InventorySourceList ...
awx/main/tests/unit/test_views.py
import pytest import mock # Django REST Framework from rest_framework import exceptions from rest_framework.generics import ListAPIView # Django from django.core.urlresolvers import RegexURLResolver, RegexURLPattern # AWX from awx.main.views import ApiErrorView from awx.api.views import JobList, InventorySourceList ...
0.479747
0.242351
import pygame import math pygame.init() class TowerTutorial(pygame.sprite.Sprite): def __init__(Self): Self.image = pygame.image.load("Media/Towers/Machine_Gun/L1 Images/L1_MachineGun0000.tif").convert_alpha() Self.level = 1 Self.range = 40 Self.damage = 20 Self.visible = ...
TowerTutorial.py
import pygame import math pygame.init() class TowerTutorial(pygame.sprite.Sprite): def __init__(Self): Self.image = pygame.image.load("Media/Towers/Machine_Gun/L1 Images/L1_MachineGun0000.tif").convert_alpha() Self.level = 1 Self.range = 40 Self.damage = 20 Self.visible = ...
0.34798
0.352146
from __future__ import (absolute_import, print_function, unicode_literals) import math import os from colorclass import Color, Windows from terminaltables import AsciiTable from acli.utils import get_console_dimensions try: input = raw_input except NameError: pass Windows.enable(auto_colors=True, reset_atex...
lib/acli/output/__init__.py
from __future__ import (absolute_import, print_function, unicode_literals) import math import os from colorclass import Color, Windows from terminaltables import AsciiTable from acli.utils import get_console_dimensions try: input = raw_input except NameError: pass Windows.enable(auto_colors=True, reset_atex...
0.359814
0.132767
import ConfigParser import os import os.path from Log import log_main class VamosLibConfig: def __init__(self, name, mode='auto', version=0, profile=False, expunge='last_close'): self.name = name self.mode = mode self.version = version self.profile = profile self.expunge = expunge # types of...
dependencies/amitools-0.1.0/amitools/vamos/VamosConfig.py
import ConfigParser import os import os.path from Log import log_main class VamosLibConfig: def __init__(self, name, mode='auto', version=0, profile=False, expunge='last_close'): self.name = name self.mode = mode self.version = version self.profile = profile self.expunge = expunge # types of...
0.26923
0.107017
from manim import * from functions import * import color class AddingSquares(MovingCameraScene): def construct(self): self.camera.background_color = color.BACKGROUND print('First fibonacci (n value):') n = int(input()) fibo = fiboarray(2*n+2) dotGroup1 = VGroup() f...
addingSquares.py
from manim import * from functions import * import color class AddingSquares(MovingCameraScene): def construct(self): self.camera.background_color = color.BACKGROUND print('First fibonacci (n value):') n = int(input()) fibo = fiboarray(2*n+2) dotGroup1 = VGroup() f...
0.421314
0.277601
import multiprocessing as mp from datetime import datetime, timedelta import dask.dataframe import requests from PIL import ImageFont import motionshader if __name__ == '__main__': # Motionshader expects a time indexed, sorted, Dask DataFrame with columns containing EPSG:4326 coordinates. # Motionshader is o...
motionshader_categorical_example.py
import multiprocessing as mp from datetime import datetime, timedelta import dask.dataframe import requests from PIL import ImageFont import motionshader if __name__ == '__main__': # Motionshader expects a time indexed, sorted, Dask DataFrame with columns containing EPSG:4326 coordinates. # Motionshader is o...
0.827271
0.55646
import pandas as pd import matplotlib.pyplot as plt # Read data from csv into pandas dataframe data = pd.read_csv('data.csv')[ ['userid', 'From', 'To']] # Display the first 10 rows of dataframe print(data.head(10)) # Checking if there are NAN values print("Presence of NAN values : \n", data.isnull().any()) # Fu...
Task1.py
import pandas as pd import matplotlib.pyplot as plt # Read data from csv into pandas dataframe data = pd.read_csv('data.csv')[ ['userid', 'From', 'To']] # Display the first 10 rows of dataframe print(data.head(10)) # Checking if there are NAN values print("Presence of NAN values : \n", data.isnull().any()) # Fu...
0.603231
0.597725
import requests import json convert = "USD" listing_url = "https://api.coinmarketcap.com/v2/listings/" url_end = "?structure=array&convert=" + convert request = requests.get(listing_url) results = request.json() data = results["data"] ticker_url_pairs = {} for currency in data: symbol = currency...
API/coincap_specific.py
import requests import json convert = "USD" listing_url = "https://api.coinmarketcap.com/v2/listings/" url_end = "?structure=array&convert=" + convert request = requests.get(listing_url) results = request.json() data = results["data"] ticker_url_pairs = {} for currency in data: symbol = currency...
0.117408
0.144964
import os import pytest import tests from just_bin_it.endpoints.sources import HistogramSource from tests.doubles.consumer import StubConsumer INVALID_FB = b"this is an invalid fb message" class TestHistogramSource: @pytest.fixture(autouse=True) def prepare(self): # Trick to get path of test data ...
tests/test_histogram_source.py
import os import pytest import tests from just_bin_it.endpoints.sources import HistogramSource from tests.doubles.consumer import StubConsumer INVALID_FB = b"this is an invalid fb message" class TestHistogramSource: @pytest.fixture(autouse=True) def prepare(self): # Trick to get path of test data ...
0.367384
0.445469
from panda3d.core import Point3 from panda3d.core import Vec3 from wecs.aspects import Aspect from wecs.aspects import factory from wecs import panda3d from wecs import mechanics from wecs import cefconsole from wecs.panda3d import aspects # Each frame, run these systems. This defines the game itself. system_types =...
examples/panda3d-character-controller/game.py
from panda3d.core import Point3 from panda3d.core import Vec3 from wecs.aspects import Aspect from wecs.aspects import factory from wecs import panda3d from wecs import mechanics from wecs import cefconsole from wecs.panda3d import aspects # Each frame, run these systems. This defines the game itself. system_types =...
0.739422
0.443299
import contextlib import urllib.parse from typing import TYPE_CHECKING, cast import flask import peewee import werkzeug.datastructures import werkzeug.exceptions if TYPE_CHECKING: from typing import Any, Callable, List, Optional, Union from jinja2 import Environment from peewee import Model from werk...
flask_datatables/utils.py
import contextlib import urllib.parse from typing import TYPE_CHECKING, cast import flask import peewee import werkzeug.datastructures import werkzeug.exceptions if TYPE_CHECKING: from typing import Any, Callable, List, Optional, Union from jinja2 import Environment from peewee import Model from werk...
0.834441
0.392075
import os import sys import logging import redis # 项目根目录 BASE_DIR = os.path.dirname(__file__) """ 自添加USER_AGENT请按照已有数据的格式来添加 """ USER_AGENT = [ 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/201...
video/utils/proxy/config.py
import os import sys import logging import redis # 项目根目录 BASE_DIR = os.path.dirname(__file__) """ 自添加USER_AGENT请按照已有数据的格式来添加 """ USER_AGENT = [ 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/201...
0.311636
0.058373
import jsonschema from jsonschema.exceptions import ValidationError from kuryr_libnetwork import schemata from kuryr_libnetwork.schemata import commons from kuryr_libnetwork.tests.unit import base class TestKuryrSchema(base.TestKuryrBase): """Unit tests for Kuryr schema.""" def test_network_id_64_len(self)...
kuryr_libnetwork/tests/unit/test_schema.py
import jsonschema from jsonschema.exceptions import ValidationError from kuryr_libnetwork import schemata from kuryr_libnetwork.schemata import commons from kuryr_libnetwork.tests.unit import base class TestKuryrSchema(base.TestKuryrBase): """Unit tests for Kuryr schema.""" def test_network_id_64_len(self)...
0.6137
0.162579
import json import logging from functools import wraps import botocore from decouple import config import lpipe.contrib.boto3 from lpipe import utils from lpipe.contrib import mindictive def build(message_data, message_group_id=None): data = json.dumps(message_data, sort_keys=True) msg = {"Id": utils.hash(d...
lpipe/contrib/sqs.py
import json import logging from functools import wraps import botocore from decouple import config import lpipe.contrib.boto3 from lpipe import utils from lpipe.contrib import mindictive def build(message_data, message_group_id=None): data = json.dumps(message_data, sort_keys=True) msg = {"Id": utils.hash(d...
0.569733
0.093719
import os import warnings from unittest import TestCase import conf class TestConfg(TestCase): def test_read_yml(self): conf.load('test_resources/conf1.yml') self.assertEqual(conf.get('message'), 'this is yml') self.assertEqual(conf.message, 'this is yml') self.assertEqual(conf.re...
tests.py
import os import warnings from unittest import TestCase import conf class TestConfg(TestCase): def test_read_yml(self): conf.load('test_resources/conf1.yml') self.assertEqual(conf.get('message'), 'this is yml') self.assertEqual(conf.message, 'this is yml') self.assertEqual(conf.re...
0.44553
0.354768
from django.utils import timezone from meteo.models import MeteoData from .api import Weathermanager class CacheManager: def __init__(self, insee): self.insee = insee def _check_if_data_in_db(self): current_datetime_aware = timezone.localtime(timezone.now()) current_date_aware = curre...
gardenizer/meteo/utils/meteo_data_manager.py
from django.utils import timezone from meteo.models import MeteoData from .api import Weathermanager class CacheManager: def __init__(self, insee): self.insee = insee def _check_if_data_in_db(self): current_datetime_aware = timezone.localtime(timezone.now()) current_date_aware = curre...
0.48438
0.27597
import argparse import time import unicurses as uc import common from display import CursesDisplay from api import SpotifyApi from state import SpotifyState, Config logger = common.logging.getLogger(__name__) def get_args(): """Parse and return the command line arguments.""" parser = argparse.ArgumentPars...
spotify.py
import argparse import time import unicurses as uc import common from display import CursesDisplay from api import SpotifyApi from state import SpotifyState, Config logger = common.logging.getLogger(__name__) def get_args(): """Parse and return the command line arguments.""" parser = argparse.ArgumentPars...
0.611498
0.115461
from PIL import Image, ImageChops, ImageEnhance, ImageOps import requests import os from flask import Flask, redirect, jsonify, render_template, request, send_file, send_from_directory import werkzeug import datetime import uuid app = Flask(__name__) ALLOWED_IMAGE_EXTENSIONS = set(['png', 'jpg', 'jpeg']) def process...
app.py
from PIL import Image, ImageChops, ImageEnhance, ImageOps import requests import os from flask import Flask, redirect, jsonify, render_template, request, send_file, send_from_directory import werkzeug import datetime import uuid app = Flask(__name__) ALLOWED_IMAGE_EXTENSIONS = set(['png', 'jpg', 'jpeg']) def process...
0.304559
0.201538
import pickle import inspect import logging import unittest import numpy as np import tensorflow as tf from neupy import utils, layers, init from neupy.utils import tensorflow_eval, tensorflow_session, shape_to_tuple from neupy.layers.base import format_name_if_specified_as_pattern from helpers import vectors_for_te...
tests/base.py
import pickle import inspect import logging import unittest import numpy as np import tensorflow as tf from neupy import utils, layers, init from neupy.utils import tensorflow_eval, tensorflow_session, shape_to_tuple from neupy.layers.base import format_name_if_specified_as_pattern from helpers import vectors_for_te...
0.745398
0.358241
import logging, os from config import Config from logging.handlers import SMTPHandler, RotatingFileHandler from flask import Flask, request from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager from flask_mail import Mail from flask_admin import Admin from flask_...
app/__init__.py
import logging, os from config import Config from logging.handlers import SMTPHandler, RotatingFileHandler from flask import Flask, request from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager from flask_mail import Mail from flask_admin import Admin from flask_...
0.227041
0.035013
import re import locale import util def strtr(s, repl): pattern = '|'.join(map(re.escape, sorted(repl, key=len, reverse=True))) return re.sub(pattern, lambda m: repl[m.group()], s) class check: def __init__(self, conn, message, settings): self.conn = conn self.message = message s...
modules/matCheck.py
import re import locale import util def strtr(s, repl): pattern = '|'.join(map(re.escape, sorted(repl, key=len, reverse=True))) return re.sub(pattern, lambda m: repl[m.group()], s) class check: def __init__(self, conn, message, settings): self.conn = conn self.message = message s...
0.15704
0.60326
import numpy as np import os import unittest from colour import RGB_COLOURSPACES from colour_hdri import TESTS_RESOURCES_DIRECTORY from colour_hdri.generation import image_stack_to_radiance_image from colour_hdri.calibration import camera_response_functions_Debevec1997 from colour_hdri.utilities import ImageStack, fi...
colour_hdri/generation/tests/test_radiance.py
import numpy as np import os import unittest from colour import RGB_COLOURSPACES from colour_hdri import TESTS_RESOURCES_DIRECTORY from colour_hdri.generation import image_stack_to_radiance_image from colour_hdri.calibration import camera_response_functions_Debevec1997 from colour_hdri.utilities import ImageStack, fi...
0.722625
0.267041
import torch import bittensor.utils.weight_utils as weight_utils import pytest def test_convert_weight_and_uids(): uids = torch.tensor(list(range(10))) weights = torch.rand(10) weight_utils.convert_weights_and_uids_for_emit( uids, weights ) # min weight < 0 weights[5] = -1 with pytest.raises(...
tests/unit_tests/bittensor_tests/utils/test_weight_utils.py
import torch import bittensor.utils.weight_utils as weight_utils import pytest def test_convert_weight_and_uids(): uids = torch.tensor(list(range(10))) weights = torch.rand(10) weight_utils.convert_weights_and_uids_for_emit( uids, weights ) # min weight < 0 weights[5] = -1 with pytest.raises(...
0.758868
0.708717
import os import torch import torch.nn as nn import torch.utils.data as data import torch.optim as optim import torchaudio from asr.data import TextTransform, get_audio_transforms, data_processing from asr.models import SpeechRecognitionModel from asr.train import train from asr.test import test from asr.utils import ...
asr/main.py
import os import torch import torch.nn as nn import torch.utils.data as data import torch.optim as optim import torchaudio from asr.data import TextTransform, get_audio_transforms, data_processing from asr.models import SpeechRecognitionModel from asr.train import train from asr.test import test from asr.utils import ...
0.786418
0.401277
import numpy as np import torch class ppo: def __init__(self, model, env): self.model = model use_cuda = torch.cuda.is_available() self.device = torch.device("cuda" if use_cuda else "cpu") self.env = env def test_env(self, vis=False): state = self.env.reset() i...
Simulation/ppo_method.py
import numpy as np import torch class ppo: def __init__(self, model, env): self.model = model use_cuda = torch.cuda.is_available() self.device = torch.device("cuda" if use_cuda else "cpu") self.env = env def test_env(self, vis=False): state = self.env.reset() i...
0.874961
0.562237
from django.shortcuts import get_object_or_404 from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.decorators import action from rest_framework.exceptions import ParseError from users.models import User from .models import Post, Comment, Like from .serializers im...
petgram/views.py
from django.shortcuts import get_object_or_404 from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.decorators import action from rest_framework.exceptions import ParseError from users.models import User from .models import Post, Comment, Like from .serializers im...
0.567098
0.075007
class DoubleLinkedNode: def __init__(self, key, value): self.key = key self.value = value self.pre = None self.next = None class LRUCache: def __init__(self, capacity): """ :type capacity: int """ self.capacity = capacity self.kv = dict()...
p146_lru_cache.py
class DoubleLinkedNode: def __init__(self, key, value): self.key = key self.value = value self.pre = None self.next = None class LRUCache: def __init__(self, capacity): """ :type capacity: int """ self.capacity = capacity self.kv = dict()...
0.661595
0.327964
import os.path as osp from jacinle.cli.argument import JacArgumentParser from jacinle.logging import get_logger from jacinle.utils.container import GView from jacinle.utils.meter import GroupMeters from jacinle.utils.tqdm import tqdm_gofor, get_current_tqdm from nscl.datasets import get_available_symbolic_datasets, in...
scripts/run-symbolic-executor.py
import os.path as osp from jacinle.cli.argument import JacArgumentParser from jacinle.logging import get_logger from jacinle.utils.container import GView from jacinle.utils.meter import GroupMeters from jacinle.utils.tqdm import tqdm_gofor, get_current_tqdm from nscl.datasets import get_available_symbolic_datasets, in...
0.257672
0.108378
import json from fuzzywuzzy import fuzz from utils import db, dt from utils.cache import cache from gig._constants import GIG_CACHE_NAME, GIG_CACHE_TIMEOUT from gig._remote_data import _get_remote_tsv_data from gig.ent_types import ENTITY_TYPE, get_entity_type @cache(GIG_CACHE_NAME, GIG_CACHE_TIMEOUT) def get_entit...
src/gig/ents.py
import json from fuzzywuzzy import fuzz from utils import db, dt from utils.cache import cache from gig._constants import GIG_CACHE_NAME, GIG_CACHE_TIMEOUT from gig._remote_data import _get_remote_tsv_data from gig.ent_types import ENTITY_TYPE, get_entity_type @cache(GIG_CACHE_NAME, GIG_CACHE_TIMEOUT) def get_entit...
0.590071
0.210644
import re from typing import List def find_indexes(haystack: List[str], regex: str) -> List[int]: """ Find indexes in a list where a regular expression matches. Parameters ---------- haystack List of strings. regex Regular expression to match. Returns ------- ...
markdownreveal/tweak.py
import re from typing import List def find_indexes(haystack: List[str], regex: str) -> List[int]: """ Find indexes in a list where a regular expression matches. Parameters ---------- haystack List of strings. regex Regular expression to match. Returns ------- ...
0.656548
0.374448
from os import uname from machine import SPI, Pin, I2C, SoftSPI from micropython import const from machine import UART __version__ = "0.1.2.0" # ---------------------------------------------------------------------------- class SPIBus(object): """SPI bus access.""" def __init__(self, freq, sck, sdo, sdi=None, sp...
platform/esp32/busio.py
from os import uname from machine import SPI, Pin, I2C, SoftSPI from micropython import const from machine import UART __version__ = "0.1.2.0" # ---------------------------------------------------------------------------- class SPIBus(object): """SPI bus access.""" def __init__(self, freq, sck, sdo, sdi=None, sp...
0.700588
0.158272
import socket import time import logging from dnslib import * from treelib import Tree udp_socket = socket.socket(type=socket.SOCK_DGRAM) udp_socket.bind(("127.0.0.1", 53)) cache = Tree() ROOT_IP = ["192.168.3.11", "172.16.58.3", "192.168.3.11", "192.168.127.12", "172.16....
main.py
import socket import time import logging from dnslib import * from treelib import Tree udp_socket = socket.socket(type=socket.SOCK_DGRAM) udp_socket.bind(("127.0.0.1", 53)) cache = Tree() ROOT_IP = ["192.168.3.11", "172.16.58.3", "192.168.3.11", "192.168.127.12", "172.16....
0.236252
0.187337
import multiprocessing as mp from pretraining.pretraining_example import create_example, create_context class AlbertDataWorker(mp.Process): def __init__(self, idx, config, inqueue, outqueue, *args, **kwargs): super(AlbertDataWorker, self).__init__(*args, **kwargs) self.idx = idx self.con...
pretraining/albert_datagen.py
import multiprocessing as mp from pretraining.pretraining_example import create_example, create_context class AlbertDataWorker(mp.Process): def __init__(self, idx, config, inqueue, outqueue, *args, **kwargs): super(AlbertDataWorker, self).__init__(*args, **kwargs) self.idx = idx self.con...
0.488771
0.077588
import biplist import code_resources from exceptions import NotMatched import copy import glob import logging import os from os.path import basename, exists, join, splitext import signable import shutil log = logging.getLogger(__name__) class Bundle(object): """ A bundle is a standard directory structure, a sign...
isign/bundle.py
import biplist import code_resources from exceptions import NotMatched import copy import glob import logging import os from os.path import basename, exists, join, splitext import signable import shutil log = logging.getLogger(__name__) class Bundle(object): """ A bundle is a standard directory structure, a sign...
0.269614
0.122786
from py_ecc import optimized_bls12_381 as b from fft import fft from poly_utils import PrimeField from multicombs import lincomb from verkle import WIDTH, DEPTH, MODULUS, root_of_unity_candidates, ROOT_OF_UNITY import time ROOT_OF_UNITY2 = root_of_unity_candidates[WIDTH*2] # default O(n^2) algorithm def semi_toepli...
verkle/fk20.py
from py_ecc import optimized_bls12_381 as b from fft import fft from poly_utils import PrimeField from multicombs import lincomb from verkle import WIDTH, DEPTH, MODULUS, root_of_unity_candidates, ROOT_OF_UNITY import time ROOT_OF_UNITY2 = root_of_unity_candidates[WIDTH*2] # default O(n^2) algorithm def semi_toepli...
0.517083
0.508483
import re import sys from datetime import datetime def main(filename): git_log_text = "" with open(filename, "r") as file: git_log_text = file.read() result = process_git_log(git_log_text) print(result) def strip_timezone_offset(timestamp_str): timezone_offset_pattern = "[+\-][0-9][0-9]...
git_log_to_csv.py
import re import sys from datetime import datetime def main(filename): git_log_text = "" with open(filename, "r") as file: git_log_text = file.read() result = process_git_log(git_log_text) print(result) def strip_timezone_offset(timestamp_str): timezone_offset_pattern = "[+\-][0-9][0-9]...
0.234582
0.164148
import numpy as np import statsmodels as sm from ThymeBoost.trend_models.trend_base_class import TrendBaseModel from pmdarima.arima import auto_arima class ArimaModel(TrendBaseModel): """ARIMA Model from Statsmodels""" model = 'arima' def __init__(self): self.model_params = None self.fitte...
ThymeBoost/trend_models/arima_trend.py
import numpy as np import statsmodels as sm from ThymeBoost.trend_models.trend_base_class import TrendBaseModel from pmdarima.arima import auto_arima class ArimaModel(TrendBaseModel): """ARIMA Model from Statsmodels""" model = 'arima' def __init__(self): self.model_params = None self.fitte...
0.821223
0.402157
import math import numpy as np import pandas as pd import argparse from util import get_input_label_split, get_accuracy, get_precision, discretize class NBC: def __init__(self): self.train_data = None self.label = '' self.classes = set() self.prob = {} self.is_discrete = se...
classification/naive_bayes_clas.py
import math import numpy as np import pandas as pd import argparse from util import get_input_label_split, get_accuracy, get_precision, discretize class NBC: def __init__(self): self.train_data = None self.label = '' self.classes = set() self.prob = {} self.is_discrete = se...
0.501465
0.333069
#Copyright 2015 RAPP #Licensed under the Apache License, Version 2.0 (the "License"); #you may not use this file except in compliance with the License. #You may obtain a copy of the License at #http://www.apache.org/licenses/LICENSE-2.0 #Unless required by applicable law or agreed to in writing, software #distr...
rapp_hazard_detection/tests/hazard_detection/functional_tests.py
#Copyright 2015 RAPP #Licensed under the Apache License, Version 2.0 (the "License"); #you may not use this file except in compliance with the License. #You may obtain a copy of the License at #http://www.apache.org/licenses/LICENSE-2.0 #Unless required by applicable law or agreed to in writing, software #distr...
0.58676
0.247703
from enum import IntEnum, Enum # Depending modules import six __all__ = [ 'SubscriptionStatus', 'SocketStatus', 'MessageTypes' ] class SubscriptionStatus(IntEnum): PENDING = 1 CONNECTED = 2 CLOSING = 3 CLOSED = 4 FAILED = 5 class SocketStatus(IntEnum): CONNECTING = 1 READY = ...
appsync_subscription_manager/types.py
from enum import IntEnum, Enum # Depending modules import six __all__ = [ 'SubscriptionStatus', 'SocketStatus', 'MessageTypes' ] class SubscriptionStatus(IntEnum): PENDING = 1 CONNECTED = 2 CLOSING = 3 CLOSED = 4 FAILED = 5 class SocketStatus(IntEnum): CONNECTING = 1 READY = ...
0.5144
0.074131
import time from typing import ( Any, Callable, Coroutine, Dict, ) # Third party libraries import graphene from graphql.execution.executors.asyncio import AsyncioExecutor from starlette.applications import Starlette from starlette.graphql import GraphQLApp from starlette.middleware import Middleware fro...
server/server/asgi.py
import time from typing import ( Any, Callable, Coroutine, Dict, ) # Third party libraries import graphene from graphql.execution.executors.asyncio import AsyncioExecutor from starlette.applications import Starlette from starlette.graphql import GraphQLApp from starlette.middleware import Middleware fro...
0.51562
0.110519
import argparse import csv import logging import json from util.parse import parse_package_details, parse_package_to_repos_file from datetime import datetime logging.basicConfig(level=logging.INFO, format='%(asctime)s | [%(levelname)s] : %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') parser = argparse.Argumen...
helpers/get_matched_metadata.py
import argparse import csv import logging import json from util.parse import parse_package_details, parse_package_to_repos_file from datetime import datetime logging.basicConfig(level=logging.INFO, format='%(asctime)s | [%(levelname)s] : %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') parser = argparse.Argumen...
0.320502
0.079317
import re import secrets import string from typing import Mapping from typing import Optional from typing import Sequence from typing import Tuple from typing import TYPE_CHECKING from pyrsistent import field from pyrsistent import m from pyrsistent import PMap from pyrsistent import pmap from pyrsistent import PVecto...
task_processing/plugins/kubernetes/task_config.py
import re import secrets import string from typing import Mapping from typing import Optional from typing import Sequence from typing import Tuple from typing import TYPE_CHECKING from pyrsistent import field from pyrsistent import m from pyrsistent import PMap from pyrsistent import pmap from pyrsistent import PVecto...
0.773644
0.266044
from django.db import models class Role(models.Model): name = models.CharField(verbose_name='name', max_length=40, primary_key=True) description = models.CharField(verbose_name='description', max_length=100) functions = models.CharField(verbose_name='functions', max_length=500) class Right(models.Model)...
app/models.py
from django.db import models class Role(models.Model): name = models.CharField(verbose_name='name', max_length=40, primary_key=True) description = models.CharField(verbose_name='description', max_length=100) functions = models.CharField(verbose_name='functions', max_length=500) class Right(models.Model)...
0.485356
0.187058
from django.test import TestCase from .models import UserProfile class TestUserProfileModel(TestCase): def setUp(self): UserProfile.objects.create( default_full_name='test default full name', default_phone_number='test default phone number', default_street_address1='te...
profiles/test_models_profiles.py
from django.test import TestCase from .models import UserProfile class TestUserProfileModel(TestCase): def setUp(self): UserProfile.objects.create( default_full_name='test default full name', default_phone_number='test default phone number', default_street_address1='te...
0.647464
0.158532
import os from pybuildtool import BaseTask, expand_resource tool_name = __name__ class Task(BaseTask): name = tool_name workdir = None def prepare(self): cfg = self.conf args = self.args c = cfg.get('work_dir') if c: self.workdir = expand_reso...
pybuildtool/tools/webpack.py
import os from pybuildtool import BaseTask, expand_resource tool_name = __name__ class Task(BaseTask): name = tool_name workdir = None def prepare(self): cfg = self.conf args = self.args c = cfg.get('work_dir') if c: self.workdir = expand_reso...
0.167219
0.045628
import click import numpy as np import rasterio from scipy.stats import mode from rio_alpha.utils import ( _convert_rgb, _compute_continuous, _debug_mode, _search_image_edge, _evaluate_count, ) def discover_ndv(rgb_orig, debug, verbose): """Returns nodata value by calculating mode of RGB arr...
rio_alpha/findnodata.py
import click import numpy as np import rasterio from scipy.stats import mode from rio_alpha.utils import ( _convert_rgb, _compute_continuous, _debug_mode, _search_image_edge, _evaluate_count, ) def discover_ndv(rgb_orig, debug, verbose): """Returns nodata value by calculating mode of RGB arr...
0.651466
0.382084
import json import io import datetime import logging import boto3 import pandas import altair from shared import S3_scraper_index from twitter_shared import TwitterAPI from plot_shared import get_chrome_driver good_symb = '\u2193' bad_symb = '\u2191' def colclean(old): for name in ['Hospital', 'Care Home', 'Hos...
sam/nisra-tweeter/app.py
import json import io import datetime import logging import boto3 import pandas import altair from shared import S3_scraper_index from twitter_shared import TwitterAPI from plot_shared import get_chrome_driver good_symb = '\u2193' bad_symb = '\u2191' def colclean(old): for name in ['Hospital', 'Care Home', 'Hos...
0.372163
0.135747
import unittest import os from dao.text_contents_dao import TextContentsDAO class TestTextContentsDAO(unittest.TestCase): def setUp(self): self.db_addr = "database/test_db.db" os.popen(f"sqlite3 {self.db_addr} < database/schema.sql") self.text_contents_dao = TextContentsDAO(self.db_addr) ...
src/tests/dao_test/text_contents_dao_test.py
import unittest import os from dao.text_contents_dao import TextContentsDAO class TestTextContentsDAO(unittest.TestCase): def setUp(self): self.db_addr = "database/test_db.db" os.popen(f"sqlite3 {self.db_addr} < database/schema.sql") self.text_contents_dao = TextContentsDAO(self.db_addr) ...
0.376967
0.188716
import os import optparse import pkg_resources import subprocess import sys import zc.buildout.easy_install import zc.recipe.egg class TagsMaker(object): def __init__(self, buildout, name, options): self.buildout = buildout self.name = name self.options = options # We do this ear...
src/z3c/recipe/tag/__init__.py
import os import optparse import pkg_resources import subprocess import sys import zc.buildout.easy_install import zc.recipe.egg class TagsMaker(object): def __init__(self, buildout, name, options): self.buildout = buildout self.name = name self.options = options # We do this ear...
0.279828
0.080574
import aws_handler import simple_logger logger = simple_logger.logger() logger.info('runnint test.py') # key = "dev-client-ben/library/draft/040117_Gemtone_Radiant_Nude_OPP_2_page.pdf" # key = "dev-client-ben/library/draft/sub_folder/2016_BASF_CC_LysSun_TPP.pdf" # key = "dev-client-ben/library/draft/AAssembled.pdf" #...
functions/simple/test.py
import aws_handler import simple_logger logger = simple_logger.logger() logger.info('runnint test.py') # key = "dev-client-ben/library/draft/040117_Gemtone_Radiant_Nude_OPP_2_page.pdf" # key = "dev-client-ben/library/draft/sub_folder/2016_BASF_CC_LysSun_TPP.pdf" # key = "dev-client-ben/library/draft/AAssembled.pdf" #...
0.353875
0.14817
import numpy as np from scipy.ndimage import rotate def check_extent(n, f, e): if f > n: d = f - n f = n e = e - d return (e, f) def make_patches(image, patch_shape=(8, 256, 256)): nz, nc, ny, nx = image.shape ez = 0 ex = 0 ey = 0 dz, dy, dx = patch_shape patch...
PrepTrainingSet/make_patches_3d.py
import numpy as np from scipy.ndimage import rotate def check_extent(n, f, e): if f > n: d = f - n f = n e = e - d return (e, f) def make_patches(image, patch_shape=(8, 256, 256)): nz, nc, ny, nx = image.shape ez = 0 ex = 0 ey = 0 dz, dy, dx = patch_shape patch...
0.250088
0.324663
import os import random import django import djangae.environment from djangae.settings_base import * # noqa # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs....
testprodapp/testapp/settings.py
import os import random import django import djangae.environment from djangae.settings_base import * # noqa # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs....
0.30549
0.058912
import mysql.connector import pandas as pd from sklearn import preprocessing class ReadDB: def __init__(self, *, config, db_config): self.config = config self.db_config = db_config METHOD_COLUMNS = { 'pi': { 'pi_openness': 'PI_Openness', 'pi_conscientiousness'...
stats/db.py
import mysql.connector import pandas as pd from sklearn import preprocessing class ReadDB: def __init__(self, *, config, db_config): self.config = config self.db_config = db_config METHOD_COLUMNS = { 'pi': { 'pi_openness': 'PI_Openness', 'pi_conscientiousness'...
0.472683
0.263037
import nltk from nltk.collocations import BigramCollocationFinder from nltk.tokenize.regexp import RegexpTokenizer def get_bigram_likelihood(statements, stopwords=[], freq_filter=3, nbest=200): """ Returns n (likelihood ratio) bi-grams from a group of documents :param statements: list of st...
external_sources.py
import nltk from nltk.collocations import BigramCollocationFinder from nltk.tokenize.regexp import RegexpTokenizer def get_bigram_likelihood(statements, stopwords=[], freq_filter=3, nbest=200): """ Returns n (likelihood ratio) bi-grams from a group of documents :param statements: list of st...
0.374562
0.261127
from neomodel import (db, StructuredNode, StringProperty, IntegerProperty, FloatProperty, ArrayProperty, RelationshipTo, RelationshipFrom, StructuredRel) from metrics import metrics_query_latency, metrics_query_in_progress, metrics_query_count class Has(StructuredRel): units = IntegerPropert...
app/models/products.py
from neomodel import (db, StructuredNode, StringProperty, IntegerProperty, FloatProperty, ArrayProperty, RelationshipTo, RelationshipFrom, StructuredRel) from metrics import metrics_query_latency, metrics_query_in_progress, metrics_query_count class Has(StructuredRel): units = IntegerPropert...
0.688887
0.213931
from flexbe_core import Behavior, Autonomy, OperatableStateMachine, ConcurrencyContainer, PriorityContainer, Logger from sonia_hardware_states.wait_mission import wait_mission from sonia_navigation_states.add_pose_to_trajectory import add_pose_to_trajectory from sonia_navigation_states.init_trajectory import init_traj...
sonia_flexbe_behaviors/src/sonia_flexbe_behaviors/mission_bags_bins_sm.py
from flexbe_core import Behavior, Autonomy, OperatableStateMachine, ConcurrencyContainer, PriorityContainer, Logger from sonia_hardware_states.wait_mission import wait_mission from sonia_navigation_states.add_pose_to_trajectory import add_pose_to_trajectory from sonia_navigation_states.init_trajectory import init_traj...
0.406509
0.24116
import unittest import os, sys test_dir = os.path.dirname(__file__) src_dir = "../" sys.path.insert(0, os.path.abspath(os.path.join(test_dir, src_dir))) from bank.accounts import Accounts, CheckingAccount, SavingsAccount from bank.account_holder import AccountHolder from bank.banks import Bank from bank.cards import ...
tests/project_requirements_test.py
import unittest import os, sys test_dir = os.path.dirname(__file__) src_dir = "../" sys.path.insert(0, os.path.abspath(os.path.join(test_dir, src_dir))) from bank.accounts import Accounts, CheckingAccount, SavingsAccount from bank.account_holder import AccountHolder from bank.banks import Bank from bank.cards import ...
0.414425
0.464902
from railrl.launchers.vae_exp_launcher_util import ( train_vae, train_reprojection_network_and_update_variant, ) from railrl.launchers.rl_exp_launcher_util import ( tdm_td3_experiment, tdm_twin_sac_experiment, ih_td3_experiment, ih_twin_sac_experiment, ) def tdm_experiment(variant): experi...
railrl/launchers/exp_launcher.py
from railrl.launchers.vae_exp_launcher_util import ( train_vae, train_reprojection_network_and_update_variant, ) from railrl.launchers.rl_exp_launcher_util import ( tdm_td3_experiment, tdm_twin_sac_experiment, ih_td3_experiment, ih_twin_sac_experiment, ) def tdm_experiment(variant): experi...
0.482429
0.166743
from pathlib import Path from pprint import pprint import click from click import style import tabulate as tabulate_module from tabulate import tabulate from .app import App from .objects import LogLine from .requests import (CommitRequest, DeploysRequest, JobsRequest, JobLogRequest, PagesReque...
ghp/cli.py
from pathlib import Path from pprint import pprint import click from click import style import tabulate as tabulate_module from tabulate import tabulate from .app import App from .objects import LogLine from .requests import (CommitRequest, DeploysRequest, JobsRequest, JobLogRequest, PagesReque...
0.25488
0.171442
from hailtop.utils import (partition, url_basename, url_join, url_scheme, url_and_params, parse_docker_image_reference, grouped) from hailtop.utils.utils import digits_needed, unzip, filter_none, flatten def test_partition_zero_empty(): assert list(partition(0, [])) == [] def test_par...
hail/python/test/hailtop/utils/test_utils.py
from hailtop.utils import (partition, url_basename, url_join, url_scheme, url_and_params, parse_docker_image_reference, grouped) from hailtop.utils.utils import digits_needed, unzip, filter_none, flatten def test_partition_zero_empty(): assert list(partition(0, [])) == [] def test_par...
0.630344
0.637334
import pathlib import uuid import astropy.units as u from specutils import Spectrum1D, SpectrumCollection, SpectralRegion from jdaviz.core.helpers import ConfigHelper class SpecViz(ConfigHelper): """SpecViz Helper class""" _default_configuration = 'specviz' def load_data(self, data, data_label=None, f...
jdaviz/configs/specviz/helper.py
import pathlib import uuid import astropy.units as u from specutils import Spectrum1D, SpectrumCollection, SpectralRegion from jdaviz.core.helpers import ConfigHelper class SpecViz(ConfigHelper): """SpecViz Helper class""" _default_configuration = 'specviz' def load_data(self, data, data_label=None, f...
0.789964
0.342159
import logging import os import re import yaml from BackgroundApp import logging_conf # noqa # nopep8 os.environ["KCFG_KIVY_LOG_LEVEL"] = logging_conf["root"]["level"].lower() # noqa # nopep8 from kivy.app import App # noqa from kivy.clock import Clock # noqa from kivy.config import Config # noqa from kivy.proper...
SettingsApp.py
import logging import os import re import yaml from BackgroundApp import logging_conf # noqa # nopep8 os.environ["KCFG_KIVY_LOG_LEVEL"] = logging_conf["root"]["level"].lower() # noqa # nopep8 from kivy.app import App # noqa from kivy.clock import Clock # noqa from kivy.config import Config # noqa from kivy.proper...
0.390708
0.059921
import argparse def get_args(): parser = argparse.ArgumentParser(description='OWTF WAF-BYPASSER MODULE') parser.add_argument("-X", "--method", dest="METHODS", action='store', nargs="+", hel...
framework/http/wafbypasser/core/argument_parser.py
import argparse def get_args(): parser = argparse.ArgumentParser(description='OWTF WAF-BYPASSER MODULE') parser.add_argument("-X", "--method", dest="METHODS", action='store', nargs="+", hel...
0.605449
0.159217
from refextract import extract_references_from_file from refextract import extract_references_from_string from pathlib2 import Path import re import sys sys.path.insert(0,'../') sys.path.insert(0,'../database_queries/') from models import Biblio from database_queries_biblio import * def array_to_semicolon_separated...
extract_references/test_extract_references.py
from refextract import extract_references_from_file from refextract import extract_references_from_string from pathlib2 import Path import re import sys sys.path.insert(0,'../') sys.path.insert(0,'../database_queries/') from models import Biblio from database_queries_biblio import * def array_to_semicolon_separated...
0.179567
0.225097