id
stringlengths
3
8
content
stringlengths
100
981k
3256322
from itertools import cycle from . import JOIN_RETRANSMIT from .member import Component class Bootstrap(Component): def __init__(self, member, peers, bootstrapped_cb): super(Bootstrap, self).__init__(member) self.peers_cycle = cycle(peers) self.timer = None self.bootstrapped_cb = ...
3256342
import numpy as np import matplotlib import matplotlib.pyplot as plt from eagle_mpc.utils.tools import wayPointListToStateArray matplotlib.rcParams['mathtext.fontset'] = 'stix' matplotlib.rcParams['font.family'] = 'STIXGeneral' matplotlib.rcParams['font.size'] = 18 # matplotlib.rc('text', usetex=True) colors = [ ...
3256369
import os import sys import time import h5py import numpy as np from typing import Tuple, Optional, List from ml4h.defines import TENSOR_EXT, StorageType from ml4h.TensorMap import TensorMap, Interpretation Shape = Tuple[Optional[int], ...] DataDescription = Tuple[str, Shape, StorageType] SYNTHETIC_DATA_PATH = os....
3256382
from ansiblelater.standard import StandardBase class CheckYamlHasContent(StandardBase): sid = "LINT0007" description = "Files should contain useful content" helptext = "the file appears to have no useful content" version = "0.1" types = ["playbook", "task", "handler", "rolevars", "defaults", "met...
3256384
import json import math import pickle import random import signal import time import os import threading from joblib import Parallel, delayed from mcts import parameters as p from mcts import data_base from mcts.smiles import SMILES from mcts.node import Node from rnn.rnn import load_model def load_parameters_mcts(c...
3256388
import socket rmip =raw_input("192.168.5.6") st1= raw_input("Enter first port ") en1 = raw_input("Enter last port ") for port in xrange(st1, en1) sock= socket.socket(socket.AF_INET,socket.SOCK_STREAM) result = sock.connect_ex((rmip,port)) sock.setdefaulttimeout(1) if result == 0: print port, "--> Open" so...
3256415
import sys import unittest from io import StringIO from api.worldmap import PokeStop, Gym from pokemongo_bot.utils import distance, filtered_forts, convert, dist_to_str, format_dist, format_time class UtilsTest(unittest.TestCase): def setUp(self): self.out = StringIO() sys.stdout = self.out ...
3256527
from typing import Tuple, Callable, List import numpy as np import string from numpy import ndarray import tensorflow as tf class LowRank(object): """Create low rank training and test data. Arguments: rank: `int`, rank of the data. M_train: `Tuple[int, ...]`, shape of the training data. ...
3256528
import logging import sys import unittest from typing import List, Callable from pytest import approx from Xlib import X from Xlib.display import Display from Xlib.xobject.drawable import Window from i3ipc import Connection, Event, TickEvent logging.basicConfig(stream=sys.stdout, format='[%(asctim...
3256533
import os import time from skimage import io from .metrics import * from .image_proc import * class Generic_train_test(): def __init__(self, model, opts, dataloader, logger, dataloader_val=None): self.model=model self.opts=opts self.dataloader=dataloader self.logger=logger self.dataloader_val = dataloader_...
3256576
import streamlit as st from streamlit_server_state import server_state, server_state_lock st.title("Globally Shared Slider Example") st.markdown( "Open this app in multiple tabs/windows and " "see the slider value is shared and synchronized across the sessions." ) with server_state_lock["slider_value"]: ...
3256577
import logging from pyspedas.utilities.data_exists import data_exists from pytplot import get_data, store_data, options logging.captureWarnings(True) logging.basicConfig(format='%(asctime)s: %(message)s', datefmt='%d-%b-%y %H:%M:%S', level=logging.INFO) def mms_split_fgm_data(probe, data_rate, level, instrument, suf...
3256583
import pytest import os import json from waterbutler.providers.dataverse.metadata import ( DataverseDatasetMetadata, DataverseRevision, DataverseFileMetadata ) @pytest.fixture def auth(): return { 'name': 'cat', 'email': '<EMAIL>', } @pytest.fixture def credentials(): return...
3256622
from collections import defaultdict from itertools import count from operator import itemgetter from pathlib import Path from typing import Dict, Optional from typing import List, Tuple, Union import htbuilder import streamlit as st from htbuilder import span, div, script, style, link, styles, HtmlElement, br from htb...
3256625
from .presets import preset_map, COMPARE_PRIMER import pandas as pd def load_questions(filename='questions.csv'): """Loads csv of questions into a pandas dataframe""" questions = pd.read_csv(filename) questions.dropna(axis=1, how='all', inplace=True) # drop all-null columns return questions def ...
3256647
from ramda.insert import insert from ramda.private.asserts import * def insert_test(): assert_equal(insert(2, "x", [1, 2, 3, 4]), [1, 2, "x", 3, 4])
3256667
import os import tempfile TEMPDIR = os.getenv('TEMPDIR', tempfile.gettempdir()) class LinenoAndSource: ROBOT_LISTENER_API_VERSION = 2 def __init__(self): self.suite_output = open(os.path.join(TEMPDIR, 'LinenoAndSourceSuite.txt'), 'w') self.test_output = open(os.path.join(TEMPDIR, 'LinenoAnd...
3256676
import matplotlib.pyplot as plt import pandas as pd import prince wines = { 1: 'barolo', 2: 'grignolino', 3: 'barbera' } df = pd.read_csv('data/wine.csv') df['kind'] = df['class'].apply(lambda x: wines[x]) df.drop('class', axis=1, inplace=True) pca = prince.PCA(df, n_components=-1) fig1, ax1 = pca.plot...
3256726
from setuptools import setup, find_packages setup( name='geesedb', version='0.0.2', description='Graph Engine for Exploration and Search over Evolving DataBases', author='<NAME>', author_email='<EMAIL>', url='https://github.com/informagi/GeeseDB', install_requires=['duckdb', 'numpy', 'panda...
3256736
from records_mover.records.records_format import ParquetRecordsFormat import unittest class TestParquetRecordsFormat(unittest.TestCase): def test_init(self): out = ParquetRecordsFormat() self.assertIsNotNone(out) def test_str(self): out = ParquetRecordsFormat() self.assertEqua...
3256766
n = int(input()) total = sum(list(map(int, input().split(' ')))) if total == 2*(n-1): print('Yes') else: print('No')
3256802
from django.core.exceptions import ObjectDoesNotExist from django.db import migrations, models def fill_report(apps, schema_editor): Resource = apps.get_model('marketplace', 'Resource') ContentType = apps.get_model('contenttypes', 'ContentType') for resource in Resource.objects.exclude(content_type_id=No...
3256848
import unittest from PythonBuddy.app import * class TestProcessingFunctions(unittest.TestCase): # def test_evaluate_pylint(self): # test_code = "def foo(bar, baz):\n pass\nfoo(42)" # self.assertNotEqual(evaluate_pylint(test_code), {}) # def test_slow(self): # self.assertFalse(slow())...
3256853
import numpy as np from robosuite_extra.env_base import make from robosuite_extra.reach_env.sawyer_reach import SawyerReach import time from robosuite_extra.wrappers import EEFXVelocityControl, GymWrapper, FlattenWrapper goal1 = np.array([0.,0.]) goal2 = np.array([-4.465e-2,5.85e-2]) goal3 = np.array([8.37e-2,-5.78e...
3256867
from . import prepared_stmt # noqa from .connection import Connection from .types import Record # noqa async def connect(dsn: str, **kwargs) -> Connection: ...
3256901
import numpy as np class LabelDataConverter: """Convert .label binary data to instance id and rgb""" def __init__(self, labelscan): self.convertdata(labelscan) def convertdata(self, labelscan): self.semantic_id = [] self.rgb_id = [] for counting in range(len...
3256908
ACTION_CREATE = "create" ACTION_DELETE = "delete" ACTION_REMOVE_ATTRIBUTE = "attribute_delete" ACTION_RESTORE = "restore" ACTION_UPDATE = "update" ADD = 'ADD' ALLOW_RUNTIME_DELETE_MODE_CHANGE = "AllowRuntimeDeleteModeChange" APP = 'app' ARN = "arn" ARN_ACCOUNT = 'AccountNumber' ARN_ID = "ID" ARN_REGION = 'Region' ARN_T...
3256969
from pytest_bdd import scenario, when # Scenarios @scenario("../features/bootstrap.feature", "Re-run bootstrap") def test_bootstrap(host): pass # When @when("we run bootstrap a second time") def rerun_bootstrap(request, host): iso_root = request.config.getoption("--iso-root") cmd = str(iso_root / "boots...
3257052
import cv2 from PIL import Image from matplotlib import pyplot as plt image = cv2.cvtColor( cv2.imread('./dump/image.ppm'), cv2.COLOR_BGR2RGB ) image = Image.fromarray(image) image.save('./dump/image.png') print('Image saved as ./dump/image.png') plt.figure(figsize=(10, 10)) plt.imshow(image) plt.axis('off')...
3257087
import logging from django.db import migrations from django.contrib.auth.models import Group from guardian.shortcuts import assign_perm, get_perms, remove_perm logger = logging.getLogger(__file__) class GroupHelper(object): """ Helper for managing permission groups for a given provider during migrations. ...
3257093
import datetime import platform import time import unittest import ctds class TestTdsDate(unittest.TestCase): def test_date(self): val = ctds.Date(1, 2, 3) self.assertEqual(val, datetime.date(1, 2, 3)) val = ctds.Date(9999, 12, 31) self.assertEqual(val, datetime.date(9999, 12, 3...
3257098
def load_tf_opt(opt_name: str, lr: float, **args): """ This module is used for loading tensorflow/keras optimizers Args: opt_name: lr: **args: Returns: """ from tensorflow.keras.optimizers import Adam, RMSprop, SGD, Adadelta opt_dict = { 'adam': Adam, ...
3257117
from django import forms from smalluuid.smalluuid import TypedSmallUUID from django_smalluuid.forms import ShortUUIDField class TestForm(forms.Form): uuid = ShortUUIDField() class TypedTestForm(forms.Form): uuid = ShortUUIDField(uuid_class=TypedSmallUUID)
3257130
import os def remove_pipfile(): os.remove("Pipfile") def remove_publish_pypi_github_action(): os.remove(".github/workflows/python-publish.yaml") def remove_docker_file(): os.remove("Dockerfile") def main(): if "{{ cookiecutter.dependency_management_tool }}" != "pipenv": remove_pipfile() ...
3257141
import json import global_settings as gs from collections import defaultdict def query_bigquery(query): import boto3 import google.auth from google.cloud import bigquery """ Runs a query in Google BigQuery and returns the result as a list of dicts (each line is an element in the list, and each ...
3257170
from .flatfile_sink import SimpleFlatfile from .mongo_sink import MongoStore from .twitterscraper_emailer_sink import TwitterScraperEmailUpdates from .pastebinscraper_emailer_sink import PastebinScraperEmailUpdates OUTPUT_CLASS_MAPS = { SimpleFlatfile.class_map_key(): SimpleFlatfile, MongoStore.class_map_key()...
3257224
from aiogram.types import Message from aiogram_dialog import DialogManager, StartMode @dp.message_handler(commands=["start"]) async def start(m: Message, dialog_manager: DialogManager): # Important: always set `mode=StartMode.RESET_STACK` you don't want to stack dialogs await dialog_manager.start(MySG.main, mo...
3257229
import os import argparse import zipfile import numpy as np from tqdm import tqdm from h3ds.dataset import H3DS from h3ds.mesh import Mesh from h3ds.log import logger from h3ds.utils import error_to_color, download_file_from_google_drive, create_parent_directory, create_directory, remove def method_file_id(method):...
3257244
from shard.exceptions import RequireSpecificDatabaseException from shard.mixins import SpecificDatabaseMixin from tests.base import BaseTestCase class SpecificDatabaseMixinTestCase(BaseTestCase): def setUp(self): class NotSelectSpecificDatabase(SpecificDatabaseMixin): pass class Selec...
3257259
import datetime from random import randint from django.conf import settings from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.core.validators import MaxLengthValidator, MinLengthValidator, MinValueValidator from django.db import models from django.db.mod...
3257263
from a10sdk.common.A10BaseClass import A10BaseClass class SystemLog(A10BaseClass): """This class does not support CRUD Operations please use parent. :param log_data_search: {"type": "string", "format": "string"} :param log_data: {"type": "string", "format": "string"} :param DeviceProxy: The devi...
3257275
import pathlib from aiohttp import web from .views import SiteHandler PROJECT_PATH = pathlib.Path(__file__).parent def init_routes(app: web.Application, handler: SiteHandler) -> None: add_route = app.router.add_route add_route('GET', '/', handler.index, name='index') add_route('POST', '/predict', hand...
3257430
from rest_framework import viewsets, permissions from apps.core.serializers.faq import FAQSerializer from ara.classes.viewset import ActionAPIViewSet from apps.core.models import FAQ class FAQViewSet(viewsets.ReadOnlyModelViewSet, ActionAPIViewSet): queryset = FAQ.objects.all() serializer_class = FAQSeriali...
3257445
import scipy.io import matplotlib.pyplot as plt import data import pickle import numpy as np beta = scipy.io.loadmat('./beta_100.mat')['values'] ## K x T x V print('beta: ', beta.shape) with open('un/min_df_100/timestamps.pkl', 'rb') as f: timelist = pickle.load(f) print('timelist: ', timelist) T = len(timel...
3257518
import queue import numpy as np import warnings import copy from ._action import Action class ActionOptimizer(): def __init__(self, model, actions): self.model = model warnings.warn("Note that ActionOptimizer is still in an alpha state and is subjust to API changes.") # actions go into mut...
3257531
from dagster import Bool, Field, Float, StringSource, resource from dagster_msteams.client import TeamsClient @resource( { "hook_url": Field( StringSource, description="""To send messages to MS Teams channel, an incoming webhook has to be created. The incoming w...
3257552
from fastapi import Depends, Form from starlette.requests import Request from fastapi_admin.depends import get_current_admin, get_resources from fastapi_admin.models import AbstractAdmin from fastapi_admin.providers.login import UsernamePasswordProvider class LoginProvider(UsernamePasswordProvider): async def pa...
3257571
from .. import stats from . import Clothing,CLOTHES class NormalClothes( Clothing ): true_name = "Travelers Garb" true_desc = "" itemtype = CLOTHES avatar_image = "avatar_clothing.png" avatar_frame = 3 male_frame = None pants_image = "avatar_legs.png" pants_frame = 3 male_pants = No...
3257623
from typing import Callable import jax.numpy as jnp import jax.scipy.linalg as jlinalg from jax import lax, vmap, jacfwd from parsmooth.utils import MVNormalParameters from .ekf import filter_routine from .operators import smoothing_operator def make_associative_smoothing_params(transition_function, Qk, i, n, mk, P...
3257633
from torchvision import transforms import torchvision from torch.utils.data import DataLoader import random def _get_transforms(): """ The AdaMatch paper uses CTAugment as its strong augmentations. I'm going to create a pipeline of transforms similar to the ones used by CTAugment. """ train_transf...
3257655
import screenpoint import cv2 # Load input images. screen = cv2.imread('example/screen.png', 0) view = cv2.imread('example/view.jpg', 0) # Project centroid. x, y, img_debug = screenpoint.project(view, screen, True) # Write debug image. cv2.imwrite('example/match_debug.png', img_debug)
3257675
def username_generator(first_name, last_name): if len(first_name) < 3: user_name = first_name else: user_name = first_name[0:3] if len(last_name) < 4: user_name += last_name else: user_name += last_name[0:4] return user_name def password_generator(user_name): ...
3257719
char_embedding_len = 100 word_embedding_len = 100 char_hidden_size = 512 context_hidden_size = 1024 agg_hidden_size = 128 num_perspective = 12 class_size = 2 max_char_len = 15 max_word_len = 15 batch_size = 100 char_vocab_len = 1692 learning_rate = 0.0002 keep_prob = 0.7 epochs = 50
3257747
from typing import List, Collection SEP = '###' def annotate_spans( tokens: List[str], span_token_indices: List[int], delimiter: str = '#', separator: str = ' ', ) -> List[str]: annotated = tokens[:span_token_indices[0]] if len(span_token_indices) == 1: annotated = annotated + [delimi...
3257767
import json import time import math def python_factors(request): f=open("/proc/cpuinfo", "r") if f.mode == 'r': cpuinfo =f.read() f.close() f=open("/proc/meminfo", "r") if f.mode == 'r': meminfo =f.read() f.close() f=open("/proc/uptime", "r") if f.mode...
3257842
from torch.utils.data import Dataset from torch import tensor import pandas as pd import h5py,os import numpy as np from utils.util import polish_signal feature_table="/home/weir/m6a_model/DENA/step3_train_model/pytorch/feature_selection/RNN_features_motif.txt" class DENA_dataset(Dataset): def __init__(self,hdf5_dir,...
3257869
from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import TelForm, TelFormAttrs, TelFormNoInit, TwoTelForm def home(request): if request.POST: form = TelForm(request.POST) return HttpResponseRedirect('{path}?ok'.format(path=request.path)) else: ...
3257912
import MWPotential2014Likelihood import astropy.units as u import gd1_util import hypothesis import numpy import numpy as np import numpy as np import pickle import torch from galpy.orbit import Orbit from galpy.potential import MWPotential2014, turn_physical_off, vcirc from galpy.util import bovy_conversion, bovy_coo...
3257939
import numpy as np import os import glob import multiprocessing import tqdm import trimesh import objio import prt.prt_util as prt_util mesh_dir = '../dataset_example/mesh_data' def get_data_list(): """reads data list""" data_list = glob.glob(os.path.join(mesh_dir, './*/')) return sorted(data_list) de...
3257952
from setuptools import find_packages from setuptools import setup setup( name='example', packages=find_packages(include=['example']) )
3257953
import xml.dom.minidom def getDom(): dom = xml.dom.minidom.parse("data/model.xml") root = dom.documentElement return root # print(root.nodeName) def getPointDic(root): point_dic = {} points = root.getElementsByTagName("point") for point in points: # list_point_name = list(map(int,...
3257964
import pandas as pd import numpy as np from statsmodels.stats.anova import AnovaRM from numpy.testing import (assert_array_almost_equal, assert_raises, assert_equal) from pandas.util.testing import assert_frame_equal DV = [7, 3, 6, 6, 5, 8, 6, 7, 7, 11, 9, 11, 10, 10, 11, 11, 8,...
3258024
import logging import random as rnd import lea import scapy.layers.inet as inet import Attack.BaseAttack as BaseAttack import Lib.Utility as Util from Attack.Parameter import Parameter, Float, IntegerPositive, IPAddress, MACAddress, Port logging.getLogger("scapy.runtime").setLevel(logging.ERROR) # noinspection PyP...
3258029
import numpy as np import keras.models from keras.models import model_from_json from keras.applications import VGG16,imagenet_utils from keras.preprocessing.image import load_img,img_to_array import argparse preprocess=imagenet_utils.preprocess_input parser = argparse.ArgumentParser(description='Enter the Image Path')...
3258045
from .base import NullBrowser # noqa: F401 from .edge import (EdgeBrowser, # noqa: F401 EdgeDriverWdspecExecutor, # noqa: F401 check_args, # noqa: F401 browser_kwargs, # noqa: F401 executor_kwargs, # noqa: F401 env_extr...
3258068
from zeep import Client from zeep.cache import SqliteCache from zeep.transports import Transport import ns_config # cache WSDL and XSD for a year cache = SqliteCache(timeout=60*60*24*365) transport = Transport(cache=cache) client = Client(ns_config.WSDL_URL, transport=transport) model = client.get_type Passport = m...
3258088
from __future__ import print_function # Dictionary printer def print_dict(dct): for key, value in sorted(dct.items(), reverse=True): print("{}: {}".format(key, value)) # Set string printer def set_to_string(iset=None): sstr = ', '.join([str(i) for i in iset]) return sstr # Dictionary string ke...
3258097
try: from distributed_single_sentence_classification.model_interface import model_zoo from distillation import distillation_utils from loss import loss_utils, triplet_loss_utils except: from distributed_single_sentence_classification.model_interface import model_zoo from distillation import distillation_utils fro...
3258107
def check_goldbach_for_num(n, primes_set): for x in primes_set: for y in primes_set: if x + y == n : return True return False
3258135
import matplotlib.pyplot as plt import numpy as np n= 1024 X = np.random.normal(0,1,n) Y = np.random.normal(0,1,n) # 颜色显示 T = np.arctan2(Y,X) plt.scatter(X,Y,s=75,c=T,alpha=0.5 ) plt.xlim( (-1.5, 1.5) ) plt.ylim( (-1.5, 1.5) ) plt.show()
3258144
import os from yamtbx.util import call from yamtbx.util import xtal from yamtbx.dataproc.xds.xds_ascii import XDS_ASCII from cctbx import sgtbx def xds2shelx(xds_file, dir_name, prefix=None, dmin=None, dmax=None, force_anomalous=False, space_group=None, flag_source=None, add_flag=False): if prefix is None: ...
3258190
from collections import Counter from shapely.validation import explain_validity from gerrychain.vendor.utm import from_latlon def utm_of_point(point): return from_latlon(point.y, point.x)[2] def identify_utm_zone(df): wgs_df = df.to_crs("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs") utm_counts = Co...
3258196
import asyncio import hondana # Auth is not required for this process, so just a Client will work. client = hondana.Client() async def main(): current_tags = hondana.MANGA_TAGS print(current_tags) # Use the client convenience method to update the local cache # This will also update the local store...
3258230
import os from tqdm import tqdm import torch from torch import nn from torch.autograd import Variable from torch.nn import functional as F from .utils import Plotter def weights_init(m): """ Custom weights initialization as suggested in DCGAN article :param m: module :return: """ if type(m) in...
3258246
from pymclevel.materials import BlockstateAPI from pymclevel import nbt import numpy def perform(level, box, options): block_api = level.materials.blockstate_api assert isinstance(block_api, BlockstateAPI) print block_api.idToBlockstate(251, 1) root = nbt.TAG_Compound() data = nbt.TAG_Compound() ...
3258275
from spidermon.contrib.scrapy.monitors import ( WarningCountMonitor, SPIDERMON_MAX_WARNINGS, ) from spidermon import MonitorSuite def new_suite(): return MonitorSuite(monitors=[WarningCountMonitor]) def test_warning_monitor_should_fail_zero(make_data): """WarningCount should fail if the # of warning...
3258305
from django.core.management.base import BaseCommand from human_lambdas.workflow_handler.data_mapping import migrate_data from human_lambdas.workflow_handler.models import Workflow class Command(BaseCommand): help = "migrates inputs and outputs to data" def handle(self, *args, **options): workflows =...
3258306
class MeuErro(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return f'Meu erro foi crer que estar ao seu lado bastaria: {self.msg}' raise MeuErro('Batatinha quando nasce')
3258362
a = input("Enter the string:") b = a.split() list(a) while "the" in b: b.remove("the") c=" ".join(b) print("After removing 'the' from a given string :",c)
3258363
import random import time from dataclasses import dataclass from typing import Optional import cv2 import numpy as np import textdistance from Arknights.addons.common import CommonAddon from automator import AddonBase, cli_command from imgreco import imgops, resources, ocr import imgreco.ocr.tesseract as tesseract im...
3258365
import pytest from jax import random import jax.numpy as jnp import cr.sparse.dict as crdict import cr.nimble as cnb import cr.sparse as crs def test_random_onb(): key = random.PRNGKey(0) N = 16 A = crdict.random_onb(key, N) assert cnb.is_matrix(A) assert cnb.is_square(A) assert A.shape == (N...
3258367
import logging from django.conf import settings logging.basicConfig(filename=settings.LOG_LOCATION + "test.log", level=logging.DEBUG)
3258388
from yacs.config import CfgNode from torch import nn from src.tools.registry import Registry LOSS_REGISTRY = Registry() def build_loss(loss_cfg: CfgNode, **kwargs) -> nn.Module: loss_module = LOSS_REGISTRY[loss_cfg.NAME](loss_cfg, **kwargs) return loss_module
3258391
import io from os import path from setuptools import setup this_directory = path.abspath(path.dirname(__file__)) with io.open(path.join(this_directory, "README.md"), encoding="utf-8") as f: long_description = f.read() about = {} with io.open("striprtf/_version.py", "r", encoding="utf-8") as f: exec(f.read(),...
3258402
import re RENAME = 'rename' SKIP = 'skip' CREATE = 'create' CURRENT_RELEASE_REGEX = re.compile('R\d{4}q\dr\d') RENAME_DEID_MAP_TABLE_QUERY = """ CREATE OR REPLACE TABLE `{project}.{dataset}._deid_map` AS ( SELECT * FROM `{project}.{dataset}.deid_map` ) """ CREATE_DEID_MAP_TABLE_QUERY = """ CREATE OR REPLACE TABLE `{...
3258410
try: from bidict import loosebidict except ImportError: import bidict class loosebidict(bidict.bidict): on_dup_val = bidict.OVERWRITE
3258416
import logging from bentoml.utils.log import configure_logging def test_configure_logging_default(): configure_logging() bentoml_logger = logging.getLogger("bentoml") assert bentoml_logger.level == logging.INFO assert bentoml_logger.propagate is False assert len(bentoml_logger.handlers) == 2 ...
3258451
from controller.invoker.invoker_cmd_base import BaseMirControllerInvoker from controller.utils import checker, revs, utils from id_definition.error_codes import CTLResponseCode from proto import backend_pb2 class EvaluateInvoker(BaseMirControllerInvoker): """ invoker for command evaluate request.in_datase...
3258452
import json import os from collections import ChainMap class Configurations: DEFAULTS_FILE = 'settings_default.json' CONFIG_FILE = 'settings.json' def __init__(self): with open(self.DEFAULTS_FILE) as f: self.defaults = json.load(f) self.raw_config = {} if os.path.exist...
3258483
import sys from PyQt5 import QtCore, QtWidgets, QtGui from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget #from PyQt5.QtCore import QSize from pylabnet.utils.helper_methods import load_config class GUIWindowFromConfig(QMainWindow): def __init__(self, config=None): QMainWindow.__init__(...
3258486
from picamera.array import PiRGBArray from picamera import PiCamera import cv2, time, os #import send_email import queue import numpy as np import sys sys.path.append(os.getcwd()+'/common/') from config import * #h264_folder, mp4_folder, motion_threshold,log_dir,log_file,countfile from file_manager import FileManagerTh...
3258497
from keyword import iskeyword import pytest from hypothesis import given, strategies as st from sidekick.hypothesis import atoms, identifiers, kwargs pytestmark = pytest.mark.slow() class TestBaseStrategies: @given(atoms(finite=True)) def test_valid_atom(self, x): assert x == x @given(identifi...
3258499
import h5py import numpy as np from scipy.io import loadmat from operator import itemgetter import math import scipy as sp import cv2 import matplotlib.pyplot as plt import os, sys import time import multiprocessing import random # Generate Observation Map def func(theta, m, I, imax, L, w, N, anglemask): print('...
3258519
def is_palindrome(yarn): """Return whether or not a string is a palindrome. A palindrome is a word/phrase that's the same in both directions. """ return yarn == yarn[::-1]
3258534
import os from codes.utils import seed_torch def set_config(args): setting = os.path.join( f'source_{args.arch}', f'L_{args.p}_eps_{args.epsilon}', '_'.join([args.attack_method, f'lam_{args.lam}_seed_{args.seed}'])) args.adv_image_root = os.path.join(args.adv_image_root, setting) ...
3258536
import lambda_handlers as handlers import validation_json_schemas as schemas from jsonschema import validate from jsonschema.exceptions import ValidationError import log_helper import sys logger = log_helper.getLogger(__name__) def financial_functions_handler(request, context): """ This function takes in an a...
3258598
from flask import Flask,render_template,Response import cv2 app=Flask(__name__) camera=cv2.VideoCapture(0) # for cctv camera use 'rtsp://username:password@ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp' def genFrames(): while True: success,frame=camera....
3258648
from pylab import * def initialize(): global x, result x = 0.1 result = [] def observe(): global x, result result.append(x) def update(): global x, result x = r * x * (1 - x) def plot_asymptotic_states(): initialize() for t in range(100): # first 100 steps are di...
3258738
import os import pyNastran from pyNastran.converters.panair.panair_grid import PanairGrid PKG_PATH = pyNastran.__path__[0] def run(): infilename = os.path.join(PKG_PATH, 'converters', 'panair', 'M100', 'M100.inp') model = PanairGrid(log=None, debug=True) model.read_panair(infilename) p3d_name = 'M100....
3258756
import logging import pytest from ocs_ci.framework.testlib import E2ETest, workloads from ocs_ci.ocs.jenkins import Jenkins from ocs_ci.ocs.constants import STATUS_COMPLETED log = logging.getLogger(__name__) @pytest.fixture(scope="function") def jenkins(request): jenkins = Jenkins() def teardown(): ...