id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
97086 | import pendulum
import pytest
import prefect.schedules.filters as filters
def test_on_datetime_0():
filter_fn = filters.on_datetime(pendulum.datetime(2019, 1, 2, 3, 4, 5))
assert filter_fn(pendulum.datetime(2019, 1, 2, 3, 4, 5))
def test_on_datetime_1():
filter_fn = filters.on_datetime(pendulum.datetim... |
97125 | from vnpy.event import EventEngine, Event
from vnpy.trader.engine import MainEngine
from vnpy.trader.ui import QtWidgets, QtCore
from ..engine import APP_NAME, EVENT_RPC_LOG
class RpcManager(QtWidgets.QWidget):
""""""
signal_log = QtCore.pyqtSignal(Event)
def __init__(self, main_engine: MainEngine, event... |
97154 | from insights.parsers.neutron_ovs_agent_log import NeutronOVSAgentLog
from insights.tests import context_wrap
from datetime import datetime
LOG = """
2016-11-09 14:39:25.348 3153 WARNING oslo_config.cfg [-] Option "rabbit_password" from group "oslo_messaging_rabbit" is deprecated for removal. Its value may be silent... |
97195 | import pytest
import mitzasql.sql_parser.tokens as Token
from mitzasql.sql_parser.lexer import Lexer
from mitzasql.utils import token_is_parsed
def test_schema_object_is_tokenized():
raw = '''
`schema`.`object`
@`not a schema object`
'''
tokens = list(Lexer(raw).tokenize())
assert token_is_parsed((Token.Na... |
97202 | import logging
from typing import Optional, Text, List, Any
from pybeerxml.fermentable import Fermentable
from pybeerxml.hop import Hop
from pybeerxml.mash import Mash
from pybeerxml.misc import Misc
from pybeerxml.yeast import Yeast
from pybeerxml.style import Style
from pybeerxml.water import Water
from pybeerxml.eq... |
97204 | load("@com_github_reboot_dev_pyprotoc_plugin//:rules.bzl", "create_protoc_plugin_rule")
cc_eventuals_library = create_protoc_plugin_rule(
"@com_github_3rdparty_eventuals_grpc//protoc-gen-eventuals:protoc-gen-eventuals", extensions=(".eventuals.h", ".eventuals.cc")
)
|
97252 | import unittest
from brume.config import Config
class TestConfig(unittest.TestCase):
"""Test for brume.Config."""
def test_load(self):
"""A configuration file can be loaded."""
conf = Config.load()
assert conf['region'] == 'eu-west-1'
assert isinstance(conf['stack'], dict)
... |
97279 | from fpds import FIELDS, CALCULATED_FIELDS
import os.path
from django.db import connection
from django.db import transaction
import re
class Loader():
def fields(self):
return [ x[0] for x in FIELDS ] + [ x[0] for x in CALCULATED_FIELDS ]
def sql_str(self, infile):
table = 'usaspending_contrac... |
97335 | import diffractsim
diffractsim.set_backend("CPU") #Change the string to "CUDA" to use GPU acceleration
from diffractsim import PolychromaticField,ApertureFromImage, cf, mm, cm
F = PolychromaticField(
spectrum=1.5 * cf.illuminant_d65,
extent_x=20 * mm,
extent_y=20 * mm,
Nx=1600,
Ny=1600,
)
F.add(A... |
97365 | import logging
logging.basicConfig(
format="%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s",
datefmt="%Y-%m-%d:%H:%M:%S",
level=logging.DEBUG,
)
logger = logging.getLogger(__name__)
import os
import uuid
import glob
import json
import time
import shlex
import shutil
from dat... |
97378 | import numpy as np
from scipy import special as special
from scipy.special import logsumexp
from mimo.abstraction import MixtureDistribution
from mimo.abstraction import BayesianMixtureDistribution
from mimo.distributions.bayesian import CategoricalWithDirichlet
from mimo.distributions.bayesian import CategoricalWith... |
97379 | class SearchParams(object):
def __init__(self):
self.maxTweets = 0
def set_username(self, username):
self.username = username
return self
def set_since(self, since):
self.since = since
return self
def set_until(self, until):
self.until = until
r... |
97386 | import os
import time
import scipy
import numpy as np
import soundfile as sf
def mel_scale(freq):
return 1127.0 * np.log(1.0 + float(freq)/700)
def inv_mel_scale(mel_freq):
return 700 * (np.exp(float(mel_freq)/1127) - 1)
class MelBank(object):
def __init__(self,
low_freq=20,
... |
97477 | from .base_serializer import BaseSerializer
from .binary_serializer import BinarySerializer
from .json_serializer import JsonSerializer
__all__ = [
'BaseSerializer',
'BinarySerializer',
'JsonSerializer',
]
|
97529 | import numpy as np
from .base_likelihood import Likelihood
from scipy.special import logsumexp, softmax
from tramp.utils.linear_region import LinearRegionLikelihood
class PiecewiseLinearLikelihood(Likelihood):
def __init__(self, name, regions, y, y_name="y"):
self.y_name = y_name
self.size = self.... |
97537 | import collections
import contextlib
import pytest
from siosocks.exceptions import SocksException
from siosocks.protocol import SocksClient, SocksServer
from siosocks.sansio import SansIORW
class ConnectionFailed(Exception):
pass
class Node:
def __init__(self, generator):
self.generator = generat... |
97598 | import cv2
#读取视频
cap = cv2.VideoCapture("rtsp://admin:IVDCRX@192.168.1.139:554//Streaming/Channels/1") # 打开摄像头
ret,frame = cap.read()
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output1.avi', fourcc, 6.0, siz... |
97605 | from typing import Optional
from setuptools import setup, find_packages
package_name = 'rozental_as_a_service'
def get_version() -> Optional[str]:
with open('rozental_as_a_service/__init__.py', 'r') as f:
lines = f.readlines()
for line in lines:
if line.startswith('__version__'):
... |
97610 | from typing import List
import logging
import orjson
from instauto.api.actions.structs.feed import FeedGet
from instauto.api.client import ApiClient
from instauto.helpers import models
logging.basicConfig()
logger = logging.getLogger(__name__)
def get_feed(client: ApiClient, limit: int) -> List[models.Post]:
... |
97617 | from collections import Counter
def can_scramble(source, dest):
if len(source) != len(dest):
return False
return Counter(source) == Counter(dest)
assert(can_scramble("abc", "cba") == True)
assert(can_scramble("abc", "ccc") == False)
assert(can_scramble("aab", "bbc") == False)
assert(can_scramble("aabaaaa", "... |
97628 | from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from users.forms import LoginForm, RegistrationForm
import cass
def login(request):
login_form = LoginForm()
register_form = RegistrationForm()
next = request.REQUEST.ge... |
97640 | from django_webserver.management.commands.pyuwsgi import Command as uWSGICommand
class Command(uWSGICommand):
help = "Start Nautobot uWSGI server."
|
97682 | import testutil
import responses
@responses.activate
def test_search():
testutil.add_response("login_response_200")
testutil.add_response("search_response_200")
testutil.add_response("api_version_response_200")
client = testutil.get_client()
search_result = client.search(
"FIND {sfdc_py} R... |
97704 | from flask import Blueprint, make_response, url_for
from portality import util
from portality.core import app
from portality import models
from portality.lib import dates
import json, requests, math, os, time
from datetime import datetime
blueprint = Blueprint('status', __name__)
@blueprint.route('/stats')
@util.jso... |
97708 | import myprofiler
import pytest
def test_SummingCollector():
collector = myprofiler.SummingCollector()
assert collector.summary() == []
collector.append("foo")
collector.append("bar")
collector.append("foo")
assert collector.summary() == [("foo", 2), ("bar", 1)]
collector.turn()
def te... |
97736 | from kivy.uix.label import Label
from kivy.uix.widget import Widget
from utils import import_kv
import_kv(__file__)
class BaseDescriptionWidget(Widget):
pass
class TextDescriptionWidget(Label, BaseDescriptionWidget):
pass
class SymbolTextDescriptionWidget(Label, BaseDescriptionWidget):
def __init__(s... |
97761 | from AppKit import *
from vanillaButton import ImageButton
class GradientButton(ImageButton):
nsBezelStyle = NSSmallSquareBezelStyle
|
97811 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.utilities2 import utilities2
def test_utilities2():
"""Test module utilities2.py by downloading
utilities2.csv and testing shape of
extrac... |
97852 | from typing import Callable, Dict, Optional, Sequence, Tuple, Union
import pytest # type: ignore
from looker_sdk import methods, models
from henry.modules import exceptions, fetcher
@pytest.fixture(name="fc")
def initialize() -> fetcher.Fetcher:
"""Returns an instance of fetcher"""
options = fetcher.Input(... |
97886 | class Book:
"""The Book object contains all the information about a book"""
def __init__(self, title, author, date, genre):
"""Object constructor
:param title: title of the Book
:type title: str
:param author: author of the book
:type author: str
:param data: the date at which the book has been p... |
97891 | from __future__ import absolute_import
__version__ = "0.3.6"
from pyfor import cloud
from pyfor import rasterizer
from pyfor import gisexport
from pyfor import clip
from pyfor import ground_filter
from pyfor import collection
from pyfor import voxelizer
from pyfor import metrics
|
98000 | import os
import numpy as np
from pyfftw.builders import rfft
from scipy.interpolate import interp1d
from scipy.special import gamma
from scipy.integrate import quad
import matplotlib.pyplot as plt
class FFTLog(object):
def __init__(self, **kwargs):
self.Nmax = kwargs['Nmax']
self.xmin = kwargs['xm... |
98011 | from django.shortcuts import render
from django.views.generic.base import View
from base.models import SiteInfo
class IndexView(View):
def get(self, request):
site_infos = SiteInfo.objects.all().filter(is_live=True)[0]
context = {
'site_infos': site_infos
}
request.se... |
98028 | from .. import util
import duo_client.admin
from .base import TestAdmin
class TestPhones(TestAdmin):
def test_get_phones_generator(self):
""" Test to get phones generator.
"""
generator = self.client_list.get_phones_generator()
response = next(generator)
self.assertEqual(re... |
98072 | import pyaf.Bench.TS_datasets as tsds
import pyaf.Bench.MComp as mcomp
#tester1 = mcomp.cMComp_Tester(tsds.load_M1_comp());
#tester1.testSignals('')
#tester1.testAllSignals()
#tester2 = mcomp.cMComp_Tester(tsds.load_M2_comp());
#tester1.testSignals('')
#tester2.testAllSignals()
#tester3 = mcomp.cMComp_Tester(tsds.... |
98101 | import asyncio
from irrexplorer.backends.bgp import BGPImporter
from irrexplorer.backends.rirstats import RIRStatsImporter
from irrexplorer.state import RIR
async def main():
"""
Run an import for all backends with local data.
All imports are run "simultaneously" (one CPU, but async)
"""
tasks = ... |
98106 | import json
import os
import sys
import argparse
import subprocess
import tempfile
import shutil
from collections import namedtuple
from molotov import __version__
from molotov.run import run
def clone_repo(github):
# XXX security
subprocess.check_call('git clone %s .' % github, shell=True)
def create_virt... |
98108 | class KelvinHelmholtzUniform:
"""
Kelvin-Helmholtz instability with anisotropic viscosity and a constant
magnetic field in the x-direction. The equilibrium is assumed to have
constant density, temperature and pressure. The velocity profile varies
smoothly and the setup is periodic.
... |
98110 | from .merge_result_infos import merge_result_infos
from .field_to_fc import field_to_fc
from .html_doc import html_doc
from .unitary_field import unitary_field
from .extract_field import extract_field
from .bind_support import bind_support
from .scalars_to_field import scalars_to_field
from .change_location impo... |
98164 | import pathlib
import pytest
import pymatgen as pmg
from pymatgen.io.cif import CifParser
from dftfit.potential import Potential
from dftfit.training import Training
@pytest.fixture
def structure():
def f(filename, conventional=True, oxidized=False):
filename = pathlib.Path(filename)
if not file... |
98186 | import json
import os
import random
import string
from math import asin
from math import ceil
from math import cos
from math import degrees
from math import pi
from math import radians
from math import sin
from math import sqrt
from math import tan
from pyaedt.generic.general_methods import _retry_ntimes
from pyaedt.g... |
98195 | from arekit.common.news.objects_parser import SentenceObjectsParserPipelineItem
from arekit.contrib.source.ruattitudes.text_object import TextObject
class RuAttitudesTextEntitiesParser(SentenceObjectsParserPipelineItem):
def __init__(self):
super(RuAttitudesTextEntitiesParser, self).__init__(
... |
98202 | from .tresnet import tresnet_m, tresnet_l, tresnet_xl, tresnet_m_448, tresnet_l_448, tresnet_xl_448
__all__ = ['tresnet_m', 'tresnet_l', 'tresnet_xl', 'tresnet_m_448', 'tresnet_l_448', 'tresnet_xl_448']
__version__ = '1.0.8'
__authors__ = '<NAME>'
|
98205 | import traceback
import sys
import depgraph
from common import utils
from common.constants import UNKNOWN_LABEL, VOID, LOC_VAR, FUN_ARG, INT
from common.constants import ENUM_DW_FORM_exprloc, ENUM_ABBREV_CODE, TTYPES
from elements.ttype import Ttype
from elements.givs import Node
class Offset(Node):
total = 0
... |
98232 | import cv2
import numpy as np
from paz.backend.image.draw import put_text, draw_rectangle
from paz.backend.image.draw import GREEN
def draw_box(image, coordinates, class_name, score,
color=GREEN, scale=0.7, weighted=False):
x_min, y_min, x_max, y_max = coordinates
if weighted:
color = [in... |
98322 | import unittest
import os.path
import numpy as np
import numpy.lib.recfunctions as rfn
from geodepy.convert import (hp2dec, dec2hp, rect2polar, polar2rect,
grid2geo, llh2xyz, DMSAngle)
from geodepy.geodesy import vincinv, vincdir, vincinv_utm, vincdir_utm, enu2xyz, xyz2enu
class TestGeode... |
98348 | import unittest
import warnings
from gmplot.utility import StringIO, _format_LatLng
from gmplot.writer import _Writer
from gmplot.drawables.route import _Route
from gmplot.google_map_plotter import GoogleMapPlotter
class GMPlotTest(unittest.TestCase):
def test_format_LatLng(self):
self.assertEqual(_format_... |
98368 | import json
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import financespy.account as account
from financespy.memory_backend import MemoryBackend
from financespy.sql_backend import SQLBackend
from fin... |
98371 | base_rf.fit(X_train, y_train)
under_rf.fit(X_train, y_train)
over_rf.fit(X_train, y_train)
plot_roc_and_precision_recall_curves([
("original", base_rf),
("undersampling", under_rf),
("oversampling", over_rf),
]) |
98397 | import numpy as np
from mlflow import log_metric, log_param, set_experiment, active_run, log_metrics
from yaaf import mkdir, flatten_dict
class MLFlowLogger:
def __init__(self, params, metrics=None, experiment_name=None):
if experiment_name is not None: set_experiment(f"{experiment_name}")
self... |
98409 | import unittest
import os
import logging
from flask_testing import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import selenium.webdriver.support.ui as ui
from webapp.routes import create_app
class TestBase(LiveServerTestCase):
def create_app(self):
... |
98428 | import json
import boto3
import tempfile
import zipfile
import uuid
import time
sc = boto3.client("servicecatalog")
code_pipeline = boto3.client('codepipeline')
s3 = boto3.client("s3")
sts = boto3.client("sts")
ssm = boto3.client("ssm")
def get_file(artifact, f_name):
bucket = artifact["location"]["s3Location"]["... |
98430 | import pytest
from django.core.cache import cache
from rest_framework.test import APIClient
from environments.identities.models import Identity
from environments.identities.traits.models import Trait
from environments.models import Environment
from features.feature_types import MULTIVARIATE
from features.models import... |
98451 | from django.http import HttpResponse
from django.middleware.csrf import get_token
from django.template import Context, RequestContext, Template
from django.template.context_processors import csrf
from django.views.decorators.csrf import ensure_csrf_cookie
def post_form_view(request):
"""Return a POST form (withou... |
98463 | import json
from os.path import join
from tarfile import TarFile
from enot.action import action_factory
from enot.action.release import Release
from enot.compiler.compiler_type import Compiler
from enot.packages.config.config import ConfigFile, get_dep_info_from_hex
from enot.packages.dep import Dep
from enot.utils.fi... |
98473 | import json
import pytest
from custom_components.hacs.validate.brands import Validator
from tests.sample_data import response_rate_limit_header
@pytest.mark.asyncio
async def test_added_to_brands(repository, aresponses):
aresponses.add(
"brands.home-assistant.io",
"/domains.json",
"get"... |
98483 | import urllib
import urllib2
import json
import sys
import urlparse
import os
import difflib
import shutil
import hashlib
import guido_utilities
from optparse import OptionParser
from filecmp import dircmp
'''
BELOW YOU CAN SET CERTAIN SCRIPT VARIABLES
THAT CANNOT BE SET FROM THE COMMAND LINE.
IN THEORY, THESE ARE TH... |
98503 | import os
import sys
import pickle
from tqdm import tqdm
import numpy as np
import cv2
from fsgan.utils.bbox_utils import scale_bbox, crop_img
from fsgan.utils.video_utils import Sequence
def main(input_path, output_dir=None, cache_path=None, seq_postfix='_dsfd_seq.pkl', resolution=256, crop_scale=2.0,
selec... |
98508 | import click
from picomc.cli.utils import pass_global_config
@click.group()
def config_cli():
"""Configure picomc."""
pass
@config_cli.command()
@pass_global_config
def show(cfg):
"""Print the current config."""
for k, v in cfg.bottom.items():
if k not in cfg:
print("[default] ... |
98522 | from __future__ import (absolute_import, division,
print_function, unicode_literals)
import pty, os, tty, termios, time, sys, base64, struct, signal
from fcntl import fcntl, F_GETFL, F_SETFL, ioctl
class TerminalServer:
def __init__(self):
self.closed = False
self.pid, self... |
98548 | from sqlalchemy import (create_engine, Column, Integer, String, DateTime,
Boolean, BigInteger)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
from datetime import datetime
import os
"""A cache for storing account details as they a... |
98569 | import sys
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.utils import check_random_state
from sklearn.decomposition import PCA
import keras
class LIMESimpleModel... |
98595 | class BatmanQuotes(object):
@staticmethod
def get_quote(quotes, hero):
index = int(sorted(hero)[0])
return {'B':'Batman: ','R':'Robin: ','J':'Joker: '}[hero[0]] + quotes[index]
|
98640 | from mtree.tests.fixtures.generator import ADD, REMOVE, QUERY
"""
actions = '12a12r12a12r'
dimensions = 4
remove_chance = 0.1
"""
DIMENSIONS = 4
def PERFORM(callback):
callback(ADD((98, 6, 62, 83), QUERY((76, 5, 88, 66), 26.243784265073067, 3)))
callback(ADD((50, 28, 1, 72), QUERY((90, 40, 27, 38), 47.3551429390136... |
98687 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.pumps import PumpVariableSpeedCondensate
log = logging.getLogger(__name__)
class TestPumpVariableSpeedCondensate(unittest.TestCase):
def setUp(self):
self.fd, self.... |
98694 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, torch
from tqdm import tqdm
from silence_tensorflow import silence_tensorflow
silence_tensorflow()
import tensorflow.compat.v1 as tf
from metrics.FVD.FVD import Embedder, preprocess, calculate_fvd
imp... |
98716 | import torch
import torch.nn as nn
import torch.nn.functional as F
from Regressor import Regressor
from utils import *;
class Model(nn.Module):
def __init__(self, input_dim, embed_dim, output_dim, data=None):
super(Model, self).__init__()
self.input_dim = input_dim;
self.embed_dim = embed_d... |
98725 | from .utils import *
from .mobject.geometry import *
from .scene import SceneGL
from manim_express.backend.manimgl.express.eager import EagerModeScene
|
98730 | from flatdata.generator.tree.nodes.node import Node
from flatdata.generator.tree.nodes.references import ResourceReference, FieldReference, StructureReference
class ExplicitReference(Node):
def __init__(self, name, properties=None):
super().__init__(name=name, properties=properties)
@staticmethod
... |
98752 | from sklearn.model_selection import StratifiedKFold, KFold
from skopt.utils import use_named_args
from .pipes_and_transformers import MidasEnsembleClassifiersWithPipeline, wrap_pipeline, get_metadata_fit, _MidasIdentity
from imblearn.pipeline import Pipeline
from sklearn.calibration import CalibratedClassifierCV
from c... |
98800 | from importlib.util import find_spec
def module_available(module_path: str) -> bool:
"""Function to check whether the package is available or not.
Args:
module_path : The name of the module.
"""
try:
return find_spec(module_path) is not None
except AttributeError:
# Python... |
98823 | import errno
import os
import requests
from messagebuf import MessageBuf
class ResException(Exception):
pass
class ResLayer(object):
def __init__(self, ltype, ldata):
self.ltype = ltype
self.ldata = ldata
class Resource(object):
def __init__(self, resname, resver, rawinfo):
s... |
98841 | import sys
from benchmark_paths import get_result_path
from benchmark_tools import run
assert len(sys.argv) == 3, "Usage: python script.py scene_name scene_depth"
scene = sys.argv[1]
scene_depth = int(sys.argv[2])
replay_name = "small_edits"
num_threads = ["2", "4", "6"];
base_defines = [
("SCENE", "\"{}\"".for... |
98972 | from functools import wraps
import inspect
from typing import Any, Callable, Union
from requests.adapters import Response
from mstrio import config
from mstrio.api.exceptions import MstrException, PartialSuccess, Success
from mstrio.utils.helper import get_default_args_from_func, response_handler
def get_args_and_b... |
98973 | B77;10003;0c#!python
import os, sys, string, time, BaseHTTPServer, getopt, re, subprocess, webbrowser
from operator import itemgetter
from utils import *
from preprocess import Preprocess
from assemble import Assemble
sys.path.append(INITIAL_UTILS)
from ruffus import *
_readlibs = []
_skipsteps = []
_settings = Sett... |
98981 | import torch
import torch.fx as fx
from torch.utils._pytree import tree_flatten
aten = torch.ops.aten
rand_ops = [aten.dropout, aten._fused_dropout, aten._standard_gamma,
aten.bernoulli, aten.multinomial, aten.native_dropout,
aten.normal, aten.poisson, aten.binomial, aten.rrelu,
ate... |
99031 | from rpython.jit.backend.llsupport.test.ztranslation_test import TranslationTestCallAssembler
class TestTranslationCallAssemblerPPC(TranslationTestCallAssembler):
pass
|
99034 | from __future__ import division, print_function
import CoolProp
from CoolProp import unit_systems_constants
from CoolProp.CoolProp import Props, get_REFPROPname, IsFluidType, set_standard_unit_system
import CoolProp.CoolProp as CP
import numpy as np
modes = []
modes.append('pure')
#modes.append('pseudo-pure')
# Check... |
99079 | import numpy as np
import matplotlib.pyplot as plt
import time
def completeRank1Matrix(observations,mask,PLOT=False):
# observations and mask are two 2D numpy arrays of the same size, where observations is a
# numerical matrix indicating the observed values of the matrix and mask is a boolean array
# indicating ... |
99106 | import asyncio
from asynctest import TestCase, mock
from aiohttp import client_exceptions, WSMsgType
from aiocometd.transports.websocket import WebSocketTransport, WebSocketFactory
from aiocometd.constants import ConnectionType
from aiocometd.exceptions import TransportConnectionClosed, TransportError
class TestWeb... |
99116 | import click
import pyperclip
from ..utils.logging import logger
from ..utils.exceptions import handle_exceptions
from ..utils.load import get_default_code_name
import os
@click.command(short_help='Copies code from file to clipboard.')
@click.argument('code_file',
type=click.Path(exists=True, dir_okay... |
99139 | from ..factory import Type
class inputMessageLocation(Type):
location = None # type: "location"
live_period = None # type: "int32"
|
99162 | fp = open("./packet.csv", "r")
vals = fp.readlines()
count = 1
pre_val = 0
current = 0
sampling_rate = 31
val_bins = []
for i in range(len(vals)):
pre_val = current
current = int(vals[i])
if current == pre_val:
count = count + 1
else:
count = 1
if count == sampling_rate:
... |
99165 | import sys
from oletools import olevba
class OfficeParser():
def __init__(self,sample):
self.sample = sample
self.results = {}
def extract_macro(self):
vba = olevba.VBA_Parser(self.sample)
macro_code = ""
if vba.detect_vba_macros():
for (filename, stream... |
99179 | from ScrollText import ScrollText
from Tkinter import *
from PrologFrame import PrologFrame
from Prolog import PrologException
from FastIndex import FastIndex
import ErrDialog
import re
import AnnotationColours
#import Colour
import parser
def startCompare(x, y):
(xLine, xCol) = x[1].split('.')
(yLine, yCol... |
99185 | import SCons.Builder
import os
import shutil
from subprocess import Popen
def nmAction(target, source, env):
'''
set up notmuch test db in target directory
'''
config = os.path.abspath(os.path.join (os.path.curdir, 'test/mail/test_config'))
env['ENV']['NOTMUCH_CONFIG'] = config
# run notmuch
myenv = o... |
99189 | from pyxie.model.pynodes.values import ProfilePyNode
import pyxie.model.functions
def initialise_external_function_definitions():
# Inside <Servo.h>
function_calls = {
"Servo": {
"iterator": False,
"return_ctype": "Servo", # C type of the... |
99190 | from setuptools import *
from os import path
this_dir = path.abspath(path.dirname(__file__))
with open(path.join(this_dir, "README.md"), encoding = "utf-8") as file:
long_description = file.read()
with open(path.join(this_dir, "requirements.txt"), encoding = "utf-8") as file:
requirements = file.readlines()
... |
99256 | from .parser import Parser
# This class was used in the paper for translating, all the translating logic is now implemented in Parser
# So this class is a wrapper for that one.
class Translator:
def __init__(self, database):
self.parser = Parser(database)
def translate(self, query):
return se... |
99285 | from typing import List, Tuple, Dict
from copy import deepcopy
from sqlite3 import Cursor
import os
from parsimonious import Grammar
from parsimonious.exceptions import ParseError
from allennlp.common.checks import ConfigurationError
from allennlp.semparse.contexts.sql_context_utils import SqlVisitor
from allennlp.se... |
99295 | r"""
Commutative algebras
"""
#*****************************************************************************
# Copyright (C) 2005 <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# 2008-2009 <NAME> <nthiery at users.sf.net>
#
# Distributed under the terms of the GNU General Public Lice... |
99329 | import pytest
from sdk.data.Mappable import NoneAsMappable, StringAsMappable
def test_none_as_mappable():
none = NoneAsMappable()
assert none.to_json() == ''
assert none == NoneAsMappable()
@pytest.mark.parametrize('string', [
'asdfg',
'test-test',
'dunnoLol'
])
def test_string_as_mappable(... |
99354 | def condensate_to_gas_equivalence(api, stb):
"Derivation from real gas equation"
Tsc = 519.57 # standard temp in Rankine
psc = 14.7 # standard pressure in psi
R = 10.732
rho_w = 350.16 # water density in lbm/STB
so = 141.5 / (api + 131.5) # so: specific gravity of oil (dimensionless)
Mo = 5854 / (api - 8... |
99376 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __repr__(self):
return str(self.data)
def count_unival_trees(root):
if not root:
return 0
elif not root.left and not root.right:
return 1
elif not root.... |
99383 | from pyco import user_input
from pyco.color import Fore, Back, Style
user_input("Plain prompt: ")
user_input(Fore.GREEN + "Prompt in green: ")
user_input(Fore.BRIGHT_RED + "Prompt in bright red, user input in cyan: ", input_color=Fore.CYAN)
user_input(Fore.BLUE + Back.BRIGHT_WHITE + "Prompt in blue on a bright white b... |
99386 | import binascii
import datetime
import hashlib
import hmac
import os
import uuid
from typing import Dict, List, Optional, Type, Union
from fastapi import HTTPException, Query, status
from pydantic import BaseModel, Extra, validator
from ..config import settings
from .auth import TYPING_AUTH
from . import EBaseModel, ... |
99392 | from hashlib import sha256
from hmac import new as hmac
from random import randint
from re import fullmatch
from socket import socket
from struct import pack as encode
from subprocess import PIPE, STDOUT, Popen
from crcmod.predefined import mkCrcFun
from goodix import FLAGS_TRANSPORT_LAYER_SECURITY_DATA, Device
from ... |
99402 | import argparse
import json
import re
from typing import List
quiet = False
def print_message(message: str):
"""
Print message to STDOUT if the quiet option is set to False (this is the default).
:param message: message to print
:return: None
"""
global quiet
if not quiet:
print(m... |
99406 | from .ReportDaily import *
# Lists which git version was used by how many users yesterday
class ReportGitVersionsNew(ReportDaily):
def name(self):
return "git-versions-new"
def updateDailyData(self):
newHeader, newData = self.parseData(
self.executeScript(self.scriptPath("git-versions.sh")))
self.header =... |
99453 | import FWCore.ParameterSet.Config as cms
from CalibMuon.DTCalibration.dtSegmentSelection_cfi import dtSegmentSelection
dtVDriftSegmentCalibration = cms.EDAnalyzer("DTVDriftSegmentCalibration",
# Segment selection
dtSegmentSelection,
recHits4DLabel = cms.InputTag('dt4DSegments'),
rootFileName = cms.unt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.