id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
498842 | from gurobipy import Model, GRB, quicksum
import networkx as nx
def create_model(G, terminals, root=None, weight='weight', warmstart=[], lower_bound=None):
r""" Create an ILP for the minimum Steiner tree problem in graphs.
This formulation enforces a cycle in the solution if it is not connected.
Cycles a... |
498845 | from typing import List
from rich.table import Table
from kaskade.kafka.models import GroupMember
from kaskade.renderables.paginated_table import PaginatedTable
class MembersTable(PaginatedTable):
def __init__(
self,
group_members: List[GroupMember],
page_size: int = -1,
page: in... |
498892 | def print_formatted(number):
# your code goes here
width=len(str(bin(number))[2:])
for i in range(1,number+1):
print(str(i).rjust(width," "),oct(i)[2:].rjust(width," "),hex(i)[2:].upper().rjust(width," "),bin(i)[2:].rjust(width," "))
if __name__ == '__main__':
n = int(input())
print_formatt... |
498929 | import json
import uuid
import pdb
import os
from tdcosim.global_data import GlobalData
#===================================================================================================
#==============================================CONFIG===============================================
#==========================... |
498959 | import logging
import warnings
from copy import deepcopy
from time import sleep
from typing import TYPE_CHECKING
from pyramid.httpexceptions import (
HTTPConflict,
HTTPForbidden,
HTTPInternalServerError,
HTTPNotFound,
HTTPOk,
HTTPUnauthorized
)
from pyramid.settings import asbool
from weaver i... |
498990 | from __future__ import absolute_import
import torch
import torch.nn.functional as F
import numpy as np
from pytorch_wavelets.utils import symm_pad_1d as symm_pad
def as_column_vector(v):
"""Return *v* as a column vector with shape (N,1).
"""
v = np.atleast_2d(v)
if v.shape[0] == 1:
return v.... |
499078 | import re
import functools
import inspect
import traceback
import logging
import pymel.core as pymel
from PySide import QtCore
from PySide import QtGui
from ui import widget_list_modules
from omtk.libs import libSkinning
from omtk.libs import libQt
from omtk.libs import libPython
from omtk.libs import libPymel
from o... |
499082 | import torch
from stylefusion.fusion_net import FusionNet
class SFHierarchyFFHQ:
def __init__(self):
self.nodes = dict()
self.nodes["clothes"] = SFNode("clothes")
self.nodes["mouth"] = SFNode("mouth")
self.nodes["eyes"] = SFNode("eyes")
self.nodes["bg"] = SFNode("bg")
... |
499092 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from pykin.utils import transform_utils as tf
# Colors of each directions axes. For ex X is green
directions_colors = ["green", "cyan", "orange"]
def init_3d_figure(name=... |
499100 | import unittest
from neo.rawio.elanrawio import ElanRawIO
from neo.test.rawiotest.common_rawio_test import BaseTestRawIO
class TestElanRawIO(BaseTestRawIO, unittest.TestCase, ):
rawioclass = ElanRawIO
entities_to_test = [
'elan/File_elan_1.eeg'
]
entities_to_download = [
'elan',
... |
499153 | import datetime
from django.test import TestCase
from django.utils import timezone
from helium.auth.tests.helpers import userhelper
from helium.planner.models import Reminder
from helium.planner.tests.helpers import coursegrouphelper, coursehelper, homeworkhelper, eventhelper, reminderhelper
__author__ = "<NAME>"
__... |
499163 | import komand
from .schema import NodeInput, NodeOutput
# Custom imports below
from urllib.parse import urljoin
from komand_logstash.util import utils
import requests
class Node(komand.Action):
TYPES = ["pipeline", "os", "jvm"]
def __init__(self):
super(self.__class__, self).__init__(
n... |
499194 | import torch
import car_racing_simulator.Track as Track
import numpy as np
import copy
class VehicleModel():
def __init__(self,n_batch,device,config):
self.device = device
self.track = Track.Track(config)
self.track_s = torch.from_numpy(self.track.s).type(torch.FloatTensor).to(self.devic... |
499205 | from pprint import pprint
from finnews.client import News
# Create a new instance of the News Client.
news_client = News()
# Grab the NASDAQ News Client.
nasdaq_news_client = news_client.nasdaq
# Grab the original content news.
content = nasdaq_news_client.original_content()
pprint(content)
# Grab the Commodity ne... |
499213 | import sys
from constants import SYMBOL
from db import create_engine, fetch_dataframe, plot_stats
def main():
engine = create_engine(SYMBOL)
dataframe = fetch_dataframe(SYMBOL, engine)
if dataframe is None:
raise Exception("Unable to fetch dataframe")
if len(sys.argv) == 2 and (sys.argv[1] == ... |
499247 | import time
def get_bitsize(v):
return 1 << v
def get_timestamp():
now = int((time.time()) * 1000)
return now
def til_next_millis(last):
timestamp = get_timestamp()
while (timestamp <= last):
time.sleep(0.001)
timestamp = get_timestamp()
return timestamp
|
499254 | import json
import glob
import os
import argparse
import sys
import re
class QueryAttackEval:
def __init__(self, args):
self.args = args
# this line is only to protect the object and should never trigger if running from this script
assert(self.args.technique or self.args.procedure or self.args.search)
def g... |
499259 | from civic_scraper.base.site import Site
def test_site_default():
"Site should receive a url"
class Example(Site):
pass
site = Example("https://foo.com")
assert hasattr(site, "url")
assert site.runtime.__class__.__name__ == "date"
assert not hasattr(site, "parser_kls")
def test_sit... |
499323 | from abc import ABC, abstractmethod
from random import randrange
from typing import List
class Observer(ABC):
@abstractmethod
def update(self, subject):
pass
class Subject(ABC):
@abstractmethod
def append(self, observer):
pass
@abstractmethod
def remove(self, observer):
... |
499329 | import json
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(dir_path, 'insights_hosts.json')) as data_file:
TEST_INSIGHTS_HOSTS = json.load(data_file)
with open(os.path.join(dir_path, 'insights.json')) as data_file:
TEST_INSIGHTS_PLANS = json.load(data_file)
with op... |
499365 | class QLayer():
def get_quant_weight(self):
raise NotImplementedError
def set_quant_weight(self):
raise NotImplementedError
def restore_weight(self):
raise NotImplementedError |
499386 | from bert_nli import BertNLIModel
if __name__ == '__main__':
bert_type = 'bert-base'
model = BertNLIModel('output/{}.state_dict'.format(bert_type), bert_type=bert_type)
sent_pairs = [('The lecturer committed plagiarism.','He was promoted.')]
labels, probs = model(sent_pairs)
print(labels)
prin... |
499389 | from django.conf import settings
def vault_settings(request):
return {
'DEBUG': settings.DEBUG,
'ENVIRON': settings.ENVIRON,
'HELP_URL': settings.HELP_URL,
'SWIFT_CLOUD_ENABLED': settings.SWIFT_CLOUD_ENABLED,
}
def vault_session(request):
return {
'logged_user': r... |
499393 | from __future__ import absolute_import
from jinja2 import Markup
from changes.buildfailures.base import BuildFailure
class MissingTests(BuildFailure):
def get_html_label(self, build):
return Markup('Tests were expected for all results, but some or all were missing.')
|
499399 | from evoflow.config import floatx, intx
def _infer_dtype(a):
"infers what tensor.dtype to use for a given variable during conversion"
if isinstance(a, int):
dtype = intx()
elif isinstance(a, float):
dtype = floatx()
elif isinstance(a, list):
have_float = False
for v in ... |
499400 | import pymongo
client = pymongo.MongoClient('mongodb://172.17.0.3:27017/')
db = client['diagram']
col = db["http2Form"]
http2 = {
'header': {
'filter': False, 'fields': [], 'ShowOnMainLine': False
},
'payload': {
'filter': False, 'fields': [], 'ShowOnMainLine': False
},
}
x = col.del... |
499407 | from flask import Blueprint, Response, jsonify, request
from flask_cors import CORS
import requests
import json
pars = Blueprint('pars', __name__)
CORS(pars)
@pars.route('/parser', methods=['POST'])
def PARSER():
body = request.json
res = requests.post('http://localhost:8887/Query/Parser',json = body)
re... |
499412 | import pytest
from salesforce_api.const.service import VERB
from . import helpers
from salesforce_api import login, core, exceptions, const
class TestOAuth:
def create_connection(self, api_version: str = None):
return login.oauth2(
client_id=helpers.TEST_CLIENT_KEY,
cli... |
499497 | from __future__ import absolute_import, unicode_literals
from celery.utils import encoding
class test_encoding:
def test_safe_str(self):
assert encoding.safe_str(object())
assert encoding.safe_str('foo')
def test_safe_repr(self):
assert encoding.safe_repr(object())
class fo... |
499517 | import uuid
from datetime import datetime as dt, timezone as tz
from typing import List
import pytest
from botx import ChatTypes, CommandTypes, EntityTypes
from botx.models.messages.incoming_message import Command, IncomingMessage, Sender
@pytest.mark.parametrize(
("body", "command", "arguments", "single_argume... |
499575 | from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class AnnouncementsConfig(AppConfig):
"""
Katago Announcements app handles some messages for the front page of the site
"""
name = "src.apps.announcements"
verbose_name = _("Announcements")
def ready(sel... |
499609 | import pytest
from apachelogs import InvalidDirectiveError, LogParser, UnknownDirectiveError
@pytest.mark.parametrize(
"fmt",
[
"%",
"% ",
"%^x",
"%^",
"%{param",
],
)
def test_malformed_directive(fmt):
with pytest.raises(InvalidDirectiveError) as excinfo:
... |
499624 | import os
import sys
import cv2
import json
import fnmatch
import argparse
import numpy as np
from tqdm import tqdm
from scipy.spatial import cKDTree
import torch
from torch.utils.data.dataset import Dataset
from utils import *
sys.path.append('./SuperGlueMatching')
from models.utils import read_image
from models.su... |
499701 | from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy_serializer import SerializerMixin
Base = declarative_base(cls=SerializerMixin)
|
499705 | import shm
from shm.watchers import watcher
from mission.framework.task import Task
from mission.framework.targeting import PIDLoop
from mission.framework.combinators import (
Sequential,
Concurrent,
MasterConcurrent,
Retry,
Conditional,
Defer,
)
from mission.framework.movement import (
Dept... |
499731 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import pytest # type: ignore
def pytest_addoption(parser):
parser.addoption(
"--can-out-interface", default="None",
action="store",
help="The CAN interface to use with ... |
499735 | from itertools import chain
import torch
import numpy as np
import glob
import os
import MYTH
from datasets.dataset_adapter import DatasetAdapter
from local_config import base_data_folder
import os
class FlyingThingsAdapter(DatasetAdapter):
"""Adapter for the synthetic Flying Things dataset."""
base_datapath... |
499766 | import os
import logging
from datetime import datetime
def get_timestamp():
return datetime.now().strftime('%y%m%d-%H%M%S')
def mkdir(path):
if not os.path.exists(path):
os.makedirs(path)
def mkdirs(paths):
if isinstance(paths, str):
mkdir(paths)
else:
for path in paths:
... |
499782 | import collections.abc
import copy
import importlib
import yaml
import jinja2
from .parser_constants import FIRECROWN_RESERVED_NAMES
def parse(config_or_filename):
"""Parse a configuration file.
Parameters
----------
config_or_filename : str or dict
The config file to parse or an already par... |
499840 | import sys,os
#sys
# li = sys.argv
#
# if li[1] == "post":
# print("post")
# elif li[1] == "down":
# print("1111")
'''
sys.argv #在命令行参数是一个空列表,在其他中第一个列表元素中程序本身的路径
sys.exit(n) #退出程序,正常退出时exit(0)
sys.version #获取python解释程序的版本信息
sys.path #返回模块的搜索路径,初始化时使用python PATH环境变量的值
sys.platform #返回操作系统平台的名称
sys.stdin #输... |
499843 | from collections import Counter
from graphbrain import hedge
from graphbrain.hyperedge import edge_matches_pattern
argrole_order = {
'm': -1,
's': 0,
'p': 1,
'a': 2,
'c': 3,
'o': 4,
'i': 5,
't': 6,
'j': 7,
'x': 8,
'r': 9,
'?': 10
}
def normalize_edge(edge):
if edg... |
499898 | from dataclasses import dataclass
from typing import Iterator, List, Set, Tuple
@dataclass(frozen=True)
class Range:
min_val: int
max_val: int
def lits_to_ranges(
literals: Iterator[int],
) -> Tuple[Set[int], Set[Range]]:
lits = set()
ranges = set()
buf: List[int] = []
for lit in sorted(... |
499904 | from rpython.rlib.objectmodel import specialize
class Cache(object):
def __init__(self, space):
self.space = space
self.contents = {}
@specialize.memo()
def getorbuild(self, key):
try:
return self.contents[key]
except KeyError:
builder = self._build... |
500001 | import pytest
from conftest import generate_unique_name
from lahja import AsyncioEndpoint, ConnectionConfig
@pytest.mark.asyncio
async def test_endpoint_run():
endpoint = AsyncioEndpoint("test-run")
assert endpoint.is_running is False
async with endpoint.run():
assert endpoint.is_running is Tru... |
500031 | from collections import defaultdict
from sklearn.metrics import adjusted_mutual_info_score, normalized_mutual_info_score
def ami(p1, p2):
return adjusted_mutual_info_score(p1, p2)
def nmi(p1, p2):
return normalized_mutual_info_score(p1, p2, average_method='arithmetic')
def all_degrees(G):
return G.deg... |
500071 | from datetime import datetime
from pytz import timezone, UnknownTimeZoneError
from typing import Union
from .baseclasses import AbsoluteDateTime, RelativeDateTime
from .enums import Method
from .evaluatormethods import EvaluatorMethods
class Evaluator:
def __init__(self, parsed_object, tz="Europe/Berlin"):
... |
500157 | class HokiDialogue(object):
def __init__(self):
self.RED = '\u001b[31;1m'
self.ORANGE = '\u001b[33;1m'
self.GREEN = '\u001b[32;1m'
self.BLUE = '\u001b[36;1m'
self.ENDC = '\033[0m'
self.BOLD = '\033[1m'
self.UND = '\033[4m'
self.BCKG='\u001b[46;1m'
... |
500163 | import os, sys
import numpy as np
import torch.backends.cudnn as cudnn
import torch
from tqdm import tqdm
import argparse
import cv2
import imageio
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from pixielib.pixie import PIXIE
from pixielib.visualizer import Visualizer
from pixieli... |
500172 | from .base import *
SECRET_KEY = os.environ['DJANGO_SECRET_KEY']
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
DEBUG = False
ALLOWED_HOSTS = ['*']
|
500181 | from flask import Blueprint, render_template, request, redirect, url_for, flash
import requests
import logging
import utils
log = logging.getLogger("Nurevam.site")
blueprint = Blueprint('memes', __name__, template_folder='../templates/memes')
name = "memes"
description = "Allow to post a custom memes you like!"
db... |
500187 | from torch.nn.modules.module import Module
from ..functions.roi_align_3d import RoIAlignFunction3D
class RoIAlign3D(Module):
def __init__(self, out_size, out_size_depth, spatial_scale, spatial_scale_depth, sample_num=0):
super(RoIAlign3D, self).__init__()
self.out_size = out_size
self.ou... |
500228 | from ..factory import Type
class messageCall(Type):
discard_reason = None # type: "CallDiscardReason"
duration = None # type: "int32"
|
500240 | from ..value_set import ValueSet
class PositiveFinding(ValueSet):
"""
**Clinical Focus:** This value set contains concepts that represent positive test results. This is intended to be paired with other concepts that identify specific medical tests.
**Data Element Scope:** This value set may use the Quali... |
500295 | import bayesnewton
import objax
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import time
import tikzplotlib
print('loading rainforest data ...')
data = np.loadtxt('../data/TRI2TU-data.csv', delimiter=',')
nr = 50 # spatial grid point (y-axis)
nt = 100 # temporal grid points (x-axis)... |
500296 | import time
import serial
try:
import numpy as np
except ImportError:
np = None # You won't be able to use retrieve_data_log()
class C867_XY_Stage:
def __init__(self, which_port, verbose=True):
try:
self.port = serial.Serial(
port=which_port, baudrate=115200, timeout=1)
... |
500319 | from ._delta_graph import DeltaGraph
from ._node_classes.placeholder_node import PlaceholderNode
from ._node_classes.real_nodes import as_node
def placeholder_node_factory(*args, name=None, **kwargs) -> PlaceholderNode:
"""Node factory for for :py:class:`PlaceholderNode`.
The main use case of such nodes is a... |
500367 | import argparse
import logging
from collections import defaultdict
from overrides import overrides
from typing import Dict, List
from sacrerouge.commands import RootSubcommand
from sacrerouge.common import Params
from sacrerouge.common.logging import prepare_global_logging
from sacrerouge.common.util import import_mod... |
500394 | from .erd_cycle_state import ErdCycleState, ErdCycleStateRaw
CYCLE_STATE_RAW_MAP = {
ErdCycleStateRaw.PREWASH: ErdCycleState.PRE_WASH,
ErdCycleStateRaw.PREWASH1: ErdCycleState.PRE_WASH,
ErdCycleStateRaw.AUTO_HOT_START1: ErdCycleState.PRE_WASH,
ErdCycleStateRaw.AUTO_HOT_START2: ErdCycleState.PRE_WASH,
... |
500400 | import argparse
import logging
# Need to import there for pickle
from debias.datasets.dataset_utils import QuantileBatcher
from debias.datasets.squad import AnnotatedSquadLoader
from debias.experiments.eval_debiased_squad import compute_all_scores
from debias.models.text_pair_qa_model import TextPairQaDebiasingModel
f... |
500500 | import os
import shutil
from tempfile import gettempdir
import unittest
import modelforge.index as index
from modelforge.tests import fake_dulwich as fake_git
class GitIndexTests(unittest.TestCase):
tempdir = gettempdir()
cached_path = os.path.join(tempdir, "modelforge-test-cache")
repo_path = os.path.jo... |
500514 | from magma import *
from magma.testing import check_files_equal
def test():
class main(Circuit):
name = "main"
io = IO(O=Out(Bits[2]))
wire(array([0,1]), io.O)
compile("build/out2", main, output="verilog")
assert check_files_equal(__file__, "build/out2.v", "gold/out2.v")
|
500551 | import os
from pprint import pprint
from environs import Env, EnvValidationError
from marshmallow.validate import OneOf, Email, Length, Range
os.environ["TTL"] = "-2"
os.environ["NODE_ENV"] = "invalid"
os.environ["EMAIL"] = "^_^"
env = Env(eager=False)
TTL = env.int("TTL", validate=Range(min=0, max=100))
NODE_ENV ... |
500556 | import numpy as np
import torch
import albumentations as A
__all__ = ["SigmoidNormalization", "channel_name_to_mean_std", "CubicRootNormalization"]
channel_name_to_mean_std = {
"vv": (0, 50),
"vh": (0, 50),
"bathymetry": (
0,
1000.0,
),
"wind_speed": (6.81594445, 1.62833557),
}
# V... |
500593 | import numpy as np
def get_kaiserWindow(kHW):
kaiserWindow = np.zeros(kHW * kHW)
if kHW == 8:
kaiserWindow[0 + kHW * 0] = 0.1924
kaiserWindow[0 + kHW * 1] = 0.2989
kaiserWindow[0 + kHW * 2] = 0.3846
kaiserWindow[0 + kHW * 3] = 0.4325
kaiserWindow[1 + kHW * 0] = 0.2989
... |
500611 | for nname, net in ctx.nets:
ctx.lockNetRouting(nname)
ctx.cells["slice_i"].addInput("A0")
ctx.connectPort("ctr[26]", "slice_i", "A0")
ctx.cells["slice_i"].setParam("LUT0_INITVAL", "0101010101010101") # LED is active low so invert
ctx.cells["slice_i"].setParam("A0MUX", "A0") # remove constant mux on LUT input
|
500623 | import json
from editor.views.generic import user_json, stamp_json, comment_json
from editor.models import TimelineItem
from django.views import generic
from django import http
from django.urls import reverse
event_json_views = {
'stamp': stamp_json,
'comment': comment_json,
}
def event_json(event, viewed_by)... |
500625 | import maya.mel as mm
def evalMelString(pyString):
return mm.eval(pyString)
def convertStringsToMelArray(pyStrings):
return str([str(x) for x in pyStrings]).replace("'","\"").replace("[","{").replace("]", "}") |
500653 | from __future__ import print_function, absolute_import, division, unicode_literals
import numpy as np
import pytest
import pdb
from astropy import units as u
from astropy import constants as const
from linetools.spectralline import AbsLine
from linetools.analysis import voigt as lav
c_kms = const.c.to('km/s').value... |
500671 | import FWCore.ParameterSet.Config as cms
from Configuration.EventContent.EventContent_cff import *
# in case we want only the tagInfos and nothing more:
# (this means we need the jets for pt, eta and the JTA for being able
# to find the jet ref from the tag info)
BTAGCALAbtagCalibEventContent = cms.PSet(
outputCo... |
500681 | import numpy as np
from skorecard.bucketers import AsIsCategoricalBucketer
def test_correct_output(df):
"""Test that correct use of CatBucketTransformer returns expected results."""
X = df
y = df["default"].values
asb = AsIsCategoricalBucketer(variables=["EDUCATION"])
asb.fit(X, y)
X_trans = ... |
500687 | import pytest
import pylint_protobuf
@pytest.fixture
def motorcycle_mod(proto_builder):
preamble = """
syntax = "proto3";
package bikes;
"""
return proto_builder("""
message Engine {
int32 displacement = 2;
}
message Motorcycle {
string br... |
500699 | import discord
import asyncio
import logging
from discord.ext import commands
# self-created modules below
import lib.embedCreation as embedCreation #contains functions for creating an embed
import lib.tekkenFinder as tekkenFinder #contains functions for finding character and move details
# Get token from local dir... |
500701 | from enum import Enum
GENERIC_JSON_RPC_EXCEPTIONS = {
-32700: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.",
-32601: "Method not found",
-32602: "Problem parsing the parameters, or a mandatory parameter was not found",
-32603: "Internal JSON-RP... |
500702 | import unittest
from .utils import *
class TestReverseLdCoeffs(unittest.TestCase):
def test_reverse_ld_coeffs(self):
pass
class TestReverseQCoeffs(unittest.TestCase):
def test_quadratic(self):
expected_q1 = 36.
expected_q2 = 0.16666666666666666
q1, q2 = reverse_q_coeffs("q... |
500706 | import os
import unittest
from collections import namedtuple
import pandas as pd
from pmutt import cantera
class TestCantera(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
def test_get_omkm_range(self):
# Test that CTI range handles strings that can be directly converted... |
500804 | from cfast_slic import SlicModel
class BaseSlic(object):
arch_name = "__TODO__"
def __init__(self,
num_components=400,
slic_model=None,
compactness=10,
min_size_factor=0.25,
subsample_stride=3,
convert_to_lab... |
500912 | from __future__ import absolute_import, division, print_function
import cv2
import os
import os.path as osp
import pprint
import time
import numpy as np
import torch
import yaml
from torch.autograd import Variable
from torch.utils.data import DataLoader
from sacred import Experiment
from tracktor.config import get_o... |
500916 | import logging
import re
from contextlib import suppress
from datetime import timedelta, datetime, timezone
from pathlib import Path
from tempfile import NamedTemporaryFile
from time import monotonic, sleep
from typing import Callable, Optional, List, cast, ClassVar, Pattern, Tuple, IO
from urllib.parse import urljoin
... |
500927 | from Box2D import *
from typing import List
from settings import get_boxcar_constant
import math
import numpy as np
def rotate_floor_tile(coords: List[b2Vec2], center: b2Vec2, angle: float) -> List[b2Vec2]:
"""
Rotate a given floor tile by some number of degrees.
"""
rads = angle * math.pi ... |
500934 | from public import public
from ...common import exceptions as com
from .. import datatypes as dt
from .. import rules as rlz
from ..signature import Argument as Arg
from .core import ValueOp
@public
class MapLength(ValueOp):
arg = Arg(rlz.mapping)
output_type = rlz.shape_like('arg', dt.int64)
@public
class... |
500956 | from time import time
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from canvas.models import Comment, Category
from canvas import search
from django.conf import settings
class Command(BaseCommand):
args = 'solr_core'
help = 'WARNING: Deletes everything firs... |
500957 | import timm
import torch
import torch.nn.functional as F
from detectron2.layers import NaiveSyncBatchNorm, ShapeSpec
from detectron2.modeling import Backbone
from torch import nn
__all__ = ["BiFPN"]
class DepthwiseSeparableConv2d(nn.Sequential):
def __init__(
self,
in_channels,
... |
500991 | import re
from django.core.exceptions import ValidationError
def safe_character_validator(value):
unsafe_chars = re.compile(r'.*[<>\/\\;:&].*')
message = 'Enter only safe characters.'
if unsafe_chars.match(value):
raise ValidationError(message)
|
500994 | from .metrics import *
from .classifier_metric import accuracy
from .sr_metric import *
from .segmentation_metric import *
|
501023 | try:
from setuptools import setup
except:
from distutils.core import setup
setup(
name='t',
version='1.2.0',
author='<NAME>',
author_email='<EMAIL>',
url='https://hg.stevelosh.com/t',
py_modules=['t'],
entry_points={
'console_scripts': [
't = t:_main',
],... |
501035 | import enum
from typing import Iterable, Optional
from lms.lmsdb.models import Notification, User
class NotificationKind(enum.Enum):
CHECKED = 1
FLAKE8_ERROR = 2
UNITTEST_ERROR = 3
USER_RESPONSE = 4
def get(user: User) -> Iterable[Notification]:
return Notification.fetch(user)
def read(user: ... |
501041 | import tensorflow as tf
import numpy as np
from . import base_model
class Qnetwork(base_model.BaseModel):
"""
Args:
name (string): label for model namespace
path (string): path to save/load model
input_shape (tuple): tuple of inputs to network.
output_shape (int): number of out... |
501042 | INITIAL_RPC_IF_ID = RPC_IF_ID
class _RPC_IF_ID(INITIAL_RPC_IF_ID):
def __repr__(self):
return '<RPC_IF_ID "{0}" ({1}, {2})>'.format(self.Uuid.to_string(), self.VersMajor, self.VersMinor) |
501072 | import torch
from model import resnet34
from PIL import Image
import matplotlib.pyplot as plt
import json
import os
import torch.utils.data as data
import numpy as np
import pandas as pd
from PIL import Image
import cv2
import logging
from torchvision import transforms, datasets
from torch.utils.data import DataLoade... |
501107 | import sys
import os
import bz2
import pandas as pd
import numpy as np
import MySQLdb
from collections import defaultdict
file_path = os.path.dirname(os.path.realpath(__file__))
growth_lib_path = os.path.abspath(os.path.join(file_path, "..", "common"))
sys.path.insert(0, growth_lib_path)
''' Connect to DB '''
db = My... |
501207 | import random
import re
from contextlib import suppress
from socket import socket
from socks import ProxyError
from ripper.constants import HTTP_STATUS_CODE_CHECK_PERIOD_SEC
from ripper.context.events_journal import EventsJournal
from ripper.context.target import Target
from ripper.actions.attack_method import AttackM... |
501274 | import os, glob
from conans import CMake, ConanFile, tools
class MdnsConan(ConanFile):
name = "mdns"
license = "Unlicense"
homepage = "https://github.com/mjansson/mdns"
url = "https://github.com/conan-io/conan-center-index"
description = "Public domain mDNS/DNS-SD library in C"
topics = ("cona... |
501307 | import re
from collections import OrderedDict
from datetime import timedelta
from logging import Handler, LogRecord
from pathlib import Path
from threading import Thread
from typing import Dict, Any, TYPE_CHECKING, List, Optional, Union, Type, Tuple
from django.core.exceptions import ObjectDoesNotExist
from django.uti... |
501314 | from ..core import aio
from progressivis import ProgressiveError
from ..table.module import TableModule
from ..utils.psdict import PsDict
class DynVar(TableModule):
def __init__(self, init_val=None, vocabulary=None, **kwds):
super().__init__(**kwds)
self._has_input = False
if not (vocabula... |
501317 | import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from DeepRL.Agent import DoubleDQNAgent
from DeepRL.Env.gym_wrapper import CartPoleEnv
from DeepRL.Replay import NaiveReplay
from DeepRL.Train import Train
logging.basicConfig(level=logging.INFO)
logger = lo... |
501365 | import os
import argparse
import numpy as np
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
from utils.outputlib import WriteConfusionSeaborn
import torch
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', type=int, default=64)
parser.add_argument('--l... |
501384 | import asyncio
import logging
import pathlib
import aiohttp_jinja2
import jinja2
from aiohttp import web
from aiohttp_security import setup as setup_security
from aiohttp_security import CookiesIdentityPolicy
from motortwit.routes import setup_routes
from motortwit.security import AuthorizationPolicy
from motortwit.u... |
501406 | from amadeus.client.decorator import Decorator
class Activity(Decorator, object):
def __init__(self, client, activity_id):
Decorator.__init__(self, client)
self.activity_id = activity_id
def get(self, **params):
'''
Returns a single activity from a given id.
.. code-b... |
501463 | import os,re,glob
import numpy as np
from collections import defaultdict
import subprocess
import pandas as pd
RNA_dict = {'SRR3184279':'Pt1','SRR3184280':'Pt2','SRR3184281':'Pt4','SRR3184282':'Pt5','SRR3184283':'Pt6',
'SRR3184284': 'Pt7','SRR3184285':'Pt8','SRR3184286':'Pt9','SRR3184287':'Pt10','SRR318428... |
501573 | import ctypes
import os
import mobula
from mobula.testing import assert_almost_equal, gradcheck
def test_custom_struct():
class MyStruct(ctypes.Structure):
_fields_ = [
('hello', ctypes.c_int),
('mobula', ctypes.c_float),
]
mobula.glue.register_cstruct('MyStruct', MyS... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.