id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9830679 | import time
import torch
import sys
def show_progress_bar(epo, current_batch, total_batch, time_start, time_current, data_string):
sys.stdout.write('\r')
hours, rem = divmod(time_current - time_start, 3600)
minutes, seconds = divmod(rem, 60)
rate = int(40 * current_batch / total_batch)
progress = ... |
9830727 | import numpy as np
from keras.callbacks import ModelCheckpoint
from keras.callbacks import EarlyStopping
from keras.callbacks import ReduceLROnPlateau
from keras.optimizers import Adam
from model import get_model
from data import get_train_data
from metrics import dice_coef, dice_coef_loss
from all_params import *
X_t... |
9830767 | from pymongo import MongoClient
from unittest import TestCase
from algotrader.utils.protobuf_to_dict import *
from tests.sample_factory import *
class MongoPersistenceTest(TestCase):
host = "localhost"
port = 27017
dbname = "test"
client = None
db = None
@classmethod
def setUpClass(cls):... |
9830780 | import numpy as np
def get_f1(key, prediction):
correct_by_relation = ((key == prediction) & (prediction != 0)).astype(np.int32).sum()
guessed_by_relation = (prediction != 0).astype(np.int32).sum()
gold_by_relation = (key != 0).astype(np.int32).sum()
prec_micro = 1.0
if guessed_by_relation > 0:
... |
9830783 | import sys
import json
predict = open(sys.argv[1])
features = open(sys.argv[2] + 'Processed/Card3Processed.txt')
targetFea = {}
students = features.readlines()
for each in students:
featureDict = json.loads(each)
targetFea[featureDict['stuId']] = featureDict['if_change_card']
count = 0
countAll = 0
countNotIn... |
9830859 | import os
import unittest
from test import support
from test.support import import_helper
# skip tests if _ctypes was not built
ctypes = import_helper.import_module('ctypes')
ctypes_symbols = dir(ctypes)
def need_symbol(name):
return unittest.skipUnless(name in ctypes_symbols,
'{!r... |
9830881 | import numpy as np
from numpy import sqrt, empty, zeros, empty_like, zeros_like
from numba import njit, prange
from .kernel import *
def PotentialTarget_bruteforce(x_target, softening_target, x_source, m_source, softening_source,G=1.):
"""Returns the exact gravitational potential due to a set of particles, at a s... |
9830916 | from qtpy import uic
from qtpy.QtWidgets import QWidget, QApplication, QTableWidgetItem
from qtpy.QtCore import Qt, PYQT_VERSION_STR, qVersion
from .about_ui import Ui_Form
from numpy import __version__ as numpyver
from pyqtgraph import __version__ as pyqtgraphver
import pydm
import sys
from os import path
import inspe... |
9830917 | import json
import httpretty
import pytest
from instagram_api.constants import Constants
@pytest.fixture(scope='session')
def base_uri(request):
for key, value in Constants.API_URLS.items():
Constants.API_URLS[key] = value.replace('https', 'http')
return Constants.API_URLS[1]
|
9830942 | class Ec2Catalog:
"""
download ec2 catalog: 2 columns: ec2 type, ec2 cost per hour
"""
def __init__(self, allow_ec2_different_family):
self.allow_ec2_different_family = allow_ec2_different_family
def handle_pre(self, context_pre):
import requests
from cachecontrol import CacheControl
from cac... |
9830945 | from stable_baselines3.ppo.ppo import PPO
from algorithms.common.extractors import AugmentHybridCnnExtractor
from algorithms.common.models.cnn import cnn_registry
from algorithms.ppo_pixel.ppo_pixel_policy import MultiviewAugmentPpoPolicy
from experiments.common.base_config import ppo_pixel_config_registry
from experim... |
9830994 | from typing import Optional
from fastapi import FastAPI, Request, Response
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from datetime import datetime
from bs4 import BeautifulSoup
import httpx
import sys
from random import random
from math import log
import simplejson as json
import url... |
9831000 | from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from faker import Faker
from gdpr.models import LegalReason
from germanium.tools import assert_equal, assert_not_equal, assert_true, assert_raises
from tests.models import Account, Customer, Email, Payment
from tests.purposes i... |
9831004 | import time
import numpy as np
class KalmanFilterPixel:
def __init__(self, ax, ay, rx, ry, px0, py0, pu0, pv0):
"""
Linear Kalman filter for single pixel tracking. It assumes a constant velocity model.
The state vector is (x, y, u, v) where (x, y) is the pixel position and (u, v) is ... |
9831013 | import pygame as pg
import random as rnd
def zeichne_brett(board):
br = hö = raster - rand
for ze,sp in board:
x, y = ze*raster+rand, sp*raster+rand
pg.draw.rect(screen, farben[board[(ze,sp)]], (x, y, br, hö), border_radius=15)
if board[(ze,sp)] == 0: continue
zeichne_text(str(board[(ze,sp)]), ras... |
9831075 | from torch import Tensor
from torch.autograd import Variable
from torch.optim import Adam
from models import *
from misc import *
class DDPG():
def __init__(self, actor_input_dim, actor_output_dim, critic_input_dim, hidden_dim, lr):
self.policy = MLP(actor_input_dim, actor_output_dim, hidden_dim)
... |
9831083 | import platform
import os
# ok, I don't want this to work in travis.ci env or on anything other than linux
try:
if 'CI' in os.environ or platform.system() != 'Linux':
raise ImportError()
import Adafruit_GPIO.SPI as SPI
except ImportError:
class SPI(object):
MSBFIRST = 1
class SpiDev(object):
def __init__(s... |
9831085 | from typing import Optional
from aiogram.types import ContentType
from cachetools import LRUCache
from ..manager.protocols import MediaIdStorageProtocol
class MediaIdStorage(MediaIdStorageProtocol):
def __init__(self, maxsize=10240):
self.cache = LRUCache(maxsize=maxsize)
async def get_media_id(
... |
9831089 | from ruleblock import RuleBlock
__author__ = ''
class System(object):
"""
Base class for fuzzy inference system
Holds all stuff together (predicates, rules, ...)
"""
__slots__ = ('name', 'blocks')
def __init__(self, name, *blocks):
"""
Initialize a fuzzy system
... |
9831098 | import copy
import logging
import os
import shutil
import subprocess
import pysam
import pysam.bcftools
from cluster_vcf_records import variant_tracking, vcf_file_read
from varifier import global_align, dnadiff, probe_mapping, utils
def _check_dependencies_in_path():
programs = ["minimap2", "paftools.js", "k8"... |
9831101 | class ProgressionClass:
def __init__(self):
self.s = 0
def get_sum(self):
return self.s
def calculate(self):
...
def info(self):
...
|
9831117 | import torch
from nequip.data import AtomicDataDict
from nequip.nn import GraphModuleMixin
class SaveForOutput(torch.nn.Module, GraphModuleMixin):
"""Copy a field and disconnect it from the autograd graph.
Copy a field and disconnect it from the autograd graph, storing it under another key for inspection as... |
9831128 | import torch
from torch import nn
from ..backbone.utils import conv3x3
from .base import SegBaseModule
__all__ = ["GCN"]
class GCNModule(nn.Module):
def __init__(self, in_ch, out_ch, k):
super(GCNModule, self).__init__()
padding = (k - 1) // 2
self.gcn1 = nn.Sequential(
nn.Con... |
9831175 | import sys
import os
class LS:
def __repr__(self):
self.__call__()
return ""
def __call__(self, path="."):
l = os.listdir(path)
l.sort()
for f in l:
st = os.stat("%s/%s" % (path, f))
if st[0] & 0x4000: # stat.S_IFDIR
print(" <... |
9831275 | import torch
import numpy as np
from models import MainModel
from losses_metrics import TotalLoss
from tqdm import tqdm
def data_augmentation(img, flip_v, flip_h):
axis = []
if flip_v:
axis.append(2)
if flip_h:
axis.append(3)
if len(axis):
img = torch.flip(img, axis)
ret... |
9831279 | def generate_random_string(rng):
return ''.join(rng.choice('abcdefg098765$&.()[]{}\n') for _ in range(rng.randint(0, 6)))
def generate_random_json(rng, max_depth=4, sets=False, hashable=False):
types = [None, bool, float, str]
if max_depth > 1:
types += [tuple]
if not hashable:
... |
9831302 | from twisted.names import dns
# Adapted from https://github.com/ajxchapman/ReServ/blob/5d95950a26e7d97f387872b6d49db2c3b2a8c57e/servers/dns.py#L17
class Record_CAA:
TYPE = 257
fancybasename = 'CAA'
def __init__(self, value, ttl=None):
self.flags = 0
self.tag = 'issue'
self.value =... |
9831320 | import pytest
from tests.factory.form import BaseFormFactory
from wagtailformblocks.blocks import FormChooserBlock, WagtailFormBlock
@pytest.mark.django_db
def test_wagtail_form_block_with_parent_context():
form = BaseFormFactory()
block = WagtailFormBlock()
parent_context = {'parent_context': 1}
ctx... |
9831329 | import unittest
from exporters.progress_callback import (
FtpDownloadProgress,
FtpUploadProgress,
BotoUploadProgress,
)
class FakeLogger(object):
def __init__(self):
self.messages = []
def info(self, mesg):
self.messages.append(mesg)
class ProgressCallbackTest(unittest.TestCase)... |
9831363 | import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
filepath='../all_ages_genders.txt'
datas=open(filepath,'r').readlines()
tips=pd.read_csv('age_sex.csv')
tips["sex"] = pd.Categorical(tips["gender"], tips["gender"].unique())
def getthings(datas):
name=[da.split('\t')[0] for... |
9831452 | from yarl import URL
def latest_request(mocked, request_type, path):
return mocked.requests.get((request_type, URL(path)))
def json_of_latest_request(r):
return r[-1].kwargs["json"]
|
9831464 | import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
# 0: tokens, 1: pos, 2: mask_s, 3: labels
class JointClassifier(nn.Module):
def __init__(self, args, emb_matrix=None):
super().__init__()
self.args = args
se... |
9831473 | import pandas as pd
from pmlb import fetch_data, nearest_datasets
def test_nearest_dataset_is_itself():
"""Tests whether the nearest dataset is itself"""
for test_dataset in ['lupus', 'analcatdata_aids', 'car']:
df = fetch_data(test_dataset, local_cache_dir='../datasets/')
nearest = nearest_d... |
9831498 | from functools import wraps
import time
from bamboo.config.settings import RUN_PROFILER
from bamboo.lib.async import set_async
def requires_async(func):
@wraps(func)
def wrapper(*args, **kwargs):
set_async(True)
result = func(*args, **kwargs)
set_async(False)
return result
... |
9831514 | import json
import os
from pathlib import Path
from typing import TextIO
env_dir = Path(__file__).absolute().parents[1] / 'modelci'
def _decode_dotenv(env_file: TextIO):
lines = env_file.readlines()
env_data = dict()
for line in lines:
key, value = line.strip().split('=')
env_data[key] =... |
9831530 | import base64
num = 0
count = 0
cipher_b64 = b"<KEY>
def a(num):
if (num > 1):
for i in range(2,num):
if (num % i) == 0:
return False
break
return True
else:
return False
def b(num):
my_str = str(num)
rev_str = reversed(my_str)... |
9831533 | import pandas as pd
import time
from datetime import datetime
from datetime import timedelta
import numpy as np
import os
import glob
import re
import mysql.connector
import pyodbc
import argparse
from mktcalendar import *
def add_mktcap(uni_df, price_df, start, end, out_dir):
date = end - TDay
sql = ("SELECT... |
9831550 | from playhouse.tests.base import database_class
from playhouse.tests.base import ModelTestCase
from playhouse.tests.base import test_db
from playhouse.tests.models import *
class TestMetadataIntrospection(ModelTestCase):
requires = [
User, Blog, Comment, CompositeKeyModel, MultiIndexModel, UniqueModel,
... |
9831591 | from datetime import datetime
from hooks.db.hive_helper import HiveHelper
class ImpalaHelper(HiveHelper):
__slots__ = ('hive_conn', 'kerberos_service_name', 'kerberos_service_name')
def __init__(
self,
hive_conn: str = 'impala',
kerberos_service_name: str = 'impala',
*args,
... |
9831595 | import collections
import datetime as dt
from abc import ABC, abstractmethod
from dataclasses import replace
from enum import Enum
from pathlib import Path
from textwrap import dedent
from typing import Any, Dict, List, Optional, Tuple, Union, cast
import cf_xarray
import cftime
import numpy as np
import xarray as xr
... |
9831633 | from inspect import iscoroutinefunction
from typing import Any, Dict
import aiohttp
from tempo.serve.base import ModelSpec
from ..errors import InvalidUserFunction, UndefinedCustomImplementation
class _AsyncMixin:
def __init__(self):
if self._user_func is not None:
is_async = iscoroutinefun... |
9831635 | from django.contrib import admin
from demo.models import Demo
class DemoAdmin(admin.ModelAdmin):
list_display = ('name', 'master_version')
admin.site.register(Demo, DemoAdmin)
|
9831674 | from rest_framework import permissions
from api.base.utils import assert_resource_type
from osf.models import AbstractNode
class IsPublic(permissions.BasePermission):
"""
Only returning public nodes as meeting submissions.
"""
acceptable_models = (AbstractNode,)
def has_object_permission(self, ... |
9831728 | import urllib2
import datetime
import dateutil.parser
import util
import time
from BeautifulSoup import BeautifulSoup
NUM_DAYS = 30
ALL_OR_NOTHING=True
MAX_ATTEMPTS=5
def get_yearn(date):
result = []
for i in range(NUM_DAYS):
attempt=0
err=None
while attempt<MAX_ATTEMPTS:
... |
9831732 | from earthchem import Query
import unittest
class TestRESTClientQuery(unittest.TestCase):
"Tests for RESTClient"
def setUp(self):
self.query = Query()
def test_set_author(self):
"Check that author setting works ok"
for auth in ('smith', 'barnes'):
self.query['author'... |
9831737 | import argparse
from multiprocessing import Process
import subprocess
import os
def guetzli_dumper(input_file_path, input_q_file_path, input_o_file_path):
command = ["train_bin/Release/guetzli_dumper", input_file_path, input_q_file_path, input_o_file_path]
try:
subprocess.check_call(command)
except:
pass... |
9831740 | import os
import sys
import json
import argparse
import requests
from pathlib import Path
from shutil import copyfile
from bs4 import BeautifulSoup
image_extensions = ['.jpg','.jpeg','.png','.gif']
# Directory for storing the database file
data_dir = str(Path.home()) + '/.config/akari'
"""
Submits the search for... |
9831778 | import os
import sys
from nose.tools import assert_equal, with_setup
from .project import load_lsdsng
from .utils import temporary_file
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
sys.path.append(
os.path.dirname(os.path.abspath(os.path.join(__file__, os.path.pardir))))
from . import savfile as savf... |
9831811 | from coremltools.converters.keras import convert
from keras.models import model_from_json
model = None
with open('generator.json', 'r') as f:
model = model_from_json(f.read())
model.load_weights('generator.h5')
coreml_model = convert(model)
coreml_model.save('mnistGenerator.mlmodel')
|
9831863 | import random
import functools
import asyncio
from collections import defaultdict
from collections import deque
import redis
import pydatacoll.utils.logger as my_logger
from pydatacoll.protocols.iec104.frame import *
from pydatacoll.utils import str_to_number
from pydatacoll.utils.read_config import *
logger = my_log... |
9831871 | import sys
import math
import attr
from beastling.util import xml
__all__ = ['Distribution', 'Calibration']
registered_distributions = (
("Beta", "beast.math.distributions.Beta"),
("Exponential", "beast.math.distributions.Exponential"),
("InverseGamma", "beast.math.distributions.InverseGamma"),
("Lo... |
9831890 | from stories import arguments
from stories import story
# Base classes.
class Child:
@story
def x(I):
I.one
class ParamChild:
@story
@arguments("bar")
def x(I):
I.one
class Parent:
@story
def a(I):
I.before
I.x
I.after
class ParamParent:
... |
9831915 | from evennia_extensions.object_extensions.validators import get_model_by_id_or_name
def race_validator(value):
from evennia_extensions.character_extensions.models import Race
return get_model_by_id_or_name(Race, value)
def fealty_validator(value):
from world.dominion.models import Fealty
return ge... |
9831950 | import os
import copy
import math
import time
import numpy as np
from sklearn.neighbors import NearestNeighbors
from sklearn.cluster import KMeans
from sklearn import svm
from model_coin.prediction_strength import optimalK
from tqdm import tqdm
class COIN(object):
def __init__(self, data, inds_otlr, nbrs_ratio,
... |
9832019 | import datetime
from django.db.models import Count, Case, When
from fruit.models import Fruit
from .models import FruitUser
def fruit_counter(**filters):
return {
'fruit_count': Count(Case(When(fruits__deleted=False, fruits__kind__deleted=False, then=1, **filters)))
}
def top_pickers(**filters):
... |
9832080 | import pandas as pd
import statsmodels.api as sm
def counts(df, groupby, wt):
gdf = df.groupby(groupby)
count = gdf.size().reset_index(name="count")
wt = gdf[wt].sum().reset_index(name="wt")
return pd.concat([count, wt["wt"]], axis=1, sort=False)
def reg(df, dep_var, indep_vars, wt):
if "const" ... |
9832099 | from heapq import *
r, thm = int(0), int(0)
print("Enter the Number of Requests : ") # Number of I/O Requets
req = int(input())
print("Enter the Initial Head Position : ") # Initial position of Disk Head
hp = int(input())
position = hp
print("Enter the Seek Rate : ")
srate = int(input())
print("Enter the Requests : ... |
9832113 | import sys
from typing import Any, Type, Tuple, Union
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock # type: ignore
if sys.version_info[0] > 2:
from http.server import BaseHTTPRequestHandler, HTTPServer
else:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServ... |
9832174 | from setuptools import setup, find_packages
setup(
name="Dummy",
version="1.0.0",
url="https://git-place.org/dummy/dummy.git",
author="<NAME>",
author_email="<EMAIL>",
description="Dummy package for testing purposes only",
packages=find_packages(),
install_requires=["pypi-pkg-test==0.0.... |
9832215 | import os
import subprocess
import multiprocessing
import cloudpickle
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import clear_output
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.tri
from . import siay
from .data import skip_existing_prefixed_folders
from .bas... |
9832216 | from cyberbrain import InitialValue, Binding, Symbol
def test_mutation(tracer, check_golden_file):
text = "AAAA"
tracer.start()
lower_text = text.lower() # Test this line does not emit a mutation of `text`.
tracer.stop()
|
9832219 | from itertools import product
import numpy as np
import pandas as pd
import pytest
from muarch import UArch
np.random.seed(8)
TRAIN_SIZE = 500
HORIZON = 100
REPS = 5
BURN = 500
Y = np.random.normal(size=TRAIN_SIZE)
X = np.random.normal(size=(TRAIN_SIZE, 1))
X_SIM = np.random.normal(size=(HORIZON + BURN, 1))
known_... |
9832253 | import nibabel
import numpy as np
import sys
subjname = sys.argv[1] #"example_brain_t1"
for fname in [ "{}_mask_L.nii.gz".format(subjname), "{}_mask_R.nii.gz".format(subjname) ]:
img = nibabel.load( fname )
d = img.get_data(caching="unchanged")
d[d < 128] = 0
outimg = nibabel.Nifti1Image( d.astype("u... |
9832255 | from qcor import *
import numpy as np
@qjit
def ansatz(q : qreg, theta : float):
X(q[0])
X(q[2])
with compute:
Rx(q[0], np.pi/2.)
H(q.tail(3))
for i in range(3):
X.ctrl([q[i]], q[i+1])
with action:
Rz(q.tail(), theta)
h2_geom = '''H 0.000000 0.0 0.0
... |
9832269 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import numpy as np
from .cyclegan_networks import init_net
class GANLoss(nn.Module):
"""Define different GAN objectives.
The GANLoss class abstracts away the need to create the target label tensor
that ... |
9832289 | import struct
from bxutils import logging
logger = logging.get_logger(__name__)
class PayloadElement:
"""payload element
name (str): element block name
structure (str): python struct packing format
optionally provide decode,encode functions to be applied
"""
def __init__(self, name, struct... |
9832290 | from collections import namedtuple, OrderedDict
import copy
import logging
import json
import os
import re
import boto3
from botocore.exceptions import ClientError
from jinja2 import Environment, DictLoader, FileSystemLoader
import jsonref
from lambda_uploader import package, uploader
from retrying import retry
import... |
9832295 | from pathlib import Path
from typing import List, Literal, Optional
from httpx import AsyncClient
from nonebot.adapters.onebot.v11 import Message, MessageSegment
from src.modules.group_info import GroupInfo
from src.modules.plugin_info import PluginInfo
from src.modules.search_record import SearchRecord
from src.modul... |
9832359 | import pytest
import saq
import saq.settings
from saq.settings.settings import *
@pytest.mark.integration
def test_setting():
# insert some settings to test
saq.settings.load()
saq.settings.root.children['key'] = DictionarySetting(key='key')
saq.settings.root.children['key'].children['num'] = NumericSe... |
9832381 | import numbers
import numpy as np
import torch
from functools import reduce
from torch.optim import Optimizer
from scipy import optimize
from torch._vmap_internals import _vmap
from torch.autograd.functional import (_construct_standard_basis_for,
_grad_postprocess, _tuple_postproc... |
9832402 | import math
import random
from tkinter import Tk, Listbox
from tkinter.constants import W, END, E
from civil import building as building
from internal import utility as utility, gui as gui
from internal.terrain.terrain import Terrain, BASE_CELL_MIN_FOOD_PRODUCTION, BASE_CELL_FOOD_PRODUCTION, to_meters, \
MAX_HEIG... |
9832437 | from GB_model import *
#Paths to images in npy format (dir contains subdirectories, one for each expert)
# (provide the parent directory to the dataset generator's output)
data_path = 'data/<path_here>'
# Load model
GB = GhostBusters(model_path='models', device_ID='0')
# predict
pred, filenames = GB.predict(p... |
9832473 | import datetime
import functools
import inspect
import time
from pathlib import Path
from absl import logging # noqa: F401
from icubam.analytics import preprocessing
from icubam.db import store
BASE_PATH = Path(__file__).resolve().parent
CUM_COLUMNS = [
"n_covid_deaths",
"n_covid_healed",
"n_covid_transfered... |
9832499 | import struct
import codecs
RPLIDAR_SYNC_BYTE1 = b'\xA5'
RPLIDAR_SYNC_BYTE2 = b'\x5A'
RPLIDAR_DESCRIPTOR_LEN = 7
RPLIDAR_SEND_MODE_SINGLE_RES = b'\x00'
RPLIDAR_SEND_MODE_MULTIPLE_RES = b'\x01'
RPLIDAR_CMD_STOP = b'\x25'
RPLIDAR_CMD_RESET = b'\x40'
RPLIDAR_CMD_SCAN = b'\x20'
RP... |
9832519 | from .gfa1_to_gfa2 import GFA1ToGFA2
from .length_gfa1 import LengthGFA1
from .coverage import Coverage
from .references import References
from .writer_wo_sequence import WriterWoSequence
from . import Segment
class GFA1(WriterWoSequence, References, Coverage,
LengthGFA1, GFA1ToGFA2, Segment):
"""
A seg... |
9832535 | from pybench import Test
# First imports:
import os
import package.submodule
class SecondImport(Test):
version = 2.0
operations = 5 * 5
rounds = 40000
def test(self):
for i in xrange(self.rounds):
import os
import os
import os
import os
... |
9832617 | from bs4 import BeautifulSoup
import grequests
import argparse
import requests
import time
import lxml
import tqdm
import re
""" ____ _ __
/ __ \\ ____ (_)____ / /_ __ __
/ /_/ // __ \\ / // __ \\ / __// / / /
/ ____// /_/ // // / / // /_ / /_/ /
/_/ \\____//_//_/ /_/ \\__... |
9832626 | if __name__ == "__main__":
while True:
print("Near-infinite")
break
count = 0
while count < 5:
count += 1
if count % 2 == 0:
continue
print("count is {0}".format(count))
|
9832677 | input = """
1 2 0 0
1 3 0 0
1 4 0 0
1 5 0 0
1 6 0 0
1 7 0 0
1 8 0 0
1 9 0 0
1 10 0 0
1 11 0 0
1 12 0 0
1 13 0 0
1 14 0 0
1 15 0 0
1 16 0 0
1 17 0 0
1 18 0 0
1 19 0 0
1 20 0 0
1 21 0 0
1 22 0 0
1 23 0 0
1 24 0 0
1 25 0 0
1 26 0 0
1 27 0 0
1 28 0 0
1 29 0 0
1 30 0 0
1 31 0 0
1 32 0 0
1 33 0 0
1 34 0 0
1 35 0 0
1 36 0 0
1... |
9832704 | from .fcn import FCNResNet101
from .bisenetv2 import BiSeNetV2
from .models import models
from .models import load_model
from .models import LossWithAux |
9832712 | from tool.runners.python import SubmissionPy
from collections import defaultdict
target_bag = 'shiny gold'
class EvqnaSubmission(SubmissionPy):
def parse_rule(self, rule):
bag_type, _, contains = rule.partition(' bags contain ')
if contains.startswith('no'):
return bag_type, []
... |
9832726 | from datetime import timedelta
from inflection import camelize
from statsnba.api import Api
import gevent
from cached_property import cached_property
_async_fetch = True
__all__ = ['Game', 'Player', 'Team', 'Matchup']
# noinspection PyUnresolvedReferences
class Model(object):
"""Base class for other models such... |
9832730 | import asyncio
from telethon import events
from userbot.cmdhelp import CmdHelp
from userbot.utils import admin_cmd
@borg.on(admin_cmd(pattern="replymarry ?(.*)"))
async def _(event):
if not event.text[0].isalpha() and event.text[0] not in ("/", "#", "@", "!"):
await event.edit("I")
await asyncio... |
9832733 | rows = 6
# if you want user to enter a number, uncomment the below line
# rows = int(input('Enter the number of rows'))
# outer loop
for i in range(rows):
# nested loop
for j in range(i):
# display number
print(i, end=' ')
# new line after each row
print('')
|
9832734 | import sys
from pypy.objspace.flow.model import Variable, Constant, Block, Link
from pypy.objspace.flow.model import SpaceOperation, mkentrymap
from pypy.annotation import model as annmodel
from pypy.jit.hintannotator import model as hintmodel
from pypy.jit.hintannotator.model import originalconcretetype
from py... |
9832739 | import math
import pytest
from pandas import DataFrame
from stock_pandas import (
StockDataFrame,
)
from .common import (
get_tencent,
get_1m_tencent,
TIME_KEY
)
LENGTH = 20
@pytest.fixture()
def tencent():
return get_1m_tencent().iloc[:LENGTH]
def expect_cumulated_result(
series,
... |
9832757 | import os
import logging
from modules.andForensics.modules.utils.android_sqlite3 import SQLite3
import collections
logger = logging.getLogger('andForensics')
LIST_EXCEPTION_DB = list()
LIST_EXCEPTION_TABLE = list()
LIST_EXCEPTION_DB_TABLE = list()
class AnalyzerUtils(object):
def load_exception_rule(config_file):
... |
9832764 | from PyQt5.QtGui import QPen, QBrush, QColor
from .base import VisualizationModule
from ..pyqt_helper import *
from ...road import Lane, Sign, Border, LateralMarking, FlatMarking, Boundary
from ...enums import ReferenceTypes
class VisualizeBorders(VisualizationModule):
def __init__(self, **kwargs):
... |
9832776 | from os.path import join
import json
import numpy as np
from rastervision.common.settings import results_path
from rastervision.tagging.data.planet_kaggle import TagStore
from rastervision.tagging.tasks.utils import compute_prediction
from rastervision.tagging.tasks.train_thresholds import load_thresholds
from raste... |
9832778 | from __future__ import annotations
from typing import Any, TYPE_CHECKING
from click.testing import CliRunner
from .app import TestApp
from .client import QuartClient
from .connections import WebsocketResponseError
from .utils import (
make_test_body_with_headers,
make_test_headers_path_and_query_string,
... |
9832806 | from datetime import datetime
import pytz
UTC = pytz.utc
def utcnow() -> datetime:
return datetime.now(tz=UTC)
def as_utc(dt: datetime) -> datetime:
return dt.replace(tzinfo=UTC)
|
9832807 | import os
import shutil
import unittest
import tensorflow as tf
import numpy as np
from tensorflow.core.framework import attr_value_pb2
from tensorflow.core.framework import graph_pb2
from tensorflow.core.framework import node_def_pb2
from tensorflow.python.framework import tensor_util
from tensorflow.python.framework ... |
9832813 | import json
import time
import os
import pyperclip#调用pyperclip模块
while True:
f = open('c:\\cdr\\responseBody.txt', 'r', encoding='utf-8')
j = json.load(f)
#print(j['data']['options'])
if 'options' in j['data']:
answer3 = str(j['data']['topic_mode'])
if answer3 == '32':
print(... |
9832831 | from bonsai.base.regtree import RegTree
from sklearn.datasets import make_friedman1
import pickle
import numpy as np
import unittest
class DumpLoadTestCase(unittest.TestCase):
def test_dumpload(self):
n_samples = 10000
max_depth = 3
X, y = make_friedman1(n_samples=n_samples)
mod... |
9832844 | def zeros(dimensions):
"""
Attempted clone of numpy zeros.
Not as quick, but might be useful if long lists are desired
and numpy not available.
"""
x = y = None
try:
y, x = dimensions # If it cannot unpack it as tuple, it will fail
except TypeError:
x = dimensions # If ... |
9832849 | import pytest
import cftime
import datetime as dt
import unittest
import iris
import numpy as np
from forest import util
@pytest.mark.parametrize(
"given,expect",
[
pytest.param(
"2019-10-10 01:02:34",
dt.datetime(2019, 10, 10, 1, 2, 34),
id="str with space",
... |
9832955 | import os
import numpy as np
from PIL import Image
import multiprocessing
categories = ['background','aeroplane','bicycle','bird','boat','bottle','bus','car','cat','chair','cow',
'diningtable','dog','horse','motorbike','person','pottedplant','sheep','sofa','train','tvmonitor']
def do_python_eval(predict_... |
9832999 | import json
import os
from io import StringIO
from django.apps.registry import apps
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Updates fixtures from the database'
def handle(self, *a... |
9833002 | from useb import run_on
from sentence_transformers import SentenceTransformer
import torch
sbert = SentenceTransformer('bert-base-nli-mean-tokens')
@torch.no_grad()
def semb_fn(sentences) -> torch.Tensor:
return torch.Tensor(sbert.encode(sentences, show_progress_bar=False))
result = run_on(
'askubuntu',
... |
9833003 | import os
import pydiscourse
import fire
from deploy_util import get_config
def _create_discourse_client():
c = get_config()
hub_api_token = c["HUB_CLIENT_API_TOKEN"]
hub_api_url = "http://{}:{}/hub/api".format(
"127.0.0.1",
c["HUB_API_PORT"]
)
client = pydiscourse.DiscourseClient... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.