id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11597556 | import time
LPWAN_MAC_PATH='/flash/sys/lpwan.mac'
def MAC_to_bytearray(mac):
import struct
mac = mac.replace("-","").replace(":","")
mac = int(mac, 16)
return struct.pack('>Q', mac)
def write_mac(mac):
with open(LPWAN_MAC_PATH, 'wb') as output:
output.write(mac)
time.sleep(0.5)
t... |
11597579 | from app import create_app, db
from app.models import (
User,
ScopeItem,
ConfigItem,
NatlasServices,
AgentConfig,
RescanTask,
Tag,
Agent,
AgentScript,
ScopeLog,
UserInvitation,
)
from app.instrumentation import initialize_sentryio
from sentry_sdk import capture_exception
from... |
11597610 | import os
import shutil
import time
import numpy as np
from baselines import logger
from collections import deque
import tensorflow as tf
from baselines.common import explained_variance, set_global_seeds
from ppo_iter.policies import build_policy
from baselines.common.tf_util import get_session
from baselines.common.mp... |
11597615 | import networkx as nx
import netomaton as ntm
if __name__ == '__main__':
"""
In Smith's Restricted NA Game of Life example, they define an Underlying network that restricts what links can be
formed. Alternatively, one can instead begin with a lattice network, and change the link weights; or, one can add ... |
11597622 | class Solution:
def canCompleteCircuit(self, gas, cost):
tg = tc = md = d = s = 0
for i, (g, c) in enumerate(zip(gas, cost)):
tg += g
tc += c
d = tg - tc
if d < md:
md, s = d, i
return -1 if tc > tg else (s + 1) % len(gas)
|
11597630 | from models import User, WaitingListUser, ActiveChatsUser, db
from campaign import send_campaign
from utilities import send_message
from templates import TextTemplate
import os
import config
APP_URL = os.environ.get('APP_URL', config.APP_URL)
def log_waitlisted_users():
waitlist = WaitingListUser.query.all()
... |
11597692 | from __future__ import absolute_import
from chart_studio.api.v2 import files
from chart_studio.tests.test_plot_ly.test_api import PlotlyApiTestCase
class FilesTest(PlotlyApiTestCase):
def setUp(self):
super(FilesTest, self).setUp()
# Mock the actual api call, we don't want to do network tests he... |
11597725 | import matplotlib.patches as patches
import matplotlib.pyplot as plt
def cal_IOU(bb1, bb2):
i_x1 = max(bb1[0], bb2[0])
i_y1 = max(bb1[1], bb2[1])
i_x2 = min(bb1[2], bb2[2])
i_y2 = min(bb1[3], bb2[3])
i_h = i_y2 - i_y1
i_w = i_x2 - i_x1
if i_h > 0 and i_w > 0:
i = i_h * i_w
... |
11597726 | from .resnet18 import ResNet18
from .wrn import WideResNet
from .densenet import DenseNet3
import torch
def get_network(
name: str, num_classes: int, num_clusters: int = 0, checkpoint: str = None
):
if name == "res18":
net = ResNet18(num_classes=num_classes, dim_aux=num_clusters)
elif name == "wr... |
11597770 | from elasticsearch_dsl import Document, Keyword, Text
class LetterDocument(Document):
title = Text(
analyzer="snowball", required=True, fields={"raw": Keyword()}, term_vector="yes"
)
body = Text(analyzer="snowball", required=True, term_vector="yes")
content = Text(analyzer="snowball", multi=Tr... |
11597823 | import datetime
import time
import os
def log(fileName, line):
f = open(fileName, "a", errors='ignore')
f.write(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') + " " + line + "\n")
f.close()
def readFileContents(fileName):
if(os.path.exists(fileName)):
try:
... |
11597832 | from __future__ import print_function
from __future__ import unicode_literals
import sys
from Registry import *
def rec(key):
for value in key.values():
print("%s : %s : %s" % (key.path(), value.name(), value.value_type_str()))
for subkey in key.subkeys():
rec(subkey)
reg = Registry.Registry... |
11597833 | from django.db import models
from django.db.models import Count, Max, Q, Sum, Case, When, IntegerField, Value
from django.urls import reverse # TODO ideally this shouldn't be in the model
from django.utils import timezone
from django.contrib.auth.models import User
from django.db.models import F
from django.utils.tran... |
11597841 | from django.db import models
from django_serializable_model import SerializableModel
class User(SerializableModel):
email = models.CharField(max_length=765, blank=True)
name = models.CharField(max_length=100)
# whitelisted fields that are allowed to be seen
WHITELISTED_FIELDS = set([
'name',
... |
11597845 | import abc
import numpy as np
class BaseSampler(abc.ABC):
@abc.abstractmethod
def __iter__(self):
pass
def __len__(self):
raise NotImplementedError
class BatchSampler(BaseSampler):
def __init__(self, dataset, batch_size, shuffle=True):
self.dataset = dataset
self.bat... |
11597855 | from copy import deepcopy
from agent import pipeline, source, di
from agent.modules import logger
logger_ = logger.get_logger('scripts.upgrade.3.13.0', stdout=True)
di.init()
for pipeline_ in pipeline.repository.get_by_type(source.TYPE_INFLUX):
logger_.info(f'Updating `{pipeline_.name}` pipeline')
values = {... |
11597858 | for row in range(7):
for col in range(7):
if (col == 0) or (col == 6 and (row != 0 and row != 3 and row != 6)) or ((row == 0 or row == 3 or row == 6) and (col > 0 and col < 6)):
print("*", end="")
else:
print(end=" ")
print() |
11597934 | import logging
import os
from piplapis.data import Person, Email, Name, URL, Username, UserID, Image, Phone, Address, OriginCountry, Language, \
DOB, Gender
from piplapis.data.containers import Relationship
from piplapis.search import SearchAPIRequest, SearchAPIResponse
from unittest import TestCase
# Tests for t... |
11597948 | from excel4lib.utils import *
from excel4lib.sheet.cell import *
from excel4lib.lang import *
from .excel4_name import *
class Excel4Instruction(Cell):
'''
Represents Excel4 instruction (could be formula, empty cell, variable, obfuscated formula) which should be placed
at specified address.
Excel4Instr... |
11598014 | class Motor:
# membuat variabel yang bersifat private
__kecepatan = 0
def __init__(self):
# memasukkan value dalam variabel kecepatan
self.__kecepatan = 120
# membuat fungsi untuk memanggil variabel
# dari kecepatan
def jalan(self):
print("jalan dengan kecepatan {} km".... |
11598078 | import FWCore.ParameterSet.Config as cms
from RecoBTag.SecondaryVertex.inclusiveSecondaryVertexFinderFilteredTagInfos_cfi import *
inclusiveSecondaryVertexFinderFilteredNegativeTagInfos = inclusiveSecondaryVertexFinderFilteredTagInfos.clone(
extSVDeltaRToJet = -0.4,
vertexCuts = dict(distVal2dMin = -2.5,
... |
11598103 | import os
import nltk
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('averaged_perceptron_tagger')
path = 'data/external/nltk_download_SUCCESS'
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w') as f:
f.write('Downloaded nltk: stopwords, punkt, wordnet'... |
11598212 | import wave
import sys
import struct
import time
import subprocess
import threading
import traceback
import shlex
import os
import string
import random
import datetime as dt
import numpy as np
import scipy as sp
import scipy.special
from contextlib import closing
from argparse import ArgumentParser
from pyoperant impor... |
11598214 | import os
import json
import logging
from fnmatch import fnmatch
from pathlib import Path
from version import VERSION
from typing import List
import mypy.stubgen as stubgen
import sys
log = logging.getLogger(__name__)
STUB_FOLDER = "./all-stubs"
def clean_version(version: str, build: bool = False):
"omit the ... |
11598274 | import os
import stat
import sys
_PATH = os.environ.get('PATH', '').split(os.pathsep)
_IS_WINDOWS = sys.platform.lower().startswith('win')
def is_executable(p, *path):
path = os.path.join(p, *path)
return os.path.exists(path) and \
not os.path.isdir(path) and \
os.stat(path)[stat.ST_MODE] & stat.S_IXUSR
... |
11598304 | r"""
.. codeauthor:: <NAME> <<EMAIL>>
This module handles the boundaries of a single axis of a grid. There are
generally only two options, depending on whether the axis of the underlying
grid is defined as periodic or not. If it is periodic, the class
:class:`~pde.grids.boundaries.axis.BoundaryPeriodic` should be use... |
11598310 | import argparse
import re
import sys
import logging
from datetime import datetime
import hashlib
import gzip
import requests
import os
import json
import time
from splunk_http_event_collector import http_event_collector
from helpers.certparser import process_cert
from helpers.hostparser import proccess_host
def proce... |
11598318 | from tick.plot import plot_hawkes_kernels
from tick.hawkes import SimuHawkesExpKernels, SimuHawkesMulti, HawkesExpKern
import matplotlib.pyplot as plt
end_time = 1000
n_realizations = 10
decays = [[4., 1.], [2., 2.]]
baseline = [0.12, 0.07]
adjacency = [[.3, 0.], [.6, .21]]
hawkes_exp_kernels = SimuHawkesExpKernels(... |
11598347 | from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.framework import ops
from tensorflow.python.eager import context
from tensorflow.python.framework import dtypes
from ... |
11598391 | import jsonlines
import argparse
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument("--corpus", type=str, default="../scifact/data/corpus.jsonl")
parser.add_argument("--claims", type=str, default="../scifact/data/claims_train.jsonl")
parser.add_argument("--t5_input", type=str, required=True)
... |
11598392 | from typing import Tuple
import plotly.express as px
def hex_to_rgb(hex_string: str) -> Tuple[int, int, int]:
"""
Converts a hex_string to a tuple of rgb values.
Requires format including #, e.g.:
#000000
#ff00ff
"""
if len(hex_string) != 7:
raise ValueError(f"Invalid length for #{... |
11598425 | import requests
# from: http://www.omdbapi.com/
title_text = input("Enter a title search string: ")
url = 'http://www.omdbapi.com/?y=&plot=short&r=json&s={}'.format(title_text)
# process json-> Search -> Title
resp = requests.get(url)
if resp.status_code != 200:
print("Whoa, status code unexpected! {}".format(res... |
11598429 | import ctypes
import numpy as np
import os
import subprocess
import tempfile
import tvm
from tvm import relay, get_global_func, target, register_func
from tvm.relay.function import Function
from tvm.relay.expr import Expr, Let, GlobalVar
from tvm.relay.adt import Constructor
from tvm.relay.expr_functor import ExprFunct... |
11598446 | from enum import Enum
from typing import List, Optional, Tuple
import faiss
import numpy as np
import torch
import typer
from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizer
from semantic_search.schemas import Document
from semantic_search.ncbi import uids_to_docs
UID = str
class ... |
11598511 | import os
import uuid
import time
import json
import sys
import logging
import pymysql
import boto3
import base64
from botocore.exceptions import ClientError
from typing import Optional
from fastapi import FastAPI
_log_level = logging.INFO
logger = logging.getLogger()
logger.setLevel(_log_level)
log_handler = logging.... |
11598515 | import pandas as pd
data = [
['The', 'Business', 'Centre', '15', 'Stevenson', 'Lane'],
['6', 'Mossvale', 'Road'],
['Studio', '7', 'Tottenham', 'Court', 'Road']
]
class Address(object):
def __init__(self, *address):
if not address:
self.address = None
print('No address g... |
11598543 | from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from newsSpiders.items import ArticleItem, ArticleSnapshotItem
from newsSpiders.helpers import generate_next_snapshot_time
import zlib
import time
class BasicDiscoverSpider(CrawlSpider):
name = "basic_discover"
def _... |
11598573 | from copy import deepcopy
import numpy as np
import torch
from numpy.fft import *
def bandpass_filter(im: torch.Tensor, band_center=0.3, band_width_lower=0.1, band_width_upper=0.1):
'''Bandpass filter the image (assumes the image is square)
Returns
-------
im_bandpass: torch.Tensor
B, C, H, ... |
11598609 | from keras.models import Model
from keras.layers import Input, Dense, Dropout, Concatenate, Activation
from keras.optimizers import Adam
from utils import *
#------------------------------------------------------------------------------
def siamese_model():
input1 = (image_size_h_p,image_size_w_p,nchannels)
... |
11598644 | from collections import namedtuple
from typing import NamedTuple, Any
class LogOptions(NamedTuple):
overwrite: bool = None
write_mode: str = None
class LogEntry(NamedTuple):
key: str
data: Any
type: str
options: LogOptions = None
class LoadEntry(NamedTuple):
key: str
type: str
... |
11598646 | from django.apps import AppConfig
from lims.plugins.mounts import load_plugins
class PluginsConfig(AppConfig):
name = 'lims.plugins'
verbose_name = 'Plugins'
def ready(self):
load_plugins()
|
11598648 | import unittest
from passlib.hash import bcrypt
import fabfile
import models
import settings
import utils
class TestUserModel(unittest.TestCase):
user_dict = None
user = None
def setUp(self):
users = fabfile.load_users()
self.user_dict = users[0]
self.user = models.User(self.user... |
11598674 | from html import escape
from decimal import Decimal
def html_escape(arg):
return escape(str(arg))
def html_int(a):
return f'{a}(<i>{str(hex(a))}</i>)'
def html_real(a):
return f'{round(a, 2):.2f}'
def html_str(s):
return html_escape(s).replace('/n', '<br/>\n')
def html_list(l):
items = (f'... |
11598744 | import os
def relative_path(base, file):
# https://stackoverflow.com/questions/4060221 for more options
return os.path.join(os.path.dirname(base), file)
class ResourceLoader():
'''
Mixin which provides JS and CSS for apps.
'''
def load_resources(self):
self._css_urls = [
... |
11598754 | from canvas.util import base36decode, Base36DecodeException
from services import Services
from apps.share_tracking.models import ShareTrackingUrl
class TrackShareViewsMiddleware(object):
def process_request(self, request):
share_b36 = request.GET.get('s')
if not share_b36:
return
... |
11598767 | import math
import torch
import torch.nn as nn
from torch.autograd import Variable
from cuda import try_cuda
from attentions import WhSoftDotAttention
from context_encoder import ContextEncoder
class PositionalEncoding(nn.Module):
def __init__(self, d_model, dropout, max_len):
super(PositionalEncoding, self)._... |
11598770 | from app.models.apply import GoingoutApplyModel
from tests.v2.views import TCBase
class TestGoingoutApplyInquire(TCBase):
"""
외출신청 정보 조회를 테스트합니다.
"""
def __init__(self, *args, **kwargs):
super(TestGoingoutApplyInquire, self).__init__(*args, **kwargs)
self.method = self.client.get
... |
11598791 | import __init__
import redis
from Kite import config
from Killua.denull import DeNull
from Killua.deduplication import Deduplication
from Gon.nbdspyder import NbdSpyder
redis_client = redis.StrictRedis(config.REDIS_IP,
port=config.REDIS_PORT,
db=c... |
11598809 | p = [2,3,5,7,11]
l = []
up = 1
for x in p:
up *= x
for i in xrange(1, up+1):
flag = True
for j in p:
if i % j == 0:
flag = False
break
if flag:
l.append(i)
print l
print len(l)
|
11598820 | import optparse
parser = optparse.OptionParser(
usage='%prog COMMAND [OPTIONS]',
version="x.x.x",
add_help_option=False)
parser.add_option(
'-h', '--help',
dest='help',
action='store_true',
help='Show help')
parser.disable_interspersed_args()
|
11598845 | import pipert.core.shared_memory_generator as sm
from pipert.core.shared_memory_generator import get_shared_memory_object
class DummySharedMemoryGenerator(sm.SharedMemoryGenerator):
def __init__(self):
super().__init__("dummy_component", max_count=5)
self.create_memories()
def test_cleanup():
... |
11598893 | from neukivy.app import NeuApp
from kivy.lang import Builder
from kivy.animation import Animation
kv_string = """
Screen:
canvas:
Color:
rgba:app.theme_manager._bg_color_alp
Rectangle:
size:self.size
pos:self.pos
NeuCircularIconButton:
id:button
... |
11598902 | from functools import partial
import pickle
import multiprocessing as mp
from multiprocessing.pool import ThreadPool
import traceback
import numpy as np
import pandas as pd
from sklearn.externals import joblib
from sklearn.linear_model import Lasso
from mercari.config import \
DUMP_DATASET, USE_CACHED_DATASET, DE... |
11598929 | import torch
from torch import nn, Tensor, cos
from ..utils import to_onehotv2
__all__ = ['ZeroCenterRelu', 'LWTA', 'Snake']
class ZeroCenterRelu(nn.ReLU):
"""
As described by Jeremy of FastAI
"""
def __init__(self, inplace: bool=False):
super(ZeroCenterRelu, self).__init__(inplace)
def... |
11598942 | import requests
from requests.auth import HTTPBasicAuth
from insightconnect_plugin_runtime.exceptions import PluginException
from json import JSONDecodeError
class ProofpointTapApi:
def __init__(self, service_principal: dict, secret: dict):
self.base_url = "https://tap-api-v2.proofpoint.com/v2/"
i... |
11598943 | from .signed_object import SignedObject
from .experiments_path_controller import ExperimentsPathController
from .signature_scraper import SignatureScraper
|
11598952 | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField,SubmitField,TextAreaField,FormField,SelectField
from wtforms.validators import DataRequired, EqualTo, length, regexp, optional, ValidationError
import re
isbn_regex = '^[0-9]{13}$'
book_id_regex = '^[0-9]{16}$'
user_id_regex ... |
11598953 | import sys
if sys.version_info >= (3, 10): # pragma: no cover
from importlib import metadata
else: # pragma: no cover
import importlib_metadata as metadata
import pytest
from .sensor.test_sensor import GoodData
sem_ver: str = metadata.version("PyPMS")
version = tuple(int(v) for v in sem_ver.split("."))
... |
11598971 | import requests
from bs4 import BeautifulSoup
try:
from urlparse import urljoin
except ImportError:
from urllib.parse import urljoin
from pyoembed.exceptions import ProviderException
from pyoembed.providers import BaseProvider
class AutoDiscoverProvider(BaseProvider):
priority = 99999999 # should be t... |
11599034 | import os
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
experiment_base_folder = '/itet-stor/baumgach/net_scratch/logs/phiseg/lidc/'
experiment_list = ['probunet',
'phiseg_7_1',
'phiseg_7_5',
... |
11599107 | import streamlit.util as util
def test_repr_simple_class():
class Foo:
def __init__(self, foo, bar=5):
self.foo = foo
self.bar = bar
def __repr__(self):
return util.repr_(self)
foo = Foo("words")
assert repr(foo) == "Foo(foo='words', bar=5)"
def test... |
11599138 | from insights.tests import context_wrap
from insights.parsers.greenboot_status import GreenbootStatus
GREEN = """
Boot Status is GREEN - Health Check SUCCESS
"""
RED = """
Mar 04 15:47:12 example greenboot[768]: Script 'check-dns.sh' SUCCESS
Mar 04 15:47:12 example required-services.sh[999]: active
Mar 04 15:47:12 e... |
11599177 | import numpy as np
import numba
"""
lineshapes.py
Module for defining line shape functions. The two that
are explicitly coded are Gaussian and Lorentizan functions,
and derivatives of these are calculated analytically
using SymPy.
When available, use the lmfit built-in functions for
lines... |
11599180 | from typing import Dict, Union
from collections import Counter
from spacy.tokens import Doc
from .constants import BASIC_STATS_DESC, COMPLEX_SYL_FACTOR, PUNCTUATIONS, RU_LETTERS, SPACES
from .extractors import SentsExtractor, WordsExtractor
from .utils import count_syllables
class BasicStats(object):
"""
К... |
11599218 | from typing import Callable, Any
from .core_functions import quick_fn, to_callable
from .fn import fn
from .._toolz import compose as _compose, juxt as _juxt
from ..typing import Func, TYPE_CHECKING
if TYPE_CHECKING:
from .. import api as sk # noqa: F401
from ..api import X, op # noqa: F401
@fn
def compos... |
11599236 | import pickle
from itertools import combinations_with_replacement as comb_w_r
import numpy as np
import tensorflow as tf
class TensorMinMax:
"""Copy of sklearn's MinMaxScaler implemented to work with tensorflow.
When used, tensorflow is able to take gradients on the transformation as
well as on the netw... |
11599247 | from django.apps import apps
from django.utils.html import mark_safe
from mako.exceptions import RichTraceback
from mako.template import Template as MakoTemplate
from mako.runtime import Context as MakoContext, _populate_self_namespace
import io
import os, os.path
def template_inheritance(obj):
'''
Generator... |
11599283 | import pytest
from virtool.users.utils import PERMISSIONS
@pytest.fixture
def bob(no_permissions, static_time):
return {
"_id": "abc123",
"handle": "bob",
"administrator": False,
"force_reset": False,
"groups": ["peasants"],
"last_password_change": static_time.date... |
11599288 | import numpy as np
import os
import pandas as pd
from snorkel.labeling import PandasLFApplier
from synthesizer.parser import nlp
from config import DATASETS_PATH
from config import DEFAULT_MAX_TRAINING_SIZE
from config import MIN_LABELLED_SIZE
from config import PROCESSED_FILE_NAME
ALLOWED_EXTENSIONS = {'csv'}
def ... |
11599305 | from unittest.mock import patch, MagicMock
from rest_framework.reverse import reverse
from rest_framework.status import (
HTTP_200_OK,
HTTP_204_NO_CONTENT,
HTTP_206_PARTIAL_CONTENT,
HTTP_400_BAD_REQUEST,
HTTP_401_UNAUTHORIZED,
)
from authy.api.resources import User
from rest_framework.test import ... |
11599320 | from typing import List, Optional, Tuple
from PyQt5.QtGui import QColor
from brainframe.api.bf_codecs import Detection
from brainframe_qt.ui.resources.config import RenderSettings
from brainframe_qt.ui.resources.video_items.base import LabelItem, VideoItem
class DetectionLabelItem(LabelItem):
MIN_WIDTH = 150
... |
11599357 | import random
from collections.abc import Iterable
from uninas.optimization.hpo.uninas.candidate import Candidate
from uninas.optimization.hpo.uninas.values import ValueSpace
class Crossover:
def __init__(self, value_space: ValueSpace, fixed_num_crossover: int = None):
self.value_space_size = value_space.... |
11599377 | import copy
import logging
import numpy as np
from matminer.datasets import get_all_dataset_info
from matminer.featurizers.conversions import (
StrToComposition,
StructureToComposition,
)
from monty.json import MSONable
from matbench.constants import (
CLF_KEY,
CLF_METRICS,
FOLD_DIST_METRICS,
... |
11599402 | from __future__ import annotations
import itertools
import re
from collections import defaultdict
from configparser import ConfigParser
from typing import Callable, Mapping
from .requires import requires
from .util import fix_and_reorder, is_substitute, to_boolean
def format_test_env(parser: ConfigParser, name: str... |
11599449 | from .inference import *
from .model_selection import *
from .objective_functions import ObjectiveFunction
from .objective_functions import TraditionalUnnormalizedLogLikelyhood
from .objective_functions import TraditionalMicrocanonicalEntropy
from .objective_functions import DegreeCorrectedUnnormalizedLogLikelyhood
fro... |
11599487 | import numpy as np
import scipy.sparse as sp
import sklearn
import sklearn.metrics
import torch
import pandas as pd
import random
def boolean_string(s):
if s not in {'False', 'True'}:
raise ValueError('Not a valid boolean string')
return s == 'True'
def encode_onehot(labels):
classes = set(labels)... |
11599490 | class EvaluateConfig:
def __init__(self):
self.game_num = 400
self.replace_rate = 0.55
self.play_config = PlayConfig()
self.play_config.simulation_num_per_move = 200
self.play_config.thinking_loop = 1
self.play_config.c_puct = 1
self.play_config.change_tau_tur... |
11599497 | import collections
class FirstUnique:
def __init__(self, nums: List[int]):
self.table = collections.Counter(nums)
self.Q = collections.deque(nums)
def showFirstUnique(self) -> int:
while self.Q and self.table[self.Q[0]] > 1:
self.Q.popleft()
return self.Q[0] if self... |
11599503 | from ninja import Body, Form, NinjaAPI
from ninja.testing import TestClient
api = NinjaAPI()
# testing Body marker:
@api.post("/task")
def create_task(request, start: int = Body(...), end: int = Body(...)):
return [start, end]
@api.post("/task2")
def create_task2(request, start: int = Body(2), end: int = Form... |
11599516 | import os
import json
"""
Details of models for the simulated eval.
"""
LOG_PATH = 'logs'
MANIFEST_PATH = LOG_PATH + '/manifest.json'
def check_args(cfg, **kwargs):
good = True
for val in cfg.values():
if val is None:
good = False
break
good = good and os.path.isfile(cfg['log'])
if not good:
... |
11599591 | import collections
import functools
import operator
from typing import Any, Callable, Tuple
from river import utils
__all__ = ["NearestNeighbors", "MinkowskiNeighbors"]
DistanceFunc = Callable[[Any, Any], float]
class NearestNeighbors:
"""A basic data structure to hold nearest neighbors.
Parameters
--... |
11599604 | import pygame
import random
import time
import math
import pygame.gfxdraw
# knob1 = x pos ; knob2 = y pos ; knob3 = length ; knob4 = color select
def setup(screen, etc):
pass
def draw(screen, etc):
etc.color_picker_bg(etc.knob5)
yr = etc.yres
xr = etc.xres
sel = etc.knob4*5
i = ((180*yr)/720)
... |
11599652 | import config.config as config
import termcolor
import sys
import os
output = config.output_dir
try:
sys.argv[1]
if sys.argv[1] == "--new":
try:
sys.argv[2]
try:
sys.argv[3]
if sys.argv[3] == "--fa":
os.system(f"mkdir {... |
11599675 | def minimumSwaps(arr):
count = 0
for i in range(len(arr)):
while arr[i] != i+1:
temp = arr[i];
arr[i] = arr[temp-1];
arr[temp-1] = temp;
count +=1;
return count;
n=int(input())
a=list(map(int,input().split()))
print(minimumSwaps(a)) |
11599699 | import sys
import os, errno
import logging
#-----------------------------------------------------------------------------------------------------------#
def set_logger(out_dir=None):
console_format = BColors.OKBLUE + '[%(levelname)s]' + BColors.ENDC + ' (%(name)s) %(message)s'
#datefmt='%Y-%m-%d %Hh-%Mm-%Ss'
logge... |
11599717 | from django.test import TestCase
from pydis_site.apps.resources.templatetags.to_kebabcase import _to_kebabcase
class TestToKebabcase(TestCase):
"""Tests for the `as_css_class` template tag."""
def test_to_kebabcase(self):
"""Test the to_kebabcase utility and template tag."""
weird_input = (
... |
11599737 | import pysam
import pathlib
import tempfile
import shutil
def get_read_zmw_counts(file):
bf = pysam.Samfile(file, 'rb', check_sq=False)
zmw_counts = {}
for read in bf:
zmw = read.get_tag("zm")
zmw_counts[zmw] = zmw_counts.get(zmw, 0) + 1
bf.close()
return zmw_counts
def test_s... |
11599757 | from shexer.utils.factories.triple_yielders_factory import get_triple_yielder
from shexer.core.class_profiler import ClassProfiler
def get_class_profiler(target_classes_dict, source_file, list_of_source_files, input_format,
instantiation_property_str,
namespaces_to_ignore... |
11599782 | import math
import keras
from keras.optimizers import SGD, adadelta, rmsprop, adam
from keras.preprocessing.image import ImageDataGenerator
from keras.utils import np_utils
from keras.metrics import matthews_correlation, precision, recall
import keras.backend as K
import cPickle
import numpy as np
import getpass
user... |
11599791 | import math
import collections
class Solution:
"""
@param ring: a string
@param key: a string
@return: return a integer
"""
def findRotateSteps(self, ring, key):
# write your code here
table = collections.defaultdict(list)
for i, c in enumerate(ring):
table[c]... |
11599799 | import os
import requests
import unittest
from random import choice
from string import ascii_letters
from pyupload.uploader import *
def generate_random_file_content():
result = ''
for _ in range(30):
result += choice(ascii_letters)
return result
class TestUploadMethods(unittest.TestCase):
... |
11599829 | from __future__ import print_function
from awesome_thirdparty_library import AwesomeClass
import Pyro4
# expose the class from the library using @expose as wrapper function:
ExposedClass = Pyro4.expose(AwesomeClass)
with Pyro4.Daemon() as daemon:
# register the wrapped class instead of the library class itself... |
11599879 | import numpy as np
import glob
import multiprocessing
import os
import tensorflow as tf
from tf_model import load_one_file
def parse_args():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--target", type=str, choices=["cand", "gen"], help="Regress to PFCandidates or GenParticles",... |
11599895 | import json
import logging
import unicodedata
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
import requests
from bs4 import BeautifulSoup
from utils.constants import HEADERS, LOGFILE_PATH
from utils.reception import Reception
def normalize(text):
"""Normalizes the provided tex... |
11599935 | import logging
import tempfile
import os
import torch
from collections import OrderedDict
from tqdm import tqdm
from lvis import LVIS, LVISResults, LVISEval, LVISEvalPerCat
from maskrcnn_benchmark.modeling.roi_heads.mask_head.inference import Masker
from maskrcnn_benchmark.structures.bounding_box import BoxList
from ma... |
11599959 | from typing import Sequence
from ..simai import (
SimaiChart,
pattern_from_int,
)
from ..maima2 import MaiMa2, TapNote, HoldNote, SlideNote, TouchTapNote, TouchHoldNote
from ..event import MaiNote, NoteType
def ma2_to_simai(ma2: MaiMa2) -> SimaiChart:
simai_chart = SimaiChart()
for bpm in ma2.bpms:
... |
11599973 | from rest_framework.routers import Route
from rest_framework_nested.routers import NestedDefaultRouter
class NestedStorageRouter(NestedDefaultRouter):
routes = [
# Detail route without identifier. Viewset must override get_object to work correctly.
Route(
url=r'^{prefix}{trailing_slash... |
11599986 | import pandas as pd
from PIL import Image
import numpy as np
import keras
from math import floor
import random
from random import shuffle
from sklearn.model_selection import train_test_split
from keras import regularizers
from keras.callbacks import ModelCheckpoint
from keras.models import Sequential
from keras.mode... |
11599999 | import os
import pytest
import unittest
from sacrerouge.commands.correlate import aggregate_metrics
from sacrerouge.data import Metrics
from sacrerouge.io import JsonlReader
_metrics_A_file_path = 'datasets/duc-tac/tac2010/v1.0/task1.A.metrics.jsonl'
_metrics_B_file_path = 'datasets/duc-tac/tac2010/v1.0/task1.B.metri... |
400010 | import pytest
import torch
import pyro
import pyro.distributions as dist
import pyro.poutine as poutine
from pyro.util import set_rng_seed
from tests.common import assert_equal
EXAMPLE_MODELS = []
EXAMPLE_MODEL_IDS = []
class ExampleModel(object):
def __init__(self, fn, poutine_kwargs):
self.fn = fn
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.