id
stringlengths
3
8
content
stringlengths
100
981k
1636185
print 50 cnt = 1 for i in xrange(50): for j in xrange(50): if i == j: print 0, else: print cnt, cnt += 1 print
1636188
import unittest from followthemoney.types import registry numbers = registry.number class NumberTest(unittest.TestCase): def test_cast_num(self): self.assertEqual(numbers.to_number("1,00,000"), 100000.0) self.assertEqual(numbers.to_number(" -999.0"), -999.0) self.assertEqual(numbers.to_n...
1636289
import pytest from pynamodb.pagination import RateLimiter class MockTime(): def __init__(self): self.current_time = 0.0 def sleep(self, amount): self.current_time += amount def time(self): return self.current_time def increment_time(self, amount): self.current_time +...
1636302
import tensorflow as tf def last_relevant_output(output, sequence_length): """ Given the outputs of a LSTM, get the last relevant output that is not padding. We assume that the last 2 dimensions of the input represent (sequence_length, hidden_size). Parameters ---------- output: Tensor ...
1636309
src = Split(''' system_stm32f4xx.c STM32F4xx_StdPeriph_Driver/src/misc.c STM32F4xx_StdPeriph_Driver/src/stm32f4xx_adc.c STM32F4xx_StdPeriph_Driver/src/stm32f4xx_can.c STM32F4xx_StdPeriph_Driver/src/stm32f4xx_crc.c STM32F4xx_StdPeriph_Driver/src/stm32f4xx_dac.c STM...
1636330
from .Grammars import reference_patterns from .dictionary import wordlist_english import logging import re REFERENCE_PREFIX = "REF_" strip_table = str.maketrans("", "", "(){}<>[]") strip_table = str.maketrans("", "", "(){}<>[].,!;?") class separate_reference: """ Detects if a reference number has been mista...
1636358
import riemann import unittest from riemann import tx from riemann import utils from riemann.tests import helpers class TestOutpoint(unittest.TestCase): def setUp(self): pass def test_create_outpoint(self): outpoint_index = helpers.P2PKH1['ser']['ins'][0]['index'] outpoint_tx_id = he...
1636374
import argparse import json import os from collections import defaultdict def get_datasets(args): datasets = [] for _, _, dataset in args.input: if dataset not in datasets: datasets.append(dataset) return datasets def get_metrics(args): metrics = [] for _, metric, _ in args.i...
1636414
from river import stream from . import base class SMTP(base.RemoteDataset): """SMTP dataset from the KDD 1999 cup. The goal is to predict whether or not an SMTP connection is anomalous or not. The dataset only contains 2,211 (0.4%) positive labels. References ---------- [^1]: [SMTP (KDDCUP9...
1636438
import yaml import six script_out = """all: children: ungrouped: hosts: foobar: should_be_artemis_here: !vault | $ANSIBLE_VAULT;1.2;AES256;alan 30386264646430643536336230313232653130643332356531633437363837323430663031356364 383631393564303830626361363...
1636439
import platform import numpy as np import pytest import qtpy from napari.layers import Labels, Points from qtpy.QtCore import QCoreApplication from PartSeg._roi_analysis.image_view import ResultImageView from PartSeg.common_backend.base_settings import BaseSettings from PartSeg.common_gui.channel_control import Chann...
1636476
import torch import torch.nn as nn import torch.nn.functional as F class AGNewsmodelWrapper(nn.Module): def __init__(self, model): super(AGNewsmodelWrapper, self).__init__() self.model = model def compute_bert_outputs( # pylint: disable=no-self-use self, model_bert, embedding_input, ...
1636491
from typing import List, Iterable, Mapping from .common import write_varint, sha256 NIL = bytes([0] * 32) def floor_lg(n: int) -> int: """Return floor(log_2(n)) for a positive integer `n`""" assert n > 0 r = 0 t = 1 while 2 * t <= n: t = 2 * t r = r + 1 return r def ceil_...
1636496
import sys, os sys.path.insert(0, os.path.abspath('.') + '/_extensions') project = 'Project Bureau' copyright = '2019-2020, whitequark' master_doc = 'index' rst_epilog = """ .. |o| raw:: html <i class="fa fa-times" style="display:block;text-align:center;color:darkred;"></i> .. |x| raw:: html <i cla...
1636537
def arrange_number(a, b): if a>b: s=b else: s=a for i in range(1, s+1): if a%i==0 and b%i==0: result=i return result m=int(input()) n=int(input()) print(arrange_number(m,n))
1636576
class AudioNetwork: """Create a generic audio network""" def set_volume(self, volume): raise NotImplemented("Not implemented") def volume(self): raise NotImplemented("Not implemented") def speakers(self): """Return a list of available devices""" raise NotImplemented("Not ...
1636586
import discord import collections import operator import random import asyncio import datetime import uuid from queue import Queue from redbot.core import Config from redbot.core import commands from redbot.core import checks from redbot.core.utils.predicates import ReactionPredicate from redbot.core.utils.menus impor...
1636671
import torch.nn as nn class SubCellFNN(nn.Module): # in 10 states and a binary classification into membrane-bound vs. soluble def __init__(self, use_batch_norm=True): super(SubCellFNN, self).__init__() # Linear layer, taking embedding dimension 1024 to make predictions: if use_batch_no...
1636685
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from kubernetes import client, config from kubernetes.client.rest import ApiException from kubernetes.stream import stream class K8sController(): def __init__(self, kube_config=None): i...
1636690
import mtalg def get_num_threads(): """Get number of threads for MRNGs and algebra functions Args: num_threads: Number of threads """ return mtalg.core.threads._global_num_threads
1636702
import matplotlib.pyplot as plt import matplotlib.animation as animation import pandas as pd import time NUM_NAMESPACES = 1 TOTAL_GOAL_PODS = 10001 GOAL_PODS = TOTAL_GOAL_PODS/NUM_NAMESPACES fig = plt.figure() ax1 = fig.add_subplot(2,1,1) ax2 = fig.add_subplot(2,1,2) time_elapsed_text = ax2.text(0.1, 0.25, '', fonts...
1636735
import os import sys import traceback from zlib import compress, decompress, error as zlib_error from cmemcached_imp import * import cmemcached_imp import threading _FLAG_PICKLE = 1 << 0 _FLAG_INTEGER = 1 << 1 _FLAG_LONG = 1 << 2 _FLAG_BOOL = 1 << 3 _FLAG_COMPRESS = 1 << 4 _FLAG_MARSHAL = 1 << 5 VERSION = "0.41-green...
1636748
import subscription.signals def impossible_downgrade(sender, subscription, **kwargs): before = sender.subscription after = subscription if not after.price: if before.price: return "You cannot downgrade to a free plan." else: return None if before.recurrence_unit: if not...
1636753
import scrapy import logging from scrapy.crawler import CrawlerProcess logging.getLogger('scrapy').propagate = False class Cloner(scrapy.Spider): name = "test" custom_settings ={ 'LOG_ENABLED': False } def parse(self, response): #filename = response.url.split("/")[-1] + '.html' with open...
1636777
import requests import pandas as pd from bs4 import BeautifulSoup import numpy as np import datetime pd.set_option('display.expand_frame_repr', False) import re def get_financial_statements(code): # 인증값 추출 re_enc = re.compile("encparam: '(.*)'", re.IGNORECASE) re_id = re.compile("id: '([a-zA-Z0-9]*)'...
1636782
import torch import os import random from torch.utils.data import Dataset from PIL import Image import numpy as np import sys import json from glob import glob from PIL import ImageDraw from misc.mask_utils import scatterMask from misc.utils import denorm import glob from scipy.io import loadmat from tqdm import tqdm m...
1636789
from __future__ import absolute_import from . import backend from . import datasets from . import layers from . import preprocessing from . import utils from . import wrappers from . import callbacks from . import constraints from . import initializers from . import metrics from . import losses from . import optimizers...
1636816
import random from jinja2 import Environment, PackageLoader env = Environment(loader=PackageLoader('generate_test', '.')) template = env.get_template('template.jinja') def answer(n): s = 0 p = 0 n = str(n) for c in n: if int(c) % 2 == 1: s += 1 if p == 0: ...
1636854
import attr @attr.s(slots=True) class Booking: id: int = attr.ib() name: str = attr.ib() is_active: bool = attr.ib() asdict = attr.asdict
1636863
from photons_app.errors import ApplicationCancelled, ApplicationStopped from photons_app.errors import UserQuit from photons_app import helpers as hp import platform import asyncio import logging import signal import sys log = logging.getLogger("photons_app.tasks.runner") class Runner: def __init__(self, task, ...
1636876
from networkx.algorithms.assortativity import * from networkx.algorithms.asteroidal import * from networkx.algorithms.boundary import * from networkx.algorithms.bridges import * from networkx.algorithms.chains import * from networkx.algorithms.centrality import * from networkx.algorithms.chordal import * from networkx....
1636940
import click import src.cli.console as console from src.cli.context import show_context from src.graphql import GraphQL from src.local.providers.helper import get_cluster_or_exit from src.local.system import Telepresence from src.storage.user import get_local_storage_user @click.command() @click.pass_obj def ps(ctx,...
1636941
from datetime import datetime from django.db.models import Count import olympia.core.logger from olympia.amo.celery import task from olympia.amo.decorators import use_primary_db from .models import Collection, CollectionAddon log = olympia.core.logger.getLogger('z.task') @task @use_primary_db def collection_met...
1636942
from collections import defaultdict class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ # A char -> [list of indice] matrix = defaultdict(bool) result = "" # initialize for i in range(len(s)): ...
1636949
from numba import jit import numpy as np import cv2 random = np.array(np.power(np.random.rand(16, 8, 3), 3) * 255, dtype=np.uint8) class Camera: def _resize_frame(self, frame, dst, flip=0): frame_shape = np.shape(frame) frame_crop_height = int(frame_shape[1] / self._ratio) crop_offset = (...
1636966
from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType # Create your models here. class Feature(models.Model): object_content_type = models.ForeignKey(ContentType, related_name='features', on_delete=models.CASCADE) ...
1636974
import nbformat as nbf from astropy.table import Table #oof = nbf.read('magical_transofrms.ipynb', as_version=4) # gool = '06.01-Initial-reduction.ipynb' gool = 'magical_transofrms.ipynb' def markdown_cells(nb): """ Iterator for markdown cells in notebook. """ for cell in nb['cells']: if cel...
1636980
import os import sys STRICTDOC_ROOT_PATH = os.path.abspath( os.path.join(__file__, "../../../../strictdoc") ) assert os.path.exists(STRICTDOC_ROOT_PATH), "does not exist: {}".format( STRICTDOC_ROOT_PATH ) sys.path.append(STRICTDOC_ROOT_PATH)
1636993
import unittest import unittest.mock from programy.clients.render.html import HtmlRenderer class MockHtmlBotClient(object): def __init__(self): self._response = None self.configuration = unittest.mock.Mock() self.configuration.host = "127.0.0.1" self.configuration.port = "6666" ...
1637002
import sys, cgi import glob import re import keyword, token, tokenize import string, cStringIO, StringIO SIKULI_KEYWORDS = [ "find", "wait", "click", "clickAll", "repeatClickAll", "doubleClick", "doubleClickAll", "repeatDoubleClickAll", "rightClick", "dragDrop", "type", "sleep", "popup", "capture", "input"...
1637011
from enum import Enum from typing import Generator, NamedTuple import pytest from pms import SensorWarning from pms.core import Sensor, Supported @pytest.mark.parametrize("sensor", Supported) @pytest.mark.parametrize("attr", ["Message", "Data", "Commands"]) def test_sensor_attrs(sensor, attr): assert getattr(Se...
1637026
import logging from celery import current_app from django_celery_beat.schedulers import ModelEntry, DatabaseScheduler from nautobot.extras.models import ScheduledJob, ScheduledJobs logger = logging.getLogger(__name__) class NautobotScheduleEntry(ModelEntry): """ Nautobot variant of the django-celery-beat ...
1637035
from setuptools import setup, Extension, find_packages setup(name='gitgud', version='1.1', author='<NAME>', author_email="<EMAIL>", description="Git Gud - a utility for when you are told to 'get good'", url="https://github.com/fsufitch/git-gud", package_dir={'':'src'}, package...
1637048
import os import unittest import yaml from jsonasobj import as_json from biolinkml.meta import SchemaDefinition from biolinkml.utils.rawloader import load_raw_schema from biolinkml.utils.yamlutils import DupCheckYamlLoader, as_yaml from tests.test_utils.environment import env from tests.utils.test_environment import ...
1637080
from pytg import sender from pytg.exceptions import IllegalResponseException import os import logging import yaml import datetime import time logging.basicConfig(level=logging.INFO) # Ugly hack: increate timeout for document reception # Sub hack: use a list to assign a new value tmp_f = list(sender.functions["load_d...
1637084
import torch import torch.nn.functional as F import torch.nn as nn from IPython import embed class CrossE_Loss(nn.Module): def __init__(self, args, model): super(CrossE_Loss, self).__init__() self.args = args self.model = model def forward(self, score, label): pos = torch.log(...
1637106
from product_details import product_details def get_product_details_history(): sections = [ (u'Firefox', 'firefox_history_development_releases'), (u'Firefox', 'firefox_history_major_releases'), (u'Firefox', 'firefox_history_stability_releases'), (u'Firefox for Android', 'mobile_his...
1637107
from dataclasses import dataclass from typing import Tuple, List, Optional, Any import numpy as np import torch from src.huggingmolecules.configuration.configuration_api import PretrainedConfigMixin from src.huggingmolecules.featurization.featurization_api import PretrainedFeaturizerMixin, RecursiveToDeviceMixin from...
1637137
text = """ //------------------------------------------------------------------------------ // Explicit instantiation. //------------------------------------------------------------------------------ #include "Geometry/Dimension.hh" #include "RK/ReproducingKernelMethods.cc" namespace Spheral { template class Reproduci...
1637187
input = """ 1 2 0 0 1 3 0 0 1 4 0 0 1 5 0 0 1 6 0 0 1 7 0 0 1 8 0 0 1 9 0 0 1 10 0 0 1 11 0 0 1 12 0 0 1 13 0 0 1 14 0 0 1 15 0 0 1 16 0 0 1 17 0 0 1 18 0 0 1 19 0 0 1 20 2 1 21 22 1 21 2 1 20 22 1 22 0 0 1 23 2 1 24 25 1 24 2 1 23 25 1 25 0 0 1 26 2 1 27 28 1 27 2 1 26 28 1 28 0 0 1 29 2 1 30 31 1 30 2 1 29 31 1 31 0 ...
1637213
import ast import sys import dace from dace.transformation.transformation import Transformation from dace.transformation.dataflow import MapFission from typing import Any, Dict, Set import warnings from dace import registry, sdfg as sd, symbolic from dace.properties import make_properties from dace.sdfg import nodes, ...
1637214
run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False) call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None) check_output(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)
1637247
import copy import json import multiprocessing import os import random import shutil import string import tempfile from contextlib import contextmanager from os import chdir, getcwd, mkdir from os.path import exists import pkgpanda.build.constants import pkgpanda.build.src_fetchers from pkgpanda import expand_require ...
1637253
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: Trie = lambda : defaultdict(Trie) trie = Trie() END = True for word in dictionary: current = trie for char in word: current = current.setdefault(char, Trie()) ...
1637271
import numpy import theano from nose.plugins.skip import SkipTest from theano.tests.unittest_tools import verify_grad try: from pylearn2.sandbox.cuda_convnet.response_norm import ( CrossMapNorm, CrossMapNormUndo ) from theano.sandbox.cuda import CudaNdarrayType, CudaNdarray from theano....
1637325
from math import ceil, log2 def clog2(x): return int(ceil(log2(x))) def flatten(l): return [item for sublist in l for item in sublist] def has_kratos_runtime(): try: import kratos_runtime return True except ImportError: return False def is_valid_file_mode(file_mode): ...
1637376
from abc import abstractmethod from datetime import datetime from typing import TYPE_CHECKING, Dict, List, Optional, Type, cast import pandas as pd import pyarrow from google.protobuf.json_format import MessageToJson from feast.data_source import DataSource from feast.dqm.profilers.profiler import Profile, Profiler f...
1637394
from .__info__ import __authors__, __version__ from .analysis import DataAnalyzer from .core import MadMiner from .delphes import DelphesReader from .fisherinformation import ( FisherInformation, InformationGeometry, profile_information, project_information, ) from .lhe import LHEReader from .likelihood...
1637412
from django.db.models.sql.where import ( WhereNode, EverythingNode ) class CQLWhereNode(WhereNode): def as_cql( self, qn, connection ): return self.as_sql( qn, connection ) class CQLEverythingNode(EverythingNode): pass
1637420
from binding import * from ..namespace import llvm from src.Pass import ImmutablePass TargetLibraryInfo = llvm.Class(ImmutablePass) LibFunc = llvm.Namespace('LibFunc') LibFunc.Enum('Func', ''' ZdaPv, ZdlPv, Znaj, ZnajRKSt9nothrow_t, Znam, ZnamRKSt9nothrow_t, Znwj, ZnwjRKSt9nothrow_t,...
1637470
import emacspy, socket, tempfile, queue, threading from emacspy import sym from typing import Optional import concurrent.futures, traceback _call_soon_queue: queue.Queue = queue.Queue(0) _wakeup_conn: Optional[socket.socket] = None _emacs_thread = threading.current_thread() def call_soon_in_main_thread(f): _call...
1637481
import os class Card: suits = ["clubs", "diamonds", "hearts", "spades"] def __init__(self, suit: str, value: int, down=False): self.suit = suit self.value = value self.down = down self.symbol = self.name[0].upper() @property def name(self) -> str: """The name o...
1637485
from typing import NamedTuple import pandas as pd from pandas import DataFrame from dbnd import task @task(result=("features", "scores")) def f_returns_two_dataframes_v1(p: int) -> (DataFrame, DataFrame): return ( pd.DataFrame(data=[[p, 1]], columns=["c1", "c2"]), pd.DataFrame(data=[[p, 1]], co...
1637508
from chainerrl_visualizer.utils.string_generators import generate_timestamp, generate_random_string # NOQA from chainerrl_visualizer.utils.jsonize_datetime import jsonize_datetime # NOQA
1637540
import astropy.units as u import exifread import matplotlib import numpy as np import scipy.ndimage as ndimage from skimage.transform import hough_circle, hough_circle_peaks from sunpy.map import GenericMap import eclipse.meta as m __all__ = ['find_sun_center_and_radius', 'eclipse_image_to_map'] def find_sun_center...
1637543
import sys, boto3, json from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job from pyspark.sql.functions import * def load_state_information(): """ reads state information ...
1637555
from plex.objects.core.base import Descriptor, Property class Director(Descriptor): id = Property(type=int) tag = Property @classmethod def from_node(cls, client, node): return cls.construct(client, cls.helpers.find(node, 'Director'), child=True)
1637560
import torch import Corr2D_ext def int_2_tensor(intList): return torch.tensor(intList, dtype=torch.int, requires_grad=False) def tensor_2_int(t): assert len(t.size()) == 1 assert t.size()[0] == 5 assert t.dtype == torch.int return t.tolist() class Corr2DF(torch.autograd.Function): @staticme...
1637576
import typing from anchorpy.error import ProgramError class TileOutOfBounds(ProgramError): def __init__(self) -> None: super().__init__(6000, None) code = 6000 name = "TileOutOfBounds" msg = None class TileAlreadySet(ProgramError): def __init__(self) -> None: super().__init__(60...
1637580
import zipfile from matplotlib.ticker import FormatStrFormatter import matplotlib.ticker as tick import pandas as pd import numpy as np import matplotlib.pyplot as plt import os import logging import matplotlib.pyplot as plt from matplotlib.ticker import LinearLocator,MaxNLocator from matplotlib.offsetbox import TextAr...
1637609
from yowsup.layers.protocol_contacts.protocolentities import AddContactNotificationProtocolEntity from yowsup.structs.protocolentity import ProtocolEntityTest import time import unittest entity = AddContactNotificationProtocolEntity("1234", "<EMAIL>", int(time.time()), "notify", False, ...
1637621
from .metropolis import Metropolis from .hamiltonian import Hamiltonian from .NUTS import NUTS from .chain import Chain from .slice import Slice from .base import Sampler
1637634
import sys sys.path.append('../') import constants as cnst import os import torch import tqdm import numpy as np import constants SHAPE = [0, 1, 2] EXP = [50, 51, 52] POSE = [150, 151, 152, 153, 154, 155] def centre_using_nearest(flame_seq, flame_dataset, one_translation_for_whole_seq=True): shape_weigth = 0 ...
1637644
import numpy as np from sklearn.metrics import mean_squared_error, accuracy_score class BaseModel(object): """ Base model to run the test """ def __init__(self): self.max_depth = 6 self.learning_rate = 1 self.min_split_loss = 1 self.min_weight = 1 self.L1_r...
1637649
import asyncio import gevent.selectors __all__ = ["EventLoop"] class EventLoop(asyncio.SelectorEventLoop): """ An asyncio event loop that uses gevent for scheduling and runs in a spawned greenlet """ def __init__(self, selector=None): super().__init__(selector or gevent.selectors.Defaul...
1637675
import time import analysis.event import analysis.beamline import analysis.background import analysis.pixel_detector import ipc import random import numpy numpy.random.seed() state = { 'Facility': 'dummy', 'squareImage' : True, 'Dummy': { 'Repetition Rate' : 10, 'Data Sources': { ...
1637719
from django.db import transaction from denorm.db import base import logging logger = logging.getLogger('denorm-sqlite') class RandomBigInt(base.RandomBigInt): def sql(self): return 'RANDOM()' class TriggerNestedSelect(base.TriggerNestedSelect): def sql(self): columns = self.columns ...
1637721
import numpy as np from sklearn.linear_model import LogisticRegression from .base import TransformationBaseModel class Kane(TransformationBaseModel): """The class which implements the Kane's approach. +----------------+-----------------------------------------------------------------------------------+ ...
1637831
from pathlib import Path from numpy import array from manim import * class DottedLine(Line): """A dotted :class:`Line`. Parameters ---------- args : Any Arguments to be passed to :class:`Line` dot_spacing : Optional[:class:`float`] Minimal spacing of the dots. The spacing is scale...
1637832
from tensor2struct.models import decoder, batched_decoder from tensor2struct.utils import registry, vocab class CogsPreproc(decoder.DecoderPreproc): def add_item(self, item, section, validation_info): actions = item.code.split() if section == "train": for action in actions: ...
1637852
import torch import torch.nn as nn from torch.nn import init import functools from torch.optim import lr_scheduler from collections import OrderedDict import torch.nn.functional as F def get_scheduler(optimizer, opt): if opt.lr_policy == 'lambda': def lambda_rule(epoch): lr_l = 1.0 - max(0, epo...
1637878
import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import os import sys import tensorflow as tf import jpegio as jio from tensorflow.python.framework import ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import st...
1637923
from collections import defaultdict from stoichiograph import speller from stoichiograph.speller import Node ELEMENTS = { 'H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As...
1637936
import os, sys # sys.path.append('/home/shaunxliu/projects/nnsp') import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator import torch from torch.utils.data import DataLoader import numpy as np from src.solver import BaseSolver from src.data_load import OneshotV...
1637937
from .token import Token from typing import List from typing import Dict from typing import Set from typing import Union from typing import Generator from .span import Span from .utils import normalize_slice class TextDoc: def __init__(self): # This list is populated in the __call__ method of the Tokeni...
1637969
import enum from uuid import UUID from pydantic import BaseModel class ProfileShort(BaseModel): id: UUID username: str class FriendshipRequest(BaseModel): profile_id: UUID target_profile_id: UUID class Relationship(str, enum.Enum): FRIEND = "FRIEND" OUTGOING_FRIEND_REQUEST = "OUTGOING_FRI...
1637977
from openie import StanfordOpenIE import spacy import neuralcoref from difflib import SequenceMatcher import nltk from nltk.corpus import stopwords import argparse import random parser = argparse.ArgumentParser() parser.add_argument('--file', type=str) parser.add_argument('--outfile', type=str) parser.add_argument('--...
1637987
import os file_chars_reference = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def create_letters_text_files(): try: # Obtenemos la ruta absoluta del directorio en el que estamos trabajando script_directory = os.path.dirname(__file__) for letter in file_chars_reference: file_path = f"{script_d...
1637989
import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 def test_module(client, url): result = client._http_request('GET', full_url=url) if isinstance(result, list): return 'ok' else: return 'Test failed: ' + str(result) def find_type_and_value(indicato...
1638020
import numpy as np import torch from sklearn.preprocessing import normalize from torch_geometric.datasets import Planetoid def get_dataset(dataset): datasets = Planetoid('./dataset', dataset) return datasets def data_preprocessing(dataset): dataset.adj = torch.sparse_coo_tensor( dataset.edge_ind...
1638079
def main(): import os import sys import sysconfig import site try: import vapoursynth except ImportError as e: print("It seems you have not installed VapourSynth yet.") exit(e) from .install import install def print_help(): print( ...
1638131
from collections import deque class Node: """A Node which maps a node proto. It has pointers to its parents and children. """ def __init__(self, onnx_node): """Initialize a node. This initialization only set up the mapping to node proto. The pointers should be set up by outside. ...
1638133
from pathlib import Path import ujson class BotGeneratorPreset: def __init__(self, database_dir: Path, bot_role: str): bots_dir = database_dir.joinpath("bots", bot_role) self.generation: dict = ujson.load( bots_dir.joinpath("generation.json").open(encoding="utf8") ) s...
1638158
import sys import json import subprocess def runner(language, commands, is_test): print("\nRunning {language} formatter{mode}...\n".format( language = language, mode = " in test mode" if is_test else "" )) process = subprocess.run(commands) if process.returncode != 0: exit(process.returncode) arg...
1638164
from typing import Tuple, Dict, List import numpy as np from graph_nets.graphs import GraphsTuple from .tf_tools import graphs_tuple_to_data_dicts, data_dicts_to_graphs_tuple MIN_STD = 1E-6 class Standardizer: @staticmethod def compute_mean_std(a: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: retur...
1638205
from pkgconf import Conf class ControlCenter(Conf): DASHBOARDS = [] CHARTIST_COLORS = 'default' SHARP = '#'
1638211
import os import sys import glob import gzip import bs4, lxml import concurrent.futures import re from pathlib import Path import json import random import CONFIG def pmap(arg): key, names = arg random.shuffle(names) for name in names: try: sha256 = name.split('/')[-1] if Pa...
1638226
from django.shortcuts import render, get_object_or_404, redirect, reverse from django.http import HttpResponse, HttpResponseBadRequest, StreamingHttpResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.debug import sensitive_post_parameters from django.contrib.auth.decorators impor...
1638257
import numpy as np from .base import Prior, PriorException from .interpolated import Interped from .analytical import DeltaFunction, PowerLaw, Uniform, LogUniform, \ SymmetricLogUniform, Cosine, Sine, Gaussian, TruncatedGaussian, HalfGaussian, \ LogNormal, Exponential, StudentT, Beta, Logistic, Cauchy, Gamma, ...
1638274
import numpy as np import torch as th from torchvision import transforms from .data_utils import is_tuple_or_list class BaseDataset: """An abstract class representing a Dataset. All other datasets should subclass it. All subclasses should override ``__len__``, that provides the size of the dataset, and `...