id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
448459 | from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import tensorflow as tf
def simple_super_resolution_3d(inputs,
num_convolutions=1,
filters=(16, 32, 64),
upsampling... |
448461 | from pyradioconfig.parts.ocelot.calculators.calc_longrange import CALC_longrange_ocelot
class Calc_Longrange_Bobcat(CALC_longrange_ocelot):
pass |
448477 | from State import AI_Board
import os
import random
import numpy as np
from collections import deque
from keras.models import Sequential
from keras.layers.convolutional import Conv2D
from keras.layers.core import Dense, Activation, Flatten
from keras.optimizers import Adam
import cv2
def build_network(nu... |
448490 | from spake2 import six
from hashlib import sha256
from itertools import count
class PRG:
# this returns a callable which, when invoked with an integer N, will
# return N pseudorandom bytes derived from the seed
def __init__(self, seed):
self.generator = self.block_generator(seed)
def __call__(... |
448535 | from yacs.config import CfgNode as CN
_C = CN()
_C.EXP = "" # Experiment name
_C.DEBUG = False
_C.SYSTEM = CN()
_C.SYSTEM.SEED = 0
_C.SYSTEM.FP16 = True
_C.SYSTEM.OPT_L = "O2"
_C.SYSTEM.CUDA = True
_C.SYSTEM.MULTI_GPU = False
_C.SYSTEM.NUM_WORKERS = 8
_C.DIRS = CN()
_C.DIRS.DATA = "data/rsna/"
_C.DIRS.TRAIN = "sta... |
448550 | from autode.thermochemistry.igm import calculate_thermo_cont
from autode.thermochemistry.symmetry import symmetry_number
__all__ = ['calculate_thermo_cont',
'symmetry_number']
|
448555 | import re
pattern = "(hold\d+)"
cset = set()
count = 0
with open("reports/gf12/bp_single/min_delay_report_osta.rpt", "r") as f:
while True:
line = f.readline()
if not line:
break
m = re.search(pattern, line)
if m:
name = m.group(0)
if name not in cset:
cset.add(name)
... |
448608 | def duplicate(s):
if(len(s)<=1):
return s
if s[0]==s[1]:
return duplicate(s[1:])
return s[0]+duplicate(s[1:])
s = input()
print(duplicate(s))
|
448614 | from copy import deepcopy
from datetime import datetime
from django.test import TestCase
from xml.dom.minidom import parseString
from httmock import HTTMock
from authorizenet.cim import extract_form_data, extract_payment_form_data, \
add_profile
from .utils import xml_to_dict
from .mocks import cim_url_match, cus... |
448653 | from itertools import chain, izip
from string import ascii_lowercase as low, ascii_uppercase as up, digits
KEYS = {a: i for i, a in enumerate(chain(
up, low, chain.from_iterable(izip(xrange(10), digits))))}
def unusual_sort(array):
return sorted(array, key=lambda a: KEYS[a])
|
448700 | from setuptools import setup, Extension
import platform
version = '1.3.0'
setup(name='sololink',
zip_safe=True,
version=version,
description='Python interface for SoloLink',
long_description='Python interface for SoloLink',
url='https://github.com/OpenSolo/sololink-python',
author=... |
448708 | from migen import *
from migen.genlib.fsm import FSM, NextState
from migen.genlib.record import Record, DIR_M_TO_S
from misoc.interconnect.stream import Endpoint
from misoc.interconnect.csr import AutoCSR, CSRStorage, CSRStatus
from ovhw.constants import *
from ovhw.ov_types import ULPI_DATA_D, ULPI_DATA_TAG
class RX... |
448724 | from __future__ import absolute_import
from . import main
# function to set path to current folder (py 2 to 3)
def import_modify():
if __name__ == '__main__':
if __package__ is None:
import sys
from os import path
sys.path.append(path.abspath(path.join(path.dirname(__fi... |
448755 | from typing import Any, Sequence
from dataclasses import dataclass
import jax.numpy as jnp
from jax.tree_util import register_pytree_node_class
import operator
import itertools
import functools
from jax._src.scipy.ndimage import (
_nonempty_prod,
_nonempty_sum,
_INDEX_FIXERS,
_round_half_away_from_zero... |
448763 | import marshal
import mmap
import os
import os.path
import sys
import logging
# from profilehooks import profile
from cog.cache import Cache
import xxhash
RECORD_SEP = b'\xFD'
UNIT_SEP = b'\xAC'
class TableMeta:
def __init__(self, name, namespace, db_instance_id, column_mode):
self.name = name
... |
448768 | from django import forms
from django.utils.translation import ugettext_lazy as _
from orchestra.forms.widgets import SpanWidget
from .. import settings
from ..forms import SaaSPasswordForm
from .options import SoftwareService
class MoodleForm(SaaSPasswordForm):
admin_username = forms.CharField(label=_("Admin us... |
448790 | from ._sizemin import SizeminValidator
from ._sizemax import SizemaxValidator
from ._opacity import OpacityValidator
from ._color import ColorValidator
from ._border import BorderValidator
from ._blend import BlendValidator
|
448799 | import os.path
from typing import Dict
from jinja2 import Environment, FileSystemLoader
def apply_template(file: str, params: Dict[str, str]) -> str:
"""
Applies Jinja2 template
:param str file: Jinja2 template file
:param Dict[str, str] params: parameters
:return: processed content
:rtype: s... |
448821 | import torch
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from math import exp
import math
def gaussian(window_size, sigma):
gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])
return gauss / gauss.su... |
448887 | import sys
import json
# Open secret.config file
configFileNotFound = False
try:
configFile = open('secret.config')
except Exception as e:
print("File secret.config could not be opened in current directory.")
print(e)
configFileNotFound = True
# Script will exit after checking if the Vault request is valid
# Dec... |
448898 | from __future__ import print_function
import argparse
import os
import imp
import algorithms as alg
from dataloader import DataLoader, GenericDataset
import numpy as np
import torch
import sys
parser = argparse.ArgumentParser()
parser.add_argument('--exp', type=str, required=True, default='', help='config file with p... |
448947 | from functools import partial, update_wrapper
class SelfWrapper:
"""Wraps class attributes that could be overruled by instance attributes"""
_ATTRIBUTES = "Attributes"
def __init__(self, wrapped, attributelist):
self._attributelist = attributelist
self._wrapped = wrapped
self._cls =... |
448966 | import re
import json
import os
import logging
import time
from logging.handlers import RotatingFileHandler
from logging import Formatter
from fuzzywuzzy import fuzz
from hashlib import md5
from flask import Flask, jsonify, send_from_directory, send_file, render_template, request, redirect, make_response
import imgu... |
448973 | from six import PY2
from apitools.base.py.exceptions import HttpNotFoundError
import pytest
from ruamel.yaml import YAML
from cloud_foundation_toolkit.dm_utils import API
from cloud_foundation_toolkit.dm_utils import get_deployment
if PY2:
import mock
else:
import unittest.mock as mock
class Message():
... |
448996 | class Entity(object):
'''Class to represent an entity. Callable to update the entity's position. Very esoteric ;)'''
def __init__(self, size, x, y):
self.x, self.y = x, y
self.size = size
def __call__(self, x, y):
'''Change the position of the entity.'''
self.x, self.y = x,... |
449023 | from sqlalchemy.dialects import registry
registry.register("dremio", "sqlalchemy_dremio.pyodbc", "DremioDialect_pyodbc")
registry.register("dremio.pyodbc", "sqlalchemy_dremio.pyodbc", "DremioDialect_pyodbc")
from sqlalchemy.testing.plugin.pytestplugin import *
|
449050 | from rest_framework import viewsets, mixins, filters
from auditable.views import AuditableMixin
from api.models.DefaultCarbonIntensityCategory import \
DefaultCarbonIntensityCategory
from api.permissions.CreditCalculation import \
CreditCalculationPermissions
from api.serializers.DefaultCarbonIntensity im... |
449067 | import os
from hachoir_parser import createParser
from hachoir_metadata import extractMetadata
from core.movieinfo import TMDB
from core import sqldb
import PTN
import datetime
import logging
logging = logging.getLogger(__name__)
class ImportDirectory(object):
def __init__(self):
self.tmdb = TMDB()
... |
449071 | from ._feature_extractor import _FeatureExtractor
from .. import submodules, weight_init
class MobileNetV2(_FeatureExtractor):
def __init__(self, feature_channels=1280):
super().__init__(feature_channels)
self.initial = submodules.conv(3, 32, stride=2)
self.block1 = submodules.in... |
449078 | import os
from collections import namedtuple
from typing import Sequence, Set, TypeVar
from anoncreds.protocol.utils import toDictWithStrValues, \
fromDictWithStrValues, encodeAttr, crypto_int_to_str, to_crypto_int, isCryptoInteger, \
intToArrayBytes, bytesToInt
from config.config import cmod
from typing impor... |
449087 | import common
import numpy as np
import util
def fit_phis(adj, superclusters, supervars, method, iterations, parallel):
if method == 'debug':
# Bypass cache when debugging.
return _fit_phis(adj, superclusters, supervars, method, iterations, parallel)
key = (hash(adj.tobytes()), iterations)
if key not in ... |
449124 | class Calc:
"""Simple calculator."""
def __init__(self, a, b):
self.a = a
self.b = b
def do(self):
"""Perform calculation."""
return self.a + self.b
|
449130 | from django import template
from django.utils import dateparse
register = template.Library()
@register.filter
def mfl_bool_none_date_filter(value):
"""
Coverts None to Not Applicable
"""
if value is True:
return "Yes"
elif value is False:
return "No"
elif value is None:
... |
449145 | import random
# playables
class wizard (object):
hp = 100
stregth = 12
defence = 12
magic = 30
class warrior (object):
hp = 100
stregth = 30
defence = 18
magic = 10
class elf (object):
hp = 100
stregth = 20
defence = 18
magic = 18
# enemies
class goblin (object):
name = "Goblin"
hp = 6... |
449152 | import torch
from kornia.augmentation import RandomAffine,\
RandomCrop,\
CenterCrop, \
RandomResizedCrop
from kornia.filters import GaussianBlur2d
from torch import nn
import numpy as np
import glob
import gzip
import shutil
from pathlib import Path
import os
EPS = 1e-6
def count_parameters(model):
re... |
449200 | import collections
FieldRaw = collections.namedtuple("FieldRaw", "name value")
MediaField = collections.namedtuple("MediaField", "media port number_of_ports proto fmt")
OriginField = collections.namedtuple(
"OriginField", "username session_id session_type nettype addrtype unicast_address"
)
TimingField = collectio... |
449226 | import json
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.urls import rev... |
449248 | import sys,os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__))).replace('\\','/')+'/..')
from decimal import Decimal
from decimal import getcontext
from common.constants import MAX_PRECISION
from common.constants import LAMBERT_POS2_EXTENT
from common.constants import LAMBERT_POS2_SAMPLES
fro... |
449303 | import uuid
from cassandra.cqlengine import columns as cassandra_columns
from django_cassandra_engine.models import DjangoCassandraModel
class CassandraThing(DjangoCassandraModel):
id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4)
data_abstract = cassandra_columns.Text(max_length=10)
|
449308 | from typing import Any
def __getattr__(attr: Any) -> Any: ...
# 0: return value
# ? 0: return value
|
449318 | import os, sys
import datetime
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.basemap import Basemap
import argparse
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from data.goesr import GOESL1b, L1bBand
import interpolate
def main(args):
''' Plot mesoscale give... |
449327 | import netCDF4
import numpy as np
import matplotlib.pyplot as plt
import datetime
import time
from matplotlib import gridspec
from matplotlib import pylab
########################################################################
# Boxplot Exampe
########################################################################
... |
449342 | from sinling.core.joiner import *
from sinling.core.stemmer import *
from sinling.core.tokenizer import *
from sinling.core.tagger import *
|
449352 | from keras.models import Model
from keras.layers import Input, Dense, Dropout, Flatten, Conv2D, MaxPooling2D, BatchNormalization
from keras.callbacks import ModelCheckpoint, EarlyStopping, TensorBoard
from PIL import Image
import numpy as np
import csv
# Create CNN Model
print("Creating CNN model...")
in = Input((60,... |
449359 | import logging
import anndata as ad
import scipy.spatial
import scipy.sparse
import numpy as np
from sklearn.preprocessing import normalize
from sklearn.decomposition import TruncatedSVD
from sklearn.neighbors import NearestNeighbors
## VIASH START
# Anything within this block will be removed by `viash` and will be
... |
449374 | from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.test import TestCase
from accounts.models import Major, School, Student
class UpdateMajorsTestCase(TestCase):
def test_update_academics(self):
call_command("update_academics")
self.assertNot... |
449378 | import numpy as np
import sqlalchemy as sa
import pytest
from . import data, models
@pytest.fixture
def engine(postgresql):
return sa.create_engine('postgresql://', poolclass=sa.pool.StaticPool,
creator=lambda: postgresql)
@pytest.fixture
def session(engine):
with sa.orm.Session... |
449399 | import os
import sys
import semver
from github import Github
PLUGIN_TYPES = "[vim | nvim | sublime]"
ORG_NAME = "typeintandem"
VIM_REPO = "https://github.com/{}/vim".format(ORG_NAME)
NVIM_REPO = "https://github.com/{}/nvim".format(ORG_NAME)
SUBLIME_REPO = "https://github.com/{}/sublime".format(ORG_NAME)
def error(... |
449451 | class Formatter:
env = None
@classmethod
def get_format(cls, path):
i = path.find("{{")
if i > 0:
i = path.rfind("/", 0, i)
if i > 0:
return [path[0:i], path[i+1:]]
return [path, None]
@classmethod
def format(cls, f, value):
e... |
449475 | from PySide import QtGui, QtCore
import shiboken
import maya.OpenMayaUI as omui
mainWin = None
class TestUI(QtGui.QMainWindow):
def __init__(self, parent):
super(TestUI, self).__init__(parent=parent)
self.centralWidget = QtGui.QWidget()
self.setCentralWidget(self.centralWidget)
... |
449477 | import os
def get_directory_structure(rootdir):
"""
Creates a nested dictionary that represents the folder structure of rootdir
"""
dir = {}
rootdir = rootdir.rstrip(os.sep)
start = rootdir.rfind(os.sep) + 1
for path, dirs, files in os.walk(rootdir):
folders = path[start:].split(os.... |
449478 | import unittest
import catalogue
import scrubadub
import scrubadub.detectors.catalogue
class DetectorConfigTestCase(unittest.TestCase):
def test_register_detector(self):
class NewDetector(scrubadub.detectors.Detector):
name = 'new_detector'
scrubadub.detectors.catalogue.register_dete... |
449704 | import json
import time
# print("load============================================================")
def doload(file, count):
with open(file, "rb") as f:
str = f.read()
ti = time.time()
for i in range(count):
json.loads(str)
print("{}, seconds: {}".format(file, time.time() - ti))
# doload("test_float.json... |
449705 | import numpy as np
import anndata as ad
def remove_values_from_list(the_list, val):
return([value for value in the_list if value != val])
def imputation_feature(adata, variable_to_input, imputation_variable, var_category=None):
"""
impute the missing methylation feature according to the clusters of inte... |
449706 | from ...models import Topology
from . import BaseSaveSnapshotCommand
class Command(BaseSaveSnapshotCommand):
topology_model = Topology
|
449710 | import os
import os.path as osp
from typing import Optional, Tuple
import torch
from torch import Tensor
from pyg_lib import get_home_dir
def get_sparse_matrix(
group: str,
name: str,
dtype: torch.dtype = torch.long,
device: Optional[torch.device] = None,
) -> Tuple[Tensor, Tensor]:
r"""Returns ... |
449758 | import sys; sys.path.insert(0, sys.argv[1])
import mpi4py
if len(sys.argv) > 2:
lfn = "runtests-mpi4py-child"
mpe = sys.argv[2] == 'mpe'
vt = sys.argv[2] == 'vt'
if mpe: mpi4py.profile('mpe', logfile=lfn)
if vt: mpi4py.profile('vt', logfile=lfn)
from mpi4py import MPI
parent = MPI.Comm.Get_parent... |
449763 | import os
import json
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', type=str, default='nuscenes')
parser.add_argument('--step', type=int, default='-1')
parser.add_argument('--metric', type=str, default='label_aps')
parser.add_argument('--detailed', action='store_true')
args = pars... |
449785 | import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
def log_synonym_existed(value):
logger.info("Collection already has a value '{}'. Skipped".format(value.encode('utf-8')))
def log_synonym_for_entity_does_not_exist(entity_value, end_type, raise_exception):
message ... |
449794 | import sys
import os
import importlib
import numpy as np
import torch
import torch.nn as nn
from core.classificationnet import ClassificationNet
from core.utils import build_backbone_info, build_imagedataloaders
from core.utils import save_checkpoint, load_checkpoint, save_val_record
from core.utils import build_optimi... |
449822 | from .scroll_frame import ScrollFrame
from .label import Label
from .button import Button
from .box import Box
from .drop_target import DropTarget
from .seperator import Sep
from .widget import Widget
from .splitpane import SplitPane
from .checkbox import CheckBox
from .p... |
449825 | import asyncio
import os
from FIREX.utils import admin_cmd
from userbot import ALIVE_NAME, bot
from userbot.cmdhelp import CmdHelp
eviral = str(ALIVE_NAME) if ALIVE_NAME else "Du"
running_processes: dict = {}
@bot.on(admin_cmd(pattern="term(?: |$|\n)([\s\S]*)"))
async def dc(event):
await event.edit(f"{eviral}... |
449868 | import FWCore.ParameterSet.Config as cms
lsNumberFilter = cms.EDFilter("LSNumberFilter",
minLS = cms.untracked.uint32(21)
)
|
449899 | from math import factorial
while True:
try:
num = int(input('Enter a positive integer: '))
print(f'{num}! = {factorial(num)}')
break
except ValueError:
print('Not a positive integer, try again')
|
449907 | from migen import *
from migen.build.generic_platform import *
from migen.build.platforms.versaecp55g import Platform
from migen.genlib.io import CRG
from migen.genlib.cdc import MultiReg
from microscope import *
from ..gateware.platform.lattice_ecp5 import *
from ..gateware.serdes import *
from ..gateware.phy import ... |
449965 | import socket
def link_udp_client():
socket_client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
content = b"i am student"
addr = ("127.0.0.1",10002)
socket_client.sendto(content,addr)
socket_client.close()
if __name__ == '__main__':
link_udp_client()
|
449980 | from __future__ import print_function
from easydict import EasyDict as edict
from lib.cfgs import c as dcfgs
import lib.cfgs as cfgs
import os
os.environ['JOBLIB_TEMP_FOLDER']=dcfgs.shm
import argparse
os.environ['GLOG_minloglevel'] = '3'
import os.path as osp
import pickle
import sys
from multiprocessing import Proces... |
449986 | import math
import os
import numpy as np
from monai.data import Dataset, SmartCacheDataset
from skimage.transform import resize
from image_reader import WSIReader
class PatchWSIDataset(Dataset):
"""
Load whole slide images and associated class labels and create patches
"""
def __init__(self, data, ... |
450011 | import time
#时间戳 #计算
# print(time.time()) #1481321748.481654秒
#结构化时间---当地时间
# print(time.localtime(1531242343))
# t=time.localtime()
# print(t.tm_year)
# print(t.tm_wday)
# #-----#结构化时间---UTC
# print(time.gmtime())
#-----将结构化时间转换成时间戳
# print(time.mktime(time.localtime()))
#------将结构化时间转成字符串时间strftime
#print(tim... |
450024 | from typing import Union
import coloredlogs
# Note: be sure to call this before importing any application modules!
def configure_logging(level: Union[int, str]): # pragma: no cover
coloredlogs.install(
level=level,
fmt="[%(asctime)s][%(name)s][%(levelname)s] - %(message)s",
datefmt="%Y-%... |
450091 | from decimal import Decimal
from datetime import timedelta
from time import sleep
from math import log10
import logging
from requests.packages.urllib3.exceptions import ProtocolError
from .base import OandaBrokerBase
from ..lib.oandapy import OandaError
from ..portfolio import Position
log = logging.getLogger('pyFx... |
450125 | from node.behaviors import BoundContext
from node.interfaces import IBoundContext
from node.tests import NodeTestCase
from plumber import plumbing
from zope.interface import implementer
from zope.interface import Interface
class IBoundInterface(Interface):
pass
class BoundClass(object):
pass
@plumbing(Bou... |
450129 | import os
from django.conf import settings
from django.core.management.base import BaseCommand
from wagtail_wordpress_import.importers.wordpress import WordpressImporter
from wagtail_wordpress_import.logger import Logger
LOG_DIR = "log"
class Command(BaseCommand):
help = """Run the import process on all items i... |
450135 | from streamlink.plugins.streamable import Streamable
from tests.plugins import PluginCanHandleUrl
class TestPluginCanHandleUrlStreamable(PluginCanHandleUrl):
__plugin__ = Streamable
should_match = [
'https://streamable.com/example',
]
|
450136 | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="imax",
version="0.0.1-beta4",
author="<NAME>",
author_email="<EMAIL>",
description="Image augmentation library for Jax",
long_description=long_description,
long_d... |
450167 | from arjuna import *
@test
def check_ext_dep_dir(request):
print(C("project.root.dir"))
print(C("deps.dir"))
from sample.mod import hello
hello() |
450179 | from .markdowntoc.autorunner import AutoRunner
from .markdowntoc.markdowntoc_insert import MarkdowntocInsert
from .markdowntoc.markdowntoc_update import MarkdowntocUpdate
|
450216 | def _dump_llvm(f, output_func):
d = f.inspect_llvm()
if isinstance(d, dict):
for ty, code in d.items():
output_func("\n===== {}\n{}".format(ty, code))
else:
output_func("\n" + d)
def dump_numba_llvm(func):
out = print
module = __import__(func.__module__)
if hasattr(... |
450260 | from distutils.core import setup
setup(
name='filesearch',
version='',
packages=['', 'enjarify', 'enjarify.jvm', 'enjarify.jvm.constants', 'enjarify.jvm.optimization',
'enjarify.typeinference'],
url='',
license='',
author='<NAME>',
author_email='',
description=''
)
|
450266 | import re
import sys
import os
from typing import Optional, List
from deca.errors import *
from deca.db_processor import VfsProcessor, vfs_structure_new, vfs_structure_open, vfs_structure_empty, VfsNode
from deca.db_view import VfsView
from deca.builder import Builder
from deca.util import Logger, to_unicode
from deca.... |
450272 | import fault
import aetherling.helpers.fault_helpers as fault_helpers
from aetherling.space_time import *
from aetherling.space_time.reshape_st import DefineReshape_ST
import magma as m
import json
@cache_definition
def Module_0() -> DefineCircuitKind:
class _Module_0(Circuit):
name = "top"
IO = ... |
450277 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import fontforge # noqa
import os
import multiprocessing as mp
import argparse
# conda deactivate
# apt install python3-fontforge
def convert_mp(opts):
"""Useing multiprocessing to convert all fonts to s... |
450285 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insertNode(root, data):
if root == None:
root = Node(data)
else:
if root.data > data:
root.left = insertNode(root.left, data)
elif root.data < data:
... |
450357 | from collections import deque
import logging
import elasticsearch
from elasticsearch import Elasticsearch, helpers
from elasticsearch_dsl import Q, Search
from mayan.apps.common.utils import parse_range
from ..classes import SearchBackend, SearchModel
from ..exceptions import DynamicSearchException
from ..settings i... |
450417 | class Solution:
def longestDupSubstring(self, S: str) -> str:
nums = [ord(S[i])-ord('a') for i in range(len(S))]
left, right = 1, len(S)-1
while left<=right:
mid = left+(right-left)//2
if self.helper(mid, nums)!=-1:
left = mid + 1
else:
... |
450421 | from django.contrib import admin
from .models import RecProduct, RecVote
admin.site.register(RecProduct)
admin.site.register(RecVote)
|
450488 | from qgl2.qgl2 import qgl2decl, qgl2main, qreg
from qgl2.qgl2 import QRegister
from qgl2.qgl1 import X, Y, Z, Id, Utheta
from itertools import product
@qgl2decl
def t1():
"""
Expected: [X(q1), X(q1)]
"""
q1 = QRegister('q1')
l1 = list()
l1 += [ 0 ]
l1 += [ 1 ]
l1 += [ 2 ]
if l1 =... |
450560 | import os
from aws_xray_sdk import global_sdk_config
import pytest
from aws_xray_sdk.core import lambda_launcher
from aws_xray_sdk.core.models.subsegment import Subsegment
TRACE_ID = '1-5759e988-bd862e3fe1be46a994272793'
PARENT_ID = '53995c3f42cd8ad8'
HEADER_VAR = "Root=%s;Parent=%s;Sampled=1" % (TRACE_ID, PARENT_ID... |
450660 | from django.db import transaction
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from openbook_common.utils.model_loaders import get_emoji_group_model, get_post_model
# TODO Use post uuid a... |
450701 | from selenium.webdriver import Firefox
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support.expected_conditions import (
visibility_of_element_located,
invisibility_of_element_located
)
url = 'https://selenium.dunossauro.live/aula_10... |
450729 | import torch
import torch.nn as nn
import torch.nn.functional as F
class PreActBlock(nn.Module):
"""
Pre-activation version of the BasicBlock for Resnets.
Arguments:
in_planes (int): number of input planes.
planes (int): number of output filters.
stride (int): stride of convolution... |
450756 | from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
# Create a new chat bot named Charlie
chatbot = ChatBot('Charlie')
trainer = ListTrainer(chatbot)
trainer.train([
"Hi, can I help you?",
"Sure, I'd like to book a flight to Iceland.",
"Your flight has been booked."
])
# Get a res... |
450792 | import cgi
import unittest
from openid.consumer import consumer
from openid import message
from openid.test import support
class DummyEndpoint(object):
preferred_namespace = None
local_id = None
server_url = None
is_op_identifier = False
def preferredNamespace(self):
return self.preferred... |
450852 | import unittest
from unittest.mock import MagicMock
from heap import Heap
class HeapTests(unittest.TestCase):
def setUp(self):
self.heap = Heap()
def test_get_max_works(self):
self.heap.insert(6)
self.heap.insert(8)
self.heap.insert(10)
self.heap.insert(9)
self.heap.insert(1)
self.heap... |
450864 | import sys
sys.path.append('../build/src')
import pypangolin as pango
from OpenGL.GL import *
def a_callback():
print("a pressed")
def main():
win = pango.CreateWindowAndBind("pySimpleDisplay", 640, 480)
glEnable(GL_DEPTH_TEST)
pm = pango.ProjectionMatrix(640,480,420,420,320,240,0.1,1000);
mv = ... |
450865 | import os
import sys
from setuptools import find_packages, setup
try:
from pypandoc import convert
README = convert("README.md", "rst")
except (ImportError, OSError):
README = open(os.path.join(os.path.dirname(__file__), "README.md"), "r").read()
install_requires = ["sqlparse", "wrapt"]
if sys.version_i... |
450905 | from django.contrib.auth import get_user_model
from rest_framework.authtoken.models import Token
from rest_framework import serializers
from notifications.models import Notification
from applications.complaint_system.models import Caretaker, StudentComplain, Supervisor, Workers
from applications.globals.models import E... |
450910 | import os
from os.path import join, exists
import argparse
import pathlib
import click
import numpy as np
import pandas as pd
import scipy.stats
import download_data
import dataframe
import plotter
from plotter import transform_acc, inv_transform_acc
from model_types import ModelTypes, model_types_map, NatModelTypes,... |
450928 | from .argo_client import ArgoClient
from .argo_options import ArgoOptions
from .dsl import CronWorkflow, Workflow, WorkflowTemplate
import argo_workflow_tools.dsl.dsl_decorators as dsl
from .dsl.condition import Condition
from .exceptions.workflow_not_found_exception import WorkflowNotFoundException
from .workflow_resu... |
450993 | from .common import InfoExtractor
class MyChannelsIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?mychannels\.com/.*(?P<id_type>video|production)_id=(?P<id>[0-9]+)'
_TEST = {
'url': 'https://mychannels.com/missholland/miss-holland?production_id=3416',
'md5': 'b8993daad4262dd68d89d651c0c52... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.