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 ...rl import Policy import warnings import numpy as np class Heading(Policy): """ePuck policy with the heading as action. Due to historical reasons, it is up to the implementation of the robot to interprete the action (i.e. if it's considered relative or absolute). Note that since We...
HDPy/epuck/policy/policies.py
from ...rl import Policy import warnings import numpy as np class Heading(Policy): """ePuck policy with the heading as action. Due to historical reasons, it is up to the implementation of the robot to interprete the action (i.e. if it's considered relative or absolute). Note that since We...
0.783492
0.500549
import os, sys import subprocess, shlex import lmdb import multiprocessing as mp import numpy as np def read_lmdb(args): lmdb_path, delete = args[:] env = lmdb.open(lmdb_path, readahead=False, readonly=True, writemap=False, lock=False) num_samples = env.stat()['entries'] - 4 ## TODO: remove hard-coded # of...
scripts/summit_scripts/tally_lmdb.py
import os, sys import subprocess, shlex import lmdb import multiprocessing as mp import numpy as np def read_lmdb(args): lmdb_path, delete = args[:] env = lmdb.open(lmdb_path, readahead=False, readonly=True, writemap=False, lock=False) num_samples = env.stat()['entries'] - 4 ## TODO: remove hard-coded # of...
0.104924
0.199113
import json import os import threading import boto3 from aws_lambda_powertools import Logger, Metrics, Tracer from boto3.dynamodb.conditions import Key from shared import generate_ttl, get_cart_id, get_headers, handle_decimal_type logger = Logger() # tracer = Tracer() metrics = Metrics() dynamodb = boto3.resource("...
backend/shopping-cart-service/migrate_cart.py
import json import os import threading import boto3 from aws_lambda_powertools import Logger, Metrics, Tracer from boto3.dynamodb.conditions import Key from shared import generate_ttl, get_cart_id, get_headers, handle_decimal_type logger = Logger() # tracer = Tracer() metrics = Metrics() dynamodb = boto3.resource("...
0.410047
0.131842
import hashlib import os import sys import msgpack from struct import pack addressChecksumLength = 4 def int64ToBinary(i): # TODO: error handling # >q means big endian, long long (int64) return pack(">q", i) def intToBytes(i): return bytes([i]) def sha256(data): return hashData(...
pychain/util.py
import hashlib import os import sys import msgpack from struct import pack addressChecksumLength = 4 def int64ToBinary(i): # TODO: error handling # >q means big endian, long long (int64) return pack(">q", i) def intToBytes(i): return bytes([i]) def sha256(data): return hashData(...
0.161188
0.138287
import numpy as np ### Minecraft Notations malmo_object_to_index = { # Basics 'air' : 1, 'wooden_door' : 2, # 'wool' : 3, wall : 4, 'lever' : 5, # 'ball': 6,'box' : 7, # 'goal': 8, 'fire' : ...
gym_minigrid/index_mapping.py
import numpy as np ### Minecraft Notations malmo_object_to_index = { # Basics 'air' : 1, 'wooden_door' : 2, # 'wool' : 3, wall : 4, 'lever' : 5, # 'ball': 6,'box' : 7, # 'goal': 8, 'fire' : ...
0.314366
0.212865
import numpy as np class Point(object): def __init__(self, x=0, y=0): self.x = x self.y = y class Line(object): # 直线由两个点组成 def __init__(self, p1=Point(0, 0), p2=Point(2, 2)): self.p1 = p1 self.p2 = p2 def distance_point_to_line(self, current_line, mainline): an...
find_angle.py
import numpy as np class Point(object): def __init__(self, x=0, y=0): self.x = x self.y = y class Line(object): # 直线由两个点组成 def __init__(self, p1=Point(0, 0), p2=Point(2, 2)): self.p1 = p1 self.p2 = p2 def distance_point_to_line(self, current_line, mainline): an...
0.311113
0.287115
from mongoengine import ( Document, EmbeddedDocument, DynamicEmbeddedDocument, DynamicDocument, StringField, IntField, BooleanField, DateTimeField, ListField, DictField, EmbeddedDocumentField ) class Crontab(EmbeddedDocument): minute = StringField(default='*', required=True, description='CRON minu...
graphene_mongoengine/tests/models.py
from mongoengine import ( Document, EmbeddedDocument, DynamicEmbeddedDocument, DynamicDocument, StringField, IntField, BooleanField, DateTimeField, ListField, DictField, EmbeddedDocumentField ) class Crontab(EmbeddedDocument): minute = StringField(default='*', required=True, description='CRON minu...
0.725746
0.235086
from typing import List import torch import torch.nn.functional as f from einops import rearrange from torch import nn, einsum, Tensor from torch.nn import Softmax class Residual(nn.Module): """Define a residual block given a Pytorch Module, used for the skip connection""" def __init__(self, fn: nn.Module): ...
src/lit_saint/modules.py
from typing import List import torch import torch.nn.functional as f from einops import rearrange from torch import nn, einsum, Tensor from torch.nn import Softmax class Residual(nn.Module): """Define a residual block given a Pytorch Module, used for the skip connection""" def __init__(self, fn: nn.Module): ...
0.963916
0.685483
import logging import socket import time from .client_errors import ClientTimeoutError class TcpClient: """A tcp client Attributes ---------- host : str The ip address of the tcp server. port : int The port of the tcp server. auto_reconnect : bool If true, a reconnect...
src/pyTCP/client.py
import logging import socket import time from .client_errors import ClientTimeoutError class TcpClient: """A tcp client Attributes ---------- host : str The ip address of the tcp server. port : int The port of the tcp server. auto_reconnect : bool If true, a reconnect...
0.821689
0.285901
from app import create_app from app.models import db from config.dev import Config from app.models.admin import Admin, AdminTypeEnum from app.models.info import Info from werkzeug.security import generate_password_hash import unittest import json app = create_app(Config) class BaseTestCase(unittest.TestCase): d...
Server/test/__init__.py
from app import create_app from app.models import db from config.dev import Config from app.models.admin import Admin, AdminTypeEnum from app.models.info import Info from werkzeug.security import generate_password_hash import unittest import json app = create_app(Config) class BaseTestCase(unittest.TestCase): d...
0.532425
0.101545
import matplotlib.pyplot as plt import numpy as np from units import conv_unit class VLEBinaryMixturePlot: def __init__(self, diagtype, var, x, y, varunit, title, plottype="both"): self.diagtype = diagtype self.var = var self.x = x self.y = y self.varunit = varunit ...
Sindri/VLEBinaryDiagrams.py
import matplotlib.pyplot as plt import numpy as np from units import conv_unit class VLEBinaryMixturePlot: def __init__(self, diagtype, var, x, y, varunit, title, plottype="both"): self.diagtype = diagtype self.var = var self.x = x self.y = y self.varunit = varunit ...
0.499756
0.408985
from .exceptions import PilosaError from .internal import public_pb2 as internal __all__ = ("RowResult", "CountResultItem", "QueryResult", "ColumnItem", "QueryResponse") QUERYRESULT_NONE, QUERYRESULT_ROW, QUERYRESULT_PAIRS, \ QUERYRESULT_VAL_COUNT, QUERYRESULT_INT, QUERYRESULT_BOOL, \ QUERYRESULT_ROW_IDS,\ QUERYRE...
pilosa/response.py
from .exceptions import PilosaError from .internal import public_pb2 as internal __all__ = ("RowResult", "CountResultItem", "QueryResult", "ColumnItem", "QueryResponse") QUERYRESULT_NONE, QUERYRESULT_ROW, QUERYRESULT_PAIRS, \ QUERYRESULT_VAL_COUNT, QUERYRESULT_INT, QUERYRESULT_BOOL, \ QUERYRESULT_ROW_IDS,\ QUERYRE...
0.752559
0.216902
import math from PIL import Image, ImageDraw hex_map = { 0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f', } def mm(pixels, dpi): """ Return the length in millimet...
lcutil/util_image.py
import math from PIL import Image, ImageDraw hex_map = { 0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f', } def mm(pixels, dpi): """ Return the length in millimet...
0.823257
0.816918
from onlinejudge_verify.online_submission.submissions import * from requests import session import requests import mechanize from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By...
onlinejudge_verify/online_submission/judges.py
from onlinejudge_verify.online_submission.submissions import * from requests import session import requests import mechanize from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By...
0.413596
0.129871
import pytest from anoncreds.protocol.issuer import Issuer from anoncreds.protocol.repo.attributes_repo import AttributeRepoInMemory from anoncreds.protocol.types import ClaimDefinition, ID from anoncreds.protocol.wallet.issuer_wallet import IssuerWalletInMemory from sovrin.anon_creds.sovrin_public_repo import SovrinP...
sovrin/test/anon_creds/test_public_repo.py
import pytest from anoncreds.protocol.issuer import Issuer from anoncreds.protocol.repo.attributes_repo import AttributeRepoInMemory from anoncreds.protocol.types import ClaimDefinition, ID from anoncreds.protocol.wallet.issuer_wallet import IssuerWalletInMemory from sovrin.anon_creds.sovrin_public_repo import SovrinP...
0.394318
0.322059
import items_setup as item_s import shops_setup as shop_s ARMOR = { 1000: "Shaved", 1100: "Receding", 1200: "Short", 1300: "Swept Back", 1400: "Ponytail", 1500: "Wild", 1600: "Parted Center", 1700: "Semi-Long", 1800: "Curly", 1900: "Bobbed", 2000: "Male 11", 2100: "Male 12", 2200: "Male 13", ...
item_lot_formatter.py
import items_setup as item_s import shops_setup as shop_s ARMOR = { 1000: "Shaved", 1100: "Receding", 1200: "Short", 1300: "Swept Back", 1400: "Ponytail", 1500: "Wild", 1600: "Parted Center", 1700: "Semi-Long", 1800: "Curly", 1900: "Bobbed", 2000: "Male 11", 2100: "Male 12", 2200: "Male 13", ...
0.319121
0.513181
from __future__ import absolute_import from __future__ import unicode_literals import sys import os ROOT_DIR = os.getenv('PLASTICC_DIR') WORK_DIR = os.path.join(ROOT_DIR, 'plasticc') DATA_DIR = os.path.join(ROOT_DIR, 'plasticc_data') sys.path.append(WORK_DIR) import numpy as np import ANTARES_object import plasticc i...
bin/make_rate_vs_redshift.py
from __future__ import absolute_import from __future__ import unicode_literals import sys import os ROOT_DIR = os.getenv('PLASTICC_DIR') WORK_DIR = os.path.join(ROOT_DIR, 'plasticc') DATA_DIR = os.path.join(ROOT_DIR, 'plasticc_data') sys.path.append(WORK_DIR) import numpy as np import ANTARES_object import plasticc i...
0.302597
0.142053
import json from asyncio import sleep from datetime import datetime from itertools import chain from pathlib import Path import jsonpickle from loguru import logger from telethon import TelegramClient from telethon.tl.functions.channels import CreateChannelRequest, ReadHistoryRequest from telethon.tl.functions.message...
tgfeed/__main__.py
import json from asyncio import sleep from datetime import datetime from itertools import chain from pathlib import Path import jsonpickle from loguru import logger from telethon import TelegramClient from telethon.tl.functions.channels import CreateChannelRequest, ReadHistoryRequest from telethon.tl.functions.message...
0.453746
0.064772
import inspect from functools import partial from graphql import ( default_type_resolver, get_introspection_query, graphql, graphql_sync, introspection_types, is_type, print_schema, GraphQLArgument, GraphQLBoolean, GraphQLEnumValue, GraphQLField, GraphQLFloat, GraphQ...
graphene/types/schema.py
import inspect from functools import partial from graphql import ( default_type_resolver, get_introspection_query, graphql, graphql_sync, introspection_types, is_type, print_schema, GraphQLArgument, GraphQLBoolean, GraphQLEnumValue, GraphQLField, GraphQLFloat, GraphQ...
0.685318
0.206014
import ctypes from ctypes.wintypes import WPARAM, LPARAM, MSG WH_GETMESSAGE = 3 hook_handle = None hook_callback = None def message_hook_func(code, wParam, lParam): if hook_callback is not None: msg = ctypes.cast(lParam, ctypes.POINTER(MSG)) hook_callback(msg[0].hWnd, msg[0].messag...
Data/Packages/IMESupport/imesupport/messagehook.py
import ctypes from ctypes.wintypes import WPARAM, LPARAM, MSG WH_GETMESSAGE = 3 hook_handle = None hook_callback = None def message_hook_func(code, wParam, lParam): if hook_callback is not None: msg = ctypes.cast(lParam, ctypes.POINTER(MSG)) hook_callback(msg[0].hWnd, msg[0].messag...
0.360264
0.058212
import json, traceback import os import platform import random import sys import aiofiles import disnake from disnake.ext import commands, tasks from disnake.ext.commands import slash_command, user_command, message_command from datetime import datetime from keep_alive import keep_alive os.system('clear') if os.path.e...
main.py
import json, traceback import os import platform import random import sys import aiofiles import disnake from disnake.ext import commands, tasks from disnake.ext.commands import slash_command, user_command, message_command from datetime import datetime from keep_alive import keep_alive os.system('clear') if os.path.e...
0.21767
0.130147
from torchvision.utils import make_grid from PIL import Image import torch import shutil import re import cv2 as cv import numpy as np import os from setting import INPUT_DIR, TRAIN_DIR # 图像形态学的卷积核,可自定义或者使用api kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (25, 25)) dCount = 6 # 膨胀次数 eCount = 1 # 腐蚀次数 # 图像预处...
aae_hash/utils.py
from torchvision.utils import make_grid from PIL import Image import torch import shutil import re import cv2 as cv import numpy as np import os from setting import INPUT_DIR, TRAIN_DIR # 图像形态学的卷积核,可自定义或者使用api kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (25, 25)) dCount = 6 # 膨胀次数 eCount = 1 # 腐蚀次数 # 图像预处...
0.205256
0.183173
import argparse as argparse import logging from tempfile import TemporaryDirectory from threading import Thread import msgpack import zmq from dpu_utils.utils import RichPath, run_and_debug from buglab.utils.logging import MetricProvider, configure_logging from buglab.utils.msgpackutils import load_all_msgpack_l_gz f...
buglab/controllers/detectortrainingdatabuffer.py
import argparse as argparse import logging from tempfile import TemporaryDirectory from threading import Thread import msgpack import zmq from dpu_utils.utils import RichPath, run_and_debug from buglab.utils.logging import MetricProvider, configure_logging from buglab.utils.msgpackutils import load_all_msgpack_l_gz f...
0.533884
0.118156
from text_utils.pronunciation.arpa_symbols import ALL_ARPA_INCL_STRESSES from text_utils.pronunciation.ARPAToIPAMapper import ( __ARPABET_IPA_MAP, symbol_map_arpa_to_ipa, symbols_map_arpa_to_ipa, symbols_remove_non_arpa_symbols) def test_symbols_remove_non_arpa_symbols(): symbols = ('DH', 'IH0', 'S', ' ', '...
src/text_utils_tests/pronunciation/test_ARPAToIPAMapper.py
from text_utils.pronunciation.arpa_symbols import ALL_ARPA_INCL_STRESSES from text_utils.pronunciation.ARPAToIPAMapper import ( __ARPABET_IPA_MAP, symbol_map_arpa_to_ipa, symbols_map_arpa_to_ipa, symbols_remove_non_arpa_symbols) def test_symbols_remove_non_arpa_symbols(): symbols = ('DH', 'IH0', 'S', ' ', '...
0.643217
0.437103
import dsz, dsz.cmd, dsz.control import ops, ops.pprint import ops.data import traceback, sys from optparse import OptionParser def monitorlogs(interval=300, classic=False, logname='', target=None, filters=[]): logquerycmd = 'eventlogquery ' if classic: logquerycmd += ' -classic ' elif (logname != ...
Leak #5 - Lost In Translation/windows/Resources/Ops/PyScripts/windows/eventlogs.py
import dsz, dsz.cmd, dsz.control import ops, ops.pprint import ops.data import traceback, sys from optparse import OptionParser def monitorlogs(interval=300, classic=False, logname='', target=None, filters=[]): logquerycmd = 'eventlogquery ' if classic: logquerycmd += ' -classic ' elif (logname != ...
0.14851
0.058292
from sys import stderr from typing import List class Registers: def __init__(self, a: int, b: int, c: int, d: int): self.a = a self.b = b self.c = c self.d = d def to_int(self, value: str) -> int: result: int = 0 try: result = int(v...
Communautaires/Micro assembly.py
from sys import stderr from typing import List class Registers: def __init__(self, a: int, b: int, c: int, d: int): self.a = a self.b = b self.c = c self.d = d def to_int(self, value: str) -> int: result: int = 0 try: result = int(v...
0.239083
0.440951
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import print_function import math import pytest import requests import os from astropy.coordinates import SkyCoord import astropy.units as u from astropy.table import Table from astroquery.casda import Casda DATA_FILES = {'CIRCLE': 'co...
astroquery/casda/tests/test_casda.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import print_function import math import pytest import requests import os from astropy.coordinates import SkyCoord import astropy.units as u from astropy.table import Table from astroquery.casda import Casda DATA_FILES = {'CIRCLE': 'co...
0.848345
0.417271
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: # corner case handling: # Empty list or list with one node just return itself if head is None or head.next is None: ...
No_0024_Swap Nodes in Pairs/swap_nodes_in_pairs_node operation.py
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: # corner case handling: # Empty list or list with one node just return itself if head is None or head.next is None: ...
0.633977
0.47384
import numpy as np import gym from gym import wrappers from gym.envs.registration import register import matplotlib.pylab as plt evaluate_v = [] def run_episode(env, policy, gamma = 1.0, render = False): """ Runs an episode and return the total reward """ obs = env.reset() total_reward = 0 step_idx = ...
MDP/frozenlake_policy_iteration_.py
import numpy as np import gym from gym import wrappers from gym.envs.registration import register import matplotlib.pylab as plt evaluate_v = [] def run_episode(env, policy, gamma = 1.0, render = False): """ Runs an episode and return the total reward """ obs = env.reset() total_reward = 0 step_idx = ...
0.746786
0.474327
import numpy as np import torch import re from doc import Doc alphabet = re.compile(r'^[a-zA-Z]+$') from copy import copy from collections import defaultdict def build_graph(matrix): graph = defaultdict(list) for idx in range(0, len(matrix)): for col in range(idx+1, len(matrix)): graph[i...
source/text2kg/utils.py
import numpy as np import torch import re from doc import Doc alphabet = re.compile(r'^[a-zA-Z]+$') from copy import copy from collections import defaultdict def build_graph(matrix): graph = defaultdict(list) for idx in range(0, len(matrix)): for col in range(idx+1, len(matrix)): graph[i...
0.374219
0.245944
import re ''' A simple PDN parser. PDN (Portable Draughts Notation) is computer-processible format for recording draughts games, both the moves and related data. This module is based on features of others parser modules (such json and yaml). The basic usage:: import pdn pdn_text = open('sijbrands.pdn').r...
pdn.py
import re ''' A simple PDN parser. PDN (Portable Draughts Notation) is computer-processible format for recording draughts games, both the moves and related data. This module is based on features of others parser modules (such json and yaml). The basic usage:: import pdn pdn_text = open('sijbrands.pdn').r...
0.52902
0.347399
import torch from torch import nn import torch.nn.functional as F import torchvision from torch.utils.data import DataLoader import utils class VAE(nn.Module): """Implementation of VAE(Variational Auto-Encoder)""" def __init__(self): super(VAE, self).__init__() self.fc1 = nn.Linear(784, 200) ...
vae_on_mnist.py
import torch from torch import nn import torch.nn.functional as F import torchvision from torch.utils.data import DataLoader import utils class VAE(nn.Module): """Implementation of VAE(Variational Auto-Encoder)""" def __init__(self): super(VAE, self).__init__() self.fc1 = nn.Linear(784, 200) ...
0.924815
0.541591
import re import json import datetime from clover.exts import db from clover.models import query_to_dict, soft_delete from clover.environment.models import TeamModel from clover.environment.models import KeywordModel from clover.environment.models import VariableModel class TeamService(object): def create(self,...
clover/environment/service.py
import re import json import datetime from clover.exts import db from clover.models import query_to_dict, soft_delete from clover.environment.models import TeamModel from clover.environment.models import KeywordModel from clover.environment.models import VariableModel class TeamService(object): def create(self,...
0.297776
0.327077
import matplotlib.pyplot as plt import constants import numpy as np from statistics import mean from scipy.signal import savgol_filter def plotNodeCharacteristics(nodeList): FKs, BKs, mks= [], [], []; index = np.array(range(constants.NODES)) for node in nodeList: FKs.append(node.FK / ...
src/plotFunctions.py
import matplotlib.pyplot as plt import constants import numpy as np from statistics import mean from scipy.signal import savgol_filter def plotNodeCharacteristics(nodeList): FKs, BKs, mks= [], [], []; index = np.array(range(constants.NODES)) for node in nodeList: FKs.append(node.FK / ...
0.461259
0.64969
from os import path from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.test import TestCase, override_settings from django.test.client import RequestFactory from django.urls import reverse from ..errors import ( AttachmentTooLargeError, AuthenticationError, ) from...
inbound_email/tests/test_views.py
from os import path from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.test import TestCase, override_settings from django.test.client import RequestFactory from django.urls import reverse from ..errors import ( AttachmentTooLargeError, AuthenticationError, ) from...
0.495606
0.148695
from __future__ import division import numpy as np def make_load_func(plan): def getload(t): return plan[t-1] # ff model plans start with index 1 return getload def g(t, tau_1, w): '''time continuous version of g''' return w(t) * np.exp(-t/tau_1) def discrete_g(n, tau_1, w): g_value...
app/training/fitnessfatigue.py
from __future__ import division import numpy as np def make_load_func(plan): def getload(t): return plan[t-1] # ff model plans start with index 1 return getload def g(t, tau_1, w): '''time continuous version of g''' return w(t) * np.exp(-t/tau_1) def discrete_g(n, tau_1, w): g_value...
0.700383
0.578151
import json import math import rospy as ros from std_msgs.msg import String from std_srvs.srv import Trigger import sys import thread import time from tigrillo_ctrl.srv import Calibration, CalibrationResponse, Frequency, FrequencyResponse from tigrillo_ctrl import utils __author__ = "<NAME>" __copyright__ = "Copyri...
src/tigrillo_ctrl/src/tigrillo_ctrl/calib_ros.py
import json import math import rospy as ros from std_msgs.msg import String from std_srvs.srv import Trigger import sys import thread import time from tigrillo_ctrl.srv import Calibration, CalibrationResponse, Frequency, FrequencyResponse from tigrillo_ctrl import utils __author__ = "<NAME>" __copyright__ = "Copyri...
0.237222
0.079603
import logging import argparse import os import pwd import batchitup VERSION = "0.1.0" def welcome_banner(): print(""" \ __ __ _ _ ___ _ _ _____ _ / / /\ \ \___| | ___ ___ _ __ ___ ___ | |_ ___ / __\ __ _| |_ ___| |__ \_ \ |_ ...
batchitup/main.py
import logging import argparse import os import pwd import batchitup VERSION = "0.1.0" def welcome_banner(): print(""" \ __ __ _ _ ___ _ _ _____ _ / / /\ \ \___| | ___ ___ _ __ ___ ___ | |_ ___ / __\ __ _| |_ ___| |__ \_ \ |_ ...
0.210604
0.063337
import os import pybind11 import subprocess import sys from setuptools import setup, Extension from setuptools.command.build_ext import build_ext with open("parametric_plasma_source/__init__.py", "r") as f: for line in f.readlines(): if "__version__" in line: version = line.split()[-1].strip(...
setup.py
import os import pybind11 import subprocess import sys from setuptools import setup, Extension from setuptools.command.build_ext import build_ext with open("parametric_plasma_source/__init__.py", "r") as f: for line in f.readlines(): if "__version__" in line: version = line.split()[-1].strip(...
0.271831
0.062904
import random import logging import json import time import datetime import numpy as np import pandas as pd from sklearn.preprocessing import scale import urllib.request as urllibr from urllib.error import HTTPError import cx_Oracle from django.core.cache import cache from django.utils.six.moves import cPickle as pick...
core/datacarousel/utils.py
import random import logging import json import time import datetime import numpy as np import pandas as pd from sklearn.preprocessing import scale import urllib.request as urllibr from urllib.error import HTTPError import cx_Oracle from django.core.cache import cache from django.utils.six.moves import cPickle as pick...
0.11427
0.125896
from unittest import mock from aiohttp import web import pytest from aiohttp.test_utils import make_mocked_coro from sockjs.transports import jsonp @pytest.fixture def make_transport(make_request, make_manager, make_handler, make_fut): def maker(method="GET", path="/", query_params={}): handler = make_...
tests/test_transport_jsonp.py
from unittest import mock from aiohttp import web import pytest from aiohttp.test_utils import make_mocked_coro from sockjs.transports import jsonp @pytest.fixture def make_transport(make_request, make_manager, make_handler, make_fut): def maker(method="GET", path="/", query_params={}): handler = make_...
0.55097
0.317347
import numpy as np import matplotlib.pyplot as plt from numpy.core.fromnumeric import mean from scipy.fftpack import fft, fftshift import math data = open('./FirstExperimentData.txt') lines = data.readlines() valid_values = [] for line in lines: print(line) if(line[0:21] == 'Load_cell output val:'...
OnPC_Pipelines/Project DataCode1/CleanData_Code/ReadPlotFirstExperimentData.py
import numpy as np import matplotlib.pyplot as plt from numpy.core.fromnumeric import mean from scipy.fftpack import fft, fftshift import math data = open('./FirstExperimentData.txt') lines = data.readlines() valid_values = [] for line in lines: print(line) if(line[0:21] == 'Load_cell output val:'...
0.229535
0.505554
import itertools import multiprocessing import os import random import shutil import unittest import exemcl import numpy as np import pandas from sklearn.datasets import make_blobs DIM = 10 N = 500 def L(V, S): accu = 0 for e in V: accu += min([pow(np.linalg.norm(e - v), 2.0) for v in S]) return...
tests/UnitTests.py
import itertools import multiprocessing import os import random import shutil import unittest import exemcl import numpy as np import pandas from sklearn.datasets import make_blobs DIM = 10 N = 500 def L(V, S): accu = 0 for e in V: accu += min([pow(np.linalg.norm(e - v), 2.0) for v in S]) return...
0.44071
0.462594
import json from http import server, HTTPStatus import socketserver import ssl import datetime import uuid import time class EndpointHandler(server.BaseHTTPRequestHandler): def do_GET(self): self.common_handler() def do_POST(self): self.common_handler() def common_handler(self): t...
June-17-2020/Managing-the-Full-API-Lifecycle/servers/sandbox.py
import json from http import server, HTTPStatus import socketserver import ssl import datetime import uuid import time class EndpointHandler(server.BaseHTTPRequestHandler): def do_GET(self): self.common_handler() def do_POST(self): self.common_handler() def common_handler(self): t...
0.367157
0.081337
import numpy as np import matplotlib.pyplot as plt import pandas as pd import matplotlib.gridspec as gridspec def gini_calc(data,y): """Given input variable (data, pd series/np array) and target(y, pd series/np array), calculate the maximum information gain for a binary split. Code is not written to be...
information_gain.py
import numpy as np import matplotlib.pyplot as plt import pandas as pd import matplotlib.gridspec as gridspec def gini_calc(data,y): """Given input variable (data, pd series/np array) and target(y, pd series/np array), calculate the maximum information gain for a binary split. Code is not written to be...
0.376967
0.739411
from typing import Any, Dict, Generic, List, Optional, TypeVar, Union, cast import pystac from pystac.extensions.base import ( ExtensionManagementMixin, PropertiesExtension, ) from pystac.extensions.hooks import ExtensionHooks from pystac.utils import get_required T = TypeVar("T", pystac.Collection, pystac.It...
pystac/extensions/table.py
from typing import Any, Dict, Generic, List, Optional, TypeVar, Union, cast import pystac from pystac.extensions.base import ( ExtensionManagementMixin, PropertiesExtension, ) from pystac.extensions.hooks import ExtensionHooks from pystac.utils import get_required T = TypeVar("T", pystac.Collection, pystac.It...
0.943614
0.220657
import json import re from billy.scrape.committees import Committee, CommitteeScraper class VTCommitteeScraper(CommitteeScraper): jurisdiction = 'vt' latest_only = True def scrape(self, session, chambers): year_slug = session[5: ] # Load all committees via the private API commit...
openstates/openstates-master/openstates/vt/committees.py
import json import re from billy.scrape.committees import Committee, CommitteeScraper class VTCommitteeScraper(CommitteeScraper): jurisdiction = 'vt' latest_only = True def scrape(self, session, chambers): year_slug = session[5: ] # Load all committees via the private API commit...
0.410047
0.17172
import locale import datetime import unittest from unittest import mock from collections import OrderedDict from openfecwebapp import filters from openfecwebapp import utils from openfecwebapp.app import app, get_election_url def test_currency_filter_not_none(): locale.setlocale(locale.LC_ALL, '') assert fil...
tests/test_utils.py
import locale import datetime import unittest from unittest import mock from collections import OrderedDict from openfecwebapp import filters from openfecwebapp import utils from openfecwebapp.app import app, get_election_url def test_currency_filter_not_none(): locale.setlocale(locale.LC_ALL, '') assert fil...
0.444083
0.396594
from model import Model from model import Model_Mod import torch import numpy as np import matplotlib.pyplot as plt # Arguments: # in_features (int): the number of dimensions in the input # out_features (int): the number of dimensions in the output # num_gaussians (int): the number of Gaus...
Mixture_model/main.py
from model import Model from model import Model_Mod import torch import numpy as np import matplotlib.pyplot as plt # Arguments: # in_features (int): the number of dimensions in the input # out_features (int): the number of dimensions in the output # num_gaussians (int): the number of Gaus...
0.684897
0.653514
from math import pi, sqrt class Figure: @property def area(self): raise NotImplementedError @property def perimeter(self): raise NotImplementedError @property def name(self): raise NotImplementedError def __str__(self): return ( f'{self.name()...
lab_5/tasks/task_2.py
from math import pi, sqrt class Figure: @property def area(self): raise NotImplementedError @property def perimeter(self): raise NotImplementedError @property def name(self): raise NotImplementedError def __str__(self): return ( f'{self.name()...
0.906255
0.50531
import offsetbasedgraph as obg from collections import defaultdict from graph_peak_caller.postprocess.reference_based_max_path\ import max_path_func from offsetbasedgraph.vcfmap import VariantMap, DELMap from graph_peak_caller.sparsediffs import SparseValues from graph_peak_caller.peakcollection import Peak from gr...
tests/test_refmaxpath.py
import offsetbasedgraph as obg from collections import defaultdict from graph_peak_caller.postprocess.reference_based_max_path\ import max_path_func from offsetbasedgraph.vcfmap import VariantMap, DELMap from graph_peak_caller.sparsediffs import SparseValues from graph_peak_caller.peakcollection import Peak from gr...
0.69946
0.438364
from analysis import eval from environment import THE_GLOBAL_ENV import sys import traceback from utils import to_string from argparse import ArgumentParser from collections import Counter def repl(env=THE_GLOBAL_ENV, debug=False): # TODO: nicer REPL. Tab-completion def ask(): try: _str = ...
src/loispy/interpreter/main.py
from analysis import eval from environment import THE_GLOBAL_ENV import sys import traceback from utils import to_string from argparse import ArgumentParser from collections import Counter def repl(env=THE_GLOBAL_ENV, debug=False): # TODO: nicer REPL. Tab-completion def ask(): try: _str = ...
0.151216
0.076477
from typing import List class numerics(object): """Numeric utilities for solving the problem. """ @staticmethod def plus_to_pos(original: List[int], position: int, k: int = 3) -> List[int]: """Recursive helper function to add one at a location of a list of (bit) integers representi...
ternary_balance/utils/numerics.py
from typing import List class numerics(object): """Numeric utilities for solving the problem. """ @staticmethod def plus_to_pos(original: List[int], position: int, k: int = 3) -> List[int]: """Recursive helper function to add one at a location of a list of (bit) integers representi...
0.93064
0.753217
load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load( "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "feature", "flag_group", "flag_set", "tool_path", "with_feature_set", ) load( "@bazel_b...
toolchains/toolchains.bzl
load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load( "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "feature", "flag_group", "flag_set", "tool_path", "with_feature_set", ) load( "@bazel_b...
0.529507
0.12544
import json import logging import os try: import psutil except ImportError: psutil = None import subprocess from threading import Timer from py_trace_event import trace_time from telemetry.internal.platform import tracing_agent from telemetry.timeline import trace_data DEFAULT_MIN_PCPU = 0.1 class ProcessCollec...
telemetry/telemetry/internal/platform/tracing_agent/cpu_tracing_agent.py
import json import logging import os try: import psutil except ImportError: psutil = None import subprocess from threading import Timer from py_trace_event import trace_time from telemetry.internal.platform import tracing_agent from telemetry.timeline import trace_data DEFAULT_MIN_PCPU = 0.1 class ProcessCollec...
0.622689
0.168309
from functools import reduce from math import floor, gcd, inf _DEBUG = True def _lcm(a, b): return abs(a * b) // gcd(a, b) class Job: """A released job from a task""" def __init__(self, release, cost, deadline, task): """ :param release: release time :param cost: execution cost...
task_systems.py
from functools import reduce from math import floor, gcd, inf _DEBUG = True def _lcm(a, b): return abs(a * b) // gcd(a, b) class Job: """A released job from a task""" def __init__(self, release, cost, deadline, task): """ :param release: release time :param cost: execution cost...
0.823399
0.342379
import torch.nn as nn from module.Res_block import residual_block import torch.nn.functional as F import torch def weights_init_normal(m): classname = m.__class__.__name__ if classname.find("Conv") != -1: torch.nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find("BatchNorm3d") != -1: ...
module/Attention_block.py
import torch.nn as nn from module.Res_block import residual_block import torch.nn.functional as F import torch def weights_init_normal(m): classname = m.__class__.__name__ if classname.find("Conv") != -1: torch.nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find("BatchNorm3d") != -1: ...
0.945488
0.448849
import os from shutil import copyfile import pandas as pd import numpy as np from configuration.paths import * SEED = 1 def normalize(ds): ds = ds.groupby("patientId", as_index=False).sum() ds['diagnosis'] = np.where(ds['Target'] >= 1, 1, 0) ds = ds.rename(columns={'patientId': 'image'}) ds = ds[['...
src/preprocess/pneumonia_detection_challenge_preprocessing.py
import os from shutil import copyfile import pandas as pd import numpy as np from configuration.paths import * SEED = 1 def normalize(ds): ds = ds.groupby("patientId", as_index=False).sum() ds['diagnosis'] = np.where(ds['Target'] >= 1, 1, 0) ds = ds.rename(columns={'patientId': 'image'}) ds = ds[['...
0.128744
0.144571
from __future__ import print_function import argparse import sys import textwrap import redlock def log(*args, **kwargs): if not log.quiet: print(*args, file=sys.stderr, **kwargs) def lock(name, validity, redis, retry_count=3, retry_delay=200, **kwargs): if retry_count < 0: retry_count = 0...
redlock/cli.py
from __future__ import print_function import argparse import sys import textwrap import redlock def log(*args, **kwargs): if not log.quiet: print(*args, file=sys.stderr, **kwargs) def lock(name, validity, redis, retry_count=3, retry_delay=200, **kwargs): if retry_count < 0: retry_count = 0...
0.414188
0.052497
from sklearn.model_selection import KFold from abc import ABC, abstractmethod from typing import Tuple, Union, Dict, List, Any from torch.utils.data import Dataset, DataLoader import torch import albumentations as A from albumentations.pytorch.transforms import ToTensorV2 import random import pandas as pd import cv2 ...
KFolder.py
from sklearn.model_selection import KFold from abc import ABC, abstractmethod from typing import Tuple, Union, Dict, List, Any from torch.utils.data import Dataset, DataLoader import torch import albumentations as A from albumentations.pytorch.transforms import ToTensorV2 import random import pandas as pd import cv2 ...
0.893649
0.400867
import pytest from darwin.item_sorter import ItemSorter, SortDirection def describe_item_sorter(): def describe_parse(): def works_when_sort_is_complete_and_valid(): sort = "updated_at:asc" actual: ItemSorter = ItemSorter.parse(sort) assert actual.field == "updated_a...
tests/darwin/item_sorter_test.py
import pytest from darwin.item_sorter import ItemSorter, SortDirection def describe_item_sorter(): def describe_parse(): def works_when_sort_is_complete_and_valid(): sort = "updated_at:asc" actual: ItemSorter = ItemSorter.parse(sort) assert actual.field == "updated_a...
0.719482
0.452899
import time import json import itertools from kafka.client_async import KafkaClient from kazoo.client import KazooClient from kafka.protocol.admin import ( CreatePartitionsResponse_v0, CreateTopicsRequest_v0, DeleteTopicsRequest_v0, CreateAclsRequest_v0, CreateAclsRequest_v1, DeleteAclsRequest...
ansible/module_utils/kafka_manager.py
import time import json import itertools from kafka.client_async import KafkaClient from kazoo.client import KazooClient from kafka.protocol.admin import ( CreatePartitionsResponse_v0, CreateTopicsRequest_v0, DeleteTopicsRequest_v0, CreateAclsRequest_v0, CreateAclsRequest_v1, DeleteAclsRequest...
0.533884
0.0538
from __future__ import absolute_import, division, print_function import sys import argparse import yaml import numpy as np from scipy.sparse import csgraph from scipy.sparse.csr import csr_matrix from astropy.extern import six from astropy.table import Table, Column def read_table(filepath): """ Trivially read an...
fermipy/scripts/cluster_sources.py
from __future__ import absolute_import, division, print_function import sys import argparse import yaml import numpy as np from scipy.sparse import csgraph from scipy.sparse.csr import csr_matrix from astropy.extern import six from astropy.table import Table, Column def read_table(filepath): """ Trivially read an...
0.79858
0.478712
import asyncio from socket import gaierror as SocketGIAError from struct import error as StructError from typing import Any, Mapping, Optional import aiohttp import async_timeout from deepmerge import always_merger from yarl import URL from .__version__ import __version__ from .const import ( DEFAULT_CHARSET, ...
pyipp/ipp.py
import asyncio from socket import gaierror as SocketGIAError from struct import error as StructError from typing import Any, Mapping, Optional import aiohttp import async_timeout from deepmerge import always_merger from yarl import URL from .__version__ import __version__ from .const import ( DEFAULT_CHARSET, ...
0.77373
0.084758
import argparse from fissix.pygram import python_symbols as syms from fissix.fixer_util import Name, Dot, Newline, touch_import, find_binding from bowler import Query, TOKEN from bowler.types import Leaf, Node flags = {} def replace_unicode_methods(node, capture, arguments): # remove any existing __str__ metho...
sixify.py
import argparse from fissix.pygram import python_symbols as syms from fissix.fixer_util import Name, Dot, Newline, touch_import, find_binding from bowler import Query, TOKEN from bowler.types import Leaf, Node flags = {} def replace_unicode_methods(node, capture, arguments): # remove any existing __str__ metho...
0.556159
0.111265
import os import torch import numpy as np import cloudpickle from torch import nn, optim import matplotlib.pyplot as plt class TorchLinearRegression(torch.nn.Module): def __init__(self, input_size, output_size): super(TorchLinearRegression, self).__init__() self.linear = torch.nn.Linear(input_size...
backend/src/classifier/logistic_regression.py
import os import torch import numpy as np import cloudpickle from torch import nn, optim import matplotlib.pyplot as plt class TorchLinearRegression(torch.nn.Module): def __init__(self, input_size, output_size): super(TorchLinearRegression, self).__init__() self.linear = torch.nn.Linear(input_size...
0.929103
0.658541
import params as prm from blockchain import blockchain import pickle import socket import asyncio import sys from transactions import transaction, utxo import time #================Data Types=========================== class Version(): def __init__(self, ver, bh, nd): self.version = ver self.bestHe...
network/network.py
import params as prm from blockchain import blockchain import pickle import socket import asyncio import sys from transactions import transaction, utxo import time #================Data Types=========================== class Version(): def __init__(self, ver, bh, nd): self.version = ver self.bestHe...
0.309128
0.161023
from gimpfu import * import math def create_outline(image, fillOpacity, allLayers, cutOutCenter): xOffsets = [1, -1, 0, 0] yOffsets = [0, 0, 1, -1] originalLayers = [] if(allLayers): originalLayers = image.layers else: originalLayers.append(image.active_layer) for k in ran...
create_outline.py
from gimpfu import * import math def create_outline(image, fillOpacity, allLayers, cutOutCenter): xOffsets = [1, -1, 0, 0] yOffsets = [0, 0, 1, -1] originalLayers = [] if(allLayers): originalLayers = image.layers else: originalLayers.append(image.active_layer) for k in ran...
0.276886
0.144994
import os import time from flask import Flask, Request, g, jsonify, request, make_response from flask_cors import CORS from flask_limiter import Limiter from flask_limiter.util import get_remote_address from app.api.auth import generate_api_key from app.db.db_connect import VDBConnect, MySQLdb from app.errors import ...
app/__init__.py
import os import time from flask import Flask, Request, g, jsonify, request, make_response from flask_cors import CORS from flask_limiter import Limiter from flask_limiter.util import get_remote_address from app.api.auth import generate_api_key from app.db.db_connect import VDBConnect, MySQLdb from app.errors import ...
0.352425
0.04612
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('coreapi', '0001_initial'), ] operations = [ migrations.CreateModel( name='Brand', fields=[ ('id...
inventory/migrations/0001_initial.py
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('coreapi', '0001_initial'), ] operations = [ migrations.CreateModel( name='Brand', fields=[ ('id...
0.568536
0.242766
multiple modules.""" import io import os import logging FOUND_RICH_LIB = False try: from rich.logging import RichHandler FOUND_RICH_LIB = True logging.basicConfig( format="%(name)s: %(message)s", handlers=[RichHandler(show_time=False)], ) except ImportError: logging.basicConfig()...
python_linter/__init__.py
multiple modules.""" import io import os import logging FOUND_RICH_LIB = False try: from rich.logging import RichHandler FOUND_RICH_LIB = True logging.basicConfig( format="%(name)s: %(message)s", handlers=[RichHandler(show_time=False)], ) except ImportError: logging.basicConfig()...
0.762513
0.191252
class Storage(object): "Base storage class doin nothin." # Basic user functions def set_user_data(self, user_id, user_data): "Store user_data dictionary." print "Set user data:\t%s\n%s" % (user_id, user_data) def get_user_data(self, user_id): "Return user_id's data." return None def is_protected(self, u...
storage.py
class Storage(object): "Base storage class doin nothin." # Basic user functions def set_user_data(self, user_id, user_data): "Store user_data dictionary." print "Set user data:\t%s\n%s" % (user_id, user_data) def get_user_data(self, user_id): "Return user_id's data." return None def is_protected(self, u...
0.45641
0.10026
import os import sys cellbuf = [] def scan_to_cell(): for line in sys.stdin: if line.startswith('# '): global cellbuf cellbuf = [line] return line[2:].strip() def driver_ref(driver): with open(f'inref/drivers/{driver}') as fh: return fh.read().strip() def ...
flow/mdnote/md-to-steps.py
import os import sys cellbuf = [] def scan_to_cell(): for line in sys.stdin: if line.startswith('# '): global cellbuf cellbuf = [line] return line[2:].strip() def driver_ref(driver): with open(f'inref/drivers/{driver}') as fh: return fh.read().strip() def ...
0.191857
0.214671
import argparse import json import logging import os import random import sys import traceback from string import ascii_lowercase, ascii_uppercase, digits sys.path.append(os.path.abspath(os.path.join(__file__, "../../../.."))) from v2.lib import resource_op from v2.lib.exceptions import RGWBaseException, TestExecErr...
rgw/v2/tests/s3cmd/test_header_size.py
import argparse import json import logging import os import random import sys import traceback from string import ascii_lowercase, ascii_uppercase, digits sys.path.append(os.path.abspath(os.path.join(__file__, "../../../.."))) from v2.lib import resource_op from v2.lib.exceptions import RGWBaseException, TestExecErr...
0.296349
0.131368
from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'supported_by': 'community', 'status': ['preview'] } from ansible.errors import AnsibleConnectionFailure from ansible import __version__ as ansible_version f...
vos_ansible_files/plugins/httpapi/vos.py
from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'supported_by': 'community', 'status': ['preview'] } from ansible.errors import AnsibleConnectionFailure from ansible import __version__ as ansible_version f...
0.459804
0.114023
from abc import ABC, abstractmethod from typing import List from mpmath import eye, mpc, matrix from mpmath import expm as mp_expm from numpy import ndarray, identity from numpy.linalg import matrix_power from scipy.linalg import expm as scipy_expm from .matrices import Matrix class ProductFormula(ABC): @abstra...
matrix_extrapolation/product_formula.py
from abc import ABC, abstractmethod from typing import List from mpmath import eye, mpc, matrix from mpmath import expm as mp_expm from numpy import ndarray, identity from numpy.linalg import matrix_power from scipy.linalg import expm as scipy_expm from .matrices import Matrix class ProductFormula(ABC): @abstra...
0.94121
0.718138
from django.test import TestCase from awl.css_colours import (is_colour, colour_to_rgb, colour_to_rgb_string, LOWER_WEB_COLOUR_MAP) COLOUR_NAMES = [key.lower() for key in LOWER_WEB_COLOUR_MAP.keys()] # ============================================================================ class ColourTests(TestCase): ...
awl/tests/test_colours.py
from django.test import TestCase from awl.css_colours import (is_colour, colour_to_rgb, colour_to_rgb_string, LOWER_WEB_COLOUR_MAP) COLOUR_NAMES = [key.lower() for key in LOWER_WEB_COLOUR_MAP.keys()] # ============================================================================ class ColourTests(TestCase): ...
0.649245
0.230378
import asyncio import concurrent import importlib import inspect import logging import os import sys from functools import partial from athome.api.task import Task from athome.lib.management import managed from athome.lib.runnersupport import RunnerSupport, runner_main MODULE_PREFIX = '__athome_tasksmodule_' TASK_PR...
src/athome/lib/taskrunner.py
import asyncio import concurrent import importlib import inspect import logging import os import sys from functools import partial from athome.api.task import Task from athome.lib.management import managed from athome.lib.runnersupport import RunnerSupport, runner_main MODULE_PREFIX = '__athome_tasksmodule_' TASK_PR...
0.374905
0.128881
# X86 registers X86_REG_INVALID = 0 X86_REG_AH = 1 X86_REG_AL = 2 X86_REG_AX = 3 X86_REG_BH = 4 X86_REG_BL = 5 X86_REG_BP = 6 X86_REG_BPL = 7 X86_REG_BX = 8 X86_REG_CH = 9 X86_REG_CL = 10 X86_REG_CS = 11 X86_REG_CX = 12 X86_REG_DH = 13 X86_REG_DI = 14 X86_REG_DIL = 15 X86_REG_DL = 16 X86_REG_DS = 17 X86_REG_DX = 18 X...
bindings/python/capstone/x86_const.py
# X86 registers X86_REG_INVALID = 0 X86_REG_AH = 1 X86_REG_AL = 2 X86_REG_AX = 3 X86_REG_BH = 4 X86_REG_BL = 5 X86_REG_BP = 6 X86_REG_BPL = 7 X86_REG_BX = 8 X86_REG_CH = 9 X86_REG_CL = 10 X86_REG_CS = 11 X86_REG_CX = 12 X86_REG_DH = 13 X86_REG_DI = 14 X86_REG_DIL = 15 X86_REG_DL = 16 X86_REG_DS = 17 X86_REG_DX = 18 X...
0.31542
0.117117
from math import ceil from time import sleep import os import re from database import User, Item from . import data_manipulation from . import gtk_element_editor from . import window_creator from .decorators import use_threading, use_spinner class WindowHandler: spinner = None task_count = 0 user_list = ...
sortimentGUI/window_handler.py
from math import ceil from time import sleep import os import re from database import User, Item from . import data_manipulation from . import gtk_element_editor from . import window_creator from .decorators import use_threading, use_spinner class WindowHandler: spinner = None task_count = 0 user_list = ...
0.362405
0.164349
import smbus2 from smbus2 import i2c_msg import time from .DFRobot_SGP40_VOCAlgorithm import DFRobot_VOCAlgorithm moduleVersionString = "THV0.2" SHT_ADDR = 0x44 SGP_ADDR = 0x59 # SGP40 commands SGP40_MEASURE_RAW_SIGNAL = [0x26, 0x0F] SGP40_EXECUTE_SELF_TEST = [0x28, 0x0E] SGP40_TURN_HEATER_OFF = [0x36, 0x15] SGP4X_G...
DesignSpark/ESDK/THV.py
import smbus2 from smbus2 import i2c_msg import time from .DFRobot_SGP40_VOCAlgorithm import DFRobot_VOCAlgorithm moduleVersionString = "THV0.2" SHT_ADDR = 0x44 SGP_ADDR = 0x59 # SGP40 commands SGP40_MEASURE_RAW_SIGNAL = [0x26, 0x0F] SGP40_EXECUTE_SELF_TEST = [0x28, 0x0E] SGP40_TURN_HEATER_OFF = [0x36, 0x15] SGP4X_G...
0.531209
0.37843
import jinja2 import pytest class TestJinjaFilters: config = """ tasks: stripyear: mock: - {"title":"The Matrix (1999)", "url":"mock://local1" } - {"title":"The Matrix", "url":"mock://local2" } - {"title":"The Matrix 1999", "url":"mock://loca...
flexget/tests/test_jinja_filters.py
import jinja2 import pytest class TestJinjaFilters: config = """ tasks: stripyear: mock: - {"title":"The Matrix (1999)", "url":"mock://local1" } - {"title":"The Matrix", "url":"mock://local2" } - {"title":"The Matrix 1999", "url":"mock://loca...
0.681621
0.481027
from decimal import Decimal from functools import reduce import six # This junit backend implementation is based on the documentation # http://llg.cubic.org/docs/junit/ # also see: # https://confluence.atlassian.com/display/BAMBOO/JUnit+parsing+in+Bamboo try: from lxml import etree as ET from lxml.builder i...
lemoncheesecake/reporting/backends/junit.py
from decimal import Decimal from functools import reduce import six # This junit backend implementation is based on the documentation # http://llg.cubic.org/docs/junit/ # also see: # https://confluence.atlassian.com/display/BAMBOO/JUnit+parsing+in+Bamboo try: from lxml import etree as ET from lxml.builder i...
0.464659
0.194942
from urlresolver.plugnplay.interfaces import UrlResolver from urlresolver.plugnplay.interfaces import SiteAuth from urlresolver.plugnplay.interfaces import PluginSettings from urlresolver.plugnplay import Plugin from urlresolver import common from t0mm0.common.net import Net import re import urllib try: import sim...
script.module.urlresolver/lib/urlresolver/plugins/premiumize_me.py
from urlresolver.plugnplay.interfaces import UrlResolver from urlresolver.plugnplay.interfaces import SiteAuth from urlresolver.plugnplay.interfaces import PluginSettings from urlresolver.plugnplay import Plugin from urlresolver import common from t0mm0.common.net import Net import re import urllib try: import sim...
0.379608
0.046573
import nmrglue as ng import numpy as np import tempfile import os import glob from numpy.testing import assert_array_equal # useful functions def write_readback(dic,data): # write out and read back tf = tempfile.mktemp(dir=".") ng.pipe.write(tf,dic,data) rdic,rdata = ng.pipe.read(tf) os.remove(t...
tests/test_pipe.py
import nmrglue as ng import numpy as np import tempfile import os import glob from numpy.testing import assert_array_equal # useful functions def write_readback(dic,data): # write out and read back tf = tempfile.mktemp(dir=".") ng.pipe.write(tf,dic,data) rdic,rdata = ng.pipe.read(tf) os.remove(t...
0.38145
0.611295
from pyxlsxfunctions.math.core import SUMIF, COUNTIF, AND, OR, IF, FV, PV, AVERAGE, LEN, VLOOKUP, CORREL, AVERAGEIF, COUNTBLANK, RANDBETWEEN, POWER import numpy as np import pandas as pd # Unit tests for SUMIF def test_SUMIF_1(): assert SUMIF([1, 2, 3, 4, 5], ['yes', 'yes', 'no', 'no', 'yes'], 'yes') == 8 def tes...
tests/math/test_core.py
from pyxlsxfunctions.math.core import SUMIF, COUNTIF, AND, OR, IF, FV, PV, AVERAGE, LEN, VLOOKUP, CORREL, AVERAGEIF, COUNTBLANK, RANDBETWEEN, POWER import numpy as np import pandas as pd # Unit tests for SUMIF def test_SUMIF_1(): assert SUMIF([1, 2, 3, 4, 5], ['yes', 'yes', 'no', 'no', 'yes'], 'yes') == 8 def tes...
0.552902
0.578865
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import errno import os import stat import re import pwd import grp import time import shutil import traceback import fcntl import sys from contextlib import contextmanager from ansible.module_utils._text import to_bytes, to_nativ...
ansible/my_env/lib/python2.7/site-packages/ansible/module_utils/common/file.py
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import errno import os import stat import re import pwd import grp import time import shutil import traceback import fcntl import sys from contextlib import contextmanager from ansible.module_utils._text import to_bytes, to_nativ...
0.47098
0.066327
# BlackSmith plugin # access_plugin.py # Author: # <NAME> [<EMAIL>] # Modifications: # Als [<EMAIL>] # WitcherGeralt [<EMAIL>] ACCESS_LIST = {'-100': u'(полный игнор)', '-5': u'(заблокирован)', '0': u'(никто)','1': '(lol)', '10': u'(юзер)', '11': u'(мембер)', '15': u'(модер)', '16': u'(модер)', '20': u'(админ)'...
extensions/access.py
# BlackSmith plugin # access_plugin.py # Author: # <NAME> [<EMAIL>] # Modifications: # Als [<EMAIL>] # WitcherGeralt [<EMAIL>] ACCESS_LIST = {'-100': u'(полный игнор)', '-5': u'(заблокирован)', '0': u'(никто)','1': '(lol)', '10': u'(юзер)', '11': u'(мембер)', '15': u'(модер)', '16': u'(модер)', '20': u'(админ)'...
0.124652
0.175892
from itertools import chain class Seat(object): def __init__(self, occupied=False): self.occupied = occupied self.neighbours = [] self.pending_flip = False def flip(self): self.occupied = not self.occupied self.pending_flip = False def occupied_neighbours(self): ...
adventofcode/day11.py
from itertools import chain class Seat(object): def __init__(self, occupied=False): self.occupied = occupied self.neighbours = [] self.pending_flip = False def flip(self): self.occupied = not self.occupied self.pending_flip = False def occupied_neighbours(self): ...
0.667256
0.320662
"""Script to convert HotpotQA to MRQA format, with negatives.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gzip import json import re from absl import flags import tensorflow.compat.v1 as tf from tqdm import tqdm FLAGS = flags.FLAGS ## Requir...
language/labs/drkit/hotpotqa/preprocessing/convert_hotpot_to_mrqa.py
"""Script to convert HotpotQA to MRQA format, with negatives.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gzip import json import re from absl import flags import tensorflow.compat.v1 as tf from tqdm import tqdm FLAGS = flags.FLAGS ## Requir...
0.660501
0.182918
import boto3 import json import mimetypes import os import subprocess import time client = boto3.client("s3") with open("package.json") as json_data: d = json.load(json_data) pjson_version = d["version"] DEPLOY_TO = os.getenv("CFF_DEPLOY_TO") if DEPLOY_TO == "prod": SCRIPT_PATH = "./scripts/prod" BUC...
deploy.py
import boto3 import json import mimetypes import os import subprocess import time client = boto3.client("s3") with open("package.json") as json_data: d = json.load(json_data) pjson_version = d["version"] DEPLOY_TO = os.getenv("CFF_DEPLOY_TO") if DEPLOY_TO == "prod": SCRIPT_PATH = "./scripts/prod" BUC...
0.136781
0.07403
import os, sys, datetime,sqlite3 from flask import Flask, render_template, request, redirect from modules.search import * ############################################################ ############################################################ # FrameWork: Flask # Virtual Enveiroment > python -m venv [virtual d...
Py0729/main.py
import os, sys, datetime,sqlite3 from flask import Flask, render_template, request, redirect from modules.search import * ############################################################ ############################################################ # FrameWork: Flask # Virtual Enveiroment > python -m venv [virtual d...
0.120672
0.042862
from ghc.utils.hom import nx2homg, tree_list, cycle_list,\ path_list, hom_profile import homlib as hl import networkx as nx import numpy as np def hom_tree(F, G): """Specialized tree homomorphism in Python (serializable). Add `indexed` parameter to count for each index individually. ...
src/ghc/homomorphism.py
from ghc.utils.hom import nx2homg, tree_list, cycle_list,\ path_list, hom_profile import homlib as hl import networkx as nx import numpy as np def hom_tree(F, G): """Specialized tree homomorphism in Python (serializable). Add `indexed` parameter to count for each index individually. ...
0.786746
0.627381
from uninas.optimization.hpo.uninas.algorithms.abstract import AbstractAlgorithm from uninas.optimization.hpo.uninas.candidate import Candidate from uninas.optimization.hpo.uninas.algorithms.abstract import AbstractHPO from uninas.optimization.hpo.uninas.values import ValueSpace, SpecificValueSpace from uninas.utils.ar...
uninas/optimization/hpo/uninas/algorithms/specific.py
from uninas.optimization.hpo.uninas.algorithms.abstract import AbstractAlgorithm from uninas.optimization.hpo.uninas.candidate import Candidate from uninas.optimization.hpo.uninas.algorithms.abstract import AbstractHPO from uninas.optimization.hpo.uninas.values import ValueSpace, SpecificValueSpace from uninas.utils.ar...
0.808823
0.55435
from django.test import TestCase from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status from .utils import create_user, create_friend_request from core.models import FriendRequest CREATE_FRIEND_REQUEST_URL = reverse('api:friend_request_create') LIST_FRIEND_REQUES...
app/api/tests/test_friend_request_api.py
from django.test import TestCase from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status from .utils import create_user, create_friend_request from core.models import FriendRequest CREATE_FRIEND_REQUEST_URL = reverse('api:friend_request_create') LIST_FRIEND_REQUES...
0.556882
0.244481
from django.core.mail import send_mail from django.core.mail import mail_admins from django.template.loader import render_to_string from django.template import Context, Template from django.conf import settings from beauty_and_pics.consts import project_constants from itertools import chain import calendar, logging, j...
beauty_and_pics/email_template/email/email_template.py
from django.core.mail import send_mail from django.core.mail import mail_admins from django.template.loader import render_to_string from django.template import Context, Template from django.conf import settings from beauty_and_pics.consts import project_constants from itertools import chain import calendar, logging, j...
0.312895
0.080394
import numpy as np def continue_clamped(x, y, kind='cubic'): """ continue a clamped spline to +/- infinity Args: x (np.array): x values y (np.array): y values kind (str, optional): spline kind, default 'cubic' Return: function: ycont, y(x) defined over all x """ from scipy.interpolate import...
solith/li_nofk/expt_jofp.py
import numpy as np def continue_clamped(x, y, kind='cubic'): """ continue a clamped spline to +/- infinity Args: x (np.array): x values y (np.array): y values kind (str, optional): spline kind, default 'cubic' Return: function: ycont, y(x) defined over all x """ from scipy.interpolate import...
0.884489
0.597549
import os import re from typing import List, Union import matplotlib.pyplot as plt import matplotlib.ticker as ticker import numpy as np from networks.utility_functions.user_check import check_existing_folder class ActivationsHeatmap: def __init__(self, model): self.__model = model self.__save ...
networks/classes/specialization/ActivationsHeatmap.py
import os import re from typing import List, Union import matplotlib.pyplot as plt import matplotlib.ticker as ticker import numpy as np from networks.utility_functions.user_check import check_existing_folder class ActivationsHeatmap: def __init__(self, model): self.__model = model self.__save ...
0.891617
0.608943
from __future__ import division, unicode_literals import collections as col import copy import re from . import config from .messages import * from .ReferenceManager import linkTextsFromElement ''' A global name uniquely identifies a definition as a sequence of (value, type) tuples, with the definition itself as the f...
bikeshed/globalnames.py
from __future__ import division, unicode_literals import collections as col import copy import re from . import config from .messages import * from .ReferenceManager import linkTextsFromElement ''' A global name uniquely identifies a definition as a sequence of (value, type) tuples, with the definition itself as the f...
0.520009
0.269389
import os import numpy as np import torch as t import torch.utils.data import torchvision as tv from sklearn.model_selection import train_test_split def __balance_val_split(dataset, val_split=0.): targets = np.array(dataset.targets) train_indices, val_indices = train_test_split( np.arange(targets.sha...
util/data_loader.py
import os import numpy as np import torch as t import torch.utils.data import torchvision as tv from sklearn.model_selection import train_test_split def __balance_val_split(dataset, val_split=0.): targets = np.array(dataset.targets) train_indices, val_indices = train_test_split( np.arange(targets.sha...
0.711832
0.444263