id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
79106 | import pandas as pd
import numpy as np
from catboost import CatBoostClassifier
import xgboost as xgb
import lightgbm as lgb
from sklearn.utils import class_weight
from abc import ABC, abstractmethod
class predict_model(ABC):
"""
Abstract class for working with classifiers.
"""
@abstractmethod
def... |
79135 | from bokeh.resources import CDN
from flask import request, current_app
from flask_security import login_required
from flask_security.core import current_user
from flexmeasures.data.config import db
from flexmeasures.ui.views import flexmeasures_ui
from flexmeasures.ui.utils.view_utils import render_flexmeasures_templa... |
79146 | from keras import backend as K
from keras.layers import LSTM, time_distributed_dense
from keras import initializations, activations, regularizers
from keras.engine import InputSpec
# LSTM with Layer Normalization as described in:
# https://arxiv.org/pdf/1607.06450v1.pdf
# page 13, equation (20), (21), and (22)
class... |
79161 | import subprocess
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--batch_size", default=4)
parser.add_argument("--epochs", default=10)
args = parser.parse_args()
cl = " ".join([
"python train.py",
"--dataset", os.path.join("data", "voc2012_train.tfrecord"),
"--val_datase... |
79269 | import astropy.units as u
from astropy.coordinates import Distance
from agnpy.emission_regions import Blob
import matplotlib.pyplot as plt
from agnpy.utils.plot import load_mpl_rc
# matplotlib adjustments
load_mpl_rc()
# set the spectrum normalisation (total energy in electrons in this case)
spectrum_norm = 1e48 * ... |
79277 | import matplotlib.pyplot as plt
import numpy
from PIL import Image
import sys
import cv2
import time
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
import glob
import os
method = 'threshold'
#method = 'threshold_adp'
#method = 'backSub'
#method = 'kmeans'
dataset = 'beach'
save_frame = ... |
79298 | import numpy as np
from supervised.algorithms.knn import KNeighborsAlgorithm, KNeighborsRegressorAlgorithm
import optuna
from supervised.utils.metric import Metric
from supervised.algorithms.registry import BINARY_CLASSIFICATION
from supervised.algorithms.registry import MULTICLASS_CLASSIFICATION
from supervised.algor... |
79318 | from gtts import gTTS
def speak(text): #https://pypi.org/project/gtts/
tts = gTTS(text=text, lang='en')
tts.save("speech.mp3")
import os
import playsound
playsound.playsound("speech.mp3", True)
os.remove("speech.mp3")
'''
import pyttsx3 #https://pypi.... |
79327 | from __future__ import annotations
import pytest
from testing.runner import and_exit
@pytest.mark.parametrize('key', ('^C', 'Enter'))
def test_replace_cancel(run, key):
with run() as h, and_exit(h):
h.press('^\\')
h.await_text('search (to replace):')
h.press(key)
h.await_text('ca... |
79369 | from annotation_utils.ndds.structs import NDDS_Dataset
from annotation_utils.coco.structs import COCO_Category_Handler, COCO_Category
from annotation_utils.coco.structs import COCO_Dataset
from common_utils.file_utils import make_dir_if_not_exists, delete_all_files_in_dir
from typing import cast
from annotation_utils.c... |
79377 | import asyncio
from abc import ABC, abstractmethod
from .colors import BLACK_ON_BLACK
from .io import KeyPressEvent, MouseEvent, PasteEvent, io
from .widgets._root import _Root
RESIZE_POLL_INTERVAL = 0.5 # Seconds between polling for resize events.
RENDER_INTERVAL = 0 # Seconds between screen renders.
cl... |
79435 | import unittest
import numpy as np
import logging
from dsbox.ml.neural_networks.keras_factory.text_models import LSTMFactory
from dsbox.ml.neural_networks.processing.workflow import TextNeuralNetPipeline, ImageNeuralNetPipeline
logging.getLogger("tensorflow").setLevel(logging.WARNING)
np.random.seed(42)
class T... |
79439 | from kaa.keyboard import *
# Todo: Splitting key bind table does not make sense.
# Put them together.
# application commands
app_keys = {
(alt, 'm'): 'app.mainmenu',
(alt, '/'): 'app.mainmenu',
f1: 'app.mainmenu',
f9: 'app.global.prev',
f10: 'app.global.next',
(alt, 'w'): 'menu.window',
(a... |
79443 | from rest_framework import authentication, exceptions
from rest_framework.authentication import get_authorization_header
from django.utils.translation import ugettext_lazy as _
from .models import Token
class TokenAuthentication(authentication.BaseAuthentication):
"""
Simple token based authentication.
Cl... |
79447 | from genmod.vcf_tools.header_parser import HeaderParser
def test_parse_info():
## GIVEN a header object
head = HeaderParser()
assert 'MQ' not in head.info_dict
info_line = '##INFO=<ID=MQ,Number=1,Type=Float,Description="RMS Mapping Quality">'
## WHEN parsing a correct info line
head.parse_... |
79450 | from .layer_norm import LayerNorm
from . import dy_model
@dy_model
class SublayerConnection:
"""
A residual connection followed by a layer norm.
Note for code simplicity the norm is first as opposed to last.
"""
def __init__(self, model, size, p):
pc = model.add_subcollection()
s... |
79476 | import IPython.lib.demo as ipd
# To use, run ipython, then
#
# In [1]: %run Demos.py
# In [2]: d = ImageDemo()
# In [3]: d()
# In [4]: d()
def ImageDemo ():
return ipd.ClearIPDemo ( 'BasicTutorial1/Image.py' )
def InputOutputDemo ():
return ipd.ClearIPDemo ( 'BasicTutorial1/InputOutput.py' )
def MemoryManag... |
79489 | def extractMichilunWordpressCom(item):
'''
Parser for 'michilun.wordpress.com'
'''
bad = [
'Recommendations and Reviews',
]
if any([tmp in item['tags'] for tmp in bad]):
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title... |
79500 | from itertools import tee
import numpy as np
import scipy.interpolate as intp
from scipy.signal import savgol_filter
def get_edge_bin(array):
"""Detect the edge indcies of a binary 1-D array.
Args:
array (:class:`numpy.ndarray`): A list or Numpy 1d array, with binary
(0/1) or boolean (True... |
79503 | from kaffe.tensorflow import Network
class GoogleNet(Network):
def setup(self):
(self.feed('data')
.conv(7, 7, 64, 2, 2, name='conv1_7x7_s2')
.max_pool(3, 3, 2, 2, name='pool1_3x3_s2')
.lrn(2, 2e-05, 0.75, name='pool1_norm1')
.conv(1, 1, 64, 1, 1, name='c... |
79519 | import os
import logging
from .paths import get_path
_FORMAT = '%(asctime)s:%(levelname)s:%(lineno)s:%(module)s.%(funcName)s:%(message)s'
_formatter = logging.Formatter(_FORMAT, '%H:%M:%S')
_handler = logging.StreamHandler()
_handler.setFormatter(_formatter)
logging.basicConfig(filename=os.path.join(get_path(), 'sp... |
79520 | from pathlib import Path
from unittest.mock import MagicMock
import pytest
from gretel_client.config import configure_session
FIXTURES = Path(__file__).parent / "fixtures"
@pytest.fixture
def get_fixture():
def _(name: str) -> Path:
return FIXTURES / name
return _
@pytest.fixture(scope="function... |
79549 | from __future__ import print_function
import os
import unittest
from .test_base_column_profilers import AbstractTestColumnProfiler
from dataprofiler.profilers.column_profile_compilers import \
ColumnPrimitiveTypeProfileCompiler
test_root_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
cla... |
79570 | import unittest
from unittest.mock import MagicMock
import pandas as pd
from pandas.testing import assert_frame_equal
from data_export.pipeline.dataset import Dataset
class TestDataset(unittest.TestCase):
def setUp(self):
example = MagicMock()
example.to_dict.return_value = {"data": "example"}
... |
79619 | import copy
import logging
from abc import ABC
from typing import Dict, Optional, Type, Union
import torch
from pytorch_lightning import LightningModule
from torch.nn.modules import Module
from torch.utils.data import DataLoader
from .generic_model import GenericModel
from .lightning_model import LightningModel
logg... |
79637 | import hashlib
import sys
import getpass
import argparse
import rx7 as rx
from LIB.Functions import pause, cls
from LIB.Hash import sa
def print_hashes(word, file=None, Print=True):
word=bytes(word, encoding='utf-8')
LIST = []
for name,func in sa.items():
try:
result = func(word).he... |
79669 | import typing
from dataclasses import dataclass
from starlette.datastructures import URL, QueryParams
@dataclass
class PageControl:
text: str
url: URL = None
is_active: bool = False
is_disabled: bool = False
def inclusive_range(st: int, en: int, cutoff: int) -> typing.List[int]:
"""
Return ... |
79700 | from reconbf.modules import test_kernel
from reconbf.lib.result import Result
from reconbf.lib import utils
import unittest
from mock import patch
class PtraceScope(unittest.TestCase):
def test_no_yama(self):
with patch.object(utils, 'kconfig_option', return_value=None):
res = test_kernel.tes... |
79778 | from collections import defaultdict
import numpy as np
class MetricsAccumulator:
def __init__(self) -> None:
self.accumulator = defaultdict(lambda: [])
def update_metric(self, metric_name, metric_value):
self.accumulator[metric_name].append(metric_value)
def print_average_metric(self):
... |
79803 | data = (
'Mang ', # 0x00
'Zhu ', # 0x01
'Utsubo ', # 0x02
'Du ', # 0x03
'Ji ', # 0x04
'Xiao ', # 0x05
'Ba ', # 0x06
'Suan ', # 0x07
'Ji ', # 0x08
'Zhen ', # 0x09
'Zhao ', # 0x0a
'Sun ', # 0x0b
'Ya ', # 0x0c
'Zhui ', # 0x0d
'Yuan ', # 0x0e
'Hu ', # 0x0f
'Gang ', # 0x10
... |
79804 | from twilio.twiml.voice_response import Pay, VoiceResponse
response = VoiceResponse()
response.pay()
print(response)
|
79815 | import functools
from typing import Optional, Sequence
from fvcore.common.registry import Registry as _Registry
from tabulate import tabulate
class Registry(_Registry):
"""Extension of fvcore's registry that supports aliases."""
_ALIAS_KEYWORDS = ("_aliases", "_ALIASES")
def __init__(self, name: str):
... |
79831 | import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes2"
start_urls = [
'http://quotes.toscrape.com/page/1/',
'http://quotes.toscrape.com/page/2/',
]
def parse(self, response):
self.log('I just visited {}'.format(response.url))
|
79872 | import json
# import logging
from .utils import is_invalid_params
from .exceptions import (
JSONRPCInvalidParams,
JSONRPCInvalidRequest,
JSONRPCInvalidRequestException,
JSONRPCMethodNotFound,
JSONRPCParseError,
JSONRPCServerError,
JSONRPCDispatchException,
)
from .jsonrpc1 import JSONRPC10Re... |
79938 | import yaml
import numpy as np
from os import path
from absl import flags
from pysc2.env import sc2_env
from pysc2.lib import features
from pysc2.lib import actions
sc2_f_path = path.abspath(path.join(path.dirname(__file__), "..", "configs", "sc2_config.yml"))
with open(sc2_f_path, 'r') as ymlfile:
sc2_cfg = yam... |
79939 | from utils.path import *
from utils.audio.tools import get_mel
from tqdm import tqdm
import numpy as np
import glob, os, sys
from multiprocessing import Pool
from scipy.io.wavfile import write
import librosa, ffmpeg
from sklearn.preprocessing import StandardScaler
def job(wav_filename):
original_wav_filename, prep... |
79953 | from paleomix.nodes.bowtie2 import Bowtie2IndexNode, Bowtie2Node
########################################################################################
# Indexing
def test_index_description():
node = Bowtie2IndexNode(input_file="/path/genome.fasta")
assert str(node) == "creating Bowtie2 index for /path/g... |
80014 | import sys
import os
import argparse
import shutil
from os.path import join as pjoin
from xml.etree import ElementTree
from collections import namedtuple
from pprint import pprint
from distutils.dir_util import mkpath
class AdobeCCFontExtractor:
pass
def mkdir_p(path):
try:
os.makedirs(path)
excep... |
80017 | import logging
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from polymorphic_sqlalchemy import (create_polymorphic_base, Relation,
PolyField, NetRelationship, NetModel, BaseInitializer)
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm ... |
80032 | import torch
import numpy as np
import torch.nn as nn
from mmcv.cnn import normal_init
from ..registry import HEADS
from ..utils import ConvModule, bias_init_with_prob
from .anchor_head import AnchorHead
from mmdet.core import (delta2bbox, force_fp32,
multiclass_nms_with_feat)
""" RetinaHead t... |
80078 | from .fixture import FakeProcesses
from .wget import Wget
from .systemctl import Systemctl
from .dpkg import Dpkg
__all__ = [
"FakeProcesses",
"Wget",
"Systemctl",
"Dpkg",
]
|
80085 | import logging
import os
import threading
import time
import curio
import pytest
try:
import catvs
import catvs.server
except ImportError:
catvs = None
import caproto as ca
from caproto.tests.verify_with_catvs import CatvsIOC
logger = logging.getLogger(__name__)
# logging.getLogger('caproto').setLevel('... |
80097 | import flask
app = flask.Flask(__name__)
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
from flask.ext.babel import Babel
babel = Babel(app)
from flask import render_template
from flask.ext.babel import gettext as _, ngettext
@babel.localeselector
def get_locale():
return 'fr... |
80117 | from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
from com.android.monkeyrunner.easy import EasyMonkeyDevice
from com.android.monkeyrunner.easy import By
import time
def get_package():
return 'org.solovyev.android.messenger'
def get_start_activity():
return '.StartActivity'
def get_actions(d... |
80213 | import os
import numpy as np
import argparse
import os.path as osp
import json
from tqdm import tqdm
from mmcv import mkdir_or_exist
def getFlying3dMetas(root, Type, data_type='clean'):
Metas = []
imgDir = 'flyingthings3d/frames_' + data_type + 'pass'
dispDir = 'flyingthings3d/disparity'
Parts = ['A'... |
80215 | from unittest import TestCase
import numpy as np
from athena import NonlinearLevelSet, ForwardNet, BackwardNet, Normalizer
import torch
import os
from contextlib import contextmanager
import matplotlib.pyplot as plt
@contextmanager
def assert_plot_figures_added():
"""
Assert that the number of figures is high... |
80244 | class ShortCodeError(Exception):
"""Base exception raised when some unexpected event occurs in the shortcode
OAuth flow."""
pass
class UnknownShortCodeError(ShortCodeError):
"""Exception raised when an unknown error happens while running shortcode
OAuth.
"""
pass
class Short... |
80306 | from functools import partial
from typing import Sequence
import pytest
from torch import Tensor, tensor
from tests.text.helpers import TextTester
from tests.text.inputs import _inputs_multiple_references, _inputs_single_sentence_multiple_references
from torchmetrics.functional.text.chrf import chrf_score
from torchm... |
80311 | from share.transform.chain import * # noqa
class AgentIdentifier(Parser):
uri = IRI(ctx)
class WorkIdentifier(Parser):
uri = IRI(ctx)
class Tag(Parser):
name = ctx
class ThroughTags(Parser):
tag = Delegate(Tag, ctx)
class Person(Parser):
given_name = ParseName(ctx.creator).first
famil... |
80326 | from django.test import TestCase
from addressbase.models import UprnToCouncil, Address
from councils.tests.factories import CouncilFactory
from data_importers.tests.stubs import stub_addressimport
# High-level functional tests for import scripts
class ImporterTest(TestCase):
opts = {"nochecks": True, "verbosity"... |
80329 | from django.db import connection
from usaspending_api.common.etl import ETLQuery, ETLTable
from usaspending_api.common.etl.operations import delete_obsolete_rows, insert_missing_rows, update_changed_rows
# This is basically the desired final state of the federal_account table. We can diff this against the
# actual f... |
80363 | import sys, os, io
from twisted.internet import reactor, protocol, task, defer
from twisted.python.procutils import which
from twisted.python import usage
# run the command with python's deprecation warnings turned on, capturing
# stderr. When done, scan stderr for warnings, write them to a separate
# logfile (so the ... |
80371 | from django.forms import ModelForm
from .models import PatientRegister, DoctorRegister, Emergency
class PatientRegisterForm(ModelForm):
class Meta:
model = PatientRegister
fields = "__all__"
class DoctorRegisterForm(ModelForm):
class Meta:
model = DoctorRegister
fields = "__a... |
80400 | from nose.tools import istest, assert_equal
from mammoth.lists import unique
@istest
def unique_of_empty_list_is_empty_list():
assert_equal([], unique([]))
@istest
def unique_removes_duplicates_while_preserving_order():
assert_equal(["apple", "banana"], unique(["apple", "banana", "apple"]))
|
80404 | import struct
from abc import ABCMeta
from bxcommon import constants
from bxcommon.constants import MSG_NULL_BYTE
from bxcommon.messages.bloxroute.abstract_bloxroute_message import AbstractBloxrouteMessage
class AbstractBlockchainSyncMessage(AbstractBloxrouteMessage):
"""
Message type for requesting/receivin... |
80508 | from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from builtins import zip
from builtins import range
from builtins import object
from past.utils import old_div
from nose.tools import (assert_equal, assert_not_equal, assert_almost_equal,
... |
80574 | import sys
import os
own_dir = os.path.abspath(os.path.dirname(__name__))
repo_root = os.path.abspath(os.path.join(own_dir, os.path.pardir))
sys.path.insert(1, repo_root)
|
80593 | import smtplib
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
sender_email=input("enter sender email")
reciver_emil=input("add reciver email")
server=smtplib.SMTP_SSL('smtp.gmail.com',465)
# server.connect("smtp.gmail.... |
80629 | import matplotlib.pyplot as plt
from ._compat import *
class GridCurves(object):
def __init__(self, curves):
self._curves = curves
@property
def curves(self):
return self._curves
def __str__(self):
fh = StringIO()
fh.write('gridcurves objects:\n\n')
fh.write(... |
80637 | from .slm import StandardLinearModel
from .glm import GeneralizedLinearModel, GeneralisedLinearModel
from .btypes import Bound, Positive, Parameter
from . import likelihoods, basis_functions, metrics, btypes
|
80649 | from .report_server import ReportServer
from .report_client import ReportClient
from .record import ReportRecord
from .nsga_iii import NonDominatedSorting, SortAndSelectPopulation
|
80662 | from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
name: apt_keys
author: Manala (@manala)
short_description: returns a curated keys list
description:
- Takes a keys list and returns it curated.
'''
from ansible.plugins.lookup import Looku... |
80676 | USER_INFORMATION ={
"object": "user",
"url": "https://api.wanikani.com/v2/user",
"data_updated_at": "2020-05-01T05:20:41.769053Z",
"data": {
"id": "7a18daeb-4067-4e77-b0ea-230c7c347ea8",
"username": "Tadgh11",
"level": 12,
"profile_url": "https://www.wanikani.com/users/Tadgh11",
"started_at"... |
80696 | from textwrap import dedent
import attack_flow.graphviz
def test_convert_attack_flow_to_dot():
flow = {
"actions": [
{
"id": "action1",
"name": "action-one",
},
{
"id": "action2",
"name": "action-two",
... |
80709 | import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
import numpy as np
def dntrack(df: pd.DataFrame,
rho: (list,str) = None,
ntr: (list,str) = None,
lims: list = None,
lime: bool = False,
dtick: bool =False,
fill: bool =T... |
80735 | from sys import argv
import re
regex_pattern_string = argv[1]
strings_to_match = argv[2:]
pattern = re.compile(regex_pattern_string)
def print_case(s):
if pattern.match(s): # This is where the work happens
prefix = "Match: \t"
else:
prefix = "No match:\t"
print prefix, s
map(print_cas... |
80738 | import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib.patches import Circle
import matplotlib.patches as patches
from . import field_info as f
def draw_field(axis=plt.gca()):
mpl.rcParams['lines.linewidth'] = 2.33513514 # was 2 before
ax = axis
# draw field background
ax.ad... |
80792 | import mgear
VERSION_MAJOR = mgear.VERSION[0]
VERSION_MINOR = mgear.VERSION[1]
VERSION_PATCH = mgear.VERSION[2]
version_info = (VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH)
version = '%i.%i.%i' % version_info
__version__ = version
__all__ = ['version', 'version_info', '__version__']
|
80807 | from __future__ import annotations
import asyncio
import json
import logging
import os
from typing import Any, Mapping, Optional, Union
import aiohttp
from aiohttp import hdrs
from aiohttp.client import _RequestContextManager
from .auth import Auth
from .request import ClientRequest
from .typedefs import WsBytesHand... |
80812 | import math, random, sys, os
import numpy as np
import pandas as pd
import networkx as nx
import func_timeout
import tqdm
from rdkit import RDLogger
from rdkit.Chem import Descriptors
from rdkit.Chem import rdmolops
import rdkit.Chem.QED
import torch
from botorch.models import SingleTaskGP
from botorch.fit import fit_... |
80920 | import numpy as np
import pytest
from ansys import dpf
from ansys.dpf import core
from ansys.dpf.core import FieldDefinition
from ansys.dpf.core import operators as ops
from ansys.dpf.core.common import locations, shell_layers
@pytest.fixture()
def stress_field(allkindofcomplexity):
model = dpf.core.Model(allkind... |
80961 | from typing import List, Optional
import databases
import sqlalchemy
from fastapi import FastAPI
import ormar
app = FastAPI()
metadata = sqlalchemy.MetaData()
database = databases.Database("sqlite:///test.db")
app.state.database = database
@app.on_event("startup")
async def startup() -> None:
database_ = app.s... |
80991 | import yaml
import pytest
from unittest import mock
import kubernetes
from kubernetes.config.config_exception import ConfigException
from mlflow.projects import kubernetes as kb
from mlflow.exceptions import ExecutionException
from mlflow.entities import RunStatus
def test_run_command_creation(): # pylint: disable... |
81001 | import argparse
import os
import windows
import windows.debug.symbols as symbols
parser = argparse.ArgumentParser(prog=__file__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('pattern')
parser.add_argument('file', help="The PE file to load")
parser.add_argument('--addr', type=lambda x: ... |
81024 | import json
import numpy as np
from pycocotools import mask as maskUtils
thresh = 0.5
# load retrieval results
results_image_id_all = []
results_query_score_all = []
results_query_cls_all = []
results_query_box_all = []
results_gallery_id_all = []
results_gallery_box_all = []
results_name = ' '
with open(results_na... |
81078 | from classic_tetris_project import discord
from classic_tetris_project.env import env
@discord.client.event
async def on_ready():
import csv
from tqdm import tqdm
from classic_tetris_project import discord
from classic_tetris_project.countries import countries
from classic_tetris_project.models im... |
81090 | from a10sdk.common.A10BaseClass import A10BaseClass
class Oper(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param state: {"enum": ["UP", "DOWN", "MAINTENANCE"], "type": "string", "format": "enum"}
:param DeviceProxy: The device proxy for REST operations and sessi... |
81121 | from unittest.case import TestCase
import unittest
import pandas as pd
import numpy as np
from datetime import datetime
from qlib import init
from qlib.config import C
from qlib.log import TimeInspector
from qlib.utils.time import cal_sam_minute as cal_sam_minute_new, get_min_cal
def cal_sam_minute(x, sam_minutes):
... |
81147 | from numbers import Real, Integral
import numpy as np
import openmc.checkvalue as cv
from .angle_energy import AngleEnergy
from .endf import get_cont_record
class NBodyPhaseSpace(AngleEnergy):
"""N-body phase space distribution
Parameters
----------
total_mass : float
Total mass of product p... |
81176 | from ._interface_quantum_simulator import IQuantumSimulator
from ._projectq_quantum_simulator import ProjectqQuantumSimulator
|
81243 | from ..utils.constants import *
from ..utils.vector3 import vec3, rgb, extract
from functools import reduce as reduce
from ..ray import Ray, get_raycolor
from .. import lights
import numpy as np
from . import Material
from ..textures import *
class Emissive(Material):
def __init__(self, color, **kwargs)... |
81258 | from debug import *
from presto_instance import *
def rewrite(source, match_template, rewrite_template):
if DEBUG_ROOIBOS:
print '[DEBUG ROOIBOS] source: %r' % source
print '[DEBUG ROOIBOS] match template: %r' % match_template
print '[DEBUG ROOIBOS] rewrite template: %r' % rewrite_template
... |
81275 | import datetime
import os
from common import settings
# environment variables must be set
TEST_USE_STATIC_DATA = os.getenv('TEST_USE_STATIC_DATA', True)
test_api_key = os.getenv('TEST_API_KEY')
NUMBER_OF_ADS = 5029
DAWN_OF_TIME = '1971-01-01T00:00:01'
current_time_stamp = datetime.datetime.now().strftime(settings.DAT... |
81277 | from . import runner
from . import worker
from . import default
from . import zeromq
from . import slurm
from .runner import Runner, RunnerInterface
from .worker import Worker, Interface, Preprocessor, Postprocessor
|
81288 | import InstrumentDriver
import numpy as np
class Driver(InstrumentDriver.InstrumentWorker):
""" This class implements a simple signal generator driver"""
def performOpen(self, options={}):
"""Perform the operation of opening the instrument connection"""
pass
def performClose(self, b... |
81295 | from typing import Union
import numpy as np
def moore_n(
n: int, position: tuple, grid: np.ndarray, invariant: Union[int, np.ndarray] = 0
):
"""Gets the N Moore neighborhood at given postion."""
row, col = position
nrows, ncols = grid.shape
# Target offsets from position.
ofup, ofdo = row +... |
81301 | import moment
import os
import pandas
import pyarrow as pa
import pyarrow.parquet as pq
import requests
from func_timeout import func_set_timeout, FunctionTimedOut
from pandas import DataFrame
from pathlib import Path
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, lit
from pyspark.sql.types... |
81302 | import pyautogui as pag
from getpass import getpass
import sys
import json
import requests
import keyboard
import time
import random
import webbrowser
from os import system, name
from colorama import Fore, Back, Style
import os
os.system('cls')
def clear():
if name == 'nt':
_ = system('cls')
def add():... |
81304 | import torch
import os
import time
import numpy as np
from tqdm import tqdm
from collections import OrderedDict
from torch import optim
from torch import nn
from torchvision.utils import save_image
class Base:
def _get_stats(self, dict_, mode):
stats = OrderedDict({})
for key in dict_.keys():
... |
81463 | from .base_options import BaseOptions
class TrainOptions(BaseOptions):
def initialize(self):
BaseOptions.initialize(self)
self.parser.add_argument('--display_freq', type=int, default=50, help='frequency of displaying average loss')
self.parser.add_argument('--save_epoch_freq', type=int, def... |
81495 | from boa3.builtin import public
def TestAdd(a: int, b: int) -> int:
return a + b
@public
def Main() -> int:
return TestAdd(1, 2)
|
81544 | from pydantic.dataclasses import dataclass
from ...samplers import BaseSamplerConfig
@dataclass
class VAMPSamplerConfig(BaseSamplerConfig):
"""This is the VAMP prior sampler configuration instance deriving from
:class:`BaseSamplerConfig`.
"""
pass
|
81554 | import time
import logging
import traceback
from multiprocessing import Process
from threading import Lock
LOG = logging.getLogger(__name__)
class _Task:
def __init__(self, func, args, kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def __call__(self):
return... |
81556 | import os
import tempfile
import numpy as np
from microscopium.screens.cellomics import SPIRAL_CLOCKWISE_RIGHT_25
from microscopium import preprocess as pre
from microscopium import io as mio
import pytest
import warnings
@pytest.fixture
def image_files():
# for clarity we define images as integer arrays in [0, 1... |
81585 | from met_brewer.palettes import (
MET_PALETTES, COLORBLIND_PALETTES_NAMES, COLORBLIND_PALETTES,
met_brew, export, is_colorblind_friendly
)
MET_PALETTES
COLORBLIND_PALETTES_NAMES
COLORBLIND_PALETTES
met_brew
export
is_colorblind_friendly
|
81607 | from django.contrib import admin
from django.conf import settings
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from django.utils.translation import ugettext_lazy as _
# Register your models here.
from .models import CustomerInfo, ContactInfo, Add... |
81633 | from nutshell.algorithms.information_retrieval import ClassicalIR
from nutshell.algorithms.ranking import BaseRanker, TextRank
from nutshell.algorithms.similarity import BaseSimilarityAlgo, BM25Plus
from nutshell.preprocessing.cleaner import NLTKCleaner
from nutshell.preprocessing.preprocessor import TextPreProcessor
... |
81718 | from itertools import combinations
from solvatore import Solvatore
from cipher_description import CipherDescription
from ciphers import present
cipher = present.present
rounds = 9
solver = Solvatore()
solver.load_cipher(cipher)
solver.set_rounds(rounds)
# Look over all combination for one non active bit
for bits in ... |
81778 | import logging
def pytest_addoption(parser):
parser.addoption(
"--no-linting",
action="store_true",
default=False,
help="Skip linting checks",
)
parser.addoption(
"--linting",
action="store_true",
default=False,
help="Only run linting checks"... |
81791 | from dispatch.plugins.bases import StoragePlugin
class TestStoragePlugin(StoragePlugin):
title = "Dispatch Test Plugin - Storage"
slug = "test-storage"
def get(self, **kwargs):
return
def create(self, items, **kwargs):
return
def update(self, items, **kwargs):
return
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.