id
stringlengths
3
8
content
stringlengths
100
981k
94558
import pickle from collections import Counter from math import log from typing import List, Dict, Tuple import numpy as np from scipy.sparse import csr_matrix from scipy.spatial.distance import cosine from common import check_data_set, flatten_nested_iterables from preprocessors.configs import PreProcessingConfigs fr...
94613
import re import pkuseg from tqdm import tqdm from collections import Counter class Statistics(): def __init__(self,data): self.data = data self.min_length = 5 self.max_length = 100 self.post_num = 0 self.resp_num = 0 self.err_data = 0 def word_freq(self): ...
94631
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ] operations = [ migrations.CreateModel( name='Bookmark', fields=[ ('id', models...
94693
from sys import exit import argparse import logging _logger = logging.getLogger(__name__) _LOGGING_FORMAT = '%(name)s.%(funcName)s[%(levelname)s]: %(message)s' _DEBUG_LOGGING_FORMAT = '### %(asctime).19s.%(msecs).3s [%(levelname)s] %(name)s.%(funcName)s (%(filename)s:%(lineno)d) ###\n%(message)s' def parse_args(): ...
94696
import re import pandas as pd def update_simulation_date_time(lines, start_line, new_datetime): """ replace both the analysis and reporting start date and times """ new_date = new_datetime.strftime("%m/%d/%Y") new_time = new_datetime.strftime("%H:%M:%S") lines[start_line] = re.sub(r'\d{2}\\\d{...
94734
from __future__ import print_function import pytest import sys from operator import add import findspark findspark.init() from pyspark import SparkContext, SparkConf, SQLContext, Row import os, subprocess, json, riak, time import pyspark_riak import timeout_decorator import datetime import tzlocal import pytz import ma...
94736
from stochastic.processes.continuous import * from stochastic.processes.diffusion import * from stochastic.processes.discrete import * from stochastic.processes.noise import *
94763
import six import collections from chef.base import ChefObject from chef.exceptions import ChefError class NodeAttributes(collections.MutableMapping): """A collection of Chef :class:`~chef.Node` attributes. Attributes can be accessed like a normal python :class:`dict`:: print node['fqdn'] no...
94784
from __future__ import absolute_import from __future__ import print_function import logging import numpy as np from numpy.lib.recfunctions import append_fields from sklearn.cluster import DBSCAN from lmatools.coordinateSystems import GeographicSystem from lmatools.flashsort.flash_stats import calculate_...
94791
from . import matplotlib_fix from . import ipynb from . import colormap from . import plot from .context_manager import LatexContextManager from .context_manager import figure_context from .context_manager import axes_context from .module_facet_grid import facet_grid from .module_facet_grid import facet_grid_zero_spac...
94794
import numpy as np import quaternion def from_tqs_to_matrix(translation, quater, scale): """ (T(3), Q(4), S(3)) -> 4x4 Matrix :param translation: 3 dim translation vector (np.array or list) :param quater: 4 dim rotation quaternion (np.array or list) :param scale: 3 dim scale vector (np.array or li...
94823
import math import json from colormath.color_objects import RGBColor from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from common.models import UserBase, ResultBase from common.utils import save_obj_attr_base64_image, get_content_...
94855
from django.apps import AppConfig class Config(AppConfig): name = "paywall" verbose_name = "paywall simulator" label = "paywall"
94860
import torch from numpy.testing import assert_almost_equal import numpy from allennlp.common import Params from allennlp.common.testing.test_case import AllenNlpTestCase from allennlp.modules.matrix_attention import CosineMatrixAttention from allennlp.modules.matrix_attention.matrix_attention import MatrixAttention ...
94872
from forge.blade import lib class Recipe: def __init__(self, *args, amtMade=1): self.amtMade = amtMade self.blueprint = lib.MultiSet() for i in range(0, len(args), 2): inp = args[i] amt = args[i+1] self.blueprint.add(inp, amt)
94906
import tkinter as tk from PIL import ImageTk, Image from os import listdir import cv2 import numpy as np root=tk.Tk() root.title("DataX: Team OST, Plastic Part Matching") #Init database path=r"C:\Users\tobias.grab\IWK_data\test" files=listdir(path) nrOfFiles=len(files) bf = cv2.BFMatcher() fast=1 i...
94993
from wsgiref.simple_server import make_server from fs.osfs import OSFS from wsgi import serve_fs osfs = OSFS('~/') application = serve_fs(osfs) httpd = make_server('', 8000, application) print "Serving on http://127.0.0.1:8000" httpd.serve_forever()
95042
from .location import Location, Direction from .move import Move __all__ = ['converter', 'Location', 'Move', 'notation_const']
95063
from functools import reduce from operator import mul def product(iterable=(), start=1): """ kata currently supports only Python 3.4.3 """ return reduce(mul, iterable, start) # __builtins__.product = product
95156
import tensorflow as tf cluster = tf.train.ClusterSpec({"local": ["192.168.122.171:2222", "192.168.122.40:2222"]}) x = tf.constant(2) with tf.device("/job:local/task:1"): y2 = x - 66 with tf.device("/job:local/task:0"): y1 = x + 300 y = y1 + y2 with tf.Session("grpc://192.168.122.40:2222") as sess: ...
95188
import unittest import pyslow5 as slow5 import time import numpy as np """ Run from root dir of repo after making pyslow5 python3 -m unittest -v python/test.py """ #globals debug = 0 #TODO: make this an argument with -v class TestBase(unittest.TestCase): def setUp(self): self.s5 = slow5.Open('e...
95306
from yggdrasil.communication import FileComm class PickleFileComm(FileComm.FileComm): r"""Class for handling I/O from/to a pickled file on disk. Args: name (str): The environment variable where file path is stored. **kwargs: Additional keywords arguments are passed to parent class. """ ...
95309
import pytest from cleo.io.inputs.token_parser import TokenParser @pytest.mark.parametrize( "string, tokens", [ ("", []), ("foo", ["foo"]), (" foo bar ", ["foo", "bar"]), ('"quoted"', ["quoted"]), ("'quoted'", ["quoted"]), ("'a\rb\nc\td'", ["a\rb\nc\td"]), ...
95376
from typing import Tuple from os.path import join import sys from coreml.utils.logger import color from coreml.utils.io import read_yml from coreml.utils.typing import DatasetConfigDict def read_dataset_from_config( data_root: str, dataset_config: DatasetConfigDict) -> dict: """ Loads and returns the ...
95405
import numpy as np from igraph import * # Define some useful graph functions def plotGraph(g, name=None): '''Function that plots a graph. Requires the pycairo library.''' color_dict = {0: "blue", 1: "#008833"} visual_style = {} visual_style["vertex_label_dist"] = 2 visual_style["vertex_size"] = ...
95416
from tir import Webapp import unittest from datetime import datetime DateSystem = datetime.today().strftime("%d/%m/%Y") class TRKXFUN(unittest.TestCase): @classmethod def setUpClass(self): self.oHelper = Webapp(autostart=False) self.oHelper.SetTIRConfig(config_name="User", value="telemarket...
95422
def common_ground(s1,s2): words = s2.split() return ' '.join(sorted((a for a in set(s1.split()) if a in words), key=lambda b: words.index(b))) or 'death'
95449
from wellcomeml.datasets.conll import _load_data_spacy, load_conll import pytest def test_length(): X, Y = _load_data_spacy("tests/test_data/test_conll", inc_outside=True) assert len(X) == len(Y) and len(X) == 4 def test_entity(): X, Y = _load_data_spacy("tests/test_data/test_conll", inc_outside=False)...
95453
from .moc import MOC from .plot.wcs import World2ScreenMPL __all__ = [ 'MOC', 'World2ScreenMPL' ]
95454
from chemios.pumps import Chemyx from chemios.utils import SerialTestClass #from dummyserial import Serial import pytest import logging #Logging logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") rootLogger = logging.getLogger() rootLogger.setLevel(logging.DEBUG) lo...
95458
import pytest from paste.deploy.config import ConfigMiddleware class Bug(Exception): pass def app_with_exception(environ, start_response): def cont(): yield b"something" raise Bug start_response('200 OK', [('Content-type', 'text/html')]) return cont() def test_error(): # This ...
95489
import pika import json credentials = pika.PlainCredentials("cc-dev", "<PASSWORD>") parameters = pika.ConnectionParameters( host="127.0.0.1", port=5672, virtual_host="cc-dev-ws", credentials=credentials) conn = pika.BlockingConnection(parameters) assert conn.is_open try: ch = conn.channel() ...
95522
from django.contrib import admin from django.urls import path import wordcount.views urlpatterns = [ path('admin/', admin.site.urls), path('', wordcount.views.home, name="home"), path('about/', wordcount.views.about, name='about'), path('result/', wordcount.views.result, name='result'), ]
95545
import os import hashlib from libcard2 import string_mgr from libcard2.master import MasterData LANG_TO_FTS_CONFIG = { "en": "card_fts_cfg_english", } TLINJECT_DUMMY_BASE_LANG = "en" async def add_fts_string(lang: str, key: str, value: str, referent: int, connection): if not (fts_lang := LANG_TO_FTS_CONFIG....
95586
import numpy as np from util.gym import action_size from util.logger import logger from motion_planners.sampling_based_planner import SamplingBasedPlanner class PlannerAgent: def __init__( self, config, ac_space, non_limited_idx=None, passive_joint_idx=[], ignored_...
95617
import os import math from pprint import PrettyPrinter import random import numpy as np import torch # Torch must be imported before sklearn and tf import sklearn import tensorflow as tf import better_exceptions from tqdm import tqdm, trange import colorlog import colorful from utils.etc_utils import set_logger, set...
95624
from qt import * from qtcanvas import * from lpathtree_qt import * class Point: def __init__(self, *args): if len(args) == 2 and \ (isinstance(args[0],int) or isinstance(args[0],float)) and \ (isinstance(args[1],int) or isinstance(args[0],float)): self.x = float(args[0]) ...
95643
from binascii import hexlify from crypto.transactions.deserializers.base import BaseDeserializer class DelegateResignationDeserializer(BaseDeserializer): def deserialize(self): self.transaction.parse_signatures( hexlify(self.serialized).decode(), self.asset_offset ) ...
95697
from jivago.lang.annotations import Serializable @Serializable class MyDto(object): name: str age: int def __init__(self, name: str, age: int): self.name = name self.age = age
95706
import os from pathlib import Path import pytest @pytest.fixture def example_repo_path(): if 'HEXRD_EXAMPLE_REPO_PATH' not in os.environ: pytest.fail('Environment varable HEXRD_EXAMPLE_REPO_PATH not set!') repo_path = os.environ['HEXRD_EXAMPLE_REPO_PATH'] return Path(repo_path)
95723
from typing import Iterable, Union from datahub.emitter.mce_builder import get_sys_time from datahub.emitter.mcp import MetadataChangeProposalWrapper from datahub.ingestion.api import RecordEnvelope from datahub.ingestion.api.common import PipelineContext from datahub.ingestion.api.source import Extractor, WorkUnit fr...
95738
from __future__ import print_function, unicode_literals import logging from collections import Counter from re import compile, escape from okcli.lexer import ORACLE_KEYWORDS from prompt_toolkit.completion import Completer, Completion from .packages.completion_engine import suggest_type from .packages.parseutils impo...
95745
from uliweb.core.commands import Command, CommandManager, get_commands from optparse import make_option class DataDictCommand(CommandManager): #change the name to real command name, such as makeapp, makeproject, etc. name = 'datadict' #help information help = "Data dict tool, create index, validate mod...
95777
import json import re import urllib.parse from typing import Tuple, Dict, Union, List, Any, Optional from lumigo_tracer.libs import xmltodict import functools import itertools from collections.abc import Iterable from lumigo_tracer.lumigo_utils import Configuration, get_logger def safe_get(d: Union[dict, list], key...
95795
from __future__ import (absolute_import, division, print_function, unicode_literals) from astroid import MANAGER, Class, Instance, Function, Arguments, Pass def transform_model_class(cls): if cls.is_subtype_of('django.db.models.base.Model'): core_exceptions = MANAGER.ast_from_modu...
95822
import functools import hashlib import json import os import time import typing from collections import namedtuple from cauldron import environ from cauldron.session import definitions as file_definitions from cauldron.session import writing from cauldron.session.caching import SharedCache from cauldron.session.projec...
95856
from typing import List import ast import logging from ..module import Module, SafeFilenameModule from .path import ImportPath logger = logging.getLogger(__name__) class DependencyAnalyzer: """ Analyzes a set of Python modules for imports between them. Args: modules: list of all SafeFilenameM...
95899
import functools import warnings import matplotlib.pyplot as plt import numpy as np import seaborn as sns import tensorflow.compat.v2 as tf import tensorflow_probability as tfp from tensorflow_probability import bijectors as tfb from tensorflow_probability import distributions as tfd tf.enable_v2_behavior() warnin...
95900
import vlc import time vlc_instance = vlc.Instance('--input-repeat=-1') player = vlc_instance.media_player_new() media = vlc_instance.media_new(r"main\tracks\TRACK_1.mp3") player.set_media(media) player.play() time.sleep(10)
95901
from django.shortcuts import render, get_object_or_404 from django.views.generic.base import View from .models import Pages class Page(View): """Вывод страниц""" def get(self, request, slug=None): if slug is not None: page = get_object_or_404(Pages, slug=slug, published=True) else...
95917
import joblib import numpy as np from tqdm import tqdm import torch from torch.utils.data import TensorDataset, DataLoader from torch import nn, optim import matplotlib.pyplot as plt X_train = joblib.load('ch08/X_train.joblib') y_train = joblib.load('ch08/y_train.joblib') X_train = torch.from_numpy(X_train.astype(np....
95921
import random from time import sleep from celery import chain, chord, shared_task, states from django.core.files.base import ContentFile from django.db import transaction from django.utils import timezone from eulxml import xmlmap from extras.tasks import CurrentUserTaskMixin from ows_client.request_builder import Cat...
95952
from pddlgym.parser import PDDLDomainParser, PDDLProblemParser from pddlgym.structs import LiteralConjunction import pddlgym import os import numpy as np from itertools import count np.random.seed(0) PDDLDIR = os.path.join(os.path.dirname(pddlgym.__file__), "pddl") I, G, W, P, X, H = range(6) TRAIN_GRID1 = np.arra...
95955
import unittest from msdm.domains import GridWorld class GridWorldTestCase(unittest.TestCase): def test_feature_locations(self): gw = GridWorld([ "cacg", "sabb"]) fl = gw.feature_locations lf = gw.location_features fl2 = {} for l, f in lf.items(): ...
95980
from typing import List from avalanche.evaluation.metric_results import MetricValue from avalanche.evaluation.metric_utils import stream_type from avalanche.logging.interactive_logging import InteractiveLogger from tqdm import tqdm from avalanche.training import BaseStrategy from avalanche_rl.logging.strategy_logger i...
95984
import numpy as np from collections import OrderedDict import cPickle as pickle import time import sys sys.setrecursionlimit(2000) import argparse import RCN from RCN.preprocessing.tools import EOF from RCN.preprocessing.tools import shuffleData, splitData, mergeData from RCN.preprocessing.preprocess import preprocess_...
95985
import unittest import numpy as np import torch from pyscf import gto from torch.autograd import Variable, grad, gradcheck from qmctorch.scf import Molecule from qmctorch.wavefunction import SlaterJastrow torch.set_default_tensor_type(torch.DoubleTensor) def hess(out, pos): # compute the jacobian z = Variab...
95989
class InwardMeta(type): @classmethod def __prepare__(meta, name, bases, **kwargs): cls = super().__new__(meta, name, bases, {}) return {"__newclass__": cls} def __new__(meta, name, bases, namespace): cls = namespace["__newclass__"] del namespace["__newclass__"] for na...
95999
from icolos.core.workflow_steps.step import StepBase from pydantic import BaseModel from openmm.app import PDBFile import parmed from openff.toolkit.topology import Molecule, Topology from openff.toolkit.typing.engines.smirnoff import ForceField from openff.toolkit.utils import get_data_file_path from icolos.utils.en...
96001
import codecs from contextlib import suppress import logging import os from pathlib import Path from typing import Union import tempfile _LOGGER = logging.getLogger(__name__) def ensure_unique_string(preferred_string, current_strings): test_string = preferred_string current_strings_set = set(current_strings...
96021
import asyncio import gc import time import weakref from koala.typing import * from koala.logger import logger __TIMER_ID = 0 def _gen_timer_id() -> int: global __TIMER_ID __TIMER_ID += 1 return __TIMER_ID def _milli_seconds() -> int: return int(time.time() * 1000) class A...
96060
import json from os import getenv from pathlib import Path from typing import TypedDict, List, Any, Union from .errors_modals import * class User(TypedDict, total=False): username: str password: str is_default: bool last_login_time: str consumed_bytes: int last_login_result: str class Conf...
96081
from typing import Any, Dict, Optional, cast from django import forms from django.core.exceptions import ValidationError from django.forms.models import ModelChoiceIterator class Autocomplete(forms.Select): template_name = "reactivated/autocomplete" def get_context( self, name: str, value: Any, attr...
96117
import os.path as osp from PIL import Image import torchvision.transforms as transforms from torch.utils.data import Dataset class GBU(Dataset): def __init__(self, path, indices_list, labels, stage="train"): """This is a dataloader for the processed good bad ugly dataset. Assuming that the images...
96180
from __future__ import absolute_import, print_function, unicode_literals from .interface import Action from .named_shell_task import render_task _DEPROVISION_TITLE = "DEPROVISION CLOUD RESOURCES" _DEPROVISION_ACTION = "oct deprovision" class DeprovisionAction(Action): """ A DeprovisionAction generates a pos...
96195
from setuptools import setup setup(name='seleniumapis', version='0.1', description='Query Vanguard and other sites using the Selenium API', author='<NAME>', author_email='<EMAIL>', packages=['vanguard'], install_requires=[ 'selenium', 'nose' ], zip_sa...
96202
import dcase_util data = dcase_util.utils.Example.feature_container() data_aggregator = dcase_util.data.Aggregator( recipe=['flatten'], win_length_frames=10, hop_length_frames=1, ) data_aggregator.aggregate(data) data.plot()
96208
from importlib import import_module from shutil import copytree from datetime import date from logging import Logger from foliant.utils import spinner class BaseBackend(): '''Base backend. All backends must inherit from this one.''' targets = () required_preprocessors_before = () required_preprocess...
96227
import numpy as np from ..utils.dictionary import get_lambda_max def simulate_data(n_times, n_times_atom, n_atoms, n_channels, noise_level, random_state=None): rng = np.random.RandomState(random_state) rho = n_atoms / (n_channels * n_times_atom) D = rng.normal(scale=10.0, size=(n_atoms,...
96228
import rsa import json class LazyUser(object): def __init__(self): self.pub, self.priv = rsa.newkeys(512) def sign(self, transaction): message = json.dumps(transaction.to_dict(), sort_keys=True).encode('utf-8') signature = rsa.sign(message, self.priv, 'SHA-256') return (messag...
96278
class TaskException(Exception): """ Like classic Exception, but we keep the task result, which gets spoiled by celery cache result backend. The kwargs parameter is used for passing custom metadata. """ obj = None def __init__(self, result, msg=None, **kwargs): if msg: resul...
96294
from copy import copy import numpy as np from gym_chess import ChessEnvV1 from gym_chess.envs.chess_v1 import ( KING_ID, QUEEN_ID, ROOK_ID, BISHOP_ID, KNIGHT_ID, PAWN_ID, ) from gym_chess.test.utils import run_test_funcs # Blank board BASIC_BOARD = np.array([[0] * 8] * 8, dtype=np.int8) # Pa...
96306
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils import weight_norm from Models.AutoEncoder import create_layer def create_encoder_block(in_channels, out_channels, kernel_size, wn=True, bn=True, activation=nn.ReLU, layers=2): encoder = [] for i in range(l...
96346
from bench_db import get_timings_by_id from bench_graphs import do_warmup_plot num_iter = 7 color_copy_by_ref = 'green' name = 'native-' def warmup_all_plots(): warmup_plot_fannkuch() warmup_plot_spectralnorm() warmup_plot_bintree() def warmup_plot_fannkuch(): ids = [ 100 # fannkuchredux-...
96348
import os from django.db import transaction import csv from django.core.management.base import BaseCommand, CommandError from api.models import Country def get_bool(value): if value == 't': return True elif value == 'f': return False else: return None def get_int(value): # pri...
96369
import os import sys import cv2 import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import scipy.misc as sic class Cube2Equirec(nn.Module): def __init__(self, cube_length, equ_h): super().__init__() self.cube_length =...
96447
import time from abc import abstractmethod from datetime import datetime from typing import Optional, List, Tuple, Union from bxcommon.messages.bloxroute.tx_message import TxMessage from bxcommon.models.transaction_flag import TransactionFlag from bxcommon.utils import crypto, convert from bxcommon.utils.blockchain_ut...
96459
model_space_filename = 'path/to/metrics.json' model_sampling_rules = dict( type='sequential', rules=[ # 1. select model with best performance, could replace with your own metrics dict( type='sample', operation='top', # replace with customized metric in your o...
96480
from notifications_utils.clients.antivirus.antivirus_client import ( AntivirusClient, ) from notifications_utils.clients.redis.redis_client import RedisClient from notifications_utils.clients.zendesk.zendesk_client import ZendeskClient antivirus_client = AntivirusClient() zendesk_client = ZendeskClient() redis_cli...
96484
import contextlib import errno import os import sys import tempfile MS_WINDOWS = (sys.platform == 'win32') @contextlib.contextmanager def temporary_file(): tmp_filename = tempfile.mktemp() try: yield tmp_filename finally: try: os.unlink(tmp_filename) except OSError as...
96501
import sys from unittest import TestCase from dropSQL.ast import ColumnDef, IntegerTy, VarCharTy from dropSQL.fs.db_file import DBFile from dropSQL.parser.tokens.identifier import Identifier class LayoutCase(TestCase): def test(self): connection = DBFile(":memory:") db_name = "Database name!" ...
96531
from .ModelBuilder import ModelBuilder # noqa: F401 from .AbstractTapeModel import AbstractTapeModel # noqa: F401
96543
import random import time from collections import deque from threading import Lock import HABApp from HABApp.core.events import ValueUpdateEvent from .bench_base import BenchBaseRule from .bench_times import BenchContainer, BenchTime LOCK = Lock() class OpenhabBenchRule(BenchBaseRule): BENCH_TYPE = 'openHAB' ...
96593
from django.contrib.staticfiles import storage # Configure the permissions used by ./manage.py collectstatic # See https://docs.djangoproject.com/en/1.10/ref/contrib/staticfiles/ class TTStaticFilesStorage(storage.StaticFilesStorage): def __init__(self, *args, **kwargs): kwargs['file_permissions_mode'] = 0...
96619
Clock.bpm=144; Scale.default="lydianMinor" d1 >> play("x-o{-[-(-o)]}", sample=0).every([28,4], "trim", 3) d2 >> play("(X )( X)N{ xv[nX]}", drive=0.2, lpf=var([0,40],[28,4]), rate=PStep(P[5:8],[-1,-2],1)).sometimes("sample.offadd", 1, 0.75) d3 >> play("e", amp=var([0,1],[PRand(8,16)/2,1.5]), dur=PRand([1/2,1/4]), pan=va...
96628
import inspect from doubles.class_double import ClassDouble from doubles.exceptions import ConstructorDoubleError from doubles.lifecycle import current_space def expect(target): """ Prepares a target object for a method call expectation (mock). The name of the method to expect should be called as a metho...
96661
from xml.etree.cElementTree import fromstring from xmljson import yahoo import core from core.helpers import Url from core.providers.base import NewzNabProvider from core.providers import torrent_modules # noqa import logging logging = logging.getLogger(__name__) trackers = '&tr='.join(('udp://tracker.leechers-para...
96687
import gym import numpy as np class SpaceWrapper: def __init__(self, space): if isinstance(space, gym.spaces.Discrete): self.shape = () self.dtype = np.dtype(np.int64) elif isinstance(space, gym.spaces.Box): self.shape = space.shape self.dtype = np.d...
96692
import numpy as np import torch.nn.functional as F import math from torchvision import transforms import torch import cv2 import matplotlib import matplotlib.pyplot as plt import matplotlib.patches as patches matplotlib.use('agg') MAPS = ['map3','map4'] Scales = [0.9, 1.1] MIN_HW = 384 MAX_HW = 1584 IM_NORM_MEAN = [0...
96759
import torch import numpy as np from eval import metrics import gc def evaluate_user(model, eval_loader, device, mode='pretrain'): """ evaluate model on recommending items to users (primarily during pre-training step) """ model.eval() eval_loss = 0.0 n100_list, r20_list, r50_list = [], [], [] eval...
96876
import numpy as np from gym_env.feature_processors.enums import ACTION_NAME_TO_INDEX, DOUBLE_ACTION_PARA_TYPE class Instance: # reward is the td n reward plus the target state value def __init__(self, dota_time=None, state_gf=None, state_ucf=None, ...
96881
from abc import abstractmethod, ABC from typing import Any class Node(ABC): def __init__(self, node_name: str, node_id: str, parent_id: str) -> None: self._node_name = node_name self._node_id = node_id self._parent_id = parent_id def __str__(self) -> str: return self._node_nam...
96930
from io import BytesIO from django.shortcuts import render, get_object_or_404 from django.contrib.auth.decorators import login_required from django.template.loader import get_template from django.http import HttpResponse from xhtml2pdf import pisa from .models import Order def render_to_pdf(template_src, context_di...
96971
from elasticsearch import Elasticsearch, ElasticsearchException from oslo.config import cfg from meniscus.data.handlers import base from meniscus import config from meniscus import env _LOG = env.get_logger(__name__) #Register options for Elasticsearch elasticsearch_group = cfg.OptGroup( name="elasticsearch", ...
97029
from django.conf import settings from django.conf.urls import url from django.contrib.auth.views import (LogoutView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView) from waffle.decorators import waffle_switch from apps.accounts.views....
97051
import math __author__ = 'chenzhao' from gmission.models import * # 1km is about 0.01, 1m is 0.00001 def location_nearby_user_count(location_id, r=0.01): location = Location.query.get(location_id) P = UserLastPosition in_rect = (P.longitude >= location.coordinate.longitude - r) & (P.longitude <= locatio...
97053
SCRIPT=""" #!/bin/bash # Generate train/test script for scenario "{scenario}" using the faster-rcnn "alternating optimization" method set -x set -e rm -f $CAFFE_ROOT/data/cache/*.pkl rm -f {scenarios_dir}/{scenario}/output/*.pkl DIR=`pwd` function quit {{ cd $DIR exit 0 }} export PYTHONUNBUFFERED="True" TRA...
97054
import time import datetime now = datetime.datetime.now() mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1) while True: now = datetime.datetime.now() if mid < now < mid + datetime.timedelta(seconds=10) : print("정각입니다") mid = datetime.datetime(now.year, now.month, n...
97074
import json import pytest import uuid from pytest_httpx import HTTPXMock from tinkoff import tasks pytestmark = [pytest.mark.django_db] @pytest.fixture def idempotency_key() -> str: return str(uuid.uuid4()) def test(order, idempotency_key, httpx_mock: HTTPXMock): httpx_mock.add_response( url=f'htt...
97082
from flask import Flask, render_template, request, send_file import io import base64 as b64 import generator app = Flask(__name__) def page(**kwargs): return render_template('main.html', **kwargs) @app.route("/") def home(): return page() @app.route("/<text>", methods=['GET']) def load_origamicon(text)...