code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import pandas as pd from sqlalchemy import create_engine class DataRetriever: def retrieveAllData(): global fof_data global monthly #balance sheet global annually #balance sheet fof_data = DataRetriever.retrieve("records") monthly = DataRetriever.retrieve("monthly") ...
DataRetrieve.py
import pandas as pd from sqlalchemy import create_engine class DataRetriever: def retrieveAllData(): global fof_data global monthly #balance sheet global annually #balance sheet fof_data = DataRetriever.retrieve("records") monthly = DataRetriever.retrieve("monthly") ...
0.190988
0.183557
import os from typing import Dict, List, Optional, Tuple, Union from urllib.request import pathname2url import webbrowser from PyQt5.QtWidgets import QFileDialog, QTableWidgetItem, QWidget _TypeList = Optional[ Union[ List[Tuple[str, str]], Dict[str, str], ...
widgets.py
import os from typing import Dict, List, Optional, Tuple, Union from urllib.request import pathname2url import webbrowser from PyQt5.QtWidgets import QFileDialog, QTableWidgetItem, QWidget _TypeList = Optional[ Union[ List[Tuple[str, str]], Dict[str, str], ...
0.808332
0.214034
from credoscript import adaptors, models from tests import CredoAdaptorTestCase class ContactAdaptorTestCase(CredoAdaptorTestCase): def setUp(self): self.adaptor = adaptors.ContactAdaptor() self.expected_entity = models.Contact def test_fetch_by_contact_id(self): """Fetch a single Cont...
tests/adaptors/contactadaptortestcase.py
from credoscript import adaptors, models from tests import CredoAdaptorTestCase class ContactAdaptorTestCase(CredoAdaptorTestCase): def setUp(self): self.adaptor = adaptors.ContactAdaptor() self.expected_entity = models.Contact def test_fetch_by_contact_id(self): """Fetch a single Cont...
0.729423
0.451871
import mock import nose import ckan.new_tests.helpers as helpers import ckanext.datastore.db as db assert_equal = nose.tools.assert_equal class TestCreateIndexes(object): def test_creates_fts_index_by_default(self): connection = mock.MagicMock() context = { 'connection': connection ...
ckanext/datastore/tests/test_db.py
import mock import nose import ckan.new_tests.helpers as helpers import ckanext.datastore.db as db assert_equal = nose.tools.assert_equal class TestCreateIndexes(object): def test_creates_fts_index_by_default(self): connection = mock.MagicMock() context = { 'connection': connection ...
0.593491
0.227491
import json from alipay.aop.api.constant.ParamConstants import * class AccessProduceQrcode(object): def __init__(self): self._batch_id = None self._core_url = None self._produce_order_id = None self._qrcode = None @property def batch_id(self): return self._batch_...
alipay/aop/api/domain/AccessProduceQrcode.py
import json from alipay.aop.api.constant.ParamConstants import * class AccessProduceQrcode(object): def __init__(self): self._batch_id = None self._core_url = None self._produce_order_id = None self._qrcode = None @property def batch_id(self): return self._batch_...
0.540681
0.075687
import matplotlib matplotlib.use('TkAgg', warn=False) import scipy import numpy as np from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.pyplot as plt from Tkinter import * from tkFont i...
puq/read.py
import matplotlib matplotlib.use('TkAgg', warn=False) import scipy import numpy as np from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.pyplot as plt from Tkinter import * from tkFont i...
0.255065
0.12408
import unittest from Calculator import Calculator from CsvReader import CsvReader class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.calculator = Calculator() def test_instantiate_calculator(self): self.assertIsInstance(self.calculator, Calculator) def test_subtract(self...
src/CalculatorTests.py
import unittest from Calculator import Calculator from CsvReader import CsvReader class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.calculator = Calculator() def test_instantiate_calculator(self): self.assertIsInstance(self.calculator, Calculator) def test_subtract(self...
0.635675
0.585397
import lxml.html from billy.utils.fulltext import text_after_line_numbers from .bills import WABillScraper from .legislators import WALegislatorScraper from .committees import WACommitteeScraper from .events import WAEventScraper settings = dict(SCRAPELIB_TIMEOUT=300) metadata = dict( name='Washington', abbre...
openstates/openstates-master/openstates/wa/__init__.py
import lxml.html from billy.utils.fulltext import text_after_line_numbers from .bills import WABillScraper from .legislators import WALegislatorScraper from .committees import WACommitteeScraper from .events import WAEventScraper settings = dict(SCRAPELIB_TIMEOUT=300) metadata = dict( name='Washington', abbre...
0.350199
0.150715
import numpy as np from scipy.stats import norm from scipy.spatial.distance import cdist from .sbom import SBOM class BayesianOptimizer(SBOM): def __init__(self, init_positions, space_dim, opt_para): super().__init__(init_positions, space_dim, opt_para) self.regr = self._opt_args_.gpr ...
gradient_free_optimizers/sequence_model/bayesian_optimization.py
import numpy as np from scipy.stats import norm from scipy.spatial.distance import cdist from .sbom import SBOM class BayesianOptimizer(SBOM): def __init__(self, init_positions, space_dim, opt_para): super().__init__(init_positions, space_dim, opt_para) self.regr = self._opt_args_.gpr ...
0.678433
0.36869
__author__ = "<NAME>, <NAME>" __copyright__ = "Copyright 2016, EOSS GmbH" __credits__ = ["<NAME>", "<NAME>"] __license__ = "GPL" __version__ = "1.0.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Production" import ujson import requests from manage import ICatalog from model.plain_models import Catalo...
catalog/manage/eosscatalog.py
__author__ = "<NAME>, <NAME>" __copyright__ = "Copyright 2016, EOSS GmbH" __credits__ = ["<NAME>", "<NAME>"] __license__ = "GPL" __version__ = "1.0.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Production" import ujson import requests from manage import ICatalog from model.plain_models import Catalo...
0.512693
0.072047
import matplotlib import numpy as np import matplotlib.pyplot as plt import h5py import scipy from PIL import Image from scipy import ndimage def load_dataset(): train_dataset = h5py.File('train_catvnoncat.h5', "r") train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features...
LR.py
import matplotlib import numpy as np import matplotlib.pyplot as plt import h5py import scipy from PIL import Image from scipy import ndimage def load_dataset(): train_dataset = h5py.File('train_catvnoncat.h5', "r") train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features...
0.505859
0.580768
BUILD_PATH = "../build/" LIBNAME = "libTwitter.so" import sys sys.path.append(BUILD_PATH) import ctypes import os ctypes.CDLL(BUILD_PATH + LIBNAME, mode=os.RTLD_LAZY) from twitwi import Twitter import json from random import randint import time class TwitterRef: def __init__(self): self.tweetMap = {} ...
test/run.py
BUILD_PATH = "../build/" LIBNAME = "libTwitter.so" import sys sys.path.append(BUILD_PATH) import ctypes import os ctypes.CDLL(BUILD_PATH + LIBNAME, mode=os.RTLD_LAZY) from twitwi import Twitter import json from random import randint import time class TwitterRef: def __init__(self): self.tweetMap = {} ...
0.121048
0.075858
import unittest from riskquant import loss class FixedValueModel(object): def __init__(self, value): self.value = value def draw(self, n=1): return [self.value] * n class TestLoss(unittest.TestCase): def test_simulate_losses_one_year(self): loss_model = loss.Loss(FixedValueMode...
tests/test_loss.py
import unittest from riskquant import loss class FixedValueModel(object): def __init__(self, value): self.value = value def draw(self, n=1): return [self.value] * n class TestLoss(unittest.TestCase): def test_simulate_losses_one_year(self): loss_model = loss.Loss(FixedValueMode...
0.810779
0.625638
class ShortestWay: @classmethod def find_shortest_way_1(cls, arr): if arr is None or len(arr) == 0: return 0 my_arr = list() row_count = len(arr) col_count = len(arr[0]) for row in arr: my_arr.append([0 for _ in row]) for i in range(col_c...
dp/q2.py
class ShortestWay: @classmethod def find_shortest_way_1(cls, arr): if arr is None or len(arr) == 0: return 0 my_arr = list() row_count = len(arr) col_count = len(arr[0]) for row in arr: my_arr.append([0 for _ in row]) for i in range(col_c...
0.276105
0.310498
import numpy as np import matplotlib.pyplot as plt import torch import torch.nn.functional as F import torchvision.transforms as T from kornia.feature.hardnet import HardNet8 from kornia.feature.tfeat import TFeat from kornia.morphology import erosion from kornia.filters import laplacian from src.models.hog_layer impo...
src/losses/pixelwise_contrastive_loss_2.py
import numpy as np import matplotlib.pyplot as plt import torch import torch.nn.functional as F import torchvision.transforms as T from kornia.feature.hardnet import HardNet8 from kornia.feature.tfeat import TFeat from kornia.morphology import erosion from kornia.filters import laplacian from src.models.hog_layer impo...
0.774029
0.772874
from wikidataintegrator import wdi_login, wdi_core, wdi_helpers from scheduled_bots.geneprotein import HelperBot from scheduled_bots.geneprotein.ProteinBot import main, Protein, PROPS from pymongo import MongoClient from scheduled_bots.local import WDUSER, WDPASS def _test_write_one_protein(qid, entrezgene, taxid): ...
scheduled_bots/geneprotein/test_ProteinBot.py
from wikidataintegrator import wdi_login, wdi_core, wdi_helpers from scheduled_bots.geneprotein import HelperBot from scheduled_bots.geneprotein.ProteinBot import main, Protein, PROPS from pymongo import MongoClient from scheduled_bots.local import WDUSER, WDPASS def _test_write_one_protein(qid, entrezgene, taxid): ...
0.317532
0.27677
import argparse import shutil from functools import partial from pathlib import Path import numpy as np from python_tools.generic import namespace_as_string from python_tools.ml import metrics from python_tools.ml.default.neural_models import EnsembleModel, MLPModel from python_tools.ml.default.transformations import ...
train.py
import argparse import shutil from functools import partial from pathlib import Path import numpy as np from python_tools.generic import namespace_as_string from python_tools.ml import metrics from python_tools.ml.default.neural_models import EnsembleModel, MLPModel from python_tools.ml.default.transformations import ...
0.531696
0.391348
import torch.nn as nn import torch.nn.functional as F def conv_2d(ni, nf, stride=1, ks=3): """3x3 convolution with 1 pixel padding""" return nn.Conv2d(in_channels=ni, out_channels=nf, kernel_size=ks, stride=stride, padding=ks//2, bias=False) def bn_relu_conv(ni, nf)...
wrn.py
import torch.nn as nn import torch.nn.functional as F def conv_2d(ni, nf, stride=1, ks=3): """3x3 convolution with 1 pixel padding""" return nn.Conv2d(in_channels=ni, out_channels=nf, kernel_size=ks, stride=stride, padding=ks//2, bias=False) def bn_relu_conv(ni, nf)...
0.959677
0.469581
from django.shortcuts import reverse from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from agents.mixins import OrganiserAndLoginRequiredMixin from .models import Lead, Category, Agent from .forms import ( LeadModelForm, CustomUserCreationForm, AssignAgentForm, LeadCa...
leads/views.py
from django.shortcuts import reverse from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from agents.mixins import OrganiserAndLoginRequiredMixin from .models import Lead, Category, Agent from .forms import ( LeadModelForm, CustomUserCreationForm, AssignAgentForm, LeadCa...
0.532425
0.102844
import logging from init_program import ( init_prog, start_browser, login_base ) from full_cycle import menu_full_cycle_go, page_full_cycle_go from serializer import write_serialize_data, read_serialize_data, delete_screens_and_log from toolbox import log_record, exit_prog from scenario_mod import...
retail-smoke/main.py
import logging from init_program import ( init_prog, start_browser, login_base ) from full_cycle import menu_full_cycle_go, page_full_cycle_go from serializer import write_serialize_data, read_serialize_data, delete_screens_and_log from toolbox import log_record, exit_prog from scenario_mod import...
0.110916
0.120051
from restclients.pws import PWS from restclients.sws import encode_section_label from restclients.dao import SWS_DAO from restclients.exceptions import DataFailureException from restclients.models.sws import GradeRoster, GradeRosterItem from restclients.models.sws import GradeSubmissionDelegate from lxml import etree i...
restclients/sws/v5/graderoster.py
from restclients.pws import PWS from restclients.sws import encode_section_label from restclients.dao import SWS_DAO from restclients.exceptions import DataFailureException from restclients.models.sws import GradeRoster, GradeRosterItem from restclients.models.sws import GradeSubmissionDelegate from lxml import etree i...
0.449151
0.158012
import logging import numpy as np from .evolutionary_optimizer import EvolutionaryOptimizer from ..util.argument_validation import argument_validation LOGGER = logging.getLogger(__name__) class Island(EvolutionaryOptimizer): """ Island: a basic unit of evolutionary optimization. It performs the genera...
bingo/evolutionary_optimizers/island.py
import logging import numpy as np from .evolutionary_optimizer import EvolutionaryOptimizer from ..util.argument_validation import argument_validation LOGGER = logging.getLogger(__name__) class Island(EvolutionaryOptimizer): """ Island: a basic unit of evolutionary optimization. It performs the genera...
0.923631
0.798933
from pathlib import Path import cv2 import numpy as np import pytorch_lightning as pl import torch import torchvision from pytorch_lightning.callbacks import ModelCheckpoint from torch.nn import functional as F from torch.utils.data import DataLoader from core.dataloaders.mit_dataloader import MitData from core.netwo...
src/core/trainers/filter_trainer.py
from pathlib import Path import cv2 import numpy as np import pytorch_lightning as pl import torch import torchvision from pytorch_lightning.callbacks import ModelCheckpoint from torch.nn import functional as F from torch.utils.data import DataLoader from core.dataloaders.mit_dataloader import MitData from core.netwo...
0.882028
0.385086
from online_monitor.receiver.receiver import Receiver from zmq.utils import jsonapi import numpy as np import time from PyQt4 import Qt import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import pyqtgraph.ptime as ptime from pyqtgraph.dockarea import DockArea, Dock from online_monitor.utils import utils ...
silab_online_monitor/receiver/pybar_fei4.py
from online_monitor.receiver.receiver import Receiver from zmq.utils import jsonapi import numpy as np import time from PyQt4 import Qt import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import pyqtgraph.ptime as ptime from pyqtgraph.dockarea import DockArea, Dock from online_monitor.utils import utils ...
0.478041
0.16654
import base64 import json import logging import os from flask import Flask from flask import request import googleapiclient.discovery import google.cloud.bigquery import google.cloud.pubsub_v1 logging.basicConfig(level=logging.DEBUG) PROJECT_ID = os.environ['GOOGLE_CLOUD_PROJECT'] MODEL_NAME = os.environ['MODEL_NAME']...
examples/e2e-home-appliance-status-monitoring/server/main.py
import base64 import json import logging import os from flask import Flask from flask import request import googleapiclient.discovery import google.cloud.bigquery import google.cloud.pubsub_v1 logging.basicConfig(level=logging.DEBUG) PROJECT_ID = os.environ['GOOGLE_CLOUD_PROJECT'] MODEL_NAME = os.environ['MODEL_NAME']...
0.410874
0.148726
import argparse import os import sys import tifffile.tifffile as tf import numpy as np _description = """Normalizes image stacks against background. Uses background.tif if it already exists in the current working directory; otherwise, computes the background image at each (x,y) location as the 5th percentile of that...
elisa/normalize_bg.py
import argparse import os import sys import tifffile.tifffile as tf import numpy as np _description = """Normalizes image stacks against background. Uses background.tif if it already exists in the current working directory; otherwise, computes the background image at each (x,y) location as the 5th percentile of that...
0.395484
0.213767
import numpy as np import cupy as cp import cupyx.scipy.ndimage as cpndi from .mathtools import wrapToPi def cuGPA(image, kvec, sigma=22): """Perform spatial lock-in on an image GPU version of `optGPA()`. Parameters ---------- image : np.array 2D image input image kvec : 2-tuple or ...
pyGPA/cuGPA.py
import numpy as np import cupy as cp import cupyx.scipy.ndimage as cpndi from .mathtools import wrapToPi def cuGPA(image, kvec, sigma=22): """Perform spatial lock-in on an image GPU version of `optGPA()`. Parameters ---------- image : np.array 2D image input image kvec : 2-tuple or ...
0.762601
0.590573
import numpy as np import numpy.ma as ma from math import hypot from filters import get_filters get_filters(globals()) # imports all filters at once def comp_range(blob): # compare rng-distant pixels within blob: a component of intra_blob rng = blob.rng + 1 p__ = ma.array(blob.dert__[:, :, 0], mask=~blob....
frame_2D_alg/comp_range.py
import numpy as np import numpy.ma as ma from math import hypot from filters import get_filters get_filters(globals()) # imports all filters at once def comp_range(blob): # compare rng-distant pixels within blob: a component of intra_blob rng = blob.rng + 1 p__ = ma.array(blob.dert__[:, :, 0], mask=~blob....
0.464173
0.635873
from __future__ import absolute_import, division, unicode_literals, print_function, nested_scopes import getpass import logging from .cache import SSHConnectionCache, SSHNoConnectionCache MAXSSHBUF = 16 * 1024 g_no_cache = SSHNoConnectionCache() g_cmd_cache = SSHConnectionCache("SSH Command Cache") logger = logging.ge...
sshutil/conn.py
from __future__ import absolute_import, division, unicode_literals, print_function, nested_scopes import getpass import logging from .cache import SSHConnectionCache, SSHNoConnectionCache MAXSSHBUF = 16 * 1024 g_no_cache = SSHNoConnectionCache() g_cmd_cache = SSHConnectionCache("SSH Command Cache") logger = logging.ge...
0.626238
0.140013
import string import random import math import numpy as np from itertools import izip_longest from collections import namedtuple from fractions import gcd PublicKey = namedtuple("PublicKey", ['e', 'n']) PrivateKey = namedtuple("PrivateKey", ['d', 'n', 'phi_n']) def genkeys(bits, e): p = nextprime(random.getrandbi...
Labs/RSA/solutions.py
import string import random import math import numpy as np from itertools import izip_longest from collections import namedtuple from fractions import gcd PublicKey = namedtuple("PublicKey", ['e', 'n']) PrivateKey = namedtuple("PrivateKey", ['d', 'n', 'phi_n']) def genkeys(bits, e): p = nextprime(random.getrandbi...
0.325199
0.297732
from validator import ip_address, user_name, password, boolean, platform, MAX_PASSWD_LEN from shlex import quote import pytest @pytest.mark.parametrize('value', ['0.0.0.0', '255.255.255.255', '1.1.1.1']) def test_ip_address_must_not_raise_if_valid_value_provided(value): assert ip_address(value) == value @pytes...
app/validator_test.py
from validator import ip_address, user_name, password, boolean, platform, MAX_PASSWD_LEN from shlex import quote import pytest @pytest.mark.parametrize('value', ['0.0.0.0', '255.255.255.255', '1.1.1.1']) def test_ip_address_must_not_raise_if_valid_value_provided(value): assert ip_address(value) == value @pytes...
0.511961
0.334426
from __future__ import print_function, division, absolute_import import os import sys import pkgutil import traceback import importlib from collections import OrderedDict from tpDcc.libs.python import python def import_module(module_name): """ Static function used to import a function given its complete nam...
tpDcc/libs/python/importer.py
from __future__ import print_function, division, absolute_import import os import sys import pkgutil import traceback import importlib from collections import OrderedDict from tpDcc.libs.python import python def import_module(module_name): """ Static function used to import a function given its complete nam...
0.32306
0.07971
import random import arcade from constants import * from randomly_place_sprite import randomly_place_sprite from wander_sprite import WanderSprite def _create_grid_with_cells(width, height): """ Create a grid with empty cells on odd row/column combinations. """ grid = [] for row in range(height): ...
source/level_2.py
import random import arcade from constants import * from randomly_place_sprite import randomly_place_sprite from wander_sprite import WanderSprite def _create_grid_with_cells(width, height): """ Create a grid with empty cells on odd row/column combinations. """ grid = [] for row in range(height): ...
0.415373
0.48377
from Sanitize import * def TicTacToe(): board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] def print_board(): print("", board[0], "|", board[1], "|", board[2]) print("---+---+---") print("", board[3], "|", board[4], "|", board[5]) print("---+---+---") print("", boar...
TicTacToeOpt.py
from Sanitize import * def TicTacToe(): board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] def print_board(): print("", board[0], "|", board[1], "|", board[2]) print("---+---+---") print("", board[3], "|", board[4], "|", board[5]) print("---+---+---") print("", boar...
0.298696
0.645511
from os import X_OK import torch import torchvision from net.cvt_offical import get_cvt13_pretrained from utils import train_transform, test_transform,initialize,smooth_crossentropy from config import device from ptflops import get_model_complexity_info import torch.nn.functional as F import torch.nn as nn initial...
cmp_resnet.py
from os import X_OK import torch import torchvision from net.cvt_offical import get_cvt13_pretrained from utils import train_transform, test_transform,initialize,smooth_crossentropy from config import device from ptflops import get_model_complexity_info import torch.nn.functional as F import torch.nn as nn initial...
0.554712
0.386821
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = ['TransformArgs', 'Transform'] @pulumi.input_type class TransformArgs: def __init__(__self__, *, ...
sdk/python/pulumi_azure/media/transform.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = ['TransformArgs', 'Transform'] @pulumi.input_type class TransformArgs: def __init__(__self__, *, ...
0.85753
0.095307
import pandas as pd import time import numpy as np import re import os import sys import inspect from pathlib import Path # local modules from fastsim import simdrive, vehicle, cycle def main(use_jitclass=True, err_tol=1e-4): """Runs test test for 26 vehicles and 3 cycles. Test compares cumulative positive...
fastsim-2021a/fastsim/tests/test26veh3cyc.py
import pandas as pd import time import numpy as np import re import os import sys import inspect from pathlib import Path # local modules from fastsim import simdrive, vehicle, cycle def main(use_jitclass=True, err_tol=1e-4): """Runs test test for 26 vehicles and 3 cycles. Test compares cumulative positive...
0.313735
0.341912
import pygame from ..base import Manual from ...enums import Effects class ManualSquare(Manual): inputs = { 'up': pygame.key.key_code('Z'), 'left': pygame.key.key_code('Q'), 'down': pygame.key.key_code('S'), 'right': pygame.key.key_code('D'), } def run_one_step(self, ke...
leveltwo/algorithm/square/manual.py
import pygame from ..base import Manual from ...enums import Effects class ManualSquare(Manual): inputs = { 'up': pygame.key.key_code('Z'), 'left': pygame.key.key_code('Q'), 'down': pygame.key.key_code('S'), 'right': pygame.key.key_code('D'), } def run_one_step(self, ke...
0.810854
0.285602
import matplotlib.pyplot as plt plt.rcParams['font.size']=6 import os root_path = os.path.dirname(os.path.abspath('__file__')) # root_path = os.path.abspath(os.path.join(root_path,os.path.pardir)) graphs_path = root_path+'/results_analysis/graphs/' import sys sys.path.append(root_path) from plot_pacfs import plot_pacf...
results_analysis/plot_pacf_for_all.py
import matplotlib.pyplot as plt plt.rcParams['font.size']=6 import os root_path = os.path.dirname(os.path.abspath('__file__')) # root_path = os.path.abspath(os.path.join(root_path,os.path.pardir)) graphs_path = root_path+'/results_analysis/graphs/' import sys sys.path.append(root_path) from plot_pacfs import plot_pacf...
0.238107
0.148541
import numpy as np import cv2 import argparse from collections import deque import time from pynput.keyboard import Key, Controller class CameraCapture(): def __init__(self): self.cap = cv2.VideoCapture(0) self.Lower_green = np.array([110,50,50]) self.Upper_green = np.array([130,255,255]) ...
new_try.py
import numpy as np import cv2 import argparse from collections import deque import time from pynput.keyboard import Key, Controller class CameraCapture(): def __init__(self): self.cap = cv2.VideoCapture(0) self.Lower_green = np.array([110,50,50]) self.Upper_green = np.array([130,255,255]) ...
0.392919
0.200088
import glob import os from datetime import datetime from enum import IntEnum, auto from logging import Logger from typing import Final, Optional, Union import openpyxl import pandas as pd import python_lib_for_me as pyl from openpyxl.worksheet.worksheet import Worksheet from styleframe import StyleFrame, St...
src/fgo_farm_report_collection/logic/farm_report_gen_result_merge.py
import glob import os from datetime import datetime from enum import IntEnum, auto from logging import Logger from typing import Final, Optional, Union import openpyxl import pandas as pd import python_lib_for_me as pyl from openpyxl.worksheet.worksheet import Worksheet from styleframe import StyleFrame, St...
0.330039
0.092647
from werkzeug.contrib.cache import (BaseCache, NullCache, SimpleCache, MemcachedCache, GAEMemcachedCache, FileSystemCache) class SASLMemcachedCache(MemcachedCache): def __init__(self, servers=None, default_timeout=300, key_prefix=None, username=None, password=<...
src/lib/flask_cache/backends.py
from werkzeug.contrib.cache import (BaseCache, NullCache, SimpleCache, MemcachedCache, GAEMemcachedCache, FileSystemCache) class SASLMemcachedCache(MemcachedCache): def __init__(self, servers=None, default_timeout=300, key_prefix=None, username=None, password=<...
0.464173
0.047338
def setup(): try: from importlib import metadata except ImportError: # Running on pre-3.8 Python; use importlib-metadata package import importlib_metadata as metadata import logging from pathlib import Path import os import sys import platform logger = logging.ge...
nexxT/__init__.py
def setup(): try: from importlib import metadata except ImportError: # Running on pre-3.8 Python; use importlib-metadata package import importlib_metadata as metadata import logging from pathlib import Path import os import sys import platform logger = logging.ge...
0.232746
0.127381
from abc import ABC, abstractmethod from datetime import datetime from functools import wraps import re from typing import Any, Callable, Dict, Iterable, TypeVar from urllib.parse import urljoin, urlparse, urlunparse, urlencode from urllib.request import Request from calculate_anything.currency.data import CurrencyData...
calculate_anything/currency/providers/base.py
from abc import ABC, abstractmethod from datetime import datetime from functools import wraps import re from typing import Any, Callable, Dict, Iterable, TypeVar from urllib.parse import urljoin, urlparse, urlunparse, urlencode from urllib.request import Request from calculate_anything.currency.data import CurrencyData...
0.755005
0.14436
from typing import Any, Dict, List, Set, Type, Optional, TYPE_CHECKING from hqlib.typing import MetricValue from ..base import DomainObject if TYPE_CHECKING: # pragma: no cover # pylint: disable=unused-import from .metric import Metric from .metric_source import MetricSource class MeasurableObject(Domai...
backend/hqlib/domain/measurement/measurable.py
from typing import Any, Dict, List, Set, Type, Optional, TYPE_CHECKING from hqlib.typing import MetricValue from ..base import DomainObject if TYPE_CHECKING: # pragma: no cover # pylint: disable=unused-import from .metric import Metric from .metric_source import MetricSource class MeasurableObject(Domai...
0.914721
0.201853
import sqlite3 class dbHandler: DB_TABLE_MEMBER = 'members' DB_MEMBER_ID = 'id' DB_MEMBER_TAG = 'tag' DB_MEMBER_NAME = 'name' DB_MEMBER_KEY_STATUS = 'keyStatus' DB_TABLE_BATTLES = 'battles' DB_BATTLES_ID = 'id' DB_BATTLES_KEY_MEMBERID = 'memberId' DB_BATTLES_KEY_MATCH = 'keyMatch' DB_BATTLES_KEY...
ClanWarStatsModule/dbHandler.py
import sqlite3 class dbHandler: DB_TABLE_MEMBER = 'members' DB_MEMBER_ID = 'id' DB_MEMBER_TAG = 'tag' DB_MEMBER_NAME = 'name' DB_MEMBER_KEY_STATUS = 'keyStatus' DB_TABLE_BATTLES = 'battles' DB_BATTLES_ID = 'id' DB_BATTLES_KEY_MEMBERID = 'memberId' DB_BATTLES_KEY_MATCH = 'keyMatch' DB_BATTLES_KEY...
0.285272
0.050401
from django.shortcuts import render from django.http import HttpResponseRedirect from .models import registration from django.http import HttpResponse from django.shortcuts import redirect import requests # base url database url_root = 'https://search-build.herokuapp.com' def delete(request): """ User delet...
users/views.py
from django.shortcuts import render from django.http import HttpResponseRedirect from .models import registration from django.http import HttpResponse from django.shortcuts import redirect import requests # base url database url_root = 'https://search-build.herokuapp.com' def delete(request): """ User delet...
0.502197
0.075176
import os from datetime import datetime from urlparse import urlparse from flask import Flask, render_template, request, redirect, url_for, flash, session from flaskext.seasurf import SeaSurf from flaskext.bcrypt import Bcrypt from flaskext.gravatar import Gravatar from functools import wraps import settings from mon...
flask-job-board/app.py
import os from datetime import datetime from urlparse import urlparse from flask import Flask, render_template, request, redirect, url_for, flash, session from flaskext.seasurf import SeaSurf from flaskext.bcrypt import Bcrypt from flaskext.gravatar import Gravatar from functools import wraps import settings from mon...
0.361954
0.065009
"""Tests for plaso.output.l2t_csv.""" import StringIO import unittest from plaso.formatters import interface as formatters_interface from plaso.lib import event from plaso.lib import eventdata from plaso.output import dynamic class TestEvent(event.EventObject): DATA_TYPE = 'test:dynamic' def __init__(self): ...
plaso/output/dynamic_test.py
"""Tests for plaso.output.l2t_csv.""" import StringIO import unittest from plaso.formatters import interface as formatters_interface from plaso.lib import event from plaso.lib import eventdata from plaso.output import dynamic class TestEvent(event.EventObject): DATA_TYPE = 'test:dynamic' def __init__(self): ...
0.630344
0.252316
from trad_chiffre_mot import tradn import os import numpy as np from scipy.sparse import csr_matrix import pandas as pd from nltk.tag import StanfordPOSTagger from nltk.tokenize import RegexpTokenizer from keras import Input from keras.layers import Bidirectional, LSTM, Dropout, RepeatVector, Concatenate, Dense, Activa...
lecture.py
from trad_chiffre_mot import tradn import os import numpy as np from scipy.sparse import csr_matrix import pandas as pd from nltk.tag import StanfordPOSTagger from nltk.tokenize import RegexpTokenizer from keras import Input from keras.layers import Bidirectional, LSTM, Dropout, RepeatVector, Concatenate, Dense, Activa...
0.569613
0.448185
import logging import pathlib import tempfile import pytest from foodx_devops_tools.pipeline_config import PipelineConfiguration from foodx_devops_tools.pipeline_config._checks import ( _file_exists, do_path_check, ) from tests.ci.support.pipeline_config import MOCK_PATHS, MOCK_SECRET log = logging.getLogge...
tests/ci/unit_tests/pipeline_config/test_checks.py
import logging import pathlib import tempfile import pytest from foodx_devops_tools.pipeline_config import PipelineConfiguration from foodx_devops_tools.pipeline_config._checks import ( _file_exists, do_path_check, ) from tests.ci.support.pipeline_config import MOCK_PATHS, MOCK_SECRET log = logging.getLogge...
0.472197
0.241311
import multi_half_bridge_py as mhb from time import sleep # Tle94112 Object on Shield 1 controller = mhb.Tle94112Rpi() # Tle94112motor Objects on controller motor = mhb.Tle94112Motor(controller) # Enable motorController on all Shields and motors # Note: Required to be done before starting to configure the motor # co...
src/framework/raspberrypi/examples_py/errorDiagnosis.py
import multi_half_bridge_py as mhb from time import sleep # Tle94112 Object on Shield 1 controller = mhb.Tle94112Rpi() # Tle94112motor Objects on controller motor = mhb.Tle94112Motor(controller) # Enable motorController on all Shields and motors # Note: Required to be done before starting to configure the motor # co...
0.45423
0.336808
import pytest from collections import namedtuple from region_cache import RegionCache @pytest.fixture(params=[ {'REGION_CACHE_URL': 'redis://localhost:6379/5'}, { 'REGION_CACHE_URL': 'redis://localhost:6379/5', 'REGION_CACHE_RR_URL': 'redis://localhost:6379/5' }, { 'REGION_CAC...
tests/test_region_cache.py
import pytest from collections import namedtuple from region_cache import RegionCache @pytest.fixture(params=[ {'REGION_CACHE_URL': 'redis://localhost:6379/5'}, { 'REGION_CACHE_URL': 'redis://localhost:6379/5', 'REGION_CACHE_RR_URL': 'redis://localhost:6379/5' }, { 'REGION_CAC...
0.64646
0.284792
from __future__ import absolute_import import sys from gevent.pywsgi import WSGIServer as GeventWSGIServer from slimta import logging __all__ = ['WsgiServer'] log = logging.getHttpLogger(__name__) class WsgiServer(object): """Implements the base class for a WSGI server that logs its requests and response...
slimta/http/wsgi.py
from __future__ import absolute_import import sys from gevent.pywsgi import WSGIServer as GeventWSGIServer from slimta import logging __all__ = ['WsgiServer'] log = logging.getHttpLogger(__name__) class WsgiServer(object): """Implements the base class for a WSGI server that logs its requests and response...
0.688259
0.247544
import asyncio import logging import random import re import string import time from copy import copy from datetime import datetime, timedelta import discord from discord.errors import HTTPException from typing import Union, List, Tuple, Literal from redbot.core import Config, commands, checks from redbot.core.utils i...
cash/cash.py
import asyncio import logging import random import re import string import time from copy import copy from datetime import datetime, timedelta import discord from discord.errors import HTTPException from typing import Union, List, Tuple, Literal from redbot.core import Config, commands, checks from redbot.core.utils i...
0.655667
0.175009
from google.longrunning.operations_pb2 import ( CancelOperationRequest, DeleteOperationRequest, GetOperationRequest, ListOperationsRequest, ListOperationsResponse, Operation, google_dot_protobuf_dot_empty__pb2, ) from grpc.beta import implementations as beta_implementations from grpc.beta im...
Janaagraha Bot/venv/Lib/site-packages/gcloud/bigtable/_generated_v2/operations_grpc_pb2.py
from google.longrunning.operations_pb2 import ( CancelOperationRequest, DeleteOperationRequest, GetOperationRequest, ListOperationsRequest, ListOperationsResponse, Operation, google_dot_protobuf_dot_empty__pb2, ) from grpc.beta import implementations as beta_implementations from grpc.beta im...
0.731538
0.138928
import os import sys import subprocess import pickle import numpy from distutils.util import strtobool from lib.Regression import Regression class userInterface(): def __init__(self): self.inputTitle = ['縣市', '鄉鎮市區', '有無管理組織', '建物型態', '土地移轉總面積平方公尺', '車...
lib/userInterface.py
import os import sys import subprocess import pickle import numpy from distutils.util import strtobool from lib.Regression import Regression class userInterface(): def __init__(self): self.inputTitle = ['縣市', '鄉鎮市區', '有無管理組織', '建物型態', '土地移轉總面積平方公尺', '車...
0.147832
0.171876
from typing import Dict, List from copy import deepcopy import itertools import numpy as np from QCompute.QPlatform.QEnv import QEnv from QCompute.QPlatform.QRegPool import QRegPool from QCompute.QPlatform.QOperation.RotationGate import RX, RY from QCompute.QPlatform.QOperation.FixedGate import H, S, CX from QCompute.Q...
Example/QAPP/qapp/circuit/pauli_measurement_circuit.py
from typing import Dict, List from copy import deepcopy import itertools import numpy as np from QCompute.QPlatform.QEnv import QEnv from QCompute.QPlatform.QRegPool import QRegPool from QCompute.QPlatform.QOperation.RotationGate import RX, RY from QCompute.QPlatform.QOperation.FixedGate import H, S, CX from QCompute.Q...
0.930054
0.617743
import re filename = "input.txt" valid_props = { 'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid' } f = open(filename, 'r') passports=[] passport='' for line in f.readlines(): line = line.strip() passport = passport + line + ' ' if line == "": passports.append(passport....
day_4/passport_processing_part_2.py
import re filename = "input.txt" valid_props = { 'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid' } f = open(filename, 'r') passports=[] passport='' for line in f.readlines(): line = line.strip() passport = passport + line + ' ' if line == "": passports.append(passport....
0.117965
0.124426
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict from numba import jit import numpy as np import copy import math import hparams as hp import utils device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') def get_sinusoid_encoding_table(n_position,...
modules.py
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict from numba import jit import numpy as np import copy import math import hparams as hp import utils device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') def get_sinusoid_encoding_table(n_position,...
0.914575
0.378057
import os import argparse import instrument_benchmark as bench from statistics import mean, stdev import numpy as np import matplotlib.pyplot as plt lout = None def lprint(message): print("{}".format(message)) if lout is not None: lout.write("{}\n".format(message)) def plot(x, y, yerr, label, fna...
examples/execute.py
import os import argparse import instrument_benchmark as bench from statistics import mean, stdev import numpy as np import matplotlib.pyplot as plt lout = None def lprint(message): print("{}".format(message)) if lout is not None: lout.write("{}\n".format(message)) def plot(x, y, yerr, label, fna...
0.409103
0.294722
from enum import Enum, auto from typing import Optional from shimmer.display.data_structures import Color from shimmer.display.alignment import ( HorizontalAlignment, VerticalAlignment, ) from shimmer.display.components.box import Box, BoxDefinition from shimmer.display.widgets.text_box import TextBoxDefinitio...
est8/frontend/card.py
from enum import Enum, auto from typing import Optional from shimmer.display.data_structures import Color from shimmer.display.alignment import ( HorizontalAlignment, VerticalAlignment, ) from shimmer.display.components.box import Box, BoxDefinition from shimmer.display.widgets.text_box import TextBoxDefinitio...
0.753739
0.109658
_version_major = 0 _version_minor = 1 _version_micro = 0 _version_extra = '.dev' def get_nipype_gitversion(): """Nipype version as reported by the last commit in git Returns ------- None or str Version of NiPype according to git. """ import os import subprocess try: impor...
bips/info.py
_version_major = 0 _version_minor = 1 _version_micro = 0 _version_extra = '.dev' def get_nipype_gitversion(): """Nipype version as reported by the last commit in git Returns ------- None or str Version of NiPype according to git. """ import os import subprocess try: impor...
0.497315
0.184768
import re import pytz import copy from dateutil.parser import parse import WHOIS_parser from WHOIS_connect import WHOIS_srv_connect utc_timezone = pytz.utc # 设置utc时区 CHOSE_WHOIS_server = WHOIS_parser.WHOIS_info_extract_func() WHOIS_RECORD = { "domain": "", # 域名 "tld": "", # 顶级域 "flag": "", # 状态标记 ...
WHOISpy/WHOIS_info_extract.py
import re import pytz import copy from dateutil.parser import parse import WHOIS_parser from WHOIS_connect import WHOIS_srv_connect utc_timezone = pytz.utc # 设置utc时区 CHOSE_WHOIS_server = WHOIS_parser.WHOIS_info_extract_func() WHOIS_RECORD = { "domain": "", # 域名 "tld": "", # 顶级域 "flag": "", # 状态标记 ...
0.116512
0.198763
import os import yaml import logging from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler from flask_securest.userstores import simple from flask_securest.constants import FLASK_SECUREST_LOGGER_NAME class FileUserstore(simple.SimpleUserstore, FileSystemEventHandler): def _...
flask_securest/userstores/file_userstore.py
import os import yaml import logging from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler from flask_securest.userstores import simple from flask_securest.constants import FLASK_SECUREST_LOGGER_NAME class FileUserstore(simple.SimpleUserstore, FileSystemEventHandler): def _...
0.293708
0.062646
from wand.image import Image from wand.drawing import Drawing from wand.color import Color import os # this is original code. font_normal = 'Noto-Sans' font_italic = 'Noto-Sans-Italic' font_bold = 'Noto-Sans-Bold' if os.name == 'nt': font_normal = 'Arial' font_italic = 'Arial-Italic' font_bold = 'Arial-B...
examples/text/sample14_more_attributes.py
from wand.image import Image from wand.drawing import Drawing from wand.color import Color import os # this is original code. font_normal = 'Noto-Sans' font_italic = 'Noto-Sans-Italic' font_bold = 'Noto-Sans-Bold' if os.name == 'nt': font_normal = 'Arial' font_italic = 'Arial-Italic' font_bold = 'Arial-B...
0.429429
0.083404
import time import pickle import os.path import re from talon import ( Module, Context, actions, registry, ) from talon.grammar import Phrase from talon import speech_system, Context from talon.engines.vosk import VoskEngine vosk_de = VoskEngine(model="vosk-model-small-de-0.15", language="de_DE") vos...
adabru_talon/code/german.py
import time import pickle import os.path import re from talon import ( Module, Context, actions, registry, ) from talon.grammar import Phrase from talon import speech_system, Context from talon.engines.vosk import VoskEngine vosk_de = VoskEngine(model="vosk-model-small-de-0.15", language="de_DE") vos...
0.227813
0.102979
from __future__ import division from __future__ import print_function import os import argparse from argparse import Namespace import array import numpy as np from scipy import signal import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib import mlab from myhdl import * def _prep_...
examples/ex4_mathsop/test_verilogs/test_mathsop.py
from __future__ import division from __future__ import print_function import os import argparse from argparse import Namespace import array import numpy as np from scipy import signal import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib import mlab from myhdl import * def _prep_...
0.524882
0.372448
from subprocess import call import pexpect class LinuxInit(): def __init__(self): pass # 0.更新源和软件 def update_env(self): # cmd = "sudo apt-get update;sudo apt-get upgrade;sudo apt-get install -y python-dev" install_cmd = "sudo apt-get install -y python-dev" process = pexpec...
linux_init/linux_init.py
from subprocess import call import pexpect class LinuxInit(): def __init__(self): pass # 0.更新源和软件 def update_env(self): # cmd = "sudo apt-get update;sudo apt-get upgrade;sudo apt-get install -y python-dev" install_cmd = "sudo apt-get install -y python-dev" process = pexpec...
0.280222
0.054224
import requests import json import sys #get the secrets from your Google Cloud project, use the Oauth2 Playground for your refresh token client_id=sys.argv[1] client_secret=sys.argv[2] refresh_token=sys.argv[3] credentials=sys.argv[4] def get_list_from_file(filename): try: # open and read the file into lis...
google-workspace/offboarding-email-archive/python/google-vault-offboarding.py
import requests import json import sys #get the secrets from your Google Cloud project, use the Oauth2 Playground for your refresh token client_id=sys.argv[1] client_secret=sys.argv[2] refresh_token=sys.argv[3] credentials=sys.argv[4] def get_list_from_file(filename): try: # open and read the file into lis...
0.056165
0.114517
from typing import Mapping, Any, Type, Callable, Optional import abc import torch as tc from drl.agents.heads.abstract import Head from drl.agents.architectures.stateless.abstract import HeadEligibleArchitecture class ValueHead(Head, metaclass=abc.ABCMeta): """ Value head abstract class. """ class Sim...
drl/agents/heads/value_heads.py
from typing import Mapping, Any, Type, Callable, Optional import abc import torch as tc from drl.agents.heads.abstract import Head from drl.agents.architectures.stateless.abstract import HeadEligibleArchitecture class ValueHead(Head, metaclass=abc.ABCMeta): """ Value head abstract class. """ class Sim...
0.94325
0.326781
revision = '7829789fc19c' down_revision = 'cf<PASSWORD>b<PASSWORD>' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa table_name = 'permissions_system' column_name = 'permission' type_name = 'sys_perms' tmp_type_name = f"tmp_{type_name}" old_options = ('SUPERUSER', ) new_options ...
web/server/codechecker_server/migrations/config/versions/7829789fc19c_global_permission_to_get_access_controls.py
revision = '7829789fc19c' down_revision = 'cf<PASSWORD>b<PASSWORD>' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa table_name = 'permissions_system' column_name = 'permission' type_name = 'sys_perms' tmp_type_name = f"tmp_{type_name}" old_options = ('SUPERUSER', ) new_options ...
0.425725
0.111096
import os import re import argparse import glob def slurp_file(path): data = '' try: with open(path, 'r') as fin: data = fin.read() except IOError: pass if not (data and not data.isspace()): assent = input('Warning: ' + path + ' is empty; do you want to continue? [y...
tools/codegen/update_hdr_ftr_adoc.py
import os import re import argparse import glob def slurp_file(path): data = '' try: with open(path, 'r') as fin: data = fin.read() except IOError: pass if not (data and not data.isspace()): assent = input('Warning: ' + path + ' is empty; do you want to continue? [y...
0.234407
0.110807
from util import database, toolchain, bitdiff, progress with database.transact() as db: for device_name, device in db.items(): progress(device_name) package, pinout = next(iter(device['pins'].items())) gclk3_pad = device['specials']['CLK3'] gclr_switch = device['globals']['GCLR'] ...
fuzzers/028-gnet_invert/fuzzer.py
from util import database, toolchain, bitdiff, progress with database.transact() as db: for device_name, device in db.items(): progress(device_name) package, pinout = next(iter(device['pins'].items())) gclk3_pad = device['specials']['CLK3'] gclr_switch = device['globals']['GCLR'] ...
0.316158
0.255657
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import CubicSpline import json """ Please download the original bus signals data of each city from a2d2: https://www.a2d2.audi/a2d2/en/download.html the available locations are "Gaimersheim", "Munich" and "Ingolstadt" and ...
Clustering_approach/Data_interpolation.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import CubicSpline import json """ Please download the original bus signals data of each city from a2d2: https://www.a2d2.audi/a2d2/en/download.html the available locations are "Gaimersheim", "Munich" and "Ingolstadt" and ...
0.28897
0.577019
import argparse as arp import os import numpy as np from reinforcement_learning import logger from reinforcement_learning.gym.envs.donkey_car.donkey_env import DonkeyEnv from reinforcement_learning.common.callbacks import CheckpointCallback from reinforcement_learning.common.vec_env.subproc_vec_env import SubprocVecE...
train_expert_donkey.py
import argparse as arp import os import numpy as np from reinforcement_learning import logger from reinforcement_learning.gym.envs.donkey_car.donkey_env import DonkeyEnv from reinforcement_learning.common.callbacks import CheckpointCallback from reinforcement_learning.common.vec_env.subproc_vec_env import SubprocVecE...
0.452536
0.200323
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='MenuDetail', fields=[ ('id', models.AutoField(auto_created...
core/migrations/0001_initial.py
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='MenuDetail', fields=[ ('id', models.AutoField(auto_created...
0.510496
0.140248
import os.path from typing import List, Optional, Tuple import tensorflow as tf from mlagents_envs.side_channel.engine_configuration_channel import EngineConfigurationChannel # type: ignore from mlagents_envs.side_channel.environment_parameters_channel import EnvironmentParametersChannel # type: ignore from tensorfl...
project/learner.py
import os.path from typing import List, Optional, Tuple import tensorflow as tf from mlagents_envs.side_channel.engine_configuration_channel import EngineConfigurationChannel # type: ignore from mlagents_envs.side_channel.environment_parameters_channel import EnvironmentParametersChannel # type: ignore from tensorfl...
0.885983
0.257888
from typing import Any, Union, ClassVar, NoReturn, Optional from pathlib import Path from urllib.parse import urlparse import configparser import attr from omnipath.constants import License from omnipath._core.cache._cache import Cache, FileCache, NoopCache, MemoryCache from omnipath.constants._pkg_constants import D...
omnipath/_core/utils/_options.py
from typing import Any, Union, ClassVar, NoReturn, Optional from pathlib import Path from urllib.parse import urlparse import configparser import attr from omnipath.constants import License from omnipath._core.cache._cache import Cache, FileCache, NoopCache, MemoryCache from omnipath.constants._pkg_constants import D...
0.944203
0.239572
# namespace: FBOutput import tdw.flatbuffers class AvatarSimpleBody(object): __slots__ = ['_tab'] @classmethod def GetRootAsAvatarSimpleBody(cls, buf, offset): n = tdw.flatbuffers.encode.Get(tdw.flatbuffers.packer.uoffset, buf, offset) x = AvatarSimpleBody() x.Init(bu...
Python/tdw/FBOutput/AvatarSimpleBody.py
# namespace: FBOutput import tdw.flatbuffers class AvatarSimpleBody(object): __slots__ = ['_tab'] @classmethod def GetRootAsAvatarSimpleBody(cls, buf, offset): n = tdw.flatbuffers.encode.Get(tdw.flatbuffers.packer.uoffset, buf, offset) x = AvatarSimpleBody() x.Init(bu...
0.620047
0.235366
import pytest from eth_abi.exceptions import ( ValueOutOfBounds, ) from hypothesis import ( given, strategies as st, ) from web3._utils.events import ( DataArgumentFilter, TopicArgumentFilter, normalize_topic_list, ) @pytest.mark.parametrize( "topic_list,expected", ( ( ...
tests/core/utilities/test_event_filter_builder.py
import pytest from eth_abi.exceptions import ( ValueOutOfBounds, ) from hypothesis import ( given, strategies as st, ) from web3._utils.events import ( DataArgumentFilter, TopicArgumentFilter, normalize_topic_list, ) @pytest.mark.parametrize( "topic_list,expected", ( ( ...
0.501953
0.560403
import os from unittest import TestCase from unittest.mock import MagicMock, patch import gensim from word_vectorizer.models.model_data import ModelData from word_vectorizer.models.word2vec_vectorizer import Word2VecVectorizer class TestWord2VecVectorizer(TestCase): FOLDER_FOR_MODELS = os.path.join(os.path.dirn...
word_vectorizer/tests/unittest/models/test_word2VecVectorizer.py
import os from unittest import TestCase from unittest.mock import MagicMock, patch import gensim from word_vectorizer.models.model_data import ModelData from word_vectorizer.models.word2vec_vectorizer import Word2VecVectorizer class TestWord2VecVectorizer(TestCase): FOLDER_FOR_MODELS = os.path.join(os.path.dirn...
0.46952
0.273527
import smtplib import re import redis class Emailer: """ Function description : sends an email given certain details patterned from http://stackoverflow.com/questions/10147455/trying-to-send-email-gmail-as-mail-provider-using-python Parameters: details -> a dictionary that contains user info and email ifo a...
modules/emailer/emailer.py
import smtplib import re import redis class Emailer: """ Function description : sends an email given certain details patterned from http://stackoverflow.com/questions/10147455/trying-to-send-email-gmail-as-mail-provider-using-python Parameters: details -> a dictionary that contains user info and email ifo a...
0.237576
0.235988
import os import boto3 import logging import datetime import re import time __author__ = '<NAME> (<EMAIL>)' __copyright__ = 'Shine Solutions' __license__ = 'Apache License, Version 2.0' # setting up logger logger = logging.getLogger(__name__) logger.setLevel(int(os.getenv('LOG_LEVEL', logging.INFO))) def purge_ol...
lambda/purge_snapshots.py
import os import boto3 import logging import datetime import re import time __author__ = '<NAME> (<EMAIL>)' __copyright__ = 'Shine Solutions' __license__ = 'Apache License, Version 2.0' # setting up logger logger = logging.getLogger(__name__) logger.setLevel(int(os.getenv('LOG_LEVEL', logging.INFO))) def purge_ol...
0.269133
0.152631
import gym import numpy as np import matplotlib.pyplot as plt from itertools import product from gym import error, spaces, utils from gym.utils import seeding class MullerBrownContinuousEnv(gym.Env): metadata = {'render.modes': ['human']} def __init__(self): # state space self.x_min = -1.5 ...
gym_muller_brown/envs/muller_brown_continuous.py
import gym import numpy as np import matplotlib.pyplot as plt from itertools import product from gym import error, spaces, utils from gym.utils import seeding class MullerBrownContinuousEnv(gym.Env): metadata = {'render.modes': ['human']} def __init__(self): # state space self.x_min = -1.5 ...
0.685739
0.386706
from . import testcases from testing.testcases import tc_path_plan_a_star as testcase from logger.logger import logger import time class test_planner(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' self.list_tc = {} self.lis...
src/testing/test_planner.py
from . import testcases from testing.testcases import tc_path_plan_a_star as testcase from logger.logger import logger import time class test_planner(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' self.list_tc = {} self.lis...
0.18159
0.102709
import subprocess import argparse import sys import os import shutil import time import friendlytoml as toml config = toml.load(os.path.join(os.path.dirname(__file__), "publish_rust.toml")) HOME = os.environ["HOME"] PROJECT_FOLDER = os.path.join(HOME, os.path.join(*config["dir"]["rust"])) USER = config["user"] GITHUB...
publish_rust.py
import subprocess import argparse import sys import os import shutil import time import friendlytoml as toml config = toml.load(os.path.join(os.path.dirname(__file__), "publish_rust.toml")) HOME = os.environ["HOME"] PROJECT_FOLDER = os.path.join(HOME, os.path.join(*config["dir"]["rust"])) USER = config["user"] GITHUB...
0.275032
0.091139
from flask import Blueprint, flash, jsonify, request, redirect, render_template, session, url_for from flask_login import login_required, current_user from ims.common.ComboBoxUtil import getComCategoryList from ims.common.Messages import Messages from ims.common.RoleUtil import admin_required from ims.contents.comCont...
ims/views/masterData.py
from flask import Blueprint, flash, jsonify, request, redirect, render_template, session, url_for from flask_login import login_required, current_user from ims.common.ComboBoxUtil import getComCategoryList from ims.common.Messages import Messages from ims.common.RoleUtil import admin_required from ims.contents.comCont...
0.380759
0.21211
# Python modules from __future__ import absolute_import import socket # Third-party modules import tornado.gen import tornado.iostream from tornado.concurrent import TracebackFuture # NOC modules from .base import CLI from .telnet import TelnetIOStream class BeefCLI(CLI): name = "beef_cli" default_port = 2...
core/script/cli/beef.py
# Python modules from __future__ import absolute_import import socket # Third-party modules import tornado.gen import tornado.iostream from tornado.concurrent import TracebackFuture # NOC modules from .base import CLI from .telnet import TelnetIOStream class BeefCLI(CLI): name = "beef_cli" default_port = 2...
0.614625
0.087097
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import click import click.testing import mock import treadmill from treadmill import plugin_manager from treadmill.admin import exc as admin_exceptions ...
lib/python/treadmill/tests/cli/admin/ldap/allocation_test.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import click import click.testing import mock import treadmill from treadmill import plugin_manager from treadmill.admin import exc as admin_exceptions ...
0.700485
0.16398
import numpy as np from astropy import units as u import os from uclahedp.tools import csv as csvtools from uclahedp.tools import hdf as hdftools from uclahedp.tools import util import h5py def hrrToRaw( run, probe, hdf_dir, csv_dir, dest, verbose=False, debug=False): """ Retreives the appropriate metadata for ...
uclahedp/load/hrr.py
import numpy as np from astropy import units as u import os from uclahedp.tools import csv as csvtools from uclahedp.tools import hdf as hdftools from uclahedp.tools import util import h5py def hrrToRaw( run, probe, hdf_dir, csv_dir, dest, verbose=False, debug=False): """ Retreives the appropriate metadata for ...
0.30965
0.389488
from unittest import TestCase from daylio_parser.config import ( DEFAULT_COLOR_PALETTE, DEFAULT_MOODS, Mood, MoodConfig, MoodNotFound, ) class TestConfig(TestCase): def test_default_mood_list(self): """Test that the default config contains 5 moods with known boundaries.""" m...
tests/test_config.py
from unittest import TestCase from daylio_parser.config import ( DEFAULT_COLOR_PALETTE, DEFAULT_MOODS, Mood, MoodConfig, MoodNotFound, ) class TestConfig(TestCase): def test_default_mood_list(self): """Test that the default config contains 5 moods with known boundaries.""" m...
0.834036
0.514705
import numpy as np # linear algebra np.set_printoptions(threshold=np.nan) import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) # Input data files are available in the "../input/" directory. # For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directo...
kaggle-ml/quora/kernel.py
import numpy as np # linear algebra np.set_printoptions(threshold=np.nan) import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) # Input data files are available in the "../input/" directory. # For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directo...
0.55447
0.245384
from typing import List # MONAD = "Reader" MONAD = "State" PARAM = MONAD[0] def generic(i: int) -> str: return chr(i + ord("A")) def arg(i: int) -> str: return chr(i + ord("a")) def arg2(i: int) -> str: return arg(i) + "2" def generics(i: int) -> List[str]: return [generic(i) for i in range(0, ...
GenCode.py
from typing import List # MONAD = "Reader" MONAD = "State" PARAM = MONAD[0] def generic(i: int) -> str: return chr(i + ord("A")) def arg(i: int) -> str: return chr(i + ord("a")) def arg2(i: int) -> str: return arg(i) + "2" def generics(i: int) -> List[str]: return [generic(i) for i in range(0, ...
0.629888
0.536738
__author__ = "<NAME>" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __copyright__ = "Copyright (C) 2020, Nokia" __license__ = "BSD-3" from pybgl.automaton import Automaton, alphabet, add_vertex, add_edge, delta, set_final from pybgl.nfa import Nfa, initials, is_final, sigma def moore_deter...
pybgl/moore_determination.py
__author__ = "<NAME>" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __copyright__ = "Copyright (C) 2020, Nokia" __license__ = "BSD-3" from pybgl.automaton import Automaton, alphabet, add_vertex, add_edge, delta, set_final from pybgl.nfa import Nfa, initials, is_final, sigma def moore_deter...
0.790732
0.353847
import ctypes import io import os import struct import sys from contextlib import contextmanager from . import mcclient_const as const from . import mcclient_types as types if 'sphinx' in sys.modules: client = None else: client = types.load_library() if client is None: raise ImportError("ERROR: ...
bindings/mcclient/mcclient.py
import ctypes import io import os import struct import sys from contextlib import contextmanager from . import mcclient_const as const from . import mcclient_types as types if 'sphinx' in sys.modules: client = None else: client = types.load_library() if client is None: raise ImportError("ERROR: ...
0.617513
0.201892
import logging as log import numpy as np import random log.basicConfig(format="%(message)s", level=log.INFO) def load_data(file_path): """加载数据 源数据格式为多行,每行为两个浮点数,分别表示 (x,y) """ data = [] with open(file_path, 'r', encoding='utf-8') as fr: for line in fr.read().splitlines(): ...
_codes/machine_learning/KMeans/kmeans.py
import logging as log import numpy as np import random log.basicConfig(format="%(message)s", level=log.INFO) def load_data(file_path): """加载数据 源数据格式为多行,每行为两个浮点数,分别表示 (x,y) """ data = [] with open(file_path, 'r', encoding='utf-8') as fr: for line in fr.read().splitlines(): ...
0.242564
0.370738
import os from typing import Optional, Sequence, Dict, List from csr.exceptions import ReaderException from sources2csr.ngs import AnalysisType, NGS, LibraryStrategy class NgsReader: """Reader that reads NGS data files. """ def __init__(self, input_dir: str, library_strategy: LibraryStrategy): se...
sources2csr/ngs_reader.py
import os from typing import Optional, Sequence, Dict, List from csr.exceptions import ReaderException from sources2csr.ngs import AnalysisType, NGS, LibraryStrategy class NgsReader: """Reader that reads NGS data files. """ def __init__(self, input_dir: str, library_strategy: LibraryStrategy): se...
0.825836
0.331471
from pyhunt.deploy import WMIEXEC from pyhunt.deploy_smb import CMDEXEC from multiprocessing import Process, Pool from time import sleep class HuntScan: def __init__(self, usr, pwd, domain, hashes=''): self.targets = [] self.__currentpath = '' self.surveyfile = "survey/survey.ps1" s...
scan.py
from pyhunt.deploy import WMIEXEC from pyhunt.deploy_smb import CMDEXEC from multiprocessing import Process, Pool from time import sleep class HuntScan: def __init__(self, usr, pwd, domain, hashes=''): self.targets = [] self.__currentpath = '' self.surveyfile = "survey/survey.ps1" s...
0.240329
0.070624
import os import geopandas as gpd import numpy as np import pandas as pd from prereise.gather.demanddata.bldg_electrification import const def aggregate_puma_df( puma_states, tract_puma_mapping, tract_gbs_area, tract_degday_normals, tract_pop ): """Scale census tract data up to puma areas. :param panda...
prereise/gather/demanddata/bldg_electrification/puma_data_agg.py
import os import geopandas as gpd import numpy as np import pandas as pd from prereise.gather.demanddata.bldg_electrification import const def aggregate_puma_df( puma_states, tract_puma_mapping, tract_gbs_area, tract_degday_normals, tract_pop ): """Scale census tract data up to puma areas. :param panda...
0.764892
0.402744