id
stringlengths
3
8
content
stringlengths
100
981k
4814431
import gensim.models as g import logging import os #parameters output_dir="word2vec" input_doc="data/toy-train.txt" #main if not os.path.exists(output_dir): os.makedirs(output_dir) #logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) docs = g.word2vec.LineSentence...
4814470
from PyObjCTools.TestSupport import * from CoreFoundation import * try: unicode except NameError: unicode = str try: long except NameError: long = int class TestNumberFormatter (TestCase): def testTypes(self): self.assertIsCFType(CFNumberFormatterRef) def testTypeID(self): ...
4814509
import numpy as np import torch import tqdm from smp_manifold_learning.differentiable_models.autoencoder import AutoEncoder from smp_manifold_learning.dataset_loader.ae_dataset_loader import AutoEncoderGeneralizationDatasetLoader from smp_manifold_learning.differentiable_models.utils import move_optimizer_to_gpu, get_...
4814545
from datetime import date # Create simple factory method using class method class Person: def __init__(self, name, age): self._name = name self._age = age @classmethod def from_birth_year(cls, name, birth_year): print('cls:', cls) return cls(name, date.today().year - birth...
4814565
from kekbdatabase import * def pr(x):print x def printor(x): a=kekbdb(x) print("****description****") map(pr,a.description) print("****data****") map(pr,a) print("****end****")
4814566
import socket from unittest.mock import patch, PropertyMock import feedparser from django.core.management import call_command from django.utils import timezone from feedhq import es from feedhq.feeds.models import Favicon, Feed, UniqueFeed from feedhq.feeds.tasks import update_feed from feedhq.feeds.utils import epoch...
4814573
from sqlalchemy.dialects.postgresql import insert from flask_simple_api import error_abort from ...models import Label, Session, Test, db, session_label from .blueprint import API NoneType = type(None) @API def add_label(label: str, session_id: int): session = Session.query.get_or_404(session_id) db.sessio...
4814579
from ConfigParser import ConfigParser import glob import os # thanks, OEDA! https://github.com/openeventdata/scraper/blob/master/scraper.py def _parse_config(parser): try: if 'Auth' in parser.sections(): auth_db = parser.get('Auth', 'auth_db') auth_user = parser.get('Auth', 'auth_u...
4814636
from itertools import combinations, chain from functools import partial from bisect import bisect_left import multiprocessing import numpy as np from scipy.sparse import lil_matrix from pydigree.ibs import get_ibs_states from pydigree.cydigree.cyfuncs import set_intervals_to_value, runs_gte_uint8 from pydigree.io imp...
4814637
from django.test import TestCase from py2swagger.utils import OrderedDict from py2swagger.plugins.drf.introspectors.serializer import SerializerIntrospector, FieldIntrospector from testapp.serializers import TestModelSeriazlizer class SerializerIntrospectorTestCase(TestCase): def setUp(self): self.seri...
4814641
import torch.utils.data as data import numpy as np import os, sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) import data_transforms from .io import IO import json from .build import DATASETS # References: # - https://github.com/hzxie/GRNet/blob/master/utils/data_loaders.py @DATASET...
4814668
class Empty: pass # Handshake pattern tokens TOKEN_E = 'e' TOKEN_S = 's' TOKEN_EE = 'ee' TOKEN_ES = 'es' TOKEN_SE = 'se' TOKEN_SS = 'ss' TOKEN_PSK = 'psk' # In bytes, as in Section 8 of specification (rev 32) MAX_PROTOCOL_NAME_LEN = 255 MAX_MESSAGE_LEN = 65535 MAX_NONCE = 2 ** 64 - 1
4814672
import urllib.request from bs4 import BeautifulSoup req = urllib.request.urlopen('http://quality-start.in/company/') soup = BeautifulSoup(req,"html.parser") contact = soup.find('a',class_='btn') print(contact.string)
4814678
import torch import torch.nn as nn class GRUGate(nn.Module): def __init__(self, d_input, bg=0.1): super(GRUGate, self).__init__() self.Wr = nn.Conv2d(d_input, d_input, kernel_size = 1, bias=False, stride=1) self.Ur = nn.Conv2d(d_input, d_input, kernel_size = 1, bias=False, stride=1) ...
4814710
import FWCore.ParameterSet.Config as cms idealMagneticFieldRecordSource = cms.ESSource("EmptyESSource", recordName = cms.string('IdealMagneticFieldRecord'), iovIsRunNotTime = cms.bool(True), firstValid = cms.vuint32(1) ) ParametrizedMagneticFieldProducer = cms.ESProducer("ParametrizedMagneticFieldProducer...
4814734
try: import sl1m.planner as sl1m except ImportError: message = "ERROR: Cannot import SL1M python library.\n" message += "Did you correctly installed it?\n" message +="See https://gepgitlab.laas.fr/loco-3d/sl1m" raise ImportError(message) from pinocchio.utils import * import importlib import multicon...
4814777
alien_color = 'red' if alien_color == 'green': print("Has ganado 5 ptos!") elif alien_color == 'yellow': print("Has ganado 10 ptos!") elif alien_color == 'red': print("Has ganado 15 ptos!") print("/////////////////////////////") alien_color = 'yellow' if alien_color == 'green': print("Has ganado 5 p...
4814824
import json import pytest import time from delphi.apps.rest_api import create_app, db from delphi.apps.rest_api.models import DelphiModel, CauseMosAsyncExperimentResult, ExperimentResult @pytest.fixture(scope="module") def app(): app = create_app(debug=True) app.testing = True app.config["SQLALCHEMY_TRA...
4814833
import logging from typing import Dict, List from django.conf import settings from apps.authentication.models import OnlineUser as User from apps.gsuite.mail_syncer.utils import ( get_excess_groups_for_user, get_excess_users_in_g_suite, get_g_suite_users_for_group, get_missing_g_suite_group_names_for_...
4814880
import time import shutil # from manimlib.scene.scene_file_writer import SceneFileWriter from manimlib import Scene, Point, Camera, ShowCreation, Write, Color, VGroup, VMobject from manimlib.utils.rate_functions import linear, smooth from manimlib.extract_scene import get_scene_config import manimlib.config from maniml...
4814945
from modules import * device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class AttModel(nn.Module): def __init__(self, hp_, enc_voc, dec_voc): """Attention is all you need. https://arxiv.org/abs/1706.03762 Args: hp: Hyper Parameters enc_voc: vocabular...
4814959
from unittest import TestCase import numpy from moderngl_window.opengl.projection import Projection3D class Projection3DTestCase(TestCase): def test_default(self): """Test default values""" proj = Projection3D() self.assertAlmostEqual(proj.aspect_ratio, 16 / 9) self.assertEqual(pr...
4814973
import image, lcd, time import audio from Maix import GPIO, I2S from fpioa_manager import fm # user setting sample_rate = 16000 record_time = 4 #s # default seting sample_points = 2048 wav_ch = 2 fm.register(8, fm.fpioa.GPIO0, force=True) wifi_en = GPIO(GPIO.GPIO0, GPIO.OUT) wifi_en.value(0...
4815004
from mizarlabs.transformers.technical.mean_reversion import MeanReversionStrategy def test_predict(dollar_bar_dataframe): threshold = 0.001 short_time_period = 5 mean_reversion_strategy = MeanReversionStrategy( threshold=threshold, short_time_period=short_time_period ) preds = mean_reversi...
4815011
from collections import defaultdict from types import SimpleNamespace from typing import Union import torch import numpy as np import warnings from msdm.core.problemclasses.mdp import \ TabularMarkovDecisionProcess, TabularPolicy from msdm.core.algorithmclasses import Plans, PlanningResult def clamp_zero(tensor): ...
4815019
import datetime from imap_tools import EmailAddress DATA = dict( subject='Impress your clients with a business phone��� ', from_='<EMAIL>', to=('<EMAIL>',), cc=(), bcc=(), reply_to=('44.41.17.14.11.2010.1139.1.328.1477949.614@reply.<EMAIL>',), date=datetime.datetime(2010, 11, 14, 17, 41, 44...
4815023
import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from fastapi_event import EventHandlerMiddleware @pytest.fixture def app(): yield FastAPI() @pytest.fixture def app_with_middleware(app): app: FastAPI app.add_middleware(EventHandlerMiddleware) yield app @pytest.f...
4815029
import sys import weakref from _pydev_imps._pydev_saved_modules import thread from _pydevd_bundle.pydevd_constants import STATE_RUN, PYTHON_SUSPEND, dict_iter_items from _pydevd_bundle.pydevd_frame import PyDBFrame #======================================================================================================...
4815047
from six import text_type class OrderKeyMissing(ValueError): """ Missing an order key! """ class InvalidMerchant(ValueError): """ Provided order belongs to a different merchant! """ class DocdataException(Exception): """ Base class for all exceptions from Docdata """ def __...
4815089
import math import yaml import logging import os import inspect import torch import pickle def save(lst, path): with open(path, 'wb') as fp: pickle.dump(lst, fp) def save_checkpoint(state, filename='checkpoint.pth.tar'): torch.save(state, filename) def config_log(log_dir, fname): logger = logg...
4815134
from collections import defaultdict class Solution: def lengthOfLongestSubstring(self, s): d = defaultdict() max_len = 0 cur = '' for i in range(len(s)): if s[i] in d: max_len = max(max_len, len(cur)) c = 0 while cur[c] !=...
4815144
import tkinter from PIL import Image from PIL import ImageTk t=tkinter.Tk() def png(filename): im = Image.open('images/%s.png' % filename) im = ImageTk.PhotoImage(im) return im im = png('jarate') l = tkinter.Label(t, text="heyo", image=im) l.im = im l.pack() t.mainloop()
4815186
import numpy as np import tensorflow as tf import pandas as pd import seaborn as sns import matplotlib.pyplot as plt num_puntos = 2000 conjunto_puntos = [] for i in range(num_puntos): if np.random.random() > 0.5: x, y = np.random.normal(0.0, 0.9), np.random.normal(0.0, 0.9) conjunto_puntos.append([x...
4815198
import numpy as np import geopandas as gpd import pandas as pd from shapely.geometry import Point, Polygon, LineString, MultiPolygon def geometry_to_2d(geometry): return np.array(list(map(lambda x : (x.x, x.y), geometry))) def convert_geoseries(XYs): if isinstance(XYs, gpd.GeoDataFrame): XYs = XYs.geo...
4815203
from typing import Hashable import pandas_flavor as pf import pandas as pd from janitor.utils import deprecated_alias @pf.register_dataframe_method @deprecated_alias(column="column_name") def to_datetime( df: pd.DataFrame, column_name: Hashable, **kwargs ) -> pd.DataFrame: """ Method-chainable `pd.to_dat...
4815400
def coding_problem_21(times): """ Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required. Example: >>> coding_problem_21([(30, 75), (0, 50), (60, 150)]) 2 """ start_times = [(t[0], 1) for t in times] # [(30...
4815530
from ..operations import Operation from ..visitors import OperationVisitor class OperationTransformer(OperationVisitor): def generic_visit(self, operation: Operation) -> Operation: for name, value in operation.__dict__.items(): if isinstance(value, Operation): new_value = self....
4815634
from cdxj_indexer.main import CDXJIndexer, iter_file_or_dir from cdxj_indexer.postquery import append_method_query_from_req_resp from cdxj_indexer.bufferiter import buffering_record_iter
4815671
import torch import sys import numpy as np def encode_features(graphs, degree_encoding=None, id_encoding=None, **kwargs): ''' Encodes categorical variables such as structural identifiers and degree features. ''' encoding_kwargs = {} if hasattr(graphs[0], 'identifiers'): encoder_ids, d_...
4815682
import FWCore.ParameterSet.Config as cms process = cms.Process("SKIM") process.configurationMetadata = cms.untracked.PSet( version = cms.untracked.string('$Revision: 1.7 $'), name = cms.untracked.string('$Source: /cvs/CMSSW/CMSSW/DPGAnalysis/Skims/python/MuPDSkim_cfg.py,v $'), annotation = cms.untracked.s...
4815691
import os import subprocess def test_env_is_protected_against_malicious_recipes(tmpdir, caplog, env_setup): from conda_forge_tick.xonsh_utils import indir import logging from conda_forge_tick.feedstock_parser import populate_feedstock_attributes malicious_recipe = """\ {% set version = "0" %} ...
4815721
from ckan_cloud_operator import datapushers from ckan_cloud_operator.routers.routes.backend_url_subdomain import ( get_frontend_hostname, get_domain_parts, get_default_root_domain, get_route, _init_route ) def get_backend_url(route): name, spec = _init_route(route) datapusher_name = spec...
4815722
from enum import Enum class Goal(Enum): DARK_GAIA = 0 RED_JEWEL_HUNT = 1 APO_GAIA = 2 RANDOM_GAIA = 3
4815775
import types def isclass(obj): """ Helper. Identical to Python 2.7 's inspect.isclass. isclass in Python 2.6 also returns True when the passed object has a __bases__ attribute. (like in case of an instance.) """ return isinstance(obj, (type, types.ClassType)) from .network import * fr...
4815792
import django from django.contrib import admin from django.contrib.admin.utils import unquote from django.db.models import TextField from django.forms import ModelForm, ChoiceField, CharField, BooleanField from django.forms.widgets import Input from django.template.defaultfilters import truncatechars from django.utils....
4815835
from django.test import TestCase, override_settings from .. import get_setting class SettingsTest(TestCase): def test_get_settings_default(self): self.assertEqual(get_setting("AUTH_METHOD"), "JWT") self.assertEqual(get_setting("TIMESTAMP_TOLERANCE"), 20) @override_settings(ASYMMETRIC_JWT_AUTH...
4815839
from pybbn.graph.dag import Bbn from pybbn.graph.edge import Edge, EdgeType from pybbn.graph.jointree import EvidenceBuilder from pybbn.graph.node import BbnNode from pybbn.graph.variable import Variable from pybbn.pptc.inferencecontroller import InferenceController # create the nodes a = BbnNode(Variable(0, 'a', ['on...
4815851
import json from six import text_type as str from . import DictSource class JSONFile(DictSource): def __init__(self, jsonfilename=None, writable=True, **kwargs): """Loads and optionally saves configuration files in JSON format. Since JSON has some support for typed values (supports numbe...
4815858
import sys import os def readroi(f): with open(f) as of: s = of.read().split("\n")[1] p = s.rfind(",") p = s.rfind(",", 0, p-1) return s[:p].replace(",", " ") def listFile(dr, filter): fs = os.listdir(dr) for i in range(len(fs)-1, -1, -1): if not fs[i].lower().ends...
4815880
from .lenet300 import LeNet300, lenet300_classic, lenet300_classic_drop, lenet300_modern, lenet300_modern_drop from .lenet5 import LeNet5, lenet5_classic, lenet5_drop from .nincif import nincif_bn from .resnetcif import resnetcif20, resnetcif32, resnetcif44, resnetcif56, resnetcif110 from .vggcif import vggcif9_bn, vgg...
4815885
from unittest import TestCase import ddt from pysubparser.classes.exceptions import InvalidSubtitleTypeError, InvalidTimestampError from pysubparser import parser PATH = "./tests/files/{test_type}/test.{subtitle_type}" @ddt.ddt class ParserTester(TestCase): def _assert_subtitle(self, sub, index, text, start, ...
4815892
import unittest import random as pyrandom import numpy as np from numpy import random as numpyrandom from rlscore.learner.kron_svm import KronSVM from rlscore.utilities import sampled_kronecker_products def dual_svm_objective(a, K1, K2, Y, rowind, colind, lamb): #dual form of the objective function for support ...
4815906
import base64 import binascii import hashlib import os import time from dataclasses import dataclass import jwt def generate_token(*, size: int = 20) -> str: return binascii.hexlify(os.urandom(size)).decode() class AuthenticationError(Exception): pass class TokenValidationError(Exception): pass cla...
4815911
from django.contrib import admin from authtools.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin)
4815928
from buildtest.cli.debugreport import print_debug_report from buildtest.config import SiteConfiguration from buildtest.system import BuildTestSystem def test_debug_report(): system = BuildTestSystem() config = SiteConfiguration() print_debug_report(system, config)
4815942
from marshmallow import Schema, fields, pre_dump from zeus.models import Build, Job, Repository, TestCase, TestCaseMeta from zeus.api.schemas import BuildSchema from .base_repository import BaseRepositoryResource class TestCaseMetaSchema(Schema): name = fields.Str(required=True) hash = fields.Str(dump_only=...
4815953
def find_missing_number(lst): actual = sum(lst) # O(1) space and O(n) complexity expected = len(lst) * (len(lst) + 1) / 2 # sum equation return expected - actual if __name__ == '__main__': numbers = [0, 7, 8, 3, 5, 6, 1, 9, 4] # missing the number 2 print("The number {} is...
4815971
import datetime from .. import BaseResponder class C3(BaseResponder): """Defines functions related to Chaos Communication Congress.""" FIRST_CONGRESS_YEAR = 1984 CONGRESS_MONTH = 12 CONGRESS_DAY = 27 def command_c3(self, msg): """Displays the number of days remaining to the next congress...
4815984
import os from collections import OrderedDict import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from keras.layers import Layer, Input, Dense, Activation, Conv2D, GlobalAveragePooling2D from keras.models import Model from keras.datasets import cifar10 from keras import backend...
4816035
import maya.cmds as cmds cmds.file(f=True, new=True) def setup(): joints = [] vals = [0, 4, 2] for i in range(3): jnt = cmds.joint() cmds.xform(jnt, t=[vals[i],0,0]) joints.append(jnt) loc1 = cmds.spaceLocator(n="target")[0] loc2 = cmds.spaceLocator(n="pole")[0] cmds.xform(l...
4816070
from modules import skeleton from lib.core import utils from lib.mode import speed from lib.sender import execute from lib.sender import polling from lib.sender import report from lib.sender import summary class LinkFinding(skeleton.Skeleton): """docstring for LinkFinding""" def banner(self): utils.p...
4816071
import numpy import math from geometry_msgs.msg import Point import sys class ObstacleAviod: def __init__(self): self.indexOfObstInSp = [] self.obstInUAVCoorSys = [] self.obstlist = numpy.loadtxt('obstacle.txt') self.flag = True self.useOriginalCurPos = False self.su...
4816098
from django import template register = template.Library() def _review_score_number(context, score): if score is None: return "×" score = round(score, 1) if not context: return str(score) if isinstance(score, int) or (int(score) == score): score = int(score) return str(sco...
4816103
import numpy as np np.seterr(all='raise') import tensorflow as tf import pandas as pd class Episode: def __init__(self, observation, observation_enc, goal, reward): self.length = 1 self.observations = [observation] self.observations_enc = [observation_enc] self.rewards = [reward]...
4816128
from collections import defaultdict from functools import wraps from lru import LRU import math BoundCache = defaultdict(lambda: LRU(3000)) class Color: ZERO = (0, 0, 0, 0) WHITE = (0, 0, 1, 3500) EMPTIES = (ZERO, None) @classmethod def dead(kls, color): return color in kls.EMPTIES or c...
4816145
import math import numpy as np import torch.nn.functional as F import torch, sys from torch import nn import pystrum.pynd.ndutils as nd def sliding_predict(model, image, tile_size, n_dims, overlap=1/2, flip=False): image_size = image.shape stride_x = math.ceil(tile_size[0] * (1 - overlap)) stride...
4816212
import sqlite3 from aselite import Atoms from aselite import FixAtoms from aselite import write_vasp import local_update import numpy import sys import copy class LocalDB(): def __init__(self, db_name, nf=None, dc=None, mac=None): self.db_name = db_name self.nf = nf self.dc = dc sel...
4816216
import vtk def resize_poly_data(data, resize): " resize the poly data" pDecimate = vtk.vtkDecimatePro() pDecimate.SetInputData(data) pDecimate.SetTargetReduction(1-resize) pDecimate.PreserveTopologyOff() pDecimate.SplittingOn() pDecimate.BoundaryVertexDeletionOn() pDecimate.SetMaximumEr...
4816219
from lightCore import get_save import os.path import pickle from Classes import * Location = "" Turn = 0 TurnString = "" Places = {} Quests = {} CurQuests = [] Variables = {} def save(): f = open('Saves/World.save', 'w') pickle.dump(globals(), f) def load(): if os.path.isfile('Saves/World.save'): ...
4816220
import numpy as np INIT_POS = (2, 0) GOAL_POS_L = [(0, 8)] GRID_SHAPE = (6, 9) KEY_ACTION_DICT = { 'z': (-1, 0), 'q': (0, -1), 'd': (0, 1), 's': (1, 0), } AGENT_KEY = 'A' GOAL_KEY = 'G' INIT_KEY = 'S' WALL_KEY = 'W' WALLS = [(1, 2), (2, 2), (3, 2), (4, 5), (0, 7), (1, 7), (2, 7)] class Position: def __init_...
4816226
import torch as th import torch.nn as nn import torch.nn.functional as F import numpy as np class QMixer(nn.Module): def __init__(self, args): super(QMixer, self).__init__() self.args = args self.n_agents = args.n_agents self.state_dim = int(np.prod(args.state_shape)) se...
4816277
from operator import * from drython.macro import * from drython.core import * from drython.statement import * from drython.s_expression import S expensive_get_number = lambda: do(Print("spam"),14) # triple_1 = S(L1, S.n, # +S(sum,S(entuple,~S.n,~S.n,~S.n)), # ) # # triple_1 = S(fn, [S.n],[],...
4816279
opts = { 'main_folder': { 'custmor_config': 'custmor_config', 'readme_files': 'readme_files', 'application_manage': 'application_manage', 'data_volumn': 'data_volumn', 'backup_master': 'backup_master', 'special_api_script': 'spe...
4816284
from unittest import TestCase from cadence.decisions import DecisionTarget, DecisionId class TestDecisionId(TestCase): def setUp(self) -> None: pass def test_str(self): decision_id = DecisionId(DecisionTarget.ACTIVITY, 123) s = str(decision_id) self.assertIn(str(DecisionTarge...
4816317
import requests class Api: # Constructor def __init__(self, **kwargs): self.__base_api_path = kwargs.get("base_api_path","https://pipl.ir/v1/") self.__headers = kwargs.get("headers", {}) # Getters def get_base_api_path(self) -> str: return self.__base_api_path def get_header...
4816412
from functools import lru_cache @lru_cache() def rfa(*rfa_names): """ award.rfa auditor condition factory """ def rfa_condition(value, system): context = system['context'] award_uuid = context.upgrade_properties()['award'] rfa = _award_rfa(award_uuid, system['root']) return...
4816445
from sphinx.application import Sphinx def build_file(): """ Builds the Sphinx docs for a hardcoded rst directory. TODO: get this working. """ srcdir = "/Users/audreyr/code/pydream-repos/rstpreviewer/testfiles/rst/" confdir = "/Users/audreyr/code/pydream-repos/rstpreviewer/testfiles/" outdir = "/Users/audrey...
4816460
import abc import more_itertools as itertools import re from . import types from .types import Union, Optional, Literal, List, set_context from . import checker import logging logger = logging.getLogger(__name__) pattern = re.compile(r'(?<!^)(?=[A-Z])') def get_instances_from_hacked_dataclasses(constraint): ass...
4816473
import torch.nn as nn from .modules import Flatten, Activation, OCR class SegmentationHead(nn.Sequential): def __init__(self, in_channels, out_channels, kernel_size=3, activation=None, upsampling=1, align_corners=True): conv2d = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=kernel...
4816476
class InstanceDefinitionArchiveFileStatus(Enum,IComparable,IFormattable,IConvertible): """ The archive file of a linked instance definition can have the following possible states. Use InstanceObject.ArchiveFileStatus to query a instance definition's archive file status. enum InstanceDefinitionArchiv...
4816483
from django.core.urlresolvers import reverse def test_survey_salary_recording(webtest_client, factories, models): survey = factories.SurveyFactory(num_collected=3, _tracker=str(5 * 7 * 13)) seed = survey.total token = factories.TokenFactory( prime_identifier=17, survey_id=survey.uuid, ...
4816545
import collections import logging from typing import Dict, List import torch from mmf.common.registry import registry from mmf.common.sample import SampleList logger = logging.getLogger(__name__) class LightningTorchMetrics: """ A class used in LightningTrainer to compute torchmetrics --- An example...
4816553
import pyarrow as pa import pytest def test_slice(client): data = client.execute('{ length slice(length: 3) { columns { zipcode { values } } } }') assert data == {'length': 41700, 'slice': {'columns': {'zipcode': {'values': [501, 544, 601]}}}} data = client.execute('{ slice(offset: 1) { columns { zipcode ...
4816564
from abc import ABCMeta, abstractmethod class BoardRenderer(metaclass=ABCMeta): @abstractmethod def render(self, board): """ 棋盘渲染。 The board rendering. :param board: 棋盘。 The board. """
4816572
from samplics.weighting.adjustment import SampleWeight from samplics.weighting.replicates import ReplicateWeight __all__ = ["SampleWeight", "ReplicateWeight"]
4816593
from soundEnvelope import SoundEnvelope, Envelope import time def test1(): print "test1()" for i in range(0,2): e3=Envelope(2,1,-1,0,4,4,0,20,-1,0,-1,126,110) se.play([[24,200,e3]]) time.sleep(1) e3=Envelope(4,48,-48,0,1,1,0,127,0,0,-127,127,8) se.play([[0,25,e3],[2,25...
4816610
class Mediator(object): @classmethod def createColleagues(cls): raise NotImplementedError @classmethod def colleagueChanged(cls): raise NotImplementedError
4816612
import torch from transformers import Adafactor class FixedAdafactor(Adafactor): ''' Subclassed to use original `_approx_sq_grad` code. I found the old method broke when given a greator than 2-dim `exp_avg_sq_row`. ''' @staticmethod def _approx_sq_grad(exp_avg_sq_row, exp_avg_sq_col):...
4816639
Too big to paste here. Get it from here: http://code.google.com/p/pycopia/source/browse/trunk/core/pycopia/ipv4.py
4816712
from hyperopt import fmin, tpe, hp, space_eval, Trials from updated_pr import objective # define an objective function # def objective(args): # case, val = args # if case == 'case 1': # return val # else: # return val ** 2 #LR, MS, BS, WE # define a search space target = open('log2.txt','w'...
4816724
from hcsr04sensor import sensor # Created by <NAME> # MIT License def main(): """Calculate the distance of an object in centimeters using a HCSR04 sensor and a Raspberry Pi. This script allows for a quicker reading by decreasing the number of samples and forcing the readings to be taken at q...
4816780
import os HOME_DIR = os.path.expanduser("~") ROOT_DIR = os.path.join(HOME_DIR, "DAZ 3D", "Bridges", "Daz To Maya") EXPORT_DIR = os.path.join(ROOT_DIR, "Exports")
4816795
import logging import json from enum import Enum from azure.storage.queue import QueueClient, BinaryBase64EncodePolicy, BinaryBase64DecodePolicy from azure.core.exceptions import ResourceNotFoundError, ResourceExistsError class ExportsQueue: def __init__(self, connection_string, queue_name): self.connect...
4816809
from rest_framework import viewsets from .models import Album from .serializer import AlbumSerializer class AlbumViewSet(viewsets.ModelViewSet): queryset = Album.objects.all() serializer_class = AlbumSerializer def perform_create(self, serializer): serializer.save(author=self.request.user)
4816813
from django.conf.urls import url, include as old_include from django.urls import path, include, re_path from . import views new_style_urls = ([ path('login_required/', views.login_required_view), re_path(r'^perm_required/$', views.permission_required_view), ], 'new_style_urls') admin_namespace = ([ path(...
4816826
import os import math import time import cv2 import datetime from multiprocessing import Process from multiprocessing import Queue import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from scipy.spatial import distance import sklearn.metrics as metrics from sklearn.metrics import roc_auc_score impor...
4816882
from django.core.management.base import BaseCommand from django.conf import settings from oms_cms.backend.menu.models import Menu, MenuItem class Command(BaseCommand): help = 'Add menu' def handle(self, *args, **options): menu = Menu.objects.create(name="Main") MenuItem.objects.create( ...
4816887
import csv as csvmod import socket import sys import json as jjson from xml.dom import minidom import os if os.name == "nt": import WConio from externals.moduleman.plugin import moduleman_plugin from framework.ui.console.output import getTerminalSize from framework.ui.console.common import exec_banner, term_color...
4816899
from random import sample as random_sample from psutil import cpu_count from django import forms from dockit.models import User, IP, Container from .utils import DHost class UserForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) for field i...
4816916
import dataclasses as dc from enum import Enum import os from pathlib import Path import typing import numpy as np import optuna import yaml from . import util @dc.dataclass class TypedDataClass: @classmethod def read_settings_yaml(cls, settings_yaml): settings_yaml = Path(settings_yaml) d...