id
stringlengths
3
8
content
stringlengths
100
981k
9990955
from pathlib import Path import re def read_input_file(input_file_path): p = Path(input_file_path) with p.open() as f: #split entries by blankline raw_entries = f.read().split("\n\n") passports = [] #normalize entries by removing newlines and splitting up key value pairs ...
9990963
import torch @torch.jit.script def fn(x, scale, shift): return scale * x / shift @torch.jit.script def recurrent(x, scale, shift): y = x for i in range(100): y = fn(y, scale, shift) return y x = torch.randn(2, 2, device='cuda') scale = torch.randn(2, 2, device='cuda', requires_grad=True) s...
9991012
import numpy as np import pylab as plt import networkx as nx # Initializing points points_list = [(0, 1), (1, 5), (5, 6), (5, 4), (1, 2), (2, 3), (2, 7)] goal = 7 mapping = {0: 'Start', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7-Destination'} G = nx.Graph() G.add_edges_from(points_list) pos = n...
9991038
import logging from abc import ABCMeta import util.gcp_utils from gce_base.gce_base import GceBase class GceZonalBase(GceBase, metaclass=ABCMeta): def _gcp_zone(self, gcp_object): """Method dynamically called in generating labels, so don't change name""" try: return gcp_object["zone"]...
9991042
class Solution: def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]: if not matrix: return [] result = [0] * (len(matrix)*len(matrix[0])) row = col = 0 for i in range(len(result)): result[i] = matrix[row][col] if (row + col)&1: ...
9991086
import FWCore.ParameterSet.Config as cms import sys process = cms.Process("FlatCalib") process.load("FWCore.MessageService.MessageLogger_cfi") process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') process.load("RecoHI.HiEvtPlaneAlgos.HiEvtPlane_cfi") process.load("RecoHI.HiEvtPlaneAlgos.hiE...
9991124
import json import requests from web.config import spacy_server_url # from web.config import mongodb_uri # from web import client from bson import ObjectId from pymongo import MongoClient mongodb_uri = "mongodb://%s:%s@mongodb:27017/crawler" % ("admin", "<PASSWORD>") def _text_subject(id): s = SpacyDetector(id...
9991134
from typing import List import pytest from raiden import waiting from raiden.api.python import RaidenAPI from raiden.raiden_service import RaidenService from raiden.tests.utils.detect_failure import raise_on_failure from raiden.tests.utils.network import CHAIN from raiden.tests.utils.transfer import block_offset_time...
9991143
import unittest from eventkit import Event array = list(range(10)) class AggregateTest(unittest.TestCase): def test_min(self): event = Event.sequence(array).min() self.assertEqual(event.run(), [0] * 10) def test_max(self): event = Event.sequence(array).max() self.assertEqua...
9991154
import re import pytesseract from PIL import Image import cv2 import numpy as np import math from module.image import proc from module.princess import unitproc # η¬¬δΈ€δ½θ§’θ‰²ηš„ε·¦δΈŠθ§’εΊ§ζ¨™ pos1 = [X,Y], η¬¬δΊŒδ½θ§’θ‰²ηš„ε·¦δΈ‹θ§’εΊ§ζ¨™ pos2 = [X,Y] def main(position, unit_size, img): x, y = position w, h = unit_size[:2] print(x, y, w, h)...
9991165
import sqlite3 with sqlite3.connect('/tmp/test.db') as db: try: db.execute('''CREATE TABLE people ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT, surname TEXT, language TEXT )''') except sqlite3.OperationalError: # Table alrea...
9991181
months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] years=[2020,2021] _exercise_1=[i for i in range(5)] _exercise_2=[i for i in range(1,10) if i%2!=0] _exercise_3=[2**i - i**2 for i in range(11)] _exercise_4=[(ind,month) for ind,month in enumerate(months)] _exercise_5=[(i,c) for i in range...
9991207
import hashlib import json import os import warnings from mednorm.pmt_helpers import import_pymedtermino pymedtermino = import_pymedtermino() import requests from enum import Enum from mednorm.utils import makedirs_file try: from pymedtermino.meddra import MEDDRA except: MEDDRA = None try: from pymedter...
9991240
def cycleSort(arr): writes = 0 # Loop through the array to find cycles for cycle in range(0, len(arr) - 1): item = arr[cycle] # Find the location to place the item pos = cycle for i in range(cycle + 1, len(arr)): if arr[i] < item: pos += 1 ...
9991251
from itertools import accumulate, product, repeat from typing import Sequence, Generator, Iterable def create_quantiles(items: Sequence, lower_bound, upper_bound): """Create quantile start and end boundaries.""" interval = (upper_bound - lower_bound) / len(items) quantiles = ((g, (x - interval, x)) for ...
9991256
from .metadata_server_mock import metadata_server from yandexcloud._auth_fabric import get_auth_token_requester def test_metadata_auth(iam_token): with metadata_server(iam_token) as srv: requester = get_auth_token_requester(metadata_addr=srv.addr) token = requester.get_token() assert toke...
9991258
from collections import deque import numpy as np import pandas as pd import itertools from numpy.random import default_rng def _get_n(iterable, n): return list(itertools.islice(iterable, n)) def generate_ma(*coeffs, std=1.0, seed=12345): rng = default_rng(seed=seed) n = len(coeffs) past_terms = deq...
9991266
def reduce(lst, f, init): res = init for x in lst: res = f(res, x) return res def add(a, b): return a + b def multiply(a, b): return a * b def custom_sum(lst): return reduce(lst, add, 0) def custom_prod(lst): return reduce(lst, multiply, 1) # Tests assert custom_sum([1, 2, ...
9991273
import sys, io, random from chart.preprocessing import RangeScaler, NumberBinarizer from chart import bar, scatter, histogram def test_range_scaler(): rs = RangeScaler(out_range=(0, 10), floor=0, round=True) x = [30, 50, 100, 90, 80, 40] rs.fit(x) result = rs.transform(x) assert result == [3, 5, 1...
9991284
import os from distutils.util import strtobool import numpy as np import pytest import opendp.smartnoise.core as sn from tests import (TEST_PUMS_PATH, TEST_PUMS_NAMES) # Used to skip showing plots, etc. # IS_CI_BUILD = strtobool(os.environ.get('IS_CI_BUILD', 'False')) def test_multilayer_analysis(run=True): wi...
9991291
Example Input: 5 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //python program n=5 m=n*2 ast="* " for i in range(m,0,-2): print(i*ast) for j in range(2,m+1,2): print(j*ast)
9991297
import numpy as np import cv2 from skimage.feature import peak_local_max NOCS_CAMERA_MAT = np.array([[591.0125 , 0. , 322.525 , 0. ], [ 0. , 590.16775, 244.11084, 0. ], [ 0. , 0. , 1. , 0. ], [ 0. , 0. , 0. , 1. ...
9991306
import types # <NAME> # <EMAIL> # 12 May 2008 # Feel free to use with attribution where appropriate. If you find any errors or make any improvements, please make those freely available # (again, where appropriate). # # These functions are designed to make SQL insert statements from user defined objects. An object is...
9991308
TERM_INIT_CONFIG = { # instead of local server runnning this web terminal service # "domain" is the target that you want to access through local server (with this web terminal) # and before doing so - make sure you have username and port (on the "domain") to implement remote access 'domain': 'example.co...
9991319
import os.path as osp import numpy as np from imageio import imread from dmb.data.datasets.flow.base import FlowDatasetBase from dmb.data.datasets.utils import load_flying_chairs_flow class FlyingChairsDataset(FlowDatasetBase): def __init__(self, annFile, root, transform=None): super(FlyingChairsDataset...
9991324
from opennem.core.loader import load_data FACILITY_DUID_MAP = load_data("facility_duid_map.json") def facility_duid_map(duid: str) -> str: """ Maps a DUID to a Facility code """ if not type(FACILITY_DUID_MAP) is dict: raise Exception("Facility duid map invalid data type") if duid in...
9991328
import numpy as np import torch ############################################################################### # Sequence filters ############################################################################### def mean(signals, win_length=9): """Averave filtering for signals containing nan values ...
9991334
from collections import Counter from copy import deepcopy from functools import partial import itertools import json import math import warnings from ..stat_counter import CovarianceCounter, RowStatHelper from ..storagelevel import StorageLevel from ..utils import ( compute_weighted_percentiles, format_cell, get_k...
9991353
class Solution(object): def lengthOfLongestSubstringKDistinct(self, s, k): """ :type s: str :type k: int :rtype: int """ res = 0 i = 0 count_map = {} for j in range(len(s)): count_map[s[j]] = count_map.get(s[j], 0) + 1 ...
9991364
def save(operator, context, **kwargs): raise NotImplementedError('Export of BSP data not supported!')
9991432
import numpy as np # input: coeff with shape [1,257] def Split_coeff(coeff): id_coeff = coeff[:,:80] # identity(shape) coeff of dim 80 ex_coeff = coeff[:,80:144] # expression coeff of dim 64 tex_coeff = coeff[:,144:224] # texture(albedo) coeff of dim 80 angles = coeff[:,224:227] # ruler angles(x,y,z) for rotation ...
9991446
import torch import torch.nn as nn from torch.autograd import Variable import layers as mynn import math from collections import OrderedDict __all__ = ['FCNet', 'fcnet'] class FCNet(nn.Module): def __init__(self, block_opts, mask_path, mean, std, noise_level, encoder_learn, bernoulli_p, K): super(FCNet,...
9991452
from hyperparameter_hunter import Environment, CVExperiment from hyperparameter_hunter import GBRT, Real, Integer, Categorical import pandas as pd from sklearn.datasets import load_diabetes from xgboost import XGBRegressor #################### Format DataFrame #################### data = load_diabetes() train_df = pd....
9991470
import sys import traceback import pkg_resources import math import pprint class JsonHandler: def __init__(self, e=False, **kwargs): self.e = e self._contexts = {} self._integrations = {} self.type, self.value, self.tb = ( exc_type, exc_value, e...
9991487
from django.contrib import admin from video_encoding.admin import FormatInline from .models import Video @admin.register(Video) class VideoAdmin(admin.ModelAdmin): inlines = (FormatInline,) list_dispaly = ('get_filename', 'width', 'height', 'duration') fields = ('file', 'width', 'height', 'duration') ...
9991530
from .accountant import ( # noqa: F401 GeneralMomentAccountant, culc_tightupperbound_lowerbound_of_rdp_with_theorem6and8_of_zhu_2019, culc_upperbound_of_rdp_with_Sampled_Gaussian_Mechanism, ) from .privacy_manager import PrivacyManager # noqa: F401
9991653
from dispatch.common.utils.kandbox_clear_data import clear_kafka clear_kafka() # org_code='0', team_id=1
9991676
import re from nose2.tests._common import FunctionalTestCase class TestPrintHooksPlugin(FunctionalTestCase): def test_invocation_by_double_dash_option(self): proc = self.runIn( "scenario/no_tests", "--plugin=nose2.plugins.printhooks", "--print-hooks" ) match = re.compile( ...
9991685
import torch as T def top_k_filtering(logits, top_k=0, filter_value=-float('Inf')): """Filters a distribution of logits using top-k filtering. Args: logits: predicted word logits. [batch_size, *, vocab_size] top_k >0: keep only top k tokens with highest probability. (t...
9991706
from tensorflow.python.util import compat import numpy as np from _interpret_shapes import _interpret_shape as interpret_shape import _layers def _remove_beginning_unit_dimensions(in_tuple): for i, value in enumerate(in_tuple): if value == 1: continue else: return in_tuple[i:] def _add_const(con...
9991710
import logging def init_logger(): logger = logging.getLogger("ichrome") logger.setLevel(logging.INFO) hd = logging.StreamHandler() formatter_str = ( "%(levelname)-5s %(asctime)s [%(name)s] %(filename)s(%(lineno)s): %(message)s" ) formatter = logging.Formatter(formatter_str, datefmt="%Y...
9991725
import torch class AccuracyMetric(object): def __init__(self): self.reset() def reset(self) -> None: self.n_correct = 0 self.n_total = 0 def update(self, targets, outputs): batch_size = targets.size(0) pred = (outputs > 0.5).long() correct = pred.eq(targe...
9991762
from zope.interface import Interface from twisted.internet.protocol import Factory, Protocol class IQuoter(Interface): """ An object that returns quotes. """ def getQuote(): """ Return a quote. """ class QOTD(Protocol): def connectionMade(self): self.transport....
9991789
from unittest import TestCase, mock import pytest from organisations.models import Organisation from projects.models import Project, UserProjectPermission from projects.tags.models import Tag from projects.tags.permissions import TagPermissions from users.models import FFAdminUser mock_request = mock.MagicMock() moc...
9991820
import itertools from collections import OrderedDict import pytest import pytorch_testing_utils as ptu import torch import pystiche from pystiche.misc import build_complex_obj_repr from tests.utils import skip_if_cuda_not_available class TestComplexObject: def test_repr_smoke(self): class TestObject(p...
9991841
from typing import TYPE_CHECKING, List, Optional from pydantic import validator from qcelemental.util import which_import from simtk import unit from simtk.openmm import System from typing_extensions import Literal from qubekit.parametrisation.base_parametrisation import Parametrisation from qubekit.utils.helpers imp...
9991848
from unittest import TestCase from mock import Mock, MagicMock, patch import logging logging.getLogger("tensorflow").setLevel(logging.WARNING) # Supress excessive tesnorflow logging. Must be placed before the SessionRunner import from agent.trainer.session import SessionRunner class TestSessionRunner(TestCase): ...
9991852
from __future__ import division import csv import numpy as np import scipy as sp import pylab as py import struct import os import os, struct from array import array as pyarray from numpy import append, array, int8, uint8, zeros import matplotlib.pyplot as plt from dml.LR import * from dml.tool import normalize,disnorm...
9991854
import asyncio import random import gta.utils import gta_native import aiohttp __author__ = '<NAME> <<EMAIL>>' __status__ = 'Development' __version__ = '0.9.1' __dependencies__ = ('aiohttp>=0.15.3',) @asyncio.coroutine def main(): """ Applies the current weather from Los Angeles in game. """ url = '...
9991899
import numpy as np import torch from .upwind import * from .spectral import * __all__ = ['PDEStepper', 'TimeStepper', 'LinearTimeStepper', 'SpectStepper', 'LinearSpectStepper'] class PDEStepper(object): def step(self, init, dt, **kw): raise NotImplementedError def predict(self, init, T, **kw): ...
9991908
from lymph.core.components import Declaration def proxy(*args, **kwargs): def factory(interface): from lymph.core.interfaces import Proxy return Proxy(interface.container, *args, **kwargs) return Declaration(factory)
9991993
rt_water = 0 rt_mountain = 1 rt_steppe = 2 rt_plain = 3 rt_snow = 4 rt_desert = 5 rt_bridge = 7 rt_river = 8 rt_mountain_forest = 9 rt_steppe_forest = 10 rt_forest = 11 rt_snow_forest = 12 rt_desert_forest = 13
9992070
import unittest from tests.lib.client import get_client from tests.lib.address_verifications import verify_card_holder_address_response from tests.lib.funding_sources import FundingSources from marqeta.errors import MarqetaError class TestFundingSourcesAddressesFind(unittest.TestCase): """Tests for the funding_s...
9992114
import os def score_cvsm(result_filename): # score_instances should be a tuple of (stuff, label, score) score_instances = [] target_relation = None with open(result_filename, "r") as fh: for line in fh: line = line.strip() if not line: continue ...
9992122
from logging import CRITICAL, disable disable(CRITICAL) urls = { '': ( '/fixed_sidebar', '/fixed_footer', '/plain_page', '/page_403', '/page_404', '/page_500' ), '/home': ( '/index', '/index2', '/index3' ), '/forms': ( ...
9992131
from django.conf.urls import url from . import views urlpatterns = [ url(r'^add-to-cart/$', views.add_to_cart, name="lfs_add_to_cart"), url(r'^add-accessory-to-cart/(?P<product_id>\d*)/$', views.add_accessory_to_cart, name="lfs_add_accessory_to_cart"), url(r'^added-to-cart/$', views.added_to_cart, name="lf...
9992135
from flypylib import fplobjdetect, fplmodels, fplnetwork, fplsynapses import numpy as np import matplotlib.pyplot as plt # choose a net architecture # possible models: baseline_model, vgg_like, resnet_like, unet_like model = fplmodels.vgg_like; network = fplnetwork.FplNetwork(model) n_gpu = 4 batch_...
9992166
import random answers = ['I did not understand what you just said', 'It doesn\'t look like anything to me', 'I don\'t know, whatever'] while True: user_input = input(">>> ") if user_input.lower() == 'hi': print("Hello") else: print(random.choice(answers))
9992247
import numpy as np from scipy.optimize import minimize from math import sqrt import matplotlib.pyplot as plt import cv2 def convert_line(line): return np.array([[line[0], -line[1], -line[0]*line[2]+line[1]*line[3]]], dtype=np.float32) class GeometricError(): def __init__(self): pass @staticmethod...
9992254
import yaml import json import Core import markdown import re __yaml_frontmatter__ = r'(---)(.*?)\1' class YamlParser(Core.Parser): accepts = ["yaml", "yml"] def interpret(self, file_contents): return yaml.load(file_contents) class JsonParser(Core.Parser): accepts = ["json", "js"] def int...
9992260
from .sokoban_env import SokobanEnv from .render_utils import room_to_rgb_FT, room_to_tiny_world_rgb_FT from gym.spaces import Box class FixedTargetsSokobanEnv(SokobanEnv): def __init__(self, dim_room=(10, 10), max_steps=120, num_boxes=3, num_gen_steps=None): ...
9992284
from benchmark_xtensor_python import sum_tensor import numpy as np u = np.ones(1000000, dtype=float) #print(sum_tensor(u)) from timeit import timeit print (timeit ('sum_tensor(u)', setup='from __main__ import u, sum_tensor', number=1000))
9992285
from mmcv.runner.fp16_utils import force_fp32 from mmdet.models.utils.builder import TRANSFORMER from mmdet.models.utils import Transformer import warnings import math import copy import torch import torch.nn as nn from mmcv.cnn import build_activation_layer, build_norm_layer, xavier_init from mmcv.cnn.bricks.registry ...
9992297
from ._domain import Domain from ._caxis import Caxis from plotly.graph_objs.layout.ternary import caxis from ._baxis import Baxis from plotly.graph_objs.layout.ternary import baxis from ._aaxis import Aaxis from plotly.graph_objs.layout.ternary import aaxis
9992332
from elliptic.Kernel.Contract import DSLContract from elliptic.Kernel.Expression import Expression class DSLStub: def base_delegate(self): return None class ContractStub(DSLContract[DSLStub]): def Test(self): return self.append_tree(Expression(self.dsl_impl.base_delegate(), "Test")) def t...
9992347
from flask_restful import fields # the waypoint model contains the data of a waypoint waypoint = { "name": fields.String, "latitude": fields.Float, "longitude": fields.Float, "altitude": fields.Float }
9992356
try: from clvm.operators import OperatorDict # noqa except ImportError: OperatorDict = dict # noqa
9992368
import collections.abc import json import warnings from functools import partial from urllib.parse import urlencode from geopy.adapters import AdapterHTTPError from geopy.exc import ( ConfigurationError, GeocoderAuthenticationFailure, GeocoderInsufficientPrivileges, GeocoderQueryError, GeocoderRate...
9992377
from collections import namedtuple import rl_sandbox.constants as c class NoSampleError(Exception): pass class LengthMismatchError(Exception): pass class CheckpointIndexError(Exception): pass class Buffer: @property def memory_size(self): raise NotImplementedError @property ...
9992400
from ply import yacc, lex from .grammar import * # noqa from ..conf import settings class Rules: # Regular expression rules for simple tokens t_PLUS = r'\+' t_MINUS = r'-' t_TIMES = r'\*' t_DIVIDE = r'/' t_LPAREN = r'\(' t_RPAREN = r'\)' t_LSQUARE = r'\[' t_RSQUA...
9992406
from django.dispatch import Signal image_created = Signal(providing_args=['image', 'gallery_ct', 'gallery_id']) image_removed = Signal(providing_args=['image', 'gallery_ct', 'gallery_id'])
9992417
import collections import asyncio from valve.source.a2s import ServerQuerier ServerResponse = collections.namedtuple("ServerResponse", "info players") Player = collections.namedtuple("Player", "name duration score") async def steam_query(address, timeout=2.): def query(): players = [] server = Se...
9992418
from ..schema.nexusphp import NexusPHP from ..schema.site_base import SignState, Work from ..utils.net_utils import NetUtils class MainClass(NexusPHP): URL = 'https://www.haidan.video/' USER_CLASSES = { 'downloaded': [2199023255552, 8796093022208], 'share_ratio': [4, 5.5], 'days': [175...
9992427
from .augmentation_helpers import * from .cv_helpers import * from .dsntnn import * from .nn_helpers import * from .skeleton_helpers import * from .soft_argmax import *
9992434
from typing import Dict, List, Optional from pydantic.main import BaseModel class NotifierMessage(BaseModel): title: str message: Optional[str] = None meta: Optional[Dict] = None files: Optional[List[Dict]] = None link: Optional[Dict[str, str]] = None # info_id: Optional[InfoId] = None
9992440
import discord import os import datetime from discord.ext.commands import Bot, when_mentioned_or from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.triggers.cron import CronTrigger from discord.ext.commands import CommandNotFound, CommandOnCooldown, MissingPermissions, MissingRequiredArgument...
9992452
from fpdf import FPDF, HTMLMixin import json import requests class PDFHardwareInfo(FPDF, HTMLMixin): # TODO wywalic to !!!!!!!!!!!!! def header(self): self.set_font('Arial', 'B', 16) def headerOnlyFirstSide(self): # self.image('logo.png',90,15, 30) self.cell(0, 10, 'Information ...
9992509
import numpy as np from scipy.optimize import least_squares from scipy.integrate import odeint def sol_u(t, u0, alpha, beta): return u0 * np.exp(-beta * t) + alpha / beta * (1 - np.exp(-beta * t)) def sol_s(t, s0, u0, alpha, beta, gamma): exp_gt = np.exp(-gamma * t) if beta == gamma: s = s0 * ex...
9992537
from random import randrange import board import busio import displayio from adafruit_gizmo import tft_gizmo import adafruit_imageload import adafruit_lis3dh #---| User Config |--------------- BACKGROUND = 0xAA0000 # specify color or background BMP file NUM_FLAKES = 50 # total number of...
9992548
from context import ascii_magic ascii_art = ascii_magic.from_image_file('kid.jpg', columns=200, mode=ascii_magic.Modes.HTML_TERMINAL) markup = f"""<!DOCTYPE html> <html> <body style="background-color: black; font-size: 8px;"> <pre> {ascii_art} </pre> </body> </html>""" with open('output_html-terminal.html', 'w') as ...
9992549
from controller.invoker.invoker_cmd_base import BaseMirControllerInvoker from controller.utils import checker, invoker_call, utils from id_definition.error_codes import CTLResponseCode from controller.invoker.invoker_cmd_branch_commit import BranchCommitInvoker from controller.invoker.invoker_cmd_repo_check import Repo...
9992557
import datetime from django.db import models class Cat(models.Model): name = models.CharField(max_length=255) birth_date = models.DateField(default=datetime.date.today) bio = models.TextField(blank=True) created = models.DateTimeField(default=datetime.datetime.now) updated = models.DateTimeField(...
9992572
from dataclasses import dataclass from typing import List, Union, Optional @dataclass class Type: base: str size: Optional[int] @dataclass class Decl: input: bool # Otherwise, output. name: str type: Type @dataclass class BinExpr: op: str lhs: "Expr" rhs: "Expr" @dataclass class...
9992587
import tensorflow as tf from med_io.pipeline import * from models.ModelSet import * from sklearn.model_selection import train_test_split from util import * from utils.TensorBoardTool import * from plot.plot_figure import * from tensorflow.keras.models import load_model from med_io.keras_data_generator import DataGenera...
9992615
import unittest from zydis import * class FormatterTestCase(unittest.TestCase): def setUp(self) -> None: self.insn = Decoder().decode_one(b'\xB8\x37\x13\x00\x00') self.formatter = Formatter() def test_format_insn(self): insn = self.formatter.format_instr(self.insn) assert insn...
9992620
from snsql._ast.tokens import * """ string processing expressions """ class LowerFunction(SqlExpr): def __init__(self, expression): self.expression = expression def children(self): return [Token("LOWER"), Token("("), self.expression, Token(")")] def evaluate(self, bindings): ex...
9992652
from . import _cli from .__about__ import __author__, __author_email__, __version__, __website__ __all__ = [ "_cli", "__version__", "__author__", "__author_email__", "__website__", ]
9992689
from InstruccionesPL.TablaSimbolosPL.InstruccionPL import InstruccionPL class ReturnsQuery(InstruccionPL): def __init__(self, cadena, tipo, linea, columna, strGram): InstruccionPL.__init__(self, tipo, linea, columna, strGram) self.cadena = cadena def ejecutar(self, tabla, arbol)...
9992752
import pytest from openfecli.parameters.output import get_file_and_extension @pytest.mark.parametrize("fname,expected_ext", [ ("foo.bar", "bar"), ("foo.bar.bz", "bz"), ]) def test_get_file_and_extension(tmpdir, fname, expected_ext): with open(tmpdir / fname, mode='w') as file: outfile, ext = get_f...
9992774
import os import json import numpy as np import part_dataset_ae import part_dataset_pcn def load_data(data_path, num_point, category, seen_split, unseen_split): pcn_train_dataset, pcn_test_dataset, num_parts = load_pcn_data(data_path, num_point, category, seen_split, ...
9992789
class SimulationType(object): def __init__(self): self._type = "regular" self._agent = 1 @property def type(self): return self._type @property def agent(self): return self._agent def set_regular(self): self._type = "regular" def increase_agents(se...
9992794
class Solution: def findCircleNum(self, M: List[List[int]]) -> int: if not M: return 0 n = len(M) p = [i for i in range(n)] for i in range(n): for j in range(n): if M[i][j] == 1: self.union(p, i, j) return len(set([self.parent(p, i) for i in range(n)])) def union(self,...
9992812
import pytest from riotwatcher import TftWatcher, IllegalArgumentError @pytest.mark.tft @pytest.mark.usefixtures("reset_globals") class TestTftWatcher: def test_require_api_key(self): with pytest.raises(ValueError): TftWatcher() def test_allows_positional_api_key(self): TftWatche...
9992815
import dns.reversename domain = dns.reversename.from_address("172.16.31.10") print(domain) print(dns.reversename.to_address(domain))
9992817
import typing import mesh_tensorflow as mtf import numpy as np import tensorflow as tf from tensorflow.python.ops.init_ops import Initializer from .dataclass import BlockArgs, ModelParameter from .mtf_wrapper import cast, mtf_range, reshape, concat as mtf_concat, pad as mtf_pad, mtf_slice, add, multiply, \ negati...
9992825
import collections import json import django from django.contrib.postgres import lookups from django.contrib.postgres.fields import JSONField, jsonb from django.core import checks from django.db import NotSupportedError from django.db.models import Func, TextField, Value, lookups as builtin_lookups, Expression from dj...
9992828
from django.apps.registry import apps from django.conf import settings from django.contrib.contenttypes import management as contenttypes_management from django.contrib.contenttypes.models import ContentType from django.core.management import call_command from django.db import migrations, models from django.test import...
9992846
import os modelid='default' print('<!DOCTYPE html>') print('<html>') print('<head>') print('<meta http-equiv="Content-Type" content="text/html" charset="utf-8">') print('<title>title</title>') print('</head>') print('<body>') print('<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>') print('<...
9992920
import unittest from seesaw.item import Item class MockPipeline(object): pass class ItemTest(unittest.TestCase): def setUp(self): self.item = Item(MockPipeline(), 'FakeID', 1, prepare_data_directory=False) def test_get_returns_none_for_undefined_keys(self): self.assertEquals(None, self...
9992929
from typing import List from decimal import Decimal from ... import constants from . import utils DSR_DIVISOR = Decimal(10) ** constants.DSR_DECIMALS class DSR: def __init__(self, dsr_rates: List[dict]): self.dsr_rates = sorted(dsr_rates, key=lambda row: -row["blockNumber"]) def get(self, block_n...