id
stringlengths
3
8
content
stringlengths
100
981k
1703449
import sys import re """This script gets EMAIL, PASSWORD, SITE_URL, SECRET, ELECTION_YEAR, UPDATE_PROFILE, DB_NAME, DB_URL, and FALE_CONOSCO_EMAIL environment variables used on app engine from Github Secrets and replace on app.yaml.""" app_engine_file = "app.yaml" if __name__ == "__main__": if len(sys.argv) != 1...
1703465
from __future__ import print_function __author__ = '<NAME>, <EMAIL>' from numpy import random from random import sample from scipy import isscalar from pybrain.datasets.dataset import DataSet from pybrain.utilities import fListToString class SupervisedDataSet(DataSet): """SupervisedDataSets have two fields, on...
1703475
from sqlalchemy import Column, String, Integer, Float, Date, Boolean, create_engine, PrimaryKeyConstraint from sqlalchemy.ext.declarative import declarative_base from dotenv import load_dotenv import os Base = declarative_base() class NewHouseByArea(Base): '''--新房成交信息,按面积划分的信息''' __tablename__ = 'newhousebya...
1703510
import os from zstacklib.utils import shell from zstacklib.utils import lvm from kvmagent.plugins.bmv2_gateway_agent import exception from kvmagent.plugins.bmv2_gateway_agent import utils as bm_utils from kvmagent.plugins.bmv2_gateway_agent.volume import base from kvmagent.plugins.bmv2_gateway_agent.volume import hel...
1703570
from django.contrib import admin from .models import * # Register your models here. @admin.register(ItemType) class ItemTypeAdmin(admin.ModelAdmin): list_display = ("name","about","item_type_keywords","created_at","updated_at") @admin.register(Item) class ItemAdmin(admin.ModelAdmin): list_display = ("name","...
1703585
from pecan import rest from wsme import types as wtypes from jmilkfansblog.api.expose import expose as wsexpose from jmilkfansblog.controllers.v1.views import posts as posts_views from jmilkfansblog.db import api as db_api class Post(wtypes.Base): """Response data validation for post object""" id = str ...
1703633
import numpy as np import json def unjson(file): with open(file, 'r') as fo: dict = json.load(fo) return dict # r is noise rate r = 0.2 count = 0 p_a = '' p_g = '' a = unjson(p_a) for i in range(len(a['annotations'])): if np.random.random() < r: a['annotations'][i]['category_id'] = np....
1703640
import streamlit as st def welcome(): st.sidebar.success("Select an experiment above") st.markdown( """ # Welcome to Sapsan! --- Sapsan is a pipeline for Machine Learning (ML) based turbulence modeling. While turbulence is important in a wide...
1703687
import numpy as np import geopandas as gpd class Voronoi: def __init__(self, detection_base): """ :param detection_base: """ self.detection_base = detection_base @property def _centered_coords(self): """ scipy.spatial.Voronoi needs coordinates centered at ...
1703699
from collections import Counter from copy import deepcopy import os import yaml from urllib.parse import urlsplit import datefinder from ._base import BaseParser from .articles import Article from .cleaners import clean_hashtags from .extractors import SeleniumExtractor, RequestsExtractor from .log import get_logger ...
1703705
description = 'DEL setup at beam TREFF' includes = [ 'voltage', 'short_table_treff', ] group = 'basic'
1703711
from nose.tools import assert_equal, assert_raises class TestRadixSort(object): def test_sort(self): radix_sort = RadixSort() assert_raises(TypeError, radix_sort.sort, None) assert_equal(radix_sort.sort([]), []) array = [128, 256, 164, 8, 2, 148, 212, 242, 244] expected = ...
1703735
import numpy as np def is_numeric(u): return isinstance(u, (int, float)) \ or np.isscalar(u)
1703739
from sqlalchemy import Column, Integer, String from bitcoin_acks.database.base import Base class Repositories(Base): __tablename__ = 'repositories' id = Column(Integer, primary_key=True) path = Column(String) name = Column(String)
1703771
import unittest from dataclasses import dataclass from typing import Optional from komand_sql.connection.connection import Connection import logging from komand_sql.connection.schema import Input @dataclass class TestCase: name: str input_type: str input_port: Optional[str] expected: str testcases...
1703865
import os import random import sys import time import numpy as np import torch from tensorboardX import SummaryWriter class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self def set_cuda(config): use_cuda = torch.cuda.i...
1703884
from http import HTTPStatus from waterbutler.core.exceptions import ProviderError class DropboxUnhandledConflictError(ProviderError): def __init__(self, error_data): super().__init__('Dropbox has many unique error messages for code 409 (Conflict), this ' 'one was not specifically...
1703887
from __future__ import division import pycuda.autoinit import pycuda.driver as drv import pycuda.gpuarray as gpuarray from pycuda.tools import DeviceMemoryPool, PageLockedMemoryPool from pycuda.sparse.packeted import PacketedSpMV from pycuda.sparse.operator import DiagonalPreconditioner from pycuda.sparse.cg import sol...
1703899
import pytest import numpy as np from gibbs.minimization import PygmoSelfAdaptiveDESettings, OptimizationProblem from gibbs.minimization import OptimizationMethod, ScipyDifferentialEvolutionSettings seed = 123 def f_rosenbrock(x): """ Define the benchmark Rosenbrock function. :param numpy.ndarray x: ...
1703916
from vue import VueComponent, computed class NavigationItem(VueComponent): item: dict template = """ <el-menu-item-group v-if="is_group_header"> <span slot="title">{{ item.group }}</span> </el-menu-item-group> <component v-else @click="$emit('click', item)" :is="item_tag" ...
1703923
from .base import BaseLayer import hetu as ht class Relu(BaseLayer): def __call__(self, x): return ht.relu_op(x)
1703959
import logging from flow.utils.flow_warnings import deprecation_warning class SumoParams: def __init__(self, port=None, sim_step=0.1, emission_path=None, lateral_resolution=None, no_step_log=True, sumo_binary="s...
1703979
from django.db import models from .helper import DefaultFields, ShortableNameFields class LegislativeTerm(DefaultFields, ShortableNameFields): start = models.DateField() end = models.DateField(null=True, blank=True) def __str__(self): return self.short_name
1703994
import numpy as np from pandas import DataFrame class procrustes_test(object): """ Docstring for function ecopy.procrustes_test ==================== Conducts permutation procrustes test of relationship between two non-diagonal (raw) matrices Use ---- procrustes_test(mat1, mat2, npe...
1704011
import asyncio import importlib import logging import os import re import time import core.utils from core.exceptions import ParseTemplateError, ParseTemplateRuntimeError from core.storage import cache from core.template_parser.nodes import site_configs from core.template_parser.nodes.base import TemplateNode from cor...
1704013
import torch import torch.nn as nn import torch.utils import torch.utils.data import numpy as np from torch.autograd import Variable class VRNN(nn.Module): def __init__(self, x_dim, h_dim, z_dim, n_layers, writer, bias=False): super(VRNN, self).__init__() self.x_dim = x_dim self.h_dim = ...
1704015
import csv import re from functools import lru_cache from pathlib import Path """ The original court tag in our XML looks like this: <court abbreviation="Ill." jurisdiction="Illinois">Illinois Supreme Court</court> The tag does not follow a defined dictionary of court names, and requires a variety...
1704032
from pyjamas.JSONService import JSONProxy class SchoolCalendarService(JSONProxy): def __init__(self): JSONProxy.__init__(self, "SchoolCalendarService.php", ["getPeople"])
1704061
import pickle import time import unittest from pygsti.baseobjs import profiler from ..testutils import BaseTestCase class ProfilerTestCase(BaseTestCase): def setUp(self): super(ProfilerTestCase, self).setUp() def test_profler_methods(self): comm=None mem = profiler._get_root_mem_usa...
1704106
from torchnlp.samplers.balanced_sampler import BalancedSampler from torchnlp.samplers.bptt_batch_sampler import BPTTBatchSampler from torchnlp.samplers.bptt_sampler import BPTTSampler from torchnlp.samplers.bucket_batch_sampler import BucketBatchSampler from torchnlp.samplers.deterministic_sampler import DeterministicS...
1704115
class Solution: def minEatingSpeed(self, piles, H): piles.sort() l, r = 1, max(piles) while l <= r: mid = (l + r) // 2 h = sum(math.ceil(p / mid) for p in piles) if h > H: l = mid + 1 elif h < H: r = mid - 1 ...
1704147
from collections import OrderedDict from hitchstory import utils from strictyaml import Map from copy import copy class Arguments(object): """A null-argument, single argument or group of arguments of a hitchstory step.""" def __init__(self, yaml_args, params): """Create arguments from dict (from yaml...
1704153
from oic.utils.stateless import StateLess __author__ = 'roland' def _eq(l1, l2): return set(l1) == set(l2) def test_access_code(): keys = {"oct": ["symmetric key123"]} # keylength 16 bytes=128 bits st = StateLess(keys, enc_alg="A128KW", enc_method="A128CBC-HS256") con = st.create_authz_session("su...
1704182
import socket from .constants import (Command, CommandFlag, MonoEffect) from .utils import clamp from .WifiLedShopLightState import WifiLedShopLightState class WifiLedShopLight: """ A Wifi LED Shop Light """ def __init__(self, ip, port = 8189, timeout = 5, retries = 5): """ Creates a new Wifi LED Sho...
1704189
def decode(data, size): """ Decodes RLE encoded data. """ data = bytearray(data) # <- python 2/3 compatibility fix result = bytearray(size) src = 0 dst = 0 while src < len(data): header = data[src] if header > 127: header -= 256 src += 1 if 0...
1704205
from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt map = Basemap(projection='ortho', lat_0=0, lon_0=0) map.drawmapboundary(fill_color='aqua') map.fillcontinents(color='coral',lake_color='aqua') map.drawcoastlines() for lon in range(0, 360, 20): for lat in range(-60, 90, 30): ...
1704248
from arekit.common.data.input.providers.label.base import LabelProvider class MultipleLabelProvider(LabelProvider): def __init__(self, label_scaler): super(MultipleLabelProvider, self).__init__(label_scaler=label_scaler) def calculate_output_uint_label(self, expected_uint_label, etalon_uint_label): ...
1704256
from setuptools import setup, find_packages setup(name='lm-evaluation', version='0.1', description='LM Evaluation', url='https://github.com/AI21Labs/lm-evaluation', author='AI21 Labs', install_requires=[ "tqdm", "requests", "pandas", "smart_...
1704278
from abc import ABCMeta, abstractmethod from six import add_metaclass from cogitare.core.model import Model from cogitare.utils import not_training, training @add_metaclass(ABCMeta) class SequentialModel(Model): """ .. warning:: This module is experimental and its interface may change in future releases. ...
1704283
from django.apps import AppConfig class DjangoWebProfilerConfig(AppConfig): name = 'django_web_profiler'
1704284
import os os.environ["OMP_NUM_THREADS"] = "1" os.environ["OPENBLAS_NUM_THREADS"] = "1" os.environ["MKL_NUM_THREADS"] = "1" os.environ["VECLIB_MAXIMUM_THREADS"] = "1" os.environ["NUMEXPR_NUM_THREADS"] = "1" import copy import logging import pandas as pd import multiprocessing as mp from ..orbit import TestOrbit from ...
1704298
import functools from typing import Callable, List, Optional import click from globus_cli.parsing.command_state import ( debug_option, format_option, map_http_status_option, verbose_option, ) def common_options( f: Optional[Callable] = None, *, disable_options: Optional[List[str]] = None ) -> Ca...
1704308
from pudzu.charts import * from pudzu.sandbox.bamboo import * fg, bg="black", "white" COLS = 5 default_img = "https://s-media-cache-ak0.pinimg.com/736x/0d/36/e7/0d36e7a476b06333d9fe9960572b66b9.jpg" flags = pd.read_csv("datasets/countries.csv").split_columns(('nationality', 'tld', 'country'), "|").explode('cou...
1704414
import logging import os import pdb import socket import ssl as ssllib import sys from threading import Thread import traceback from irc.connection import Factory import six from . import paste_backends from .bot import IrcpdbBot from .exceptions import NoAllowedNicknamesSelected, NoChannelSelected from .parse import...
1704464
import pytest from parameterized import parameterized from api.saml.metadata.filter import SAMLSubjectFilter, SAMLSubjectFilterError from api.saml.metadata.model import ( SAMLAttribute, SAMLAttributeStatement, SAMLAttributeType, SAMLSubject, ) from core.python_expression_dsl.evaluator import DSLEvaluat...
1704510
import pytest from dbt.tests.util import run_dbt from tests.functional.configs.fixtures import BaseConfigProject class TestConfigIndivTests(BaseConfigProject): @pytest.fixture(scope="class") def project_config_update(self): return { "seeds": { "quote_columns": False, ...
1704550
from abc import ABCMeta, abstractmethod from ctypes import c_void_p, c_char_p, c_int, c_double, byref from .pyfluid import pyfluid as lib from . import pybindings as pb from . import method_decorators as decorators from .vector3 import Vector3, Vector3_t from .aabb import AABB, AABB_t class FluidSource: __metacla...
1704551
from cellrank.tl.estimators.mixins.decomposition import EigenMixin, SchurMixin from cellrank.tl.estimators.mixins._lineage_drivers import LinDriversMixin from cellrank.tl.estimators.mixins._absorption_probabilities import AbsProbsMixin
1704569
from .algorithmic import ( ParallelGroupBy, Rolling, nansum, masked_sum, nanmean, masked_mean, nanvar, nanstd, masked_last, masked_first, nanlast, nanmax, nanmin, pad_2d, covariance, pearsonr, linear_regression_1d, quantile, )
1704584
from django.conf import settings from django.conf.urls.defaults import * from django.views.decorators.cache import cache_page from .feeds import ArticleFeed from .views import SourceSearchView, HomepageView, SlackMessageView from haystack.forms import SearchForm from haystack.query import SearchQuerySet from haystack....
1704626
import sys __copyright__ = "Copyright 2021, AutoML.org Freiburg-Hannover" __license__ = "3-clause BSD" if __name__ == '__main__': if sys.argv[1] == "1": print("Result of this algorithm run: UNSAT,1,1,1,12354") if sys.argv[1] == "2": print("Result of this algorithm run: UNSAT,2,3,4,12354,add...
1704640
from core.constants import Visibility from django.contrib.syndication.views import Feed from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.feedgenerator import Rss201rev2Feed, rfc2822_date from entry.models import TLocation from indieweb.constants import MPostKinds, MPostSt...
1704644
import socket import json import datetime import time currentStatusFileName = "currPhase.json" currentSignalPlanFileName = "signalPlan.json" # Read a config file into a json object: configFile = open("/nojournal/bin/mmitss-phase3-master-config.json", 'r') config = (json.load(configFile)) configFile.close() hostIp = ...
1704648
import json import pymongo from flask import request, abort, json, render_template, Response from flask.ext import restful from flask.ext.restful import reqparse from flask_rest_service import app, api, mongo from bson.objectid import ObjectId from bson.code import Code # ----- /stats ----- class Stats(restful.Resour...
1704664
from chainer.links.model.vision.resnet import ResNet50Layers import collections import chainer.functions as F from chainer.links import BatchNormalization class C4Backbone(ResNet50Layers): def __init__(self, pretrained_model): super().__init__(pretrained_model) del self.res5 del self.fc6 ...
1704755
import torch.nn.init as init import torch.nn as nn import math import os def recursive_glob(rootdir='.', suffix=''): """Performs recursive glob with given suffix and rootdir :param rootdir is the root directory :param suffix is the suffix to be searched """ return [os.path.join(looproot, f...
1704798
import requests from flask import request from flask_restful import Resource from flask_jwt_extended import get_jwt_identity from flask_jwt_extended import jwt_required from ..models import User, Permission, login_manager class SearchGithub(Resource): @jwt_required() def post(self): # TODO: add abilit...
1704841
from common_utils.bio_prf_eval import BioEval class Task: def __init__(self, args): self.args = args # set up eval tool for model selection self.bio_eval = BioEval() self.bio_eval.set_logger(self.args.logger) # set up data loader # init or reload model def t...
1704857
from toee import * from combat_standard_routines import * def san_dialog( attachee, triggerer ): triggerer.begin_dialog( attachee, 1 ) return SKIP_DEFAULT def san_dying( attachee, triggerer ): if should_modify_CR( attachee ): modify_CR( attachee, get_av_level() ) game.global_flags[836] = 1 return RUN_DEFAULT...
1704875
from pytest_dash.utils import ( import_app, wait_for_text_to_equal, wait_for_element_by_css_selector ) # Basic test for the component rendering. def test_render_component(dash_threaded, selenium): # Start a dash app contained in `usage.py` # dash_threaded is a fixture by pytest-dash # It will ...
1704916
from dlib import * import numpy as np import sys sys.path = ['./superfast/build'] + sys.path import superfast import tools # img = load_grayscale_image(sys.argv[1]) img = load_grayscale_image('./images/find_page/paper01.jpg') # What about this image? Need to do something to fix it # img = load_grayscale_image('...
1704923
import re, time, string from datetime import datetime, date, timedelta __all__ = ['Cookie'] class Cookie(dict): def __init__(self, input=None): if input: self.load(input) def load(self, data): ckey = None for key, val in _rx_cookie.findall(data): if key.lower()...
1704930
import json import os import shutil import warnings from typing import List, Tuple from sklearn.model_selection import train_test_split def read_json(fp: str) -> dict: """Helper. Reads a JSON file and returns content. :param fp: The filepath to the JSON file. :dtype fp: str """ with open(fp) as ...
1704945
from .responder import Responder, ResponderType from pepper.framework import * from pepper.language import Utterance from pepper.knowledge import animations from random import choice from typing import Optional, Union, Tuple, Callable class BrexitResponder(Responder): @property def type(self): retu...
1704946
import copy from os import path from typing import Dict import torch from torch import nn from torch.utils.data import TensorDataset from torchvision.datasets import CIFAR10, MNIST from torchvision.transforms import Compose, Normalize, ToTensor from tqdm import tqdm def transform_mnist(): return Compose([ToTenso...
1704956
from TelegramBotAPI.client.requestsclient import RequestsClient from TelegramBotAPI.types.methods import getUpdates from twisted.application import service from twisted.internet import reactor, threads, defer from twisted.python import log class TwistedClient(service.Service): name = 'telegrambot_client' _l...
1705006
from .base import MIN_HEARTBEAT_CHECK_SPAN, MIN_HEARTBEAT_SPAN, DEFAULT_MASTER_PORT, DEFAULT_SLAVE_PORT, \ DEFAULT_CHANNEL, DEFAULT_HEARTBEAT_CHECK_SPAN, DEFAULT_HEARTBEAT_TOLERANCE, DEFAULT_HEARTBEAT_SPAN, LOCAL_HOST, \ GLOBAL_HOST, DEFAULT_REQUEST_RETRIES, DEFAULT_REQUEST_RETRY_WAITING
1705053
import torch.nn as nn # type: ignore import torch # type: ignore import torch.nn.init # type: ignore import math # type: ignore from collections import OrderedDict #import models use_relu = False use_bn = True def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" global use_bn ...
1705066
import os import uuid from django.db.models import CharField, FileField, BooleanField from django.utils import timezone from apps.vadmin.op_drf.models import CoreModel def files_path(instance, filename): return '/'.join(['system', timezone.now().strftime("%Y-%m-%d"), str(uuid.uuid4()) + os.path.splitext(filenam...
1705075
import magma as m from loam.boards.tinyfpga import B2 b2 = B2() b2.PIN4.input().on() b2.PIN5.output().on() main = b2.main() m.wire( main.PIN4, main.PIN5 ) m.EndDefine()
1705091
import datetime import os from functools import wraps from django.conf import settings from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY from django.contrib.sessions.backends.db import SessionStore from django.core.urlresolvers import reverse from django.test import LiveServerTestCase, TestCase from sel...
1705107
from wagtail.admin.edit_handlers import FieldPanel from wagtailleafletwidget.app_settings import ( LEAFLET_WIDGET_ZOOM ) from wagtailleafletwidget.widgets import ( GeoField, ) class GeoPanel(FieldPanel): def __init__(self, *args, **kwargs): self.classname = kwargs.pop('classname', "") sel...
1705159
from .utils import fix_unicode from .utils import swap_kar_location __all__ = ['from_unicode'] CHAR_TABLE = { 2437: 'A', 2438: 'Aw', 2439: 'B', 2440: 'C', 2441: 'D', 2442: 'E', 2443: 'F', 2447: 'G', 2448: 'H', 2451: 'I', 2452: 'J', 2453: 'K', 2454: 'L', 2455: '...
1705171
from typing import Optional from ruptures.base import BaseCost from ruptures.detection import Binseg from sklearn.linear_model import LinearRegression from etna.transforms.decomposition.change_points_trend import ChangePointsTrendTransform from etna.transforms.decomposition.change_points_trend import TDetrendModel ...
1705189
import numpy as np import pandas as pd import xarray as xr import typing as tp NdType = tp.Union[np.ndarray, pd.DataFrame, xr.DataArray, pd.Series] NdTupleType = tp.Union[ tp.Tuple[NdType], tp.Tuple[NdType, NdType], tp.Tuple[NdType, NdType, NdType], tp.Tuple[NdType, NdType, NdType, NdType], ] XR_TIME_...
1705216
import os import tempfile import unittest import numpy as np from keras_pos_embd.backend import keras from keras_pos_embd import TrigPosEmbedding class TestSinCosPosEmbd(unittest.TestCase): def test_invalid_output_dim(self): with self.assertRaises(NotImplementedError): TrigPosEmbedding( ...
1705298
print(data_view_config) # { 'dataset_ids': ['1160'], # 'group_by': [], # 'model_type': 'default', # 'descriptors': [ # { # 'category': 'Real', # 'descriptor_key': 'Temperature (Property Band gap)', # 'units': '', # 'lower_bound': 0.0, # '...
1705327
from biplist import * import os from test_utils import * import unittest class TestInvalidPlistFile(unittest.TestCase): def setUp(self): pass def testEmptyFile(self): try: readPlist(data_path('empty_file.plist')) self.fail("Should not successfully read empty plist.") ...
1705328
from xml.sax.saxutils import escape class Node: def __init__(self, start, end, tag, parent, attrs): self.start = start self.end = end self.tag = tag self.parent = parent self.children = [] if attrs: self.attrs = attrs else: self...
1705346
import logging from pytorch_pretrained_bert import BertTokenizer logger = logging.getLogger(__name__) def get_tokenizer(tokenizer_name): logger.info(f"Loading Tokenizer {tokenizer_name}") if tokenizer_name.startswith("bert"): do_lower_case = "uncased" in tokenizer_name tokenizer = BertToken...
1705372
import sys import tempfile import textwrap import unittest import shutil import subprocess class PabotArgumentsOutputsTest(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.tmpdir) def _run_tests_with(self, testfile, arg1file, ar...
1705385
import requests import argparse import datetime from app import db from models.cran_package import CranPackage from models.pypi_package import PypiPackage from models.github_repo import GithubRepo from models.github_api import make_ratelimited_call import update from util import safe_commit def add_all_new_packages(...
1705393
def Settings( **kwargs ): assert kwargs[ 'language' ] == 'java' return { 'ls': { 'java.rename.enabled' : False }, 'formatting_options': { 'org.eclipse.jdt.core.formatter.lineSplit': 30, } }
1705398
from src.alerter.alert_code.alert_code import AlertCode from src.alerter.alert_code.github_alert_code import GithubAlertCode from src.alerter.alert_code.internal_alert_code import InternalAlertCode from src.alerter.alert_code.system_alert_code import SystemAlertCode
1705405
from apps.search_head_api.views.base import SearchHeadAPIView from . import capturenode, search, tests __all__ = [capturenode, search, tests]
1705412
import pytest from dbt.tests.util import run_dbt from tests.functional.simple_snapshot.fixtures import models_slow__gen_sql snapshots_slow__snapshot_sql = """ {% snapshot my_slow_snapshot %} {{ config( target_database=var('target_database', database), target_schema=schema, ...
1705465
def hanoi(disks, source, auxiliary, target): if disks == 1: print('Move disk 1 from peg {} to peg {}.'.format(source, target)) return hanoi(disks - 1, source, target, auxiliary) print('Move disk {} from peg {} to peg {}.'.format(disks, source, target)) hanoi(disks - 1, auxiliary, sourc...
1705487
CACHE_KEY_ASSET_TASK_LOG_PREFIX = "asset:task-log:" # + task.id CACHE_KEY_AUTODJ_CURRENT_STOPSET = "autodj:current-stopset" CACHE_KEY_AUTODJ_NO_REPEAT_ARTISTS = "autodj:no-repeat-artists" CACHE_KEY_AUTODJ_NO_REPEAT_IDS = "autodj:no-repeat-ids" CACHE_KEY_AUTODJ_REQUESTS = "autodj:requests" CACHE_KEY_AUTODJ_STOPSET_LAST...
1705625
from config import * import pickle import numpy as np def prepare_mano_model(): """ Convert the official MANO model into compatible format with this project. """ with open(OFFICIAL_MANO_PATH, 'rb') as f: data = pickle.load(f, encoding='latin1') params = { 'pose_pca_basis': np.array(data['hands_compo...
1705626
import hashlib def md5sum(file_url): md5sum = hashlib.md5() with open(file_url,'rb') as f: while True: data = f.read(2048) if not data: break md5sum.update(data) return md5sum.hexdigest()
1705628
import os, time import asyncio from fastapi import FastAPI from easyjobs.workers.worker import EasyJobsWorker server = FastAPI() @server.on_event('startup') async def setup(): worker = await EasyJobsWorker.create( server, '/ws/jobs', server_secret='<KEY>', manager_host='192.168.1.1...
1705692
import sys import os sys.path.append(os.getcwd()) import time from abc import ABCMeta from .utils.util import plot_scores, print_schedule, read_file from .base_algorithm import FlightAlgorithm import random from .fitness import * class RandomSearch(FlightAlgorithm, metaclass=ABCMeta): def __init__(self, domain=...
1705707
import os import smtplib from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart import getpass host_name = 'smtp.gmail.com' port = 465 sender = '<EMAIL>' password = getpass.getpass() receiver = '<EMAIL>' text = MIMEMultipart() text['Subject'] = 'Tes...
1705730
from sqlalchemy import create_engine import time # This is a basic test for both protocols. The result set from flight and odbc must match # TODO Naren: Add unit tests for flight db_uri = "dremio+flight://dremio:dremio123@localhost:32010/dremio;SSL=0" engine = create_engine(db_uri) sql = 'SELECT * FROM flight."1m" li...
1705736
from __future__ import unicode_literals import collections import datetime import os import tempfile from copy import deepcopy from itertools import chain from shutil import rmtree from ags_utils import ( create_session, get_service_manifest, get_service_status, list_data_stores, list_service_fold...
1705742
def check_parameter_value(parameter, allowed, name): """Raise a ValueError if a parameter value is not in the set of allowed values. """ if parameter not in allowed: raise ValueError(f"Parameter '{name}' must be one of {', '.join(allowed)}.")
1705748
import collections from importlib import import_module def import_string(dotted_path): """ Copied from Django's django.utils.module_loading.import_string to be able to work framework independently. Import a dotted module path and return the attribute/class designated by the last name in the path....
1705773
import decimal import numpy as np from collections import deque import torch from config import cfg from utils.timer import Timer from utils.logger import logger_info import utils.distributed as dist from utils.distributed import sum_tensor def accuracy(output, target, topk=(1,)): """Computes the accuracy over th...
1705797
import pandas as pd import numpy as np import matplotlib.pylab as plt # read data u_cols = ['user_id', 'age', 'sex', 'occupation', 'zip_code'] users = pd.read_csv('ml-100k/u.user', sep='|', names=u_cols,encoding='latin-1') r_cols = ['user_id', 'movie_id', 'rating', 'unix_timestamp'] ratings = pd.read_csv('m...
1705846
import os from typing import Any, Dict, Iterable, List, Optional, TYPE_CHECKING import manta_lab as ml import manta_lab.base.packet as pkt if TYPE_CHECKING: from multiprocessing.process import BaseProcess from queue import Queue from manta_lab.api import MantaAPI from manta_lab.base.packet...