id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1783779 | import logging
import os
import argparse
from simpletransformers.language_generation import LanguageGenerationModel
logging.basicConfig(level=logging.INFO)
transformers_logger = logging.getLogger("transformers")
transformers_logger.setLevel(logging.WARNING)
def main():
parser = argparse.ArgumentParser()
# Re... |
1783818 | from typing import List
from esque.io.messages import BinaryMessage, Message
from esque.io.serializers.base import MessageSerializer
from esque.io.serializers.string import StringSerializer
def test_message_serializer(
binary_messages: List[BinaryMessage], string_messages: List[Message], string_serializer: Strin... |
1783828 | import os
import sys
import time
from enum import Enum
from typing import Tuple, Optional
import requests
from bs4 import BeautifulSoup
from pySmartDL import SmartDL
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, StaleElementReferenceException
from selenium.webdriver.common.by ... |
1783829 | from watchdog.utils.dirsnapshot import DirectorySnapshot
import os
from saveFileHandler.filehandler import *
from saveFileHandler.features import Terrains, Features
import time
import multiprocessing as mp
import pyqtgraph as pg
import copy
from collections import defaultdict
import numpy as np
from saveFileHandler.civ... |
1783864 | import gym
import os
from gym import spaces
import numpy as np
from pepper_2d_iarlenv import parse_iaenv_args, IARLEnv, check_iaenv_args
from pkg_resources import resource_filename
class ToyEnv(gym.Env):
def __init__(self):
super(ToyEnv, self).__init__()
self.action_space = spaces.Box(low=-1, high=... |
1783896 | import numpy as np
from sklearn.externals import joblib
import random
class Batcher:
def __init__(self,storage,data,batch_size,context_length,id2vec,vocab_size):
self.context_length = context_length
self.storage = storage
self.data = data
self.num_of_samples = int(data.shape[0])
... |
1783900 | import os
import hashlib
from time import sleep
from pathlib import Path
from threading import Thread, RLock
import cv2
import dhash
from PIL import Image
class Extractor:
MAX_SAVE_PER_STREAM = 15
MAX_BLANK = 2
def __init__(self, class_names, ip_addresses, detector, output_dir,
workers)... |
1783929 | from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.behaviors import ToggleButtonBehavior
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.properties import ObjectProperty, StringProperty
fr... |
1783937 | from os.path import join
import torch
from kornia import geometry
from ..agents.base import BaseModule
from ..dataset import JointsConstructor
from ..models.hourglass import HourglassModel
from ..models.metrics import MPJPE
from ..utils import average_loss
class HourglassEstimator(BaseModule):
"""
Agent for... |
1783942 | from xml.dom.minidom import Document
import os
import os.path
import xml.etree.ElementTree as ET
from tqdm import tqdm
opj = os.path.join
txt_path = "submit.txt"
xml_path = "inference_xml"
img_name=[]
if not os.path.exists(xml_path):
os.mkdir(xml_path)
def indent(elem, level=0):
i = "\n" +... |
1783946 | from distutils.command.register import register as _register
class register(_register):
__doc__ = _register.__doc__
def run(self):
# Make sure that we are using valid current name/version info
self.run_command('egg_info')
_register.run(self)
|
1783957 | from django import forms
from django.contrib.auth.models import User
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(label='Password',
widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username',)
|
1783993 | import os
import argparse
import numpy as np
import glob
import imageio
import scipy.io as sio
from plyfile import PlyElement, PlyData
from parse import parse
from sklearn.neighbors import NearestNeighbors as nnbrs
from scipy.spatial import KDTree
from collections import Counter
from multiprocessing import Pool
import ... |
1784009 | import json
import ssl
from http.client import HTTPSConnection, HTTPConnection
from time import time
from urllib.parse import parse_qsl, urlparse, urlencode
class Request:
def __init__(self, wsgi_environ):
self.create_time = time()
self.body = None
self._wsgi_environ = wsgi_environ
... |
1784084 | from keras.layers import Conv2D, Dense, MaxPooling2D, AveragePooling2D, BatchNormalization
from keras.layers import GlobalAveragePooling2D, GlobalMaxPooling2D
from utils.keras_sparisity_regularization import SparsityRegularization
from copy import deepcopy
import numpy as np
def freeze_SR_layer(model, prune_rate=0.):... |
1784124 | import functools
import argparse
import logging
import random
import numpy as np
import torch
from data_search import load_dir
from search import LocalSearch
from multiprocessing import Pool
logger = logging.getLogger(__name__)
def flip_update(fp, flips, max_flips):
mf, af, xf, sv = fp
med = np.median(flip... |
1784151 | from typing import List
def extract_commands(conf: dict) -> (List[str], List[str]):
commands: List[str] = conf.get("command")
if not commands:
return [], []
values = []
keys = []
for cmd in commands:
if cmd is None:
continue
if "=" in cmd:
firstEqual... |
1784180 | import json
from pathlib import Path
import numpy as np
from podm.podm import get_pascal_voc_metrics, MetricPerClass
from tests.utils import load_data, assert_results, load_data_coco
def test_sample2():
dir = Path('tests/sample_2')
gt_BoundingBoxes = load_data(dir / 'groundtruths.json')
pd_BoundingBoxes... |
1784196 | import shutil
import tempfile
import unittest
from pathlib import Path
import pandas as pd
from depiction.models.examples.celltype.celltype import CellTyper
class CellTyperTestCase(unittest.TestCase):
"""Test celltype classifier."""
def setUp(self):
"""Prepare data to predict."""
filepath =... |
1784197 | from django.db.models.signals import post_save
from django.dispatch import receiver
from researchhub_case.constants.case_constants import APPROVED, INITIATED
from researchhub_case.models import AuthorClaimCase
from researchhub_case.utils.author_claim_case_utils import (
get_new_validation_token,
reward_author_clai... |
1784228 | from __future__ import unicode_literals
import io
from future.utils import itervalues
from mock import patch
from snips_nlu.constants import (
RES_ENTITY, RES_INTENT, RES_INTENT_NAME, RES_SLOTS, RES_VALUE,
RANDOM_STATE)
from snips_nlu.dataset import Dataset
from snips_nlu.exceptions import IntentNotFoundErro... |
1784235 | import os
from mkultra.soft_prompt import SoftPrompt
import torch
import json
def test_json(inference_resources):
model, tokenizer = inference_resources
# Arrange
sp_a = SoftPrompt.from_string(" a b c d e f g", model=model, tokenizer=tokenizer)
# Act
sp_str = sp_a.to_json()
sp_b = SoftPrompt.... |
1784279 | import os
from google.cloud import datastore
PLATFORM_DIR = os.path.abspath(os.path.dirname(__file__))
BASE_DIR = os.path.dirname(PLATFORM_DIR)
PERF_DIR = os.path.join(BASE_DIR, "performance_results")
LOG_DIR = os.path.join(BASE_DIR, "logs")
STRAT_DIR = os.path.join(PLATFORM_DIR, "strategy")
DEFAULT_CONFIG_FILE = os.... |
1784318 | from os import makedirs
from os.path import expanduser, exists
from logging import getLogger, Formatter, StreamHandler, DEBUG, WARN
from logging.handlers import RotatingFileHandler
from termcolor import colored
LOG_COLORS = {
"DEBUG": "grey",
"INFO": "cyan",
"WARNING": "yellow",
"ERROR": "magenta",
... |
1784325 | from tg.request_local import Request, Response
import logging
log = logging.getLogger(__name__)
class SeekableRequestBodyMiddleware(object):
def __init__(self, app):
self.app = app
def _stream_response(self, data):
try:
for chunk in data:
yield chunk
final... |
1784332 | from .detail.const_dict import ConstDict
from .detail.common import timestamp_now, _to_float
from datetime import datetime
import pandas as pd
class QuoteBase(ConstDict):
def __init__(self, quote, time=None):
quote['time'] = time if time else timestamp_now()
ConstDict.__init__(self, quote)
def _get(self, key)... |
1784369 | import aisy_sca
from app import *
from custom.custom_models.neural_networks import *
aisy = aisy_sca.Aisy()
aisy.set_resources_root_folder(resources_root_folder)
aisy.set_database_root_folder(databases_root_folder)
aisy.set_datasets_root_folder(datasets_root_folder)
aisy.set_database_name("database_ascad.sqlite")
aisy... |
1784392 | from datetime import datetime
from pathlib import Path
import pytest
from PIL import Image
from pytest_toolbox import gettree, mktree
from pytest_toolbox.comparison import RegexStr
from harrier.build import FileData
from harrier.config import Mode
from harrier.main import build
from harrier.render import json_filter,... |
1784418 | import cv2
from imutils.video import WebcamVideoStream
from imutils import resize
import requests
def detect(img, url='http://localhost:5000/detect?landmarks=on&gender=on'):
_, img_encoded = cv2.imencode('.jpg', img)
resp = requests.post(url, data=img_encoded.tostring())
return resp.json()
camera = Webc... |
1784454 | import sys, os
sys.path.append(os.path.dirname(os.getcwd()))
from tensorflow import keras
import numpy as np
from pyradox import convnets
def test_1():
inputs = keras.Input(shape=(28, 28, 1))
x = convnets.GeneralizedVGG(
conv_config=[(2, 32), (2, 64)],
dense_config=[28],
conv_batch_n... |
1784504 | LibDir = "/var/lib/waagent"
Openssl = "openssl"
os_release = "/etc/os-release"
system_release = "/etc/system-release"
class WALAEventOperation:
HeartBeat = "HeartBeat"
Provision = "Provision"
Install = "Install"
UnInstall = "UnInstall"
Disable = "Disable"
Enable = "Enable"
Download = "Dow... |
1784528 | from typing import Tuple, Optional
import torch
import torch.nn as nn
from torecsys.layers import BiasEncodingLayer
from torecsys.models.ctr import CtrBaseModel
class DeepSessionInterestNetworkModel(CtrBaseModel):
"""
# TODO: [in development]
Model class of Deep Session Interest Network (DSIN), which i... |
1784612 | import logging
import click
import torch
from sonosco.serialization import Deserializer
from sonosco.models import TDSSeq2Seq
from sonosco.common.constants import SONOSCO
from sonosco.common.utils import setup_logging
from sonosco.common.path_utils import parse_yaml
from sonosco.training import Experiment, ModelTraine... |
1784616 | import datetime
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import timezone
import requests
from data_refinery_common.models import Dataset, DatasetAnnotation
def post_downloads_summary(days, channel):
start_time = timezone.now() - datetime.timedelta(d... |
1784620 | import click
from Bio import SeqIO
from Bio.Seq import Seq
from .CAI import CAI
@click.command()
@click.option(
"-s",
"--sequence",
type=click.Path(exists=True, dir_okay=False),
help="The sequence to calculate the CAI for.",
required=True,
)
@click.option(
"-r",
"--reference",
type=cli... |
1784641 | from __future__ import annotations
from homeassistant.components.select import (
DOMAIN as PLATFORM_SELECT,
SelectEntity
)
from .merossclient import const as mc # mEROSS cONST
from .meross_entity import _MerossEntity, platform_setup_entry, platform_unload_entry
async def async_setup_entry(hass: object, con... |
1784681 | import pytest
class TestMainModule:
def test_main_module(self, capsys):
with pytest.raises(SystemExit):
from snowfakery import __main__ as _unused
_unused = _unused # flake8
assert "Usage:" in capsys.readouterr().err
|
1784703 | from nltk import word_tokenize
import nltk.data
from readability import Readability
import pprint
import string
import numpy
import math
numpy.seterr(divide='ignore', invalid='ignore')
sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')
def clean_words(words):
new_words = []
for word in words... |
1784711 | from torch import nn
class TransBlockDual(nn.Module):
def __init__(self, size):
super(TransBlockDual, self).__init__()
self.main = nn.Sequential(
nn.Conv2d(2*size, size, 3, padding=1),
nn.BatchNorm2d(size),
nn.ReLU(True),
nn.Conv2d(size, size, 3, padd... |
1784733 | from collections import OrderedDict
TARGETS = OrderedDict([('2.7', (2, 7)),
('3.0', (3, 0)),
('3.1', (3, 1)),
('3.2', (3, 2)),
('3.3', (3, 3)),
('3.4', (3, 4)),
('3.5', (3, 5)),
... |
1784757 | import copy
import torch
from mmcv.runner import obj_from_dict
from mmgen.models import GANLoss, L1Loss, build_model
from mmgen.models.architectures.pix2pix import (PatchDiscriminator,
UnetGenerator)
def test_pix2pix():
# model settings
model_cfg = dict(
... |
1784766 | import gc
import resource
import itertools
import matplotlib
matplotlib.use('Agg') # required if X11 display is not present
import matplotlib.pyplot as plt
import pickle
import pysam
import re
import os
import numpy as np
from bisect import bisect_left
from collections import defaultdict
from math import floo... |
1784807 | import importlib
import pkgutil
from . import formatters
class AssetFormatter():
_by_name = {}
_by_extension = {}
def __init__(self, components=None, extensions=None):
self.components = components if components else (None, )
self.extensions = extensions
def __call__(self, fragment_f... |
1784845 | from __future__ import unicode_literals
import os
import unittest
from webtest import TestApp
from pyramid.testing import DummyRequest
from billy import main
from billy.db.tables import DeclarativeBase
from billy.models import setup_database
from billy.models.model_factory import ModelFactory
from billy.tests.fixture... |
1784847 | from . import good, fail
# dummy
good('*', 0)
good('*', [1])
good('*', None)
fail('#', None)
good('*|#', None)
fail('*,#', None)
|
1784848 | from utils.apicalls import GoogleAds
from utils.paths import PATH_DEFINE_VALUES
import utils.time
import pandas
import logging
def googlereports(customer_ids):
reports=pandas.DataFrame()
for customer_id in customer_ids:
data = GoogleAds()
data = data.reports(dateStart=utils.time.start... |
1784875 | from dataclasses import dataclass, replace
from typing import Type
import numpy as np
from numpy import ndarray
from ..element import Element, ElementHex1
from .mesh_3d import Mesh3D
from .mesh_tet_1 import MeshTet1
@dataclass(repr=False)
class MeshHex1(Mesh3D):
"""A standard first-order hexahedral mesh.
I... |
1784882 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
################# Postprocessing #########################
METPostprocessing = DQMEDHarvester('METTesterPostProcessor')
################ Postprocessing Harvesting #########################
METPostprocessingHarvesting... |
1784886 | from cellrank.tl.estimators._base_estimator import BaseEstimator
from cellrank.tl.estimators.terminal_states import GPCCA, CFLARE, TermStatesEstimator
|
1784899 | import pytest
import petlib
@pytest.mark.task1
def test_petlib_present():
"""
Try to import Petlib and pytest to ensure they are
present on the system, and accessible to the python
environment
"""
import petlib
import pytest
assert True
@pytest.mark.task1
def test_code_present():
... |
1784975 | from nltk import tokenize
import numpy as np
import os
import re
from itertools import permutations
# analystic constants
punc_list = [",", ".", ")", "_", "-", "/", '"', "'", "}", "]", "|", "?", "!"]
char_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "... |
1784981 | from setuptools import setup, find_packages
install_requires = [
'lxml>=4.5.0',
'zope.interface>=4.1.3',
]
setup(
name='cpcli',
version='0.8',
description='Competitive Programming CLI',
author='<NAME>',
author_email='<EMAIL>',
long_description=open('README.rst', 'r', encoding='utf-8').... |
1784999 | import os
import shutil
from sentinel_data_preparation import utils
import rasterio
import numpy as np
import matplotlib.pyplot as plt
class SensorProcessing():
def __init__(self, params):
self.params = params
self.ignore_value = -1
self.layover_mask = None
def process_data(self, input... |
1785019 | import numpy as np
from qtrader.agents.base import Agent
class UniformAgent(Agent):
"""Uniform agent."""
_id = 'uniform'
def __init__(self, action_space):
self.N = action_space.shape[0]
def act(self, observation):
return np.ones(self.N) / self.N
|
1785033 | import pytest
from api.base.settings.defaults import API_BASE
from api_tests.requests.mixins import NodeRequestTestMixin, PreprintRequestTestMixin
@pytest.mark.django_db
class TestActionDetailNodeRequests(NodeRequestTestMixin):
@pytest.fixture()
def url(self, node_request):
action = node_request.acti... |
1785058 | import numpy as np
import numpy.ma as ma
from numpy.testing import assert_array_equal
from cloudnetpy.categorize import falling
import pytest
class Obs:
def __init__(self):
self.z = ma.array([[.4, .5, .6, .7, .5, .5],
[.5, .5, .5, .5, .5, .5]],
mask=[[... |
1785107 | import unittest
import os
import flask
from mock import Mock, patch, ANY
from flask_mab import BanditMiddleware,add_bandit,choose_arm,reward_endpt
import flask_mab.storage
from flask_mab.bandits import EpsilonGreedyBandit
from werkzeug.http import parse_cookie
import json
from utils import makeBandit
class RequestFl... |
1785127 | from .recount import recount
from .admin import admin
from .default import default
from .migration import migration
from .route import route
from .translations import translations
from .user import user
commands = [migration, recount, route, admin, default, translations, user]
|
1785147 | import numpy as np
from scipy.special import gamma
def multivariate_t_density(nu, mu, Sig, x):
"""Return multivariate t distribution: t_nu(x | mu, Sig), in d-dimensions."""
detSig = np.linalg.det(Sig)
invSig = np.linalg.inv(Sig)
d = len(mu)
coef = gamma(nu/2.0+d/2.0) * detSig**(-0.5)
coef /= g... |
1785152 | from .part import Part
from .primitives import Long, Int
class Stat(Part):
"""
Znode stat structure
Contains attributes:
- **created_zxid** The zxid of the change that created this znode.
- **last_modified_zxid** The zxid of the change that last modified
this znode.
- **created** The t... |
1785154 | import torch
import torch.nn as nn
from torch import Tensor
from .Embedding import PositionalEmbedding
from .loss import SCELoss
from utils import generate_square_subsequent_mask
from typing import List, Tuple, Optional
class CapDecoder(nn.Module):
def __init__(self, num_layers, embed_dim, nhead, dim_feedforward... |
1785220 | import enum
from kopf._cogs.aiokits import aioenums
class DaemonStoppingReason(enum.Flag):
"""
A reason or reasons of daemon being terminated.
Daemons are signalled to exit usually for two reasons: the operator itself
is exiting or restarting, so all daemons of all resources must stop;
or the in... |
1785225 | from unittest.mock import Mock
class AsyncMock(Mock):
async def __call__(self, *args, **kwargs):
result = super().__call__(*args, **kwargs)
return result
|
1785226 | from torchvision.datasets.vision import VisionDataset
from PIL import Image
import os
import os.path
import torch
import numpy as np
# TODO: remove `device`?
def convert_ann(ann, device):
xmin, ymin, w, h = ann['bbox']
# DEBUG
if w <= 0 or h <= 0:
raise ValueError("Degenerate bbox (x, y, w, h): ",... |
1785232 | from fabric.api import local
exclude_command = "--exclude nlpre/spacy_models/"
def test():
local("nosetests --with-coverage --cover-package nlpre --cover-html")
def lint():
local(f"black -l 80 nlpre tests *.py {exclude_command}")
local(f"flake8 nlpre --ignore=E501,E203,W503 {exclude_command}")
def vi... |
1785242 | from .Emulator import Emulator, Device
from external.containers.emu import docker_device, emu_docker, emu_downloads_menu
import subprocess
import logging
import time
import sys
class DockerEmulator(Emulator):
def __init__(self, path_config, configuration, ):
Device.__init__(self, path_config, configurat... |
1785270 | import time
from datetime import datetime, timezone
import bme680
from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS
from pydantic import BaseSettings
class Settings(BaseSettings):
hive_name: str
token: str
org: str
bucket: str
... |
1785289 | from django.contrib import admin
from .models import Artical, Reporter
admin.site.register(Artical)
admin.site.register(Reporter)
|
1785307 | import sys
import unittest
import dask.array
import dask.distributed as dd
import numpy as np
import xarray as xr
# Import from directory structure if coverage test, or from installed
# packages otherwise
if "--cov" in str(sys.argv):
from src.geocat.comp import dewtemp, heat_index, relhum, relhum_ice, relhum_wate... |
1785383 | from cleo.commands.command import Command
from cleo.io.io import IO
class FooSubNamespaced1Command(Command):
name = "foo bar baz"
description = "The foo bar baz command"
aliases = ["foobarbaz"]
def handle(self) -> int:
return 0
|
1785398 | import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
import numpy as np
def gastrack(df: pd.DataFrame,
gas: list = None,
lims: list = None,
dtick: bool =False,
ax=None,
gas_range:list =[0.2,20000],
fontsize:int =8... |
1785433 | import numpy as np
from scipy.optimize import check_grad
from deep_rlsp.solvers.value_iter import value_iter, evaluate_policy
from deep_rlsp.solvers.ppo import PPOSolver
from deep_rlsp.util.parameter_checks import check_in
def compute_g(mdp, policy, p_0, T, d_last_step_list, expected_features_list):
nS, nA, nF =... |
1785462 | import oneflow as flow
def build_train_graph(
model, criterion, data_loader, optimizer, lr_scheduler=None, *args, **kwargs
):
return TrainGraph(
model, criterion, data_loader, optimizer, lr_scheduler, *args, **kwargs
)
def build_eval_graph(model, data_loader):
return EvalGraph(model, data_lo... |
1785529 | from __future__ import division
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.contrib.layers.python.layers import utils
import numpy as np
SCALING = 1.0
BIAS = 0.
def resize_like(inputs, ref):
iH, iW = inputs.get_shape()[1], inputs.get_shape()[2]
rH, rW = ref.get_shape()[1], re... |
1785569 | from django.contrib.auth.decorators import login_required
from django.urls import path
from . import views
app_name = "edd.load"
urlpatterns = [
path("", login_required(views.ImportTableView.as_view()), name="table"),
path("wizard/", login_required(views.ImportView.as_view()), name="wizard"),
]
|
1785591 | import numpy as np
from transonic import boost, Array, Type
A = Array[Type(np.float64, np.complex128), "3d"]
Af = "float[:,:,:]"
A = Af # issue fused type with Cython
def proj(vx: A, vy: A, vz: A, kx: Af, ky: Af, kz: Af, inv_k_square_nozero: Af):
tmp = (kx * vx + ky * vy + kz * vz) * inv_k_square_nozero
vx ... |
1785595 | import requests
import json
from config import config
from api_client.url_helpers.internal_app_url import get_create_internal_app_from_blob_url, get_edit_assignment_url
from api_client.url_helpers.internal_app_url import get_retire_app_url, get_internal_app_assignment_url
from Logs.log_configuration import configure_l... |
1785611 | from .connector import AirbyteSpec, Connector
from .entrypoint import AirbyteEntrypoint
from .logger import AirbyteLogger
__all__ = ["AirbyteEntrypoint", "AirbyteLogger", "AirbyteSpec", "Connector"]
|
1785613 | import numpy as np
import cv2
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.models import Model
import gc
tf.compat.v1.disable_eager_execution()
def normalize(x):
"""Utility function to normalize a tensor by its L2 norm"""
retu... |
1785667 | import jieba
def handle_line(entity1, entity2, sentence, begin_e1_token='<e1>', end_e1_token='</e1>', begin_e2_token='<e2>',
end_e2_token='</e2>'):
assert entity1 in sentence
assert entity2 in sentence
sentence = sentence.replace(entity1, begin_e1_token + entity1 + end_e1_token)
senten... |
1785701 | from qtpy import QtCore, QtGui, QtWidgets, uic
import os
import copy
import sys
import pathlib
import json
from logzero import logger
from modules.multithreading import Worker, ProgressDialog
class_name = 'source_update_tab'
class AddProcessingRuleDialog(QtWidgets.QDialog):
def __init__(self):
super(Add... |
1785713 | from django.conf.urls.defaults import *
from django.contrib import admin
from django.views.generic.simple import direct_to_template
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns(
'',
# Looser pattern matching for workspace username (as opposed to \w+)
# Already in madrona 4.... |
1785720 | from tree_node import TreeNode
class MerkleNode(TreeNode):
def __init__(self, value):
super(MerkleNode, self).__init__(value)
self.hash = str(value)
|
1785725 | from encoded.reports.constants import BATCH_DOWNLOAD_COLUMN_TO_FIELDS_MAPPING
from encoded.reports.constants import SERIES_BATCH_DOWNLOAD_COLUMN_TO_FIELDS_MAPPING
from encoded.reports.constants import METADATA_LINK
from encoded.reports.constants import AT_IDS_AS_JSON_DATA_LINK
from encoded.reports.metadata import Metad... |
1785726 | import logging
import sys
from utils.env_vars import is_debug_mode_on
FORMATTER = logging.Formatter("%(asctime)s — %(name)s — %(levelname)s — %(message)s")
LOG_FILE = "edr.log"
def get_console_handler():
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(FORMATTER)
return c... |
1785749 | import numpy as np
import torch
import copy, os
from collections import OrderedDict
from util.util import util
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
import glob
import torch.nn.functional as F
import cv2
from skimage import io
def norm_image(image):
"""
... |
1785792 | from pathlib import Path
from ombpdf.semdom import to_dom
from .snapshot import assert_snapshot_matches
MY_DIR = Path(__file__).parent
def assert_dom_xml_snapshot_matches(doc, force_overwrite=False):
dom = to_dom(doc)
xml = dom.toprettyxml(indent=' ')
name = Path(doc.filename).stem
expected_xml_pa... |
1785794 | import graphene
from netbox.graphql.fields import ObjectField, ObjectListField
from .types import *
class ExtrasQuery(graphene.ObjectType):
config_context = ObjectField(ConfigContextType)
config_context_list = ObjectListField(ConfigContextType)
custom_field = ObjectField(CustomFieldType)
custom_fiel... |
1785815 | from models import resnet_ilsvrc
from models import resnet_cifar as cresnet, vgg_cifar as cvgg
def check_model(opt):
if opt.model.startswith('resnet'):
if opt.dataset in ['cub200', 'indoor', 'stanford40', 'flowers102', 'dog', 'tinyimagenet']:
ResNet = resnet_ilsvrc.__dict__[opt.model]
... |
1785821 | import numpy as np
import math
class Matrix4:
def __init__(self, elements=[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], order="F") -> None:
self.__order = order
self.__matrix = np.array(elements).reshape(4, 4, order=order)
@property
def matrix(self):
return self.__m... |
1785831 | from pyrate.algorithms.aisparser import run, AIS_CSV_COLUMNS, readcsv
from pyrate.repositories.aisdb import AISdb
from pyrate.repositories import file
from utilities import setup_database
import os
import tempfile
from pytest import fixture
import csv
def make_temporary_file():
""" Returns a temporary file name
... |
1785832 | import os
import sys
cwd = os.getcwd()
sys.path.append(cwd)
from time import sleep
import pybullet as p
import numpy as np
def setUpWorld(initialSimSteps=100):
"""
Reset the simulation to the beginning and reload all models.
Parameters
----------
initialSimSteps : int
Returns
-------
... |
1785838 | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='white', palette='colorblind', context='talk')
heights = [4, 2, 4]
xlabels = ['Congruent', 'Control', 'Incongruent']
xticks = range(len(xlabels))
f, ax = plt.subplots(1, 1, figsize=(6, 5))
cpal = sns.color_palette(n_colors=len(xla... |
1785878 | from enum import IntEnum, auto
class AuditFrequency(IntEnum):
JUST_ONCE = auto()
DAILY = auto()
WEEKLY = auto()
MONTHLY = auto()
QUARTERLY = auto()
YEARLY = auto()
class AuditState(IntEnum):
SCHEDULED = auto()
REPLICATING = auto()
CRACKING = auto()
ANALYZING = auto()
SEND... |
1785890 | class SubarraySumOptimizer:
def __init__(self, arr):
self.arr = arr
total = 0
self.larr = [total]
for num in self.arr:
total += num
self.larr.append(total)
def sum(self, start, end):
if start < 0 or end > len(self.arr) or start > end:
... |
1785955 | def _repr(node, args=None, nameblacklist=None):
classname = node.__class__.__name__
args = args or []
nameblacklist = nameblacklist or []
for key, value in filter(lambda item: not item[0].startswith("_") and item[0] not in nameblacklist,
sorted(node.__dict__.items(),
... |
1785957 | import json
import logging as log
import redis
import crawl_monitor.settings as settings
NUM_SPLIT = 'num_split'
SOURCE_SET = 'inbound_sources'
def parse_message(message):
try:
decoded = json.loads(str(message.value(), 'utf-8'))
decoded['source'] = decoded['source'].lower()
except (json.JSOND... |
1785987 | import numpy as np
import unittest
import teneva
np.random.seed(42)
class TestCross(unittest.TestCase):
def test_base(self):
N = [9, 8, 8, 9, 8] # Shape of the tensor
d = len(N) # Dimension of the problem
M = 10000 # Number of test cases
nswp = 10 ... |
1786040 | from bsvlib.curve import multiply, curve, Point, get_y, negative, add
def test():
x = 0xe46dcd7991e5a4bd642739249b0158312e1aee56a60fd1bf622172ffe65bd789
y = 0x97693d32c540ac253de7a3dc73f7e4ba7b38d2dc1ecc8e07920b496fb107d6b2
p = Point(x, y)
k = 0xf97c89aaacf0cd2e47ddbacc97dae1f88bec49106ac37716c451dcdd... |
1786064 | from setuptools import setup
from os import path
requirements = [
'matplotlib>=3.3.0',
'numpy>=1.10',
'pandas',
'python-dateutil',
'scipy>=0.18',
'seaborn', # only used by bnse.py
'torch',
]
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.