id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4892281 | import torch.nn as nn
import math
from models.randwidth_ops import RWConv2d, RWLinear, RWBatchNorm2d, make_divisible
from utils.config import FLAGS
class Block(nn.Module):
def __init__(self, inp, outp, stride, tmp_ratio=1.0):
super(Block, self).__init__()
assert stride in [1, 2]
# midp =... |
4892285 | from random import choice, choices
from flask import jsonify, request, redirect, render_template
from app import app
from .image_processing import SUPPORTED_COLORS
from .utils import ALL, IN_BUILD_IMAGES, SERIES, SERIES_URL
from .utils import colored_back, image_back, in_build_image_back
from .utils import get_by_id,... |
4892324 | from datetime import datetime, timezone
def generate_notifications_verb(old, new):
expr = ""
if old['version'] != new.version:
expr += "Version updated from '{}' to '{}'".format(old['version'], new.version)
# update the version_updated_at field
new.version_updated_at = datetime.now(t... |
4892335 | import argparse, ast
import sys
sys.path.append('../..')
sys.path.append('.')
import torch
import lightreid
import yaml
import time
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument('--config_file', type=str, default='path/to/config.yaml', help='')
parser.add_argument('--model_path', type=str,... |
4892338 | from pysolr import Solr
import urllib
import json
class CoreNotStartedException(Exception): pass
class SolrCoreAdminException(Exception):
def __init__(self,http_code):
self.http_code = http_code
def __str__(self):
return self(self.http_code)
### multicore commands
class SolrCoreAdmin(object):... |
4892348 | from sqlalchemy.sql import func
from config.app import db
class SystemEvents(db.Model):
id = db.Column(db.Integer, primary_key=True)
created_at = db.Column(db.DateTime(timezone=True), default=func.now())
updated_at = db.Column(db.DateTime(timezone=True), default=db.func.now(), onupdate=func.now())
me... |
4892417 | from typing import TypeVar
import numpy as np
import xarray as xr
PreserveFloatRangeType = TypeVar("PreserveFloatRangeType", xr.DataArray, np.ndarray)
LevelsType = TypeVar("LevelsType", xr.DataArray, np.ndarray)
def preserve_float_range(
array: PreserveFloatRangeType,
rescale: bool = False,
... |
4892425 | import warnings
from numba.core.errors import NumbaDeprecationWarning, \
NumbaPendingDeprecationWarning, NumbaPerformanceWarning
warnings.simplefilter('ignore', category=NumbaDeprecationWarning)
warnings.simplefilter('ignore', category=NumbaPendingDeprecationWarning)
warnings.simplefilter('ignore', category=Numba... |
4892438 | from guizero import App, Box, Text, TextBox
app = App()
title_box = Box(app, width="fill", align="top", border=True)
Text(title_box, text="title")
buttons_box = Box(app, width="fill", align="bottom", border=True)
Text(buttons_box, text="buttons")
options_box = Box(app, height="fill", align="right", border=True)
Text... |
4892452 | from __future__ import absolute_import, division, print_function
import libtbx
import scitbx.linalg
from scitbx.array_family import flex
class real_bidiagonal(scitbx.linalg.svd_decomposition_of_bidiagonal_matrix):
def compute(self):
super(real_bidiagonal, self).compute()
assert self.has_converged
self.s... |
4892508 | from .autoray import (
do,
get_backend,
set_backend,
backend_like,
infer_backend,
get_lib_fn,
conj,
transpose,
dag,
real,
imag,
reshape,
to_backend_dtype,
astype,
get_dtype_name,
get_common_dtype,
to_numpy,
register_function,
# the numpy mimic ... |
4892548 | import time
import logging
import datetime
import gevent
from eth_utils import encode_hex
from microraiden import Session
log = logging.getLogger(__name__)
def test_resource_request(doggo_proxy, http_doggo_url: str, session: Session):
n_requests = 10
session.initial_deposit = lambda x: (n_requests + 1) * x... |
4892559 | import unittest
import sniffles.rulereader as reader
class TestXMLRuleReader(unittest.TestCase):
def test_parse_rule(self):
myrl = reader.RuleList()
myrl.readRuleFile('tests/data_files/test_all.xml')
self.assertEqual(len(myrl.getParsedRules()), 1)
for r in myrl.getParsedRules():
... |
4892560 | from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
from kitsune.sumo.models import ModelBase
class InboxMessage(ModelBase):
"""A message in a user's private message inbox."""
to = models.ForeignKey(User, on_delete=models.CASCADE, related_name="inbox")
... |
4892619 | import gdb # type: ignore
from typing import Dict, Tuple, Any, List, Tuple
from core import wl
from core.util import time_now
type_codes = {i: True for i in ['i', 'u', 'f', 's', 'o', 'n', 'a', 'h']}
wl_resource_ptr_type = None
gdb_fast_access_map: Dict[str, Tuple[int, Any]] = {}
gdb_char_ptr_type = gdb.lookup_type('... |
4892681 | from django.contrib.gis.db.backends.postgis import base
from transaction_hooks.mixin import TransactionHooksDatabaseWrapperMixin
class DatabaseWrapper(TransactionHooksDatabaseWrapperMixin,
base.DatabaseWrapper):
pass
|
4892692 | from typing import Union, Tuple, Mapping, Iterable, Optional, Callable, TypeVar, Any
from dataclasses import dataclass, replace
from .ElementSelection import ElementSelection
from .NodeSelection import NodeSelection
from .EdgeSelection import EdgeSelection, EdgeId, EdgeContext
from .LabelSelection import LabelSelectio... |
4892702 | import os
import sys
import psycopg2
from psycopg2 import connect
def main():
db_name = os.environ['PGDATABASE']
connection_parameters = {
'host': os.environ['PGHOST'],
'database': 'postgres',
'user': os.environ['PGUSER'],
'password': os.environ['PGPASSWORD']
}
drop_st... |
4892716 | import threading
from threading import Lock
import time
from tasks.Task import Task
from bot_related.bot_config import BotConfig
from bot_related.device_gui_detector import GuiDetector, GuiName
from filepath.file_relative_paths import ImagePathAndProps, VERIFICATION_CLOSE_REFRESH_OK, VERIFICATION_VERIFY_TITLE
from ta... |
4892741 | import sqlite3, sys
from PyQt5.QtWidgets import QDialog, QApplication
from sqlite3 import Error
from demoSearchRows import *
class MyForm(QDialog):
def __init__(self):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui.pushButtonSearch.clicked.connect(self.Sear... |
4892757 | import gym
import sys
import numpy as np
import os.path as osp
import multiprocessing as mp
import sys
import torch
from IPython import embed
class BasicTask:
def __init__(self, max_steps=sys.maxsize):
self.steps = 0
self.max_steps = max_steps
def reset(self, *args):
self.steps = 0
state = self.... |
4892762 | from typing import Dict, List, Optional
def cap_list_to_dict(caps: List[str]) -> Dict[str, Optional[str]]:
d: Dict[str, Optional[str]] = {}
for cap in caps:
if "=" in cap:
(key, value) = cap.split("=", 1)
d[key] = value
else:
d[cap] = None
return d
|
4892764 | from os import path, walk
from pathlib import Path
from shutil import copy
from setuptools import setup
from srsly import json_loads
def list_files(data_dir):
output = []
for root, _, filenames in walk(data_dir):
for filename in filenames:
if not filename.startswith("."):
... |
4892803 | import os
def parse_distributions_h(ffi, inc_dir):
"""
Parse distributions.h located in inc_dir for CFFI, filling in the ffi.cdef
Read the function declarations without the "#define ..." macros that will
be filled in when loading the library.
"""
with open(os.path.join(inc_dir, 'r... |
4892805 | from marshmallow import (
INCLUDE, Schema, fields as f, validate as v, validates_schema,
)
from hikcamerabot.config.schemas.validators import int_min_1, non_empty_str
from hikcamerabot.constants import (
CMD_CAM_ID_REGEX, Detection as DetectionMode,
FFMPEG_LOG_LEVELS, RTSP_DEFAULT_PORT, RTSP_TRANSPORT_TYPE... |
4892814 | load("//tools/api_proto_plugin:plugin.bzl", "api_proto_plugin_aspect", "api_proto_plugin_impl")
def _protodoc_impl(target, ctx):
return api_proto_plugin_impl(target, ctx, "rst", "protodoc", [".rst"])
# Bazel aspect (https://docs.bazel.build/versions/master/starlark/aspects.html)
# that can be invoked from the CLI... |
4892853 | import numpy as np
import pandas as pd
import os
import cv2
from tqdm import tqdm
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
import torch
from efficientnet_pytorch import EfficientNet
import pickle
import pydicom
import glob
... |
4892862 | import h5py
import os
from PySide2.QtWidgets import QDialog, QListWidgetItem, QMessageBox
from hexrd.ui.ui_loader import UiLoader
class LoadHDF5Dialog:
def __init__(self, f, saved_path=None, parent=None):
self.file = f
self.paths = []
loader = UiLoader()
self.ui = loader.load_file('load_hdf5_dial... |
4892897 | from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class ReviewsConfig(AppConfig):
name = "parsifal.apps.reviews"
verbose_name = _("Reviews")
|
4892920 | from contextlib import contextmanager
from functools import partial
from unittest import mock
from unittest.mock import Mock
from multiplex.keys import bind as _bind, HELP, SCROLL, NORMAL, GLOBAL, INPUT
from multiplex.keys_input import InputReader
def _test_set(show_help=False, auto_scroll=True, input_mode=False):
... |
4892929 | import numpy as np
import os
import pytest
import tempfile
from b3get.utils import chunk_npz
@pytest.fixture
def list_of_ndarrays():
nplist = [np.ones(shape=(256, 256), dtype='uint32') for n in range(16)] # 16*256KB
for idx in range(len(nplist)):
nplist[idx].fill(int(idx))
return nplist
def tes... |
4892994 | from rest_framework.exceptions import APIException
class RequestBodyValidationException(APIException):
def __init__(self, detail=None, code=None):
super().__init__(
{"error": "ERROR_REQUEST_BODY_VALIDATION", "detail": detail}, code=code
)
self.status_code = 400
class UnknownF... |
4893053 | from __future__ import annotations
import typing as T
from pathlib import Path
import xarray
from datetime import datetime, timedelta
import logging
from .rio import rinexinfo
from .obs2 import rinexobs2
from .obs3 import rinexobs3
from .nav2 import rinexnav2
from .nav3 import rinexnav3
from .sp3 import load_sp3
from ... |
4893060 | import re
if(__name__=="__main__"):
# Assemble the script which embeds the Markdeep page into the preview blog
PreviewBlogPage=open("PreviewBlogPage.htm","rb").read().decode("utf-8");
HeadMatch=re.search("<head(.*?)>(.*?)</head>",PreviewBlogPage,re.DOTALL);
HeadAttributes=HeadMatch.group(1);
... |
4893066 | from django.db.models import Q
#
# Secrets
#
SECRET_ASSIGNMENT_MODELS = Q(
Q(app_label='dcim', model='device') |
Q(app_label='virtualization', model='virtualmachine')
)
SECRET_PLAINTEXT_MAX_LENGTH = 65535
|
4893077 | from icolos.core.workflow_steps.gromacs.cluster import StepGMXCluster
from icolos.core.workflow_steps.gromacs.editconf import StepGMXEditConf
from icolos.core.workflow_steps.gromacs.genion import StepGMXGenion
from icolos.core.workflow_steps.gromacs.grompp import StepGMXGrompp
from icolos.core.workflow_steps.gromacs.md... |
4893079 | from exception_wrappers import ExceptionWrapper
from six import add_metaclass
from sortedcontainers import SortedSet
import collections
import logging
import sys
import time
Record = collections.namedtuple('Record', 'level timestamp message')
log = logging.getLogger(__name__)
class InterfaceMessagesMeta(type):
@... |
4893227 | from checkov.common.models.enums import CheckCategories
from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck
from checkov.common.models.consts import ANY_VALUE
class CloudformationStackNotificationArns(BaseResourceValueCheck):
def __init__(self):
name = "Ensure th... |
4893247 | from __future__ import print_function
import mxnet as mx
import sys
sys.path.insert(0, "../../python")
import bisect
import random
import numpy as np
BATCH_SIZE = 1
SEQ_LENGTH = 0
NUM_GPU = 1
def get_label(buf, num_lable):
ret = np.zeros(num_lable)
for i in range(len(buf)):
ret[i] = int(buf[i])
... |
4893248 | from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from retro_news.models import ArticleComment, CustomUser, BlogArticle
class BlogArticleSerializer(serializers.ModelSerializer):
"""Serializer for... |
4893292 | from js_helper import TestCase
class TestDoubleEscape(TestCase):
def test_double_escaped(self):
"""Test that escaped characters don't result in errors."""
self.run_script("""
var x = "\u1234\x12"
var y = "\\u1234\\x12"
""")
self.assert_silent()
|
4893334 | from simple_salesforce.exceptions import SalesforceError
from cumulusci.core.exceptions import CumulusCIException
from cumulusci.core.utils import process_bool_arg, process_list_arg
from cumulusci.tasks.salesforce import BaseSalesforceApiTask
from cumulusci.utils import inject_namespace
from cumulusci.utils.http.reque... |
4893348 | import unittest
import unittest.mock
from programy.storage.entities.binaries import BinariesStore
class BinariesStoreTests(unittest.TestCase):
def test_save_binary(self):
store = BinariesStore()
with self.assertRaises(NotImplementedError):
aiml_parser = unittest.mock.Mock()
... |
4893378 | import tensorflow as tf
import math
import numpy as np
import ast
str = open('feature_input.data', 'r').read()
data = np.array(ast.literal_eval(str))
x_data = data[:, 0:12]
y_data = data[:, 12:]
def xavier_init(n_inputs, n_outputs, uniform=True):
if uniform:
# 6 was used in the paper.
init_range = math.sqrt... |
4893391 | import logging
import multiprocessing
import os
from typing import List, Union
from modelforge import Model
from modelforge.progress_bar import progress_bar
from sourced.ml.core.utils.pickleable_logger import PickleableLogger
class Model2Base(PickleableLogger):
"""
Base class for model -> model conversions.... |
4893395 | from math import sqrt
def tuple_distance(tuple1, tuple2):
return sqrt((tuple1[0]-tuple2[0])**2 +(tuple1[1]-tuple2[1])**2)
if __name__ == '__main__':
x = (1, 0)
y = (5, 3)
print(f'Distance between {x} and {y} is {tuple_distance(x, y)}')
|
4893401 | import logging
from datetime import timedelta
from django.core.management import BaseCommand
from django.utils import timezone
from supportal.shifter.models import EventSignup
class Command(BaseCommand):
help = "If MA goes down retry the sends that failed"
def add_arguments(self, parser):
parser.ad... |
4893403 | from .mazegame import (
MazeGame,
BaseMazeGame,
WithWaterAndBlocksMixin,
RewardOnEndMixin,
AbsoluteLocationVocabulary,
BaseVocabulary,
)
from .goal_based_games import (
SingleGoal,
MultiGoals,
ConditionedGoals,
Exclusion,
Goto,
GotoHidden,
)
from .blocks_switches_games im... |
4893486 | from tests.base import DBTestCase
from tests.example_apps.music.tables import Band
class TestGetRelatedReadable(DBTestCase):
def test_get_related_readable(self):
"""
Make sure you can get the `Readable` representation for related object
from another object instance.
"""
sel... |
4893536 | from flask_restplus import Namespace, Resource, fields
from pyris.api import extract
api = Namespace('insee', description='Some stats from INSEE for each IRIS')
population_parser = api.parser()
population_parser.add_argument("by", required=True, location='args',
help="By sex or age")
... |
4893537 | class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums) - 1
# 求右边界
while left <= right:
mid = left + (right - left) // 2
if nums[mid] <= target:
left = mid + 1
elif nums[mid] > target:
... |
4893560 | def problem1_4(miles):
feet = int(miles)*5280
print("There are",feet,"feet in",miles,"miles.")
pass # replace this pass (a do-nothing) statement with your code
|
4893611 | import geopandas
import libpysal
import numpy
import unittest
from spopt.region import WardSpatial
# Empirical tests -- Mexican states
RANDOM_STATE = 12345
pth = libpysal.examples.get_path("mexicojoin.shp")
MEXICO = geopandas.read_file(pth)
class TestWard(unittest.TestCase):
def setUp(self):
self.mexi... |
4893620 | from idom import component, html, run
@component
def Photo():
return html.img(
{
"src": "https://picsum.photos/id/274/500/300",
"style": {"width": "30%"},
"alt": "<NAME>",
}
)
@component
def Gallery():
return html.section(
html.h1("Famous Music... |
4893622 | import unittest
from jivago.event.dispatch.message_dispatcher_class import MessageDispatcherClass
MESSAGE_NAME = "message_name"
class MessageDispatcherClassTest(unittest.TestCase):
def setUp(self):
self.instance = MessageHandlerMock()
def test_whenHandlingEvent_thenInvokeRegisteredInstanceWithPayl... |
4893680 | import sys
import os, os.path
import urllib.request
import json
import shutil
import platform
import hashlib
CONFIG = {
"install_path": "./pkg",
"catalog_url": "http://txlyre.ml/files/loli/pkg/catalog.json",
}
CONFIG["catalog_path"] = os.path.join(CONFIG["install_path"], "catalog_local.json")
if not... |
4893683 | from __future__ import unicode_literals
from django.apps import AppConfig
class AdministratorConfig(AppConfig):
name = 'administrator'
|
4893685 | from pkg_resources import get_distribution
from .double_ml_plr import DoubleMLPLR
from .double_ml_pliv import DoubleMLPLIV
from .double_ml_irm import DoubleMLIRM
from .double_ml_iivm import DoubleMLIIVM
from .double_ml_data import DoubleMLData, DoubleMLClusterData
__all__ = ['DoubleMLPLR',
'DoubleMLPLIV',
... |
4893723 | N, X = map(int, input().split())
[print(sum(marks) / len(marks)) for marks in zip(*[list(map(float, input().split())) for _ in range(X)])]
|
4893724 | import pytest
import sqlalchemy as sa
from muffin_databases import Plugin as DB
@pytest.fixture(scope='module')
def aiolib():
return 'asyncio', {'use_uvloop': False}
@pytest.fixture
async def db(app):
db = DB(app, url='sqlite:///:memory:', params={'force_rollback': True})
await db.connect()
yield db... |
4893725 | import FWCore.ParameterSet.Config as cms
# Settings from $HERWIGPATH/LHE-POWHEG.in, should be used together with the Herwig7LHECommonSettings
herwig7LHEPowhegSettingsBlock = cms.PSet(
hw_lhe_powheg_settings = cms.vstring(
'set /Herwig/Shower/ShowerHandler:MaxPtIsMuF Yes',
'set /Herwig/Shower/Showe... |
4893796 | from configparser import ConfigParser
# Initialize the Parser.
config = ConfigParser()
# Add the Section.
config.add_section('main')
# Set the Values.
config.set('main', 'API_KEY', '')
config.set('main', 'CHANNEL_ID', '')
config.set('main', 'PLAYLIST_ID', '')
# Write the file.
with open('configs/config.ini', 'w+') ... |
4893802 | import unittest
from programy.activate import Activatable
from programy.bot import Bot
from programy.config.bot.bot import BotConfiguration
from programy.config.bot.splitter import BotSentenceSplitterConfiguration
from programy.context import ClientContext
from programy.dialog.splitter.splitter import SentenceSplitter... |
4893819 | from typing import Generic, TypeVar
from infrastructure.cqrs.CommandQueryHandlerBase import CommandQueryHandlerBase
from infrastructure.cqrs.ICommand import ICommand
CH = TypeVar('CH', covariant=True, bound=ICommand)
class ICommandHandler(Generic[CH], CommandQueryHandlerBase[CH]):
def __init__(self) -> CH:
... |
4893831 | from boa3.builtin import public
@public
def Main(operation: str, arg: int) -> int:
a = 0
b = 0
while b < 10 < arg:
a = a + 2
b = b + 1
return a
|
4893862 | import json
from typing import Dict, Optional, Union
import sqlalchemy as sa
from sqlalchemy.engine.url import URL
from .database_interface import DBInterface, MySQLInterface
__config__: Dict = None
__db_interface__: DBInterface = None
def prepare_engine(config: Dict) -> sa.engine.Engine:
"""Create sqlalchemy ... |
4893865 | import logging
import os
import re
import stat
from pyscaffold import file_system as fs
from .helpers import temp_umask, uniqpath, uniqstr
def test_tmpfile(tmpfolder):
with fs.tmpfile(suffix=".foo.bar", dir=str(tmpfolder)) as tmp:
path = str(tmp)
assert path.endswith(".foo.bar")
assert t... |
4893963 | import os
import pandas as pd
from datetime import datetime, timedelta
import geopandas as gpd
import numpy as np
import itertools
def sanitise_time(time, gtfs_day='19700101'):
time_list = time.split(':')
if int(time_list[0]) >= 24:
days = int(time_list[0]) // 24
time_list[0] = int(time_list[0... |
4893968 | from __future__ import print_function
import sys
sys.path.insert(1,"../../../")
from tests import pyunit_utils
import h2o
import threading
from h2o.utils.typechecks import assert_is_type
def h2oshutdown():
"""
Python API test: h2o.shutdown(prompt=False)
Deprecated, use h2o.cluster().shutdown()
"""
... |
4893979 | from django.conf.urls import url
from django.test.utils import override_settings
from django.views import generic
from django_webtest import WebTest
from .. import forms
@override_settings(ROOT_URLCONF=__name__)
class Test(WebTest):
def test_default_usecase(self):
page = self.app.get('/demo/bank/')
... |
4894004 | from test import support
support.import_module("dbm.ndbm") #skip if not supported
import os
import unittest
import dbm.ndbm
from dbm.ndbm import error
class DbmTestCase(unittest.TestCase):
def setUp(self):
self.filename = support.TESTFN
self.d = dbm.ndbm.open(self.filename, 'c')
... |
4894018 | import csv
import logging
import serial
import time
_logger = logging.getLogger("regal_dump")
_logger.addHandler(logging.NullHandler())
_port_offsets = {
"C": 0,
"L": 1,
"A": 2,
}
def _read_entry(ser):
while ser.read() != b'\x02':
continue
payload = []
for byte in ser.read(3):
... |
4894033 | import numpy as np
from segmentation.segment_image import (
segment_image_unet,
train_bgsb,
)
import copy
import os
from os import path as osp
invisiable_env_id = {
'SawyerPushNIPSEasy-v0': "SawyerPushNIPSPuckInvisible-v0",
'SawyerPushHurdle-v0': 'SawyerPushHurdlePuckInvisible-v0',
'SawyerPushT-v0... |
4894036 | from ObjectCollection import *
import TclCommand
class TclCommandCncjob(TclCommand.TclCommandSignaled):
"""
Tcl shell command to Generates a CNC Job from a Geometry Object.
example:
set_sys units MM
new
open_gerber tests/gerber_files/simple1.gbr -outname margin
isolate mar... |
4894041 | import os
import math
import sys
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter, LogFormatter, StrMethodFormatter, FixedFormatter
import sklearn.metrics as skl_metrics
import numpy as np
from NoduleFinding import NoduleFinding
from tools import csvTools
# Evaluation settings
bPerformB... |
4894048 | import numpy as np
from scipy import sparse as sp
import warnings
from discretize.utils import (
sdiag,
speye,
kron3,
spzeros,
ddx,
av,
av_extrap,
make_boundary_bool,
)
from discretize.utils.code_utils import deprecate_method, deprecate_property
def _validate_BC(bc):
"""Checks if b... |
4894125 | from __future__ import division
from builtins import object
import pickle
import numpy as np
from sporco.admm import parcbpdn
from sporco.fft import fftn, ifftn
import sporco.linalg as sl
class TestSet01(object):
def setup_method(self, method):
np.random.seed(12345)
def test_01(self):
N =... |
4894167 | from django.shortcuts import render
from django.http import HttpResponse
# Include the `fusioncharts.py` file which has required functions to embed the charts in html page
from ..fusioncharts import FusionCharts
from ..fusioncharts import FusionTable
from ..fusioncharts import TimeSeries
import requests
# Loading Dat... |
4894170 | from __future__ import absolute_import, division, generators, print_function
from bisect import bisect_right
import sys
import inspect
import tokenize
import py
cpy_compile = compile
try:
import _ast
from _ast import PyCF_ONLY_AST as _AST_FLAG
except ImportError:
_AST_FLAG = 0
_ast = None
class Sour... |
4894187 | import json
from pathlib import Path
from pprint import pformat
from typing import Optional
import typer
from .config import get_skill_config
remote = typer.Typer(name='remote', help='Commands for interacting with running skills')
def prompt_for_secret():
secret: str = typer.prompt('Secret', hide_input=True)
... |
4894197 | import datetime
import pytest
import osxphotos
from osxphotos.phototemplate import RenderOptions
PHOTOS_DB_PLACES = (
"./tests/Test-Places-Catalina-10_15_1.photoslibrary/database/photos.db"
)
DATETIME_TODAY = datetime.datetime(2020, 6, 21, 13, 0, 0)
""" Used to patch osxphotos.phototemplate.TODAY for testing ""... |
4894202 | from django.test import TestCase
from django.test.utils import override_settings
from django.contrib.auth import get_user_model
from core.models import Person, App
import core.views as views
from core import helpers
import datetime
from django.utils import timezone
class PersonTest(TestCase):
def test_format_pho... |
4894221 | from ofa.utils.layers import ResidualBlock
from ofa.imagenet_classification.networks import ProxylessNASNets
from .modules import my_set_layer_from_config
__all__ = ['build_residual_block_from_config', 'build_network_from_config']
def build_residual_block_from_config(config):
conv_config = config['conv'] if 'conv' ... |
4894223 | from PIL import Image
import PIL
import torch.utils.data as data
import os
import scipy.io as io
from glob import glob
import json
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
import random
import numpy as np
import math
def random_crop(im_h, im_w, crop_h, crop_w):
... |
4894253 | import asyncio
from library.telegram.base import RequestContext
from nexus.bot.exceptions import UnknownFileFormatError
from nexus.translations import t
from nexus.views.telegram.common import close_button
from telethon import events
from .base import BaseHandler
class SubmitHandler(BaseHandler):
filter = event... |
4894306 | from colors import logcolors
from difflib import ndiff
from utils import getMaxSpaces
def calcDiff(firstFile, secondFile):
# calculate raw diff
diff = ndiff(firstFile, secondFile)
# calculate unique lines in secondfile
deltainit = ''.join(x[2:] for x in diff if x.startswith('+ '))
# reformat the l... |
4894315 | import sys
import os
from time import time
import json
import traceback
from multiprocessing import Queue
from logger import set_up_logging
import string
from ast import literal_eval
import falcon
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
sys.path.insert(0, os.path.dirname(... |
4894332 | default_value_file_yaml = \
'name_app: My first app'
default_value_file_json = \
'{\n' + \
' "name_app": "My first app",\n' + \
'}'
default_template_yaml = \
'name: {{ Values.name_app}}\n' +\
'description: my first app\n' +\
'settings:\n' +\
' app: {}\n'
default_template_json = \
'{\n' +\
' "name": "{... |
4894343 | from pactman import Term
from pactman.mock.request import Request
def test_matcher_in_path_gets_converted():
target = Request("GET", Term(r"\/.+", "/test-path"))
assert target.json("2.0.0") == {
"method": "GET",
"path": "/test-path",
"matchingRules": {"$.path": {"regex": r"\/.+"}},
... |
4894383 | from django.contrib import admin
from .models import Entry, Subscription
ENTRY_READ_ONLY_FIELDS = (
'created_at',
'created_by',
'ip_address',
'entry_type',
'message',
'context',
'organization',
'event',
'person',
'other_fields',
)
class EntryAdmin(admin.ModelAdmin):
list... |
4894440 | from appannie.util import format_request_data
class FeaturesMetadata(object):
CATEGORIES_ENDPOINT = '/meta/feature/categories'
TYPES_ENDPOINT = '/meta/feature/types'
def __init__(self, http_client, market):
self.http_client = http_client
self.market = market
def categories(self, coun... |
4894441 | import time
import random
import gym # 0.12.5
env = gym.make('MountainCar-v0')
env.reset()
score = 0
for i in range(2):
while True:
env.render()
time.sleep(0.01)
a = random.randint(0, 2)
s, reward, done, _ = env.step(a)
score += reward
if done:
print('sc... |
4894448 | import io
import os
import json
import time
import boto3
from datetime import datetime
from xml.etree import ElementTree
from textract_util import *
def lambda_handler(event, context):
s3 = boto3.resource('s3')
textract = boto3.client('textract')
dynamodb = boto3.resource('dynamodb')
table_name=os.... |
4894484 | import pandas as pd
from pandas_datareader import data as web
import matplotlib.pyplot as plt
from datetime import datetime
start = datetime(2016,1,1)
end = datetime(2017,1,1)
assets = ['AAPL', 'FB', 'TSLA']
df = pd.DataFrame()
for stock in assets:
df[stock] = web.DataReader(stock, data_source='yahoo', start=st... |
4894497 | import numpy as np
def main():
old = np.load("../data/mnist/mnist_train_labels.npy")
new = np.zeros(len(old), dtype="uint8")
new[np.where((old % 2) == 0)] = 0
new[np.where((old % 2) == 1)] = 1
np.save("../data/mnist/mnist_train_even_odd_labels.npy", new)
old = np.load("../data/mnist/mnist_test... |
4894542 | import gamma
# a trigger attached to a coin
# to allow players to collect them
class CoinTrigger(gamma.Trigger):
# called whenever an entity with a collider component
# collides with the trigger area
def onCollisionEnter(self, entity, otherEntity):
# if the other entity is tagged as a 'player'
... |
4894543 | from pydantic import BaseModel
from typing import List, Optional
from bali.decorators import action
from bali.resource import Resource
from bali.schemas import GetRequest, ListRequest
from permissions import IsAuthenticated
GREETERS = [{'id': i, 'content': 'Hi, number %s' % i} for i in range(10)]
class Greeter(Base... |
4894650 | def test_pad_ends():
from speechbrain.lm.counting import pad_ends
assert next(pad_ends(["a", "b", "c"])) == "<s>"
assert next(pad_ends(["a", "b", "c"], pad_left=False)) == "a"
assert list(pad_ends(["a", "b", "c"], pad_left=False))[-1] == "</s>"
assert list(pad_ends([], pad_left=False))
assert l... |
4894660 | import time
from labml import tracker, experiment
def main():
experiment.create(name='Test')
with experiment.start():
for i in range(1, 401):
tracker.add_global_step()
time.sleep(1)
tracker.save(loss=1.)
if __name__ == '__main__':
main()
|
4894663 | import FWCore.ParameterSet.Config as cms
process = cms.Process("ICALIB")
process.MessageLogger = cms.Service("MessageLogger",
cout = cms.untracked.PSet(
threshold = cms.untracked.string('INFO')
),
destinations = cms.untracked.vstring('cout')
)
process.source = cms.Source("EmptyIOVSource",
firs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.