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 django.conf import settings from decimal import Decimal from django.db import models from django.db.models.signals import pre_save, post_save, m2m_changed import math from products.models import Product User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request): ...
carts/models.py
from django.conf import settings from decimal import Decimal from django.db import models from django.db.models.signals import pre_save, post_save, m2m_changed import math from products.models import Product User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request): ...
0.318591
0.078501
import array import copy import pickle import numpy as np import pytest from mspasspy.ccore.seismic import (_CoreSeismogram, _CoreTimeSeries, Seismogram, SeismogramEnsemble, ...
python/tests/test_ccore.py
import array import copy import pickle import numpy as np import pytest from mspasspy.ccore.seismic import (_CoreSeismogram, _CoreTimeSeries, Seismogram, SeismogramEnsemble, ...
0.802903
0.531453
import os import unittest import tests.utils class GenerateInputTest(unittest.TestCase): def snippet_call_generate_input(self, args, input_files, expected_values, disallowed_files=None): with tests.utils.sandbox(input_files) as _: tests.utils.run(['generate-input'] + args, check=True) ...
tests/command_generate_input.py
import os import unittest import tests.utils class GenerateInputTest(unittest.TestCase): def snippet_call_generate_input(self, args, input_files, expected_values, disallowed_files=None): with tests.utils.sandbox(input_files) as _: tests.utils.run(['generate-input'] + args, check=True) ...
0.356335
0.514827
from __future__ import print_function import unittest, os, shutil, errno, sys, difflib, cgi, re from roundup.admin import AdminTool from . import db_test_base from .test_mysql import skip_mysql from .test_postgresql import skip_postgresql class AdminTest(object): backend = None def setUp(self): s...
test/test_admin.py
from __future__ import print_function import unittest, os, shutil, errno, sys, difflib, cgi, re from roundup.admin import AdminTool from . import db_test_base from .test_mysql import skip_mysql from .test_postgresql import skip_postgresql class AdminTest(object): backend = None def setUp(self): s...
0.304352
0.159479
from __future__ import absolute_import from __future__ import division from __future__ import print_function from codecs import open from os import path import sys import re import csv import os # OptionParser imports from optparse import OptionParser from optparse import OptionGroup # Options definition parser = ...
parse_ipsec_p1.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from codecs import open from os import path import sys import re import csv import os # OptionParser imports from optparse import OptionParser from optparse import OptionGroup # Options definition parser = ...
0.302082
0.070848
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the...
Test/two/payments/payments/settings.py
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the...
0.306216
0.082771
from ._base import BaseEmbedder from ._sentencetransformers import SentenceTransformerBackend languages = ['afrikaans', 'albanian', 'amharic', 'arabic', 'armenian', 'assamese', 'azerbaijani', 'basque', 'belarusian', 'bengali', 'bengali romanize', 'bosnian', 'breton', 'bulgarian', 'burmese', '...
bertopic/backend/_utils.py
from ._base import BaseEmbedder from ._sentencetransformers import SentenceTransformerBackend languages = ['afrikaans', 'albanian', 'amharic', 'arabic', 'armenian', 'assamese', 'azerbaijani', 'basque', 'belarusian', 'bengali', 'bengali romanize', 'bosnian', 'breton', 'bulgarian', 'burmese', '...
0.728459
0.270531
import pandas as pd import copy import re import altair as alt def plot_event_heatmap(event_data: pd.DataFrame, ): """Plots local event explanations Parameters ---------- event_data: pd.DataFrame Event global explanations """ event_data = copy.deepcopy(event_d...
src/timeshap/plot/event_level.py
import pandas as pd import copy import re import altair as alt def plot_event_heatmap(event_data: pd.DataFrame, ): """Plots local event explanations Parameters ---------- event_data: pd.DataFrame Event global explanations """ event_data = copy.deepcopy(event_d...
0.762601
0.464173
import re import validators import unicodedata from titlecase import titlecase def _regularize_spaces(text: str) -> str: """ Replaces spaces in a string with underscores. """ return text.replace(' ', '_') def _capitalize(text: str) -> str: if not text: return text return titlecase(text) de...
src/news_kg/nlp.py
import re import validators import unicodedata from titlecase import titlecase def _regularize_spaces(text: str) -> str: """ Replaces spaces in a string with underscores. """ return text.replace(' ', '_') def _capitalize(text: str) -> str: if not text: return text return titlecase(text) de...
0.680772
0.285372
from __future__ import absolute_import, division, print_function def test_run(dials_regression, run_in_tmpdir): from os.path import join from dxtbx.model.experiment_list import ExperimentListFactory from dials.array_family import flex from dials.command_line.export import phil_scope from dials.u...
test/util/test_nexus.py
from __future__ import absolute_import, division, print_function def test_run(dials_regression, run_in_tmpdir): from os.path import join from dxtbx.model.experiment_list import ExperimentListFactory from dials.array_family import flex from dials.command_line.export import phil_scope from dials.u...
0.663996
0.602676
from bisect import bisect_right from torch.optim.lr_scheduler import _LRScheduler, ExponentialLR, ReduceLROnPlateau class ConstantLR(_LRScheduler): """Keeps the learning rate constant.""" def get_lr(self): return [base_lr for base_lr in self.base_lrs] class MultiScheduleLR(_LRScheduler): """ ...
pytorch_lm/lr_schedule.py
from bisect import bisect_right from torch.optim.lr_scheduler import _LRScheduler, ExponentialLR, ReduceLROnPlateau class ConstantLR(_LRScheduler): """Keeps the learning rate constant.""" def get_lr(self): return [base_lr for base_lr in self.base_lrs] class MultiScheduleLR(_LRScheduler): """ ...
0.948728
0.442155
from cradmin_legacy.viewhelpers.listfilter.basefilters.multi import abstractcheckbox from cradmin_legacy.viewhelpers.listfilter.django.base import DjangoOrmFilterMixin class RelatedModelOrFilter(abstractcheckbox.AbstractCheckboxFilter, DjangoOrmFilterMixin): """ Filter on values from a related model (one-to-m...
cradmin_legacy/viewhelpers/listfilter/django/multi/checkbox.py
from cradmin_legacy.viewhelpers.listfilter.basefilters.multi import abstractcheckbox from cradmin_legacy.viewhelpers.listfilter.django.base import DjangoOrmFilterMixin class RelatedModelOrFilter(abstractcheckbox.AbstractCheckboxFilter, DjangoOrmFilterMixin): """ Filter on values from a related model (one-to-m...
0.836655
0.341006
import kfp.dsl as dsl import json import kfp.components as comp from collections import OrderedDict from kubernetes import client as k8s_client def setup(MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_MODEL_BUCKET: str, MINIO_SECRET_KEY: str): pipeline_parameters_block = ''' MINIO_ACCESS_KEY = "{}" MINIO_H...
courses/machine_learning/deepdive2/production_ml/labs/samples/contrib/e2e-outlier-drift-explainer/seldon/seldon_e2e_cifar10.kale.default.py
import kfp.dsl as dsl import json import kfp.components as comp from collections import OrderedDict from kubernetes import client as k8s_client def setup(MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_MODEL_BUCKET: str, MINIO_SECRET_KEY: str): pipeline_parameters_block = ''' MINIO_ACCESS_KEY = "{}" MINIO_H...
0.654122
0.182954
from __future__ import unicode_literals import io import os import sys import time import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from testing_support import trial_dir from third_party import mock import gclient_utils import subprocess2 class CheckCallAndFilterTes...
tests/gclient_utils_test.py
from __future__ import unicode_literals import io import os import sys import time import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from testing_support import trial_dir from third_party import mock import gclient_utils import subprocess2 class CheckCallAndFilterTes...
0.436382
0.164215
# Disabling the below pylint warnings in order to use long names convention in the tests # and because some entities are used seamlessly instead of being directly called. # pylint: disable=invalid-name # pylint: disable=unused-import """ tests.TestIntegration ------------------ The integration test set for function...
tests/test_cli.py
# Disabling the below pylint warnings in order to use long names convention in the tests # and because some entities are used seamlessly instead of being directly called. # pylint: disable=invalid-name # pylint: disable=unused-import """ tests.TestIntegration ------------------ The integration test set for function...
0.588416
0.535888
import os import random import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from torchvision.datasets import CIFAR100, CIFAR10 from tqdm import tqdm from tensorboardX import SummaryWriter from models.vae import VAE from config import * from transform import Cifar ...
autoencoder/vae.py
import os import random import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from torchvision.datasets import CIFAR100, CIFAR10 from tqdm import tqdm from tensorboardX import SummaryWriter from models.vae import VAE from config import * from transform import Cifar ...
0.754644
0.375792
import os import board from digitalio import DigitalInOut, Direction import time import touchio import adafruit_dotstar leddot = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1) leddot[0] = (128, 0, 128) leddot.brightness = 0.3 # Set this to True to turn the touchpads into a keyboard ENABLE_KEYBOARD ...
PyRuler Examples/vs-code-shortcuts.py
import os import board from digitalio import DigitalInOut, Direction import time import touchio import adafruit_dotstar leddot = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1) leddot[0] = (128, 0, 128) leddot.brightness = 0.3 # Set this to True to turn the touchpads into a keyboard ENABLE_KEYBOARD ...
0.354098
0.153169
import sqlite3 import os import pandas as pd import numpy as np # Create filepath to csv file DATABASE_FILEPATH = os.path.join(os.path.dirname(__file__), "buddymove_holidayiq.csv") # Read in csv file to dataframe place_review_df = pd.read_csv(DATABASE_FILEPATH) # Basic dataframe exploration print(place_review_df.sam...
module1-introduction-to-sql/buddymove_holidayiq.py
import sqlite3 import os import pandas as pd import numpy as np # Create filepath to csv file DATABASE_FILEPATH = os.path.join(os.path.dirname(__file__), "buddymove_holidayiq.csv") # Read in csv file to dataframe place_review_df = pd.read_csv(DATABASE_FILEPATH) # Basic dataframe exploration print(place_review_df.sam...
0.420719
0.392686
from sys import version_info as _swig_python_version_info if _swig_python_version_info < (2, 7, 0): raise RuntimeError('Python 2.7 or later required') def swig_import_helper(): import importlib pkg = __name__.rpartition('.')[0] mname = '.'.join((pkg, '_mraa')).lstrip('.') try: return importl...
FLIR_pubsub/mraa.py
from sys import version_info as _swig_python_version_info if _swig_python_version_info < (2, 7, 0): raise RuntimeError('Python 2.7 or later required') def swig_import_helper(): import importlib pkg = __name__.rpartition('.')[0] mname = '.'.join((pkg, '_mraa')).lstrip('.') try: return importl...
0.23014
0.053825
import os.path import time from threading import Thread from config_v3_2 import * class FlightLog: """ FlightLog works to intelligently capture flight data in a CSV file :param vehicle: Vehicle instance to log :param logtime: Number of seconds between logging periods (defaults to .1) :param po...
FlightLog.py
import os.path import time from threading import Thread from config_v3_2 import * class FlightLog: """ FlightLog works to intelligently capture flight data in a CSV file :param vehicle: Vehicle instance to log :param logtime: Number of seconds between logging periods (defaults to .1) :param po...
0.478041
0.270763
from . import processor import pygogo as gogo from riko.dotdict import DotDict OPTS = {'listize': True, 'extract': 'attrs', 'ftype': 'none'} logger = gogo.Gogo(__name__, monolog=True).logger def parser(_, attrs, skip=False, **kwargs): """ Parses the pipe content Args: _ (None): Ignored attrs...
riko/modules/itembuilder.py
from . import processor import pygogo as gogo from riko.dotdict import DotDict OPTS = {'listize': True, 'extract': 'attrs', 'ftype': 'none'} logger = gogo.Gogo(__name__, monolog=True).logger def parser(_, attrs, skip=False, **kwargs): """ Parses the pipe content Args: _ (None): Ignored attrs...
0.781205
0.214445
import unittest import datetime from mock import MagicMock from modules import tell class TestTell(unittest.TestCase): def setUp(self): self.phenny = MagicMock() self.phenny.nick = 'phenny' self.phenny.config.host = 'irc.freenode.net' self.input = MagicMock() tell.setup(se...
modules/test/test_tell.py
import unittest import datetime from mock import MagicMock from modules import tell class TestTell(unittest.TestCase): def setUp(self): self.phenny = MagicMock() self.phenny.nick = 'phenny' self.phenny.config.host = 'irc.freenode.net' self.input = MagicMock() tell.setup(se...
0.356447
0.31275
import sphinx.addnodes as sphinx_nodes from sphinx.transforms.post_transforms import SphinxPostTransform from sphinx.util import logging from sphinx.builders.latex import LaTeXBuilder from docutils import nodes as docutil_nodes from .utils import get_node_number, find_parent from .nodes import ( exercise_enumerabl...
sphinx_exercise/post_transforms.py
import sphinx.addnodes as sphinx_nodes from sphinx.transforms.post_transforms import SphinxPostTransform from sphinx.util import logging from sphinx.builders.latex import LaTeXBuilder from docutils import nodes as docutil_nodes from .utils import get_node_number, find_parent from .nodes import ( exercise_enumerabl...
0.694717
0.283031
import pandas as pd import glob import os from pathlib import Path from yaetos.logger import setup_logging logger = setup_logging('Pandas') # --- loading files ---- def load_multiple_csvs(path, read_kwargs): # TODO: to be made obsolete once load_multiple_files works csv_files = glob.glob(os.path.join(path, "...
yaetos/pandas_utils.py
import pandas as pd import glob import os from pathlib import Path from yaetos.logger import setup_logging logger = setup_logging('Pandas') # --- loading files ---- def load_multiple_csvs(path, read_kwargs): # TODO: to be made obsolete once load_multiple_files works csv_files = glob.glob(os.path.join(path, "...
0.200127
0.100216
import math import numpy as np import torch def get_angular_distances(target: np.ndarray, pred: np.ndarray): filter_theta = target[:, 3] == 1 filter_phi = target[:, 4] == 1 target_masked_theta = target[filter_theta] output_masked_theta = pred[filter_theta] theta_gt = target_masked_theta[:, 0] ...
pedrec/evaluations/eval_np/eval_angular.py
import math import numpy as np import torch def get_angular_distances(target: np.ndarray, pred: np.ndarray): filter_theta = target[:, 3] == 1 filter_phi = target[:, 4] == 1 target_masked_theta = target[filter_theta] output_masked_theta = pred[filter_theta] theta_gt = target_masked_theta[:, 0] ...
0.690142
0.813387
import torch from pprint import pprint import config from utils.manager import PathManager from model import * def buildModel(path_manager: PathManager, task_config=None, model_params: config.ParamsConfig = None, loss_func=None, data_source=None,): if m...
builder/model_builder.py
import torch from pprint import pprint import config from utils.manager import PathManager from model import * def buildModel(path_manager: PathManager, task_config=None, model_params: config.ParamsConfig = None, loss_func=None, data_source=None,): if m...
0.471223
0.185818
import contextlib from django.conf import settings from django.core import mail from django.template import Context, Template, loader from django.utils import six, translation from django.contrib import auth def build_mail_context_with_locale(content_dict, locale=settings.LANGUAGE_CODE): """Build context with g...
mail_helper/utils.py
import contextlib from django.conf import settings from django.core import mail from django.template import Context, Template, loader from django.utils import six, translation from django.contrib import auth def build_mail_context_with_locale(content_dict, locale=settings.LANGUAGE_CODE): """Build context with g...
0.478285
0.113481
from django.contrib import admin from django.template.defaultfilters import filesizeformat from django.utils.formats import date_format from django.utils.html import format_html, format_html_join, mark_safe from django.utils.translation import gettext_lazy as _ from cabinet.base_admin import FileAdminBase from cabinet...
cabinet/admin.py
from django.contrib import admin from django.template.defaultfilters import filesizeformat from django.utils.formats import date_format from django.utils.html import format_html, format_html_join, mark_safe from django.utils.translation import gettext_lazy as _ from cabinet.base_admin import FileAdminBase from cabinet...
0.339499
0.054955
from pytest import raises from graphql.error import GraphQLError from graphql.language import ( parse, OperationDefinitionNode, OperationTypeDefinitionNode, SchemaDefinitionNode) from graphql.type import ( GraphQLField, GraphQLObjectType, GraphQLSchema, GraphQLString) from graphql.utilities import get_oper...
tests/utilities/test_get_operation_root_type.py
from pytest import raises from graphql.error import GraphQLError from graphql.language import ( parse, OperationDefinitionNode, OperationTypeDefinitionNode, SchemaDefinitionNode) from graphql.type import ( GraphQLField, GraphQLObjectType, GraphQLSchema, GraphQLString) from graphql.utilities import get_oper...
0.732496
0.511412
import time import who_calls import neo_cgi PROFILER_DATA = [] PROFILER_START = 0 PROFILER_ENABLED = 0 PROFILER_DEPTH = 0 def enable(): global PROFILER_START global PROFILER_ENABLED global PROFILER_DATA PROFILER_START = time.time() PROFILER_ENABLED = 1 PROFILER_DATA = [] def disable(): gl...
python/examples/base/profiler.py
import time import who_calls import neo_cgi PROFILER_DATA = [] PROFILER_START = 0 PROFILER_ENABLED = 0 PROFILER_DEPTH = 0 def enable(): global PROFILER_START global PROFILER_ENABLED global PROFILER_DATA PROFILER_START = time.time() PROFILER_ENABLED = 1 PROFILER_DATA = [] def disable(): gl...
0.222362
0.055081
import copy import pdb import numpy as np from scipy import signal from sklearn.preprocessing import normalize from wfdb.processing.basic import get_filter_gain from wfdb.processing.peaks import find_local_peaks from wfdb.io.record import Record class XQRS(object): """ The QRS detector class for the XQRS algo...
Helpers/ecgpu_detector.py
import copy import pdb import numpy as np from scipy import signal from sklearn.preprocessing import normalize from wfdb.processing.basic import get_filter_gain from wfdb.processing.peaks import find_local_peaks from wfdb.io.record import Record class XQRS(object): """ The QRS detector class for the XQRS algo...
0.849691
0.59887
# Imports # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Python: # 3rd party: # Internal: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ VACCINATIONS_QUERY = """\ SELECT first.area_type, first.area_code, MAX(f...
db_etl_homepage_graphs/queries.py
# Imports # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Python: # 3rd party: # Internal: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ VACCINATIONS_QUERY = """\ SELECT first.area_type, first.area_code, MAX(f...
0.595375
0.148819
import bot import asyncio, logging, discord import unittest import collections def testLogging(): '''() -> Logger class set ups main log so that it outputs to ./test.log and then returns the log''' logger = logging.getLogger('test') logger.setLevel(logging.DEBUG) handler = logging.FileHandler(file...
libs/testlib.py
import bot import asyncio, logging, discord import unittest import collections def testLogging(): '''() -> Logger class set ups main log so that it outputs to ./test.log and then returns the log''' logger = logging.getLogger('test') logger.setLevel(logging.DEBUG) handler = logging.FileHandler(file...
0.253399
0.079603
import sys from os.path import dirname, abspath sys.path.append(dirname(dirname(abspath(__file__)))) import pytest import art from game import ConsoleGame, TimerGame from logic import (Game, GameError, Options, PlayerError, Result, Round, Selection, TimerRound) import pytest from time import time ...
tests/test_game_logic.py
import sys from os.path import dirname, abspath sys.path.append(dirname(dirname(abspath(__file__)))) import pytest import art from game import ConsoleGame, TimerGame from logic import (Game, GameError, Options, PlayerError, Result, Round, Selection, TimerRound) import pytest from time import time ...
0.401453
0.377082
# <NAME> # Center for Coastal and Ocean Mapping # University of New Hampshire # Copyright 2017, All rights reserved. import math import time import threading import rospy from std_msgs.msg import Bool from std_msgs.msg import Float64 from rosgraph_msgs.msg import Clock from asv_srvs.srv import VehicleState from asv_...
nodes/cw4_sim_node.py
# <NAME> # Center for Coastal and Ocean Mapping # University of New Hampshire # Copyright 2017, All rights reserved. import math import time import threading import rospy from std_msgs.msg import Bool from std_msgs.msg import Float64 from rosgraph_msgs.msg import Clock from asv_srvs.srv import VehicleState from asv_...
0.386879
0.116111
from os import path, makedirs # Third party imports # Package application imports import geoimagine.support.karttur_dt as mj_dt from geoimagine.gis import kt_gis as ktgis class LayerCommon: ''' ''' def __init__(self): pass def _SetDOY(self): self.datum.doyStr = mj_dt.YYYYDOYSt...
layers.py
from os import path, makedirs # Third party imports # Package application imports import geoimagine.support.karttur_dt as mj_dt from geoimagine.gis import kt_gis as ktgis class LayerCommon: ''' ''' def __init__(self): pass def _SetDOY(self): self.datum.doyStr = mj_dt.YYYYDOYSt...
0.532425
0.182498
import os from typing import Optional EON = os.path.isfile('/EON') class Service: def __init__(self, port: int, should_log: bool, frequency: float, decimation: Optional[int] = None): self.port = port self.should_log = should_log self.frequency = frequency self.decimation = decimation service_list =...
cereal/services.py
import os from typing import Optional EON = os.path.isfile('/EON') class Service: def __init__(self, port: int, should_log: bool, frequency: float, decimation: Optional[int] = None): self.port = port self.should_log = should_log self.frequency = frequency self.decimation = decimation service_list =...
0.639398
0.318121
import re from django.template.loader import render_to_string from django.conf import settings from capybara_forms.models import SelectData from capybara_forms.utils import django_field_to_capybara_field def _render_filter_string(field, filter_values): return render_to_string('capybara_forms/filter/string.html',...
capybara_forms/renderers/filter.py
import re from django.template.loader import render_to_string from django.conf import settings from capybara_forms.models import SelectData from capybara_forms.utils import django_field_to_capybara_field def _render_filter_string(field, filter_values): return render_to_string('capybara_forms/filter/string.html',...
0.272993
0.274601
from argparse import ArgumentParser from pathlib import Path def parse_args(): parser = ArgumentParser() data = parser.add_argument_group("data") model = parser.add_argument_group("model") training = parser.add_argument_group("training") data.add_argument("--dataset", help="Path to dataset file"...
argument_parser.py
from argparse import ArgumentParser from pathlib import Path def parse_args(): parser = ArgumentParser() data = parser.add_argument_group("data") model = parser.add_argument_group("model") training = parser.add_argument_group("training") data.add_argument("--dataset", help="Path to dataset file"...
0.782953
0.245079
from __future__ import annotations """Domain objects that define features associated with text. """ __author__ = '<NAME>' from typing import List, Tuple, Set, Iterable, Dict, Type, Any from dataclasses import dataclass, field import dataclasses from abc import ABCMeta, abstractmethod import sys import logging from io...
src/python/zensols/nlp/container.py
from __future__ import annotations """Domain objects that define features associated with text. """ __author__ = '<NAME>' from typing import List, Tuple, Set, Iterable, Dict, Type, Any from dataclasses import dataclass, field import dataclasses from abc import ABCMeta, abstractmethod import sys import logging from io...
0.814717
0.326325
# (c) 2018, <NAME> <<EMAIL>> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], ...
awx_collection/plugins/modules/tower_settings.py
# (c) 2018, <NAME> <<EMAIL>> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], ...
0.651355
0.18704
import random import numpy as np from PIL import Image from PIL.Image import BICUBIC from ppasr.data_utils.augmentor.base import AugmentorBase class SpecAugmentor(AugmentorBase): """Augmentation model for Time warping, Frequency masking, Time masking. SpecAugment: A Simple Data Augmentation Method for Auto...
data_utils/augmentor/spec_augment.py
import random import numpy as np from PIL import Image from PIL.Image import BICUBIC from ppasr.data_utils.augmentor.base import AugmentorBase class SpecAugmentor(AugmentorBase): """Augmentation model for Time warping, Frequency masking, Time masking. SpecAugment: A Simple Data Augmentation Method for Auto...
0.823754
0.458227
import rasterio as rio from rasterio import Affine import numpy as np import click def makehappytiff(dst_path, seams_path): kwargs = { 'blockxsize': 256, 'blockysize': 256, 'compress': 'lzw', 'count': 4, 'crs': {'init': u'epsg:3857'}, 'driver': u'GTiff', 'dt...
tests/make_testing_data.py
import rasterio as rio from rasterio import Affine import numpy as np import click def makehappytiff(dst_path, seams_path): kwargs = { 'blockxsize': 256, 'blockysize': 256, 'compress': 'lzw', 'count': 4, 'crs': {'init': u'epsg:3857'}, 'driver': u'GTiff', 'dt...
0.386069
0.435661
import numpy as np import pandas as pd import fastai from fastprogress import force_console_behavior import fastprogress from reco_utils.common import constants as cc def cartesian_product(*arrays): """Compute the Cartesian product in fastai algo. This is a helper function. Args: arrays (tuple of ...
reco_utils/recommender/fastai/fastai_utils.py
import numpy as np import pandas as pd import fastai from fastprogress import force_console_behavior import fastprogress from reco_utils.common import constants as cc def cartesian_product(*arrays): """Compute the Cartesian product in fastai algo. This is a helper function. Args: arrays (tuple of ...
0.813905
0.409339
Sample Input : 1 2 3 4 5 -1 Sample Output : 5 4 3 2 1 Solution : class Node: def __init__(self, data): self.data = data self.next = None def reverse(head): def __init__(self): head = None prev = None current =head while(current is not None): next = current.next ...
6. Linked List - 2.py
Sample Input : 1 2 3 4 5 -1 Sample Output : 5 4 3 2 1 Solution : class Node: def __init__(self, data): self.data = data self.next = None def reverse(head): def __init__(self): head = None prev = None current =head while(current is not None): next = current.next ...
0.518546
0.532729
import threading from time import sleep import InfraBot from InfraModule import InfraModule import Database db = InfraBot.db class Updater(InfraModule): def __init__(self): super().__init__("update", None) def api_entry(self, message, channel, user, team_id): if message.startswith("in "): ...
app/Updater.py
import threading from time import sleep import InfraBot from InfraModule import InfraModule import Database db = InfraBot.db class Updater(InfraModule): def __init__(self): super().__init__("update", None) def api_entry(self, message, channel, user, team_id): if message.startswith("in "): ...
0.432782
0.136522
import urwid import mitmproxy.net.http.url from mitmproxy import exceptions from mitmproxy.tools.console import common from mitmproxy.tools.console import signals from mitmproxy.addons import view from mitmproxy import export def _mkhelp(): text = [] keys = [ ("A", "accept all intercepted flows"), ...
mitmproxy/tools/console/flowlist.py
import urwid import mitmproxy.net.http.url from mitmproxy import exceptions from mitmproxy.tools.console import common from mitmproxy.tools.console import signals from mitmproxy.addons import view from mitmproxy import export def _mkhelp(): text = [] keys = [ ("A", "accept all intercepted flows"), ...
0.36727
0.230292
from keras.layers import Input, Embedding, Bidirectional, LSTM, Dropout, Dense, BatchNormalization, GaussianNoise, concatenate from keras.regularizers import l2 from keras import Model def get_parallel_branch(embeddings): dropout_rate = 0.35 x1 = LSTM(64, activation='tanh', recurrent_activation='sigmoid', r...
scripts/training/reflection/training/multi_export.py
from keras.layers import Input, Embedding, Bidirectional, LSTM, Dropout, Dense, BatchNormalization, GaussianNoise, concatenate from keras.regularizers import l2 from keras import Model def get_parallel_branch(embeddings): dropout_rate = 0.35 x1 = LSTM(64, activation='tanh', recurrent_activation='sigmoid', r...
0.835584
0.526465
import MySQLdb import random from time import sleep root_pass = '' connected = False while not connected: try: db = MySQLdb.connect(host='localhost', user='root', passwd=root_pass) connected = True except MySQLdb.OperationalError: # Poll print("Sleeping...") sleep(5) ...
web/3-sql/db_create.py
import MySQLdb import random from time import sleep root_pass = '' connected = False while not connected: try: db = MySQLdb.connect(host='localhost', user='root', passwd=root_pass) connected = True except MySQLdb.OperationalError: # Poll print("Sleeping...") sleep(5) ...
0.12031
0.089058
import numpy as np import pandas as pd from Bio import SeqIO import math import matplotlib.pyplot as plt import seaborn as sns from scipy.signal import argrelextrema from pathlib import Path from collections import Counter def seq_extract(in_file): """Extrct the sequence from the fasta file Args: ...
stats.py
import numpy as np import pandas as pd from Bio import SeqIO import math import matplotlib.pyplot as plt import seaborn as sns from scipy.signal import argrelextrema from pathlib import Path from collections import Counter def seq_extract(in_file): """Extrct the sequence from the fasta file Args: ...
0.77552
0.644085
import requests import json from purbeurre.models import Product, Category class DatabaseInit: """This class's job is to fill the database with a given file of urls of openfoodfacts categories of products.""" def __init__(self, file): urls_file = open(file, "r") self.urls = [(line.strip()...
purbeurre/database_init.py
import requests import json from purbeurre.models import Product, Category class DatabaseInit: """This class's job is to fill the database with a given file of urls of openfoodfacts categories of products.""" def __init__(self, file): urls_file = open(file, "r") self.urls = [(line.strip()...
0.500732
0.111096
from oslo_config import cfg from oslo_log import log as logging from oslo_utils import versionutils from oslo_versionedobjects import fields from cinder import db from cinder import exception from cinder.i18n import _ from cinder import objects from cinder.objects import base CONF = cfg.CONF # NOTE(thangp): OPTIONAL...
cinder/objects/snapshot.py
from oslo_config import cfg from oslo_log import log as logging from oslo_utils import versionutils from oslo_versionedobjects import fields from cinder import db from cinder import exception from cinder.i18n import _ from cinder import objects from cinder.objects import base CONF = cfg.CONF # NOTE(thangp): OPTIONAL...
0.682574
0.126353
import os import sys import time sys.path.append(os.path.abspath(os.curdir)) from utils.launcher import launch_task from test import test from train import train from test_epic_localization import test_epic_localization from submission_test import submission_test from utils.config import Config def _prepare_data(cf...
runs/run.py
import os import sys import time sys.path.append(os.path.abspath(os.curdir)) from utils.launcher import launch_task from test import test from train import train from test_epic_localization import test_epic_localization from submission_test import submission_test from utils.config import Config def _prepare_data(cf...
0.259544
0.238207
import math import pandas as pd from rpy2 import robjects from rpy2.robjects import pandas2ri def stl( # noqa:C901,WPS210,WPS211,WPS231 time_series: pd.Series, *, frequency: int, ns: int, nt: int = None, nl: int = None, ds: int = 0, dt: int = 1, dl: int = 1, js: int = None, ...
src/urban_meal_delivery/forecasts/methods/decomposition.py
import math import pandas as pd from rpy2 import robjects from rpy2.robjects import pandas2ri def stl( # noqa:C901,WPS210,WPS211,WPS231 time_series: pd.Series, *, frequency: int, ns: int, nt: int = None, nl: int = None, ds: int = 0, dt: int = 1, dl: int = 1, js: int = None, ...
0.830181
0.573141
import sys import os import argparse from sequana_pipetools.options import * from sequana_pipetools.misc import Colors from sequana_pipetools.info import sequana_epilog, sequana_prolog from sequana_pipetools import SequanaManager col = Colors() NAME = "laa" class Options(argparse.ArgumentParser): def __init__(...
sequana_pipelines/laa/main.py
import sys import os import argparse from sequana_pipetools.options import * from sequana_pipetools.misc import Colors from sequana_pipetools.info import sequana_epilog, sequana_prolog from sequana_pipetools import SequanaManager col = Colors() NAME = "laa" class Options(argparse.ArgumentParser): def __init__(...
0.245085
0.082143
import unittest from unittest.mock import Mock from collections import OrderedDict from sawtooth_sdk.processor.context import Context from sawtooth_sdk.messaging.future import Future from sawtooth_sdk.messaging.future import FutureResult from sawtooth_sdk.protobuf.validator_pb2 import Message from sawtooth_sdk.prot...
sdk/python/tests/test_context.py
import unittest from unittest.mock import Mock from collections import OrderedDict from sawtooth_sdk.processor.context import Context from sawtooth_sdk.messaging.future import Future from sawtooth_sdk.messaging.future import FutureResult from sawtooth_sdk.protobuf.validator_pb2 import Message from sawtooth_sdk.prot...
0.745398
0.368974
import unittest from gget.gget_blat import blat class TestBlat(unittest.TestCase): def test_blat_nt(self): df = blat("ATGCTGAATTTATGCTGAATTTATGCTGAATTTATGCTGAATTT") result_to_test = df.values.tolist() expected_result = [ ["hg38", 44, 17, 44, 28, 0, 63.64, 100.0, "chr18", "+", 1...
tests/test_gget_blat.py
import unittest from gget.gget_blat import blat class TestBlat(unittest.TestCase): def test_blat_nt(self): df = blat("ATGCTGAATTTATGCTGAATTTATGCTGAATTTATGCTGAATTT") result_to_test = df.values.tolist() expected_result = [ ["hg38", 44, 17, 44, 28, 0, 63.64, 100.0, "chr18", "+", 1...
0.555073
0.591546
import os import pandas as pd import csv from tqdm import tqdm import json class Format2Category: def __init__(self, source, target): self.source = source self.target = target self.uri = { "/item/getDetail": ["userId", "itemId", "categoryId"], "/item/favor": ["userI...
Stream/process/format2category.py
import os import pandas as pd import csv from tqdm import tqdm import json class Format2Category: def __init__(self, source, target): self.source = source self.target = target self.uri = { "/item/getDetail": ["userId", "itemId", "categoryId"], "/item/favor": ["userI...
0.135718
0.074433
from __future__ import print_function from __future__ import division from __future__ import absolute_import import argparse import torch from utils.names_match_torch import methods import os import numpy as np from utils.common import create_code_snapshot def main(args): # print args recap print(args, end="\...
submissions/nic/code_snapshot/general_main.py
from __future__ import print_function from __future__ import division from __future__ import absolute_import import argparse import torch from utils.names_match_torch import methods import os import numpy as np from utils.common import create_code_snapshot def main(args): # print args recap print(args, end="\...
0.44071
0.099821
import os import shutil import numpy as np from collections import namedtuple import glob import time import datetime import pickle import torch import matplotlib.pyplot as plt from termcolor import cprint from navpy import lla2ned from collections import OrderedDict from dataset import BaseDataset from utils_torch_fil...
ai_imu_dr/main_kitti.py
import os import shutil import numpy as np from collections import namedtuple import glob import time import datetime import pickle import torch import matplotlib.pyplot as plt from termcolor import cprint from navpy import lla2ned from collections import OrderedDict from dataset import BaseDataset from utils_torch_fil...
0.53777
0.26153
import tensorflow as tf import numpy as np from FUNCTION import * def psnr(input, label, shave): assert (label.dtype == input.dtype) if shave != 0: input = input[shave:-shave, shave:-shave, :] label = label[shave:-shave, shave:-shave, :] diff = np.int32(label) - np.int32(input) mse = np...
deep_preprocessing/EVALUATION.py
import tensorflow as tf import numpy as np from FUNCTION import * def psnr(input, label, shave): assert (label.dtype == input.dtype) if shave != 0: input = input[shave:-shave, shave:-shave, :] label = label[shave:-shave, shave:-shave, :] diff = np.int32(label) - np.int32(input) mse = np...
0.473414
0.44342
"""Get river name for location sites""" from django.core.management.base import BaseCommand from django.db.models import F from bims.models.location_site import ( LocationSite, ) from bims.location_site.river import ( allocate_site_codes_from_river ) from bims.utils.logger import log class Command(BaseComman...
bims/management/commands/allocate_site_codes.py
"""Get river name for location sites""" from django.core.management.base import BaseCommand from django.db.models import F from bims.models.location_site import ( LocationSite, ) from bims.location_site.river import ( allocate_site_codes_from_river ) from bims.utils.logger import log class Command(BaseComman...
0.472683
0.205974
import time import cv2 import numpy as np from copy import deepcopy from PIL import Image, ImageDraw, ImageFont from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Conv2D, MaxPooling2D from keras.utils import np_utils from keras import backend as K...
GestureCNN.py
import time import cv2 import numpy as np from copy import deepcopy from PIL import Image, ImageDraw, ImageFont from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Conv2D, MaxPooling2D from keras.utils import np_utils from keras import backend as K...
0.582372
0.213111
from crits.core.crits_mongoengine import EmbeddedCampaign from crits.vocabulary.indicators import ( IndicatorThreatTypes, IndicatorAttackTypes ) def migrate_indicator(self): """ Migrate to the latest schema version. """ migrate_4_to_5(self) def migrate_4_to_5(self): """ Migrate from s...
crits/indicators/migrate.py
from crits.core.crits_mongoengine import EmbeddedCampaign from crits.vocabulary.indicators import ( IndicatorThreatTypes, IndicatorAttackTypes ) def migrate_indicator(self): """ Migrate to the latest schema version. """ migrate_4_to_5(self) def migrate_4_to_5(self): """ Migrate from s...
0.561215
0.220678
import aws_cdk.aws_codebuild as codebuild import aws_cdk.aws_codecommit as codecommit import aws_cdk.aws_codepipeline as codepipeline import aws_cdk.aws_codepipeline_actions as codepipeline_actions import aws_cdk.aws_ecr as ecr import aws_cdk.aws_iam as iam import aws_cdk.core from aws_cdk import core class CdkPipel...
cdk/pipeline/pipeline_old.py
import aws_cdk.aws_codebuild as codebuild import aws_cdk.aws_codecommit as codecommit import aws_cdk.aws_codepipeline as codepipeline import aws_cdk.aws_codepipeline_actions as codepipeline_actions import aws_cdk.aws_ecr as ecr import aws_cdk.aws_iam as iam import aws_cdk.core from aws_cdk import core class CdkPipel...
0.499023
0.06256
import random import requests import cv2 import threading import time import numpy as np import json class Login(): LOGIN_URL = 'https://passport.jd.com/new/login.aspx' QRCODE_URL = 'http://qr.m.jd.com/show?appid=133&size=147&t=' CHECK_URL = 'https://qr.m.jd.com/check?callback=jQuery8392893&appid=133&toke...
mainFile/Login.py
import random import requests import cv2 import threading import time import numpy as np import json class Login(): LOGIN_URL = 'https://passport.jd.com/new/login.aspx' QRCODE_URL = 'http://qr.m.jd.com/show?appid=133&size=147&t=' CHECK_URL = 'https://qr.m.jd.com/check?callback=jQuery8392893&appid=133&toke...
0.155078
0.120827
from glob import glob import os from io import BytesIO import argparse import multiprocessing import cv2 import lmdb from tqdm import tqdm from PIL import Image from torchvision.transforms import functional as trans_fn import constants from utils import format_for_lmdb class Resizer: def __init__(self, data_ty...
prepare_data.py
from glob import glob import os from io import BytesIO import argparse import multiprocessing import cv2 import lmdb from tqdm import tqdm from PIL import Image from torchvision.transforms import functional as trans_fn import constants from utils import format_for_lmdb class Resizer: def __init__(self, data_ty...
0.536556
0.194502
import abc import datetime import json from tweepy import API from tweepy import AppAuthHandler from tweepy import Cursor class BaseClient(abc.ABC): def __init__(self, config_obj): self.count = 0 self.data = [] self.config = config_obj @abc.abstractmethod def fetch_data(self, key...
lib/rinnegan_worker/sources.py
import abc import datetime import json from tweepy import API from tweepy import AppAuthHandler from tweepy import Cursor class BaseClient(abc.ABC): def __init__(self, config_obj): self.count = 0 self.data = [] self.config = config_obj @abc.abstractmethod def fetch_data(self, key...
0.272508
0.103295
import collections import itertools import time from concurrent.futures import ThreadPoolExecutor class LazyThreadPoolExecutor(ThreadPoolExecutor): """ThreadPoolExecutor with lazy iterable collection in map(). Implementation taken from https://github.com/python/cpython/pull/707 """ def map(self, fn...
scripts/word_embeddings/executors.py
import collections import itertools import time from concurrent.futures import ThreadPoolExecutor class LazyThreadPoolExecutor(ThreadPoolExecutor): """ThreadPoolExecutor with lazy iterable collection in map(). Implementation taken from https://github.com/python/cpython/pull/707 """ def map(self, fn...
0.578924
0.196595
import argparse, logging from typing import Dict, Tuple, Any, Callable, Generic, TypeVar from ast import literal_eval from torch.optim import Optimizer, Adam, SparseAdam from torch.optim.lr_scheduler import * from torch.nn import L1Loss, MSELoss from torch.nn import Module # type aliases Name = str ArgumentName = str...
src/pytorch_argparse.py
import argparse, logging from typing import Dict, Tuple, Any, Callable, Generic, TypeVar from ast import literal_eval from torch.optim import Optimizer, Adam, SparseAdam from torch.optim.lr_scheduler import * from torch.nn import L1Loss, MSELoss from torch.nn import Module # type aliases Name = str ArgumentName = str...
0.918439
0.317215
# COMMAND ---------- # MAGIC %md # MAGIC ## Vaccine parameters # COMMAND ---------- # MAGIC %py # MAGIC #Dataset parameters # MAGIC gdppr_data = 'dars_nic_391419_j3w9t_collab.ccu002_vac_gdppr_dars_nic_391419_j3w9t' # MAGIC skinny_data = 'dars_nic_391419_j3w9t_collab.ccu002_vac_skinny_patient' # MAGIC death_data = '...
code/Databricks/CCU002_02-D04-quality_assurance.py
# COMMAND ---------- # MAGIC %md # MAGIC ## Vaccine parameters # COMMAND ---------- # MAGIC %py # MAGIC #Dataset parameters # MAGIC gdppr_data = 'dars_nic_391419_j3w9t_collab.ccu002_vac_gdppr_dars_nic_391419_j3w9t' # MAGIC skinny_data = 'dars_nic_391419_j3w9t_collab.ccu002_vac_skinny_patient' # MAGIC death_data = '...
0.469034
0.33595
class HydratedServiceApi: def __init__(self, client, base_path = "/v1"): self.client = client self.base_path = base_path def findHydratedDatasetVersions(self, body=None): __query = { } if body is None: raise Exception("Missing required parameter \"body\"") format_args = {} path ...
client/verta/verta/_swagger/_public/modeldb/api/HydratedServiceApi.py
class HydratedServiceApi: def __init__(self, client, base_path = "/v1"): self.client = client self.base_path = base_path def findHydratedDatasetVersions(self, body=None): __query = { } if body is None: raise Exception("Missing required parameter \"body\"") format_args = {} path ...
0.488771
0.081264
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.metrics import roc_auc_score, roc_curve import multiprocessing n_train = multiprocessing.cpu_count() n_test = multiprocessing.cpu_count() ligands = ["ADP", "COA", "FAD", "HEM", "NAD", "NAP", "SAM"] lig2num = {l:...
comparison/masif_ligand/Kripo/similarity_results/generate_ROCs.py
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.metrics import roc_auc_score, roc_curve import multiprocessing n_train = multiprocessing.cpu_count() n_test = multiprocessing.cpu_count() ligands = ["ADP", "COA", "FAD", "HEM", "NAD", "NAP", "SAM"] lig2num = {l:...
0.265404
0.304248
import cio import json from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse, NoReverseMatch from django.template.loader import render_to_string from django.utils import translation from django.utils.encoding import smart_unicode from cio.pipeline import pipeline from djed...
djedi/middleware/mixins.py
import cio import json from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse, NoReverseMatch from django.template.loader import render_to_string from django.utils import translation from django.utils.encoding import smart_unicode from cio.pipeline import pipeline from djed...
0.345105
0.068881
import os import logging import numpy as np import torch import torch.nn as nn from components.utils.visualize import plot_train_progress, plot_lcurve from components.data.common import cuda_if_gpu from torch.autograd import Variable from components.trainer import BaseTrainer logger = logging.getLogger('experiment') ...
components/trainer/e2e_trainer_MLP.py
import os import logging import numpy as np import torch import torch.nn as nn from components.utils.visualize import plot_train_progress, plot_lcurve from components.data.common import cuda_if_gpu from torch.autograd import Variable from components.trainer import BaseTrainer logger = logging.getLogger('experiment') ...
0.837686
0.299246
import grpc from tensorflow.contrib.tpu.profiler import tpu_profiler_pb2 as tensorflow_dot_contrib_dot_tpu_dot_profiler_dot_tpu__profiler__pb2 class TPUProfilerStub(object): """The TPUProfiler service retrieves performance information about the programs running on connected TPUs over a period of time. """ d...
venv/lib/python3.6/site-packages/tensorflow/contrib/tpu/profiler/tpu_profiler_pb2_grpc.py
import grpc from tensorflow.contrib.tpu.profiler import tpu_profiler_pb2 as tensorflow_dot_contrib_dot_tpu_dot_profiler_dot_tpu__profiler__pb2 class TPUProfilerStub(object): """The TPUProfiler service retrieves performance information about the programs running on connected TPUs over a period of time. """ d...
0.76476
0.087252
import abc import jsonschema from tabledata import TableData from .._constant import SourceType from .._constant import TableNameTemplate as tnt from ..error import ValidationError from ..formatter import TableFormatter class JsonConverter(TableFormatter): """ The abstract class of JSON data converter. ...
pytablereader/json/formatter.py
import abc import jsonschema from tabledata import TableData from .._constant import SourceType from .._constant import TableNameTemplate as tnt from ..error import ValidationError from ..formatter import TableFormatter class JsonConverter(TableFormatter): """ The abstract class of JSON data converter. ...
0.726814
0.299118
import collections # category: chained dictionaries def chainmap_maps(): """obj.maps(): Linked dictionaries.""" map_one = {1: 0} map_two = {99: "Link"} chained = collections.ChainMap(map_two, map_one) return map_one in chained.maps and chained[99] def chainmap_hierarchy(): """obj.parents...
pyhow/samples/lib/collections.py
import collections # category: chained dictionaries def chainmap_maps(): """obj.maps(): Linked dictionaries.""" map_one = {1: 0} map_two = {99: "Link"} chained = collections.ChainMap(map_two, map_one) return map_one in chained.maps and chained[99] def chainmap_hierarchy(): """obj.parents...
0.876145
0.535098
import sqlite3 import re import sys import time import datetime import csv ##tables creator def tbcreator(): conn = sqlite3.connect("ecom.db") c = conn.cursor() try: c.execute('''CREATE TABLE user ("USER_ID" INTEGER NOT NULL, "LOGIN" TEXT NOT NULL U...
Ecommerceapp/elib.py
import sqlite3 import re import sys import time import datetime import csv ##tables creator def tbcreator(): conn = sqlite3.connect("ecom.db") c = conn.cursor() try: c.execute('''CREATE TABLE user ("USER_ID" INTEGER NOT NULL, "LOGIN" TEXT NOT NULL U...
0.090947
0.04406
import typing as t import jwt from starlette import authentication from starlette.requests import Request from backend import constants # We must import user such way here to avoid circular imports from .user import User class JWTAuthenticationBackend(authentication.AuthenticationBackend): """Custom Starlette a...
backend/authentication/backend.py
import typing as t import jwt from starlette import authentication from starlette.requests import Request from backend import constants # We must import user such way here to avoid circular imports from .user import User class JWTAuthenticationBackend(authentication.AuthenticationBackend): """Custom Starlette a...
0.601711
0.116337
__author__ = '<EMAIL>' """ Diff with IceFiles: 1. <subread_xml> replaces <bas_fofn> (for running Arrow) 2. removed <fasta_fofn> 3. removed <ccs_fofn> 4. s/quiver/arrow """ import os.path as op import re import logging from pbtranscript.Utils import real_ppath, now_str, mkdir from pbtranscript.ice.IceFiles i...
cupcake2/ice2/IceFiles2.py
__author__ = '<EMAIL>' """ Diff with IceFiles: 1. <subread_xml> replaces <bas_fofn> (for running Arrow) 2. removed <fasta_fofn> 3. removed <ccs_fofn> 4. s/quiver/arrow """ import os.path as op import re import logging from pbtranscript.Utils import real_ppath, now_str, mkdir from pbtranscript.ice.IceFiles i...
0.455925
0.181844
import os try: os.chdir('/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/') print(os.getcwd()) except: pass #%% import csv import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt character = pd.read_csv('data/characterization_table.csv') fragments = charact...
scripts/brain_completeness/characterization_table.py
import os try: os.chdir('/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/') print(os.getcwd()) except: pass #%% import csv import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt character = pd.read_csv('data/characterization_table.csv') fragments = charact...
0.10704
0.098903
from sympy.core.numbers import I from sympy.polys.polyerrors import CoercionFailed from sympy.polys.domains import ZZ, QQ from sympy.polys.domains.algebraicfield import AlgebraicField from sympy.polys.domains.domainelement import DomainElement from sympy.polys.domains.field import Field from sympy.polys.domains.ring i...
sympy/polys/domains/gaussiandomains.py
from sympy.core.numbers import I from sympy.polys.polyerrors import CoercionFailed from sympy.polys.domains import ZZ, QQ from sympy.polys.domains.algebraicfield import AlgebraicField from sympy.polys.domains.domainelement import DomainElement from sympy.polys.domains.field import Field from sympy.polys.domains.ring i...
0.870088
0.302861
import logging from typing import Callable from collections import OrderedDict from rx import operators as ops from rx.core import Observable from rx.internal.utils import add_ref from rx.disposable import SingleAssignmentDisposable, RefCountDisposable, CompositeDisposable from rx.subjects import Subject log = loggin...
rx/core/operators/groupjoin.py
import logging from typing import Callable from collections import OrderedDict from rx import operators as ops from rx.core import Observable from rx.internal.utils import add_ref from rx.disposable import SingleAssignmentDisposable, RefCountDisposable, CompositeDisposable from rx.subjects import Subject log = loggin...
0.890938
0.543651
from docopt import docopt,DocoptExit import os import sys import json import pathlib def dictHasKey(myDict,key): if key in myDict.keys(): return True else: return False try: args=docopt(__doc__,help=True,options_first=False) except DocoptExit: print(__doc__) sys.exit(1) path = args...
basefiles/real_start.py
from docopt import docopt,DocoptExit import os import sys import json import pathlib def dictHasKey(myDict,key): if key in myDict.keys(): return True else: return False try: args=docopt(__doc__,help=True,options_first=False) except DocoptExit: print(__doc__) sys.exit(1) path = args...
0.09313
0.116036
import reframe as rfm import reframe.utility.sanity as sn from reframe.core.launchers import LauncherWrapper @rfm.required_version('>=2.14') @rfm.simple_test class CudaGdbCheck(rfm.RegressionTest): def __init__(self): super().__init__() self.valid_prog_environs = ['PrgEnv-gnu'] self.valid...
cscs-checks/tools/profiling_and_debugging/cuda_gdb.py
import reframe as rfm import reframe.utility.sanity as sn from reframe.core.launchers import LauncherWrapper @rfm.required_version('>=2.14') @rfm.simple_test class CudaGdbCheck(rfm.RegressionTest): def __init__(self): super().__init__() self.valid_prog_environs = ['PrgEnv-gnu'] self.valid...
0.30767
0.141667
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser from numpy import argsort, bincount, set_printoptions, where, zeros from numpy.random import seed from generative_process import generate_data import time def test_inference(algorithm, V, D, l, alpha, beta, num_itns, s, args): """ Generates d...
dpmm/test_inference.py
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser from numpy import argsort, bincount, set_printoptions, where, zeros from numpy.random import seed from generative_process import generate_data import time def test_inference(algorithm, V, D, l, alpha, beta, num_itns, s, args): """ Generates d...
0.727007
0.380011
import argparse import os from tempfile import mkdtemp from shutil import rmtree parser = argparse.ArgumentParser(description = 'Build C/CUDA libs with cmake and install \ them to the correct location for the python package') parser.add_argument('--build_dir', help = 't...
build_libs_for_python.py
import argparse import os from tempfile import mkdtemp from shutil import rmtree parser = argparse.ArgumentParser(description = 'Build C/CUDA libs with cmake and install \ them to the correct location for the python package') parser.add_argument('--build_dir', help = 't...
0.126502
0.040332
import maya.cmds as cmds import maya.api.OpenMaya as OpenMaya import cmt.shortcuts as shortcuts import cmt.rig.common as common class SpineRig(object): def __init__( self, start_joint, end_joint, start_control, end_control, name="spine" ): self.effector = None self.ik_handle = None ...
scripts/cmt/rig/spine.py
import maya.cmds as cmds import maya.api.OpenMaya as OpenMaya import cmt.shortcuts as shortcuts import cmt.rig.common as common class SpineRig(object): def __init__( self, start_joint, end_joint, start_control, end_control, name="spine" ): self.effector = None self.ik_handle = None ...
0.636127
0.209571
from discord.ext.commands import Context as _BaseContext import discord import asyncio import contextlib import json from typing import Any, Iterator, Optional, Sequence, Union class Context(_BaseContext): """A Custom Context for extra functionality.""" async def guild_config(self) -> dict: """Gets ...
internal/context.py
from discord.ext.commands import Context as _BaseContext import discord import asyncio import contextlib import json from typing import Any, Iterator, Optional, Sequence, Union class Context(_BaseContext): """A Custom Context for extra functionality.""" async def guild_config(self) -> dict: """Gets ...
0.83602
0.115736
from django.core.management.base import BaseCommand, CommandError from treeio.core.conf import settings import json import subprocess from os import path import sys PROJECT_ROOT = getattr(settings, 'PROJECT_ROOT') HARDTREE_DB_SETTINGS_FILE = path.join(PROJECT_ROOT, 'core/db/dbsettings.json') class Command(BaseComma...
core/management/commands/installdb.py
from django.core.management.base import BaseCommand, CommandError from treeio.core.conf import settings import json import subprocess from os import path import sys PROJECT_ROOT = getattr(settings, 'PROJECT_ROOT') HARDTREE_DB_SETTINGS_FILE = path.join(PROJECT_ROOT, 'core/db/dbsettings.json') class Command(BaseComma...
0.256553
0.035278
import sys import time import os import argparse import logging import numpy as np from picamera.array import PiRGBArray from picamera import PiCamera from skincal import * from config import Config from numpyfb import NumpyFb from PIL import Image if __name__ == "__main__": parser = argparse.ArgumentParser() ...
blackmirror.py
import sys import time import os import argparse import logging import numpy as np from picamera.array import PiRGBArray from picamera import PiCamera from skincal import * from config import Config from numpyfb import NumpyFb from PIL import Image if __name__ == "__main__": parser = argparse.ArgumentParser() ...
0.333286
0.197793
import unittest import mock from scream.monorepo import Monorepo, version_counter from scream.package import Package class MockPackage(Package): """Override Package constructor so we can test the individual methods. """ def __init__(self): pass class MockScream(): def __init__(self, packa...
test/test_monorepo_validation.py
import unittest import mock from scream.monorepo import Monorepo, version_counter from scream.package import Package class MockPackage(Package): """Override Package constructor so we can test the individual methods. """ def __init__(self): pass class MockScream(): def __init__(self, packa...
0.521227
0.504211
import os import dj_database_url import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ.get("SECRET_KEY", "placeholder") DEBUG = os.environ.get("DEBUG", False) ALLOWED_HOSTS = ["*.h...
what_does_af_stand_for/settings.py
import os import dj_database_url import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ.get("SECRET_KEY", "placeholder") DEBUG = os.environ.get("DEBUG", False) ALLOWED_HOSTS = ["*.h...
0.379953
0.147126
import numpy class BFGSFDHessian(): def __init__(self,scheme,df_pointer): self.__scheme=scheme self.__dfpointer=df_pointer def get_scheme(self): return self.__scheme def iterate_bfgs_mat(self,H,xk,xkp1,grad_k,grad_kp1): sk=numpy.atleast_2d(xkp1-xk).T#numpy...
sos_trades_core/tools/grad_solvers/validgrad/BFGSFDHessian.py
import numpy class BFGSFDHessian(): def __init__(self,scheme,df_pointer): self.__scheme=scheme self.__dfpointer=df_pointer def get_scheme(self): return self.__scheme def iterate_bfgs_mat(self,H,xk,xkp1,grad_k,grad_kp1): sk=numpy.atleast_2d(xkp1-xk).T#numpy...
0.117826
0.232163
from __future__ import unicode_literals, division, print_function, absolute_import import argparse from captain.reflection import ( ReflectCommand, ReflectMethod, ParseArg, Name, ) from captain import Command from . import testdata, TestCase, FileScript, ModuleScript class ReflectCommandTest(TestCas...
tests/reflection_test.py
from __future__ import unicode_literals, division, print_function, absolute_import import argparse from captain.reflection import ( ReflectCommand, ReflectMethod, ParseArg, Name, ) from captain import Command from . import testdata, TestCase, FileScript, ModuleScript class ReflectCommandTest(TestCas...
0.544801
0.350408
import csv import cv2 import os import numpy as np import glob import matplotlib.pyplot as plt from matplotlib.patches import Patch from ..base import BaseDataset from ..utils import image_loader from .schemas import SegmentationDatasetSchema #"Background": 0 #"Buildings": 1 LABELS = ["Background", "Buildings"] # Co...
aitlas/datasets/massachusetts_buildings.py
import csv import cv2 import os import numpy as np import glob import matplotlib.pyplot as plt from matplotlib.patches import Patch from ..base import BaseDataset from ..utils import image_loader from .schemas import SegmentationDatasetSchema #"Background": 0 #"Buildings": 1 LABELS = ["Background", "Buildings"] # Co...
0.516839
0.435271
import smtplib from os.path import basename from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate class Mailer(object): port = 25 server = "127.0.0.1" tls = False authenticat...
ad2web/mailer.py
import smtplib from os.path import basename from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate class Mailer(object): port = 25 server = "127.0.0.1" tls = False authenticat...
0.273671
0.102799
__all__ = ["SubcommandInvocationRequired", "Command", "Group", "command", "group"] from discord.ext import commands class SubcommandInvocationRequired(commands.CommandError): """A :class:`discord.ext.commands.CommandError` that is subclass raised when a subcommand needs to be invoked.""" class Command(command...
lifesaver/commands/core.py
__all__ = ["SubcommandInvocationRequired", "Command", "Group", "command", "group"] from discord.ext import commands class SubcommandInvocationRequired(commands.CommandError): """A :class:`discord.ext.commands.CommandError` that is subclass raised when a subcommand needs to be invoked.""" class Command(command...
0.87584
0.168412
from spotty.errors.instance_not_running import InstanceNotRunningError from spotty.deployment.abstract_cloud_instance.abstract_cloud_instance_manager import AbstractCloudInstanceManager from spotty.providers.aws.resource_managers.bucket_manager import BucketManager from spotty.providers.aws.config.instance_config impor...
spotty/providers/aws/instance_manager.py
from spotty.errors.instance_not_running import InstanceNotRunningError from spotty.deployment.abstract_cloud_instance.abstract_cloud_instance_manager import AbstractCloudInstanceManager from spotty.providers.aws.resource_managers.bucket_manager import BucketManager from spotty.providers.aws.config.instance_config impor...
0.849441
0.085137