id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
40829 | import glob
import pickle
import sys
import msprime as msp
import numpy as np
import os
import multiprocessing as mp
import shutil
import random
import copy
import argparse
import h5py
import allel
import time
from sklearn.neighbors import NearestNeighbors
from sklearn.utils import resample
import matplotlib as mpl
m... |
40835 | from functools import wraps
from contextlib import contextmanager
from .core import Hub, gethub, Future, Condition, Lock, TimeoutError
__version__ = '0.2.a0'
__all__ = [
'Hub',
'gethub',
'sleep',
'Future',
'Condition',
'Lock',
]
def sleep(value):
gethub().do_sleep(value)
|
40844 | import platform
"""
[Note for Windows]
- Use '\\' or '/' in path
Ex) gitStoragePath = "D:\\Source\\gitrepos"
- Install 'Git for Windows'
- Windows version of VUDDY use its own JRE
[Note for POSIX]
- Use '/' for path
Ex) gitStoragePath = "/home/ubuntu/gitrepos/"
- Java binary is only needed in POSIX
"""
gitStoragePat... |
40854 | import os
from pathlib import Path
def menpo3d_src_dir_path():
r"""The path to the top of the menpo3d Python package.
Useful for locating where the data folder is stored.
Returns
-------
path : str
The full path to the top of the Menpo3d package
"""
return Path(os.path.abspath(__... |
40858 | from ursina import *
app = Ursina()
bg = Entity(model='quad', texture='assets\BG', scale=36, z=1)
window.fullscreen = True
player = Animation('assets\player', collider='box', y=5)
fly = Entity(model='cube', texture='assets\\fly1', collider='box',
scale=2, x=20, y=-10)
flies = []
def newFly():
new = dup... |
40978 | from distutils.core import setup
from Cython.Build import cythonize
setup(
name = "tax",
ext_modules = cythonize('tax.pyx'),
script_name = 'setup.py',
script_args = ['build_ext', '--inplace']
)
import tax
import numpy as np
print(tax.tax(np.ones(10)))
|
40984 | from rest_framework.permissions import SAFE_METHODS, BasePermission
class ApiPermission(BasePermission):
def _has_permission(self, view, obj, request):
event = getattr(request, "event", None)
if not event: # Only true for root API view
return True
if request.method in SAFE_ME... |
40998 | import datetime
from django.core.management.base import BaseCommand
from data_import.models import DataFileKey
class Command(BaseCommand):
"""
A management command for expunging expired keys
"""
help = "Expunge expired keys"
def handle(self, *args, **options):
self.stdout.write("Expung... |
41002 | import argparse
import os
argparser = argparse.ArgumentParser()
argparser.add_argument("--dataset_names", default="all", type=str) # "all" or names joined by comma
argparser.add_argument("--dataset_path", default="DATASET/odinw", type=str)
args = argparser.parse_args()
root = "https://vlpdatasets.blob.core.windows.ne... |
41045 | import tensorrt as trt
import pycuda.driver as cuda
import cv2
import numpy as np
class TrtPacknet(object):
"""TrtPacknet class encapsulates things needed to run TRT Packnet (depth inference)."""
def _load_engine(self):
TRTbin = 'trt_%s.trt' % self.model
with open(TRTbin, 'rb') as f, trt.Runt... |
41049 | from random import randint
from typing import Any
from typing import Dict
from retrying import retry
import apysc as ap
from apysc._event.mouse_up_interface import MouseUpInterface
from apysc._expression import expression_data_util
from apysc._type.variable_name_interface import VariableNameInterface
cl... |
41071 | import scrapy
from aroay_cloudscraper import CloudScraperRequest
class JavdbSpider(scrapy.Spider):
name = 'javdb'
allowed_domains = ['javdb.com']
headers = {"Accept-Language": "zh-cn;q=0.8,en-US;q=0.6"}
def start_requests(self):
yield CloudScraperRequest("https://javdb.com/v/BOeQO", callback=... |
41092 | import sys
import setuptools
sys.path.insert(0, "src")
import pytorch_adapt
with open("README.md", "r") as fh:
long_description = fh.read()
extras_require_ignite = ["pytorch-ignite == 0.5.0.dev20220221"]
extras_require_lightning = ["pytorch-lightning"]
extras_require_record_keeper = ["record-keeper >= 0.9.31"]... |
41130 | from urllib import request
def download_from_url(url, filename):
request.urlretrieve(url, filename) |
41205 | import numpy as np
import queue
import cv2
import os
import datetime
SIZE = 32
SCALE = 0.007874015748031496
def quantized_np(array,scale,data_width=8):
quantized_array= np.round(array/scale)
quantized_array = np.maximum(quantized_array, -2**(data_width-1))
quantized_array = np.minimum(quantized_array, 2**... |
41238 | import os
import secrets
import threading
import tornado.web
import tornado.escape
import logging.config
from app.classes.models import Roles, Users, check_role_permission, Remote, model_to_dict
from app.classes.multiserv import multi
from app.classes.helpers import helper
from app.classes.backupmgr import backupmgr
... |
41277 | import numpy as np
import tensorflow as tf
import unittest
hungarian_module = tf.load_op_library("hungarian.so")
class HungarianTests(unittest.TestCase):
def test_min_weighted_bp_cover_1(self):
W = np.array([[3, 2, 2], [1, 2, 0], [2, 2, 1]])
M, c_0, c_1 = hungarian_module.hungarian(W)
with tf.Session()... |
41285 | from cartodb_services.refactor.storage.redis_connection_config import RedisMetadataConnectionConfigBuilder
from cartodb_services.refactor.storage.redis_connection import RedisConnectionBuilder
from cartodb_services.refactor.storage.redis_config import RedisUserConfigStorageBuilder
class UserConfigBackendFactory(object... |
41296 | from rest_framework.generics import get_object_or_404
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_200_OK
from river.models import Function
from river_admin.views import get, post, put, delete
from river_admin.views.serializers import UpdateFunctionDto, Crea... |
41299 | import logging
from logging.config import dictConfig
import dbnd
from dbnd.testing.helpers import run_dbnd_subprocess__with_home
from dbnd_airflow_contrib.dbnd_airflow_default_logger import DEFAULT_LOGGING_CONFIG
class TestDbndAirflowLogging(object):
def test_dbnd_airflow_logging_conifg(self):
# we imp... |
41311 | from base import CQPartsTest
from base import testlabel
# units under test
from cqparts_fasteners.fasteners.nutbolt import NutAndBoltFastener
# ---------- Test Assembly ----------
import cadquery
import cqparts
from partslib.basic import Box
from cqparts import constraint
from cqparts.utils import CoordSystem
class... |
41317 | from tests.utilities import is_equivalent
def test_mutate(case_data):
"""
Test :meth:`mutate`.
Parameters
----------
case_data : :class:`.CaseData`
A test case. Holds the mutator to test and the correct mutation
record.
Returns
-------
None : :class:`NoneType`
""... |
41459 | import FWCore.ParameterSet.Config as cms
pileupVtxDigitizer = cms.PSet(
accumulatorType = cms.string("PileupVertexAccumulator"),
hitsProducer = cms.string('generator'),
vtxTag = cms.InputTag("generatorSmeared"),
vtxFallbackTag = cms.InputTag("generator"),
makeDigiSimLinks = cms.untracked.bool(False... |
41473 | from dataset.transform import crop, hflip, normalize, resize, blur, cutout
import math
import os
from PIL import Image
import random
from torch.utils.data import Dataset
from torchvision import transforms
class SemiDataset(Dataset):
def __init__(self, name, root, mode, size, labeled_id_path=None, unlabeled_id_pa... |
41523 | import os
import trimesh
import unittest
import pocketing
import numpy as np
def get_model(file_name):
"""
Load a model from the models directory by expanding paths out.
Parameters
------------
file_name : str
Name of file in `models`
Returns
------------
mesh : trimesh.Geomet... |
41553 | import unittest2
import json
from datafeeds.resource_library_parser import ResourceLibraryParser
class TestResourceLibraryParser(unittest2.TestCase):
def test_parse_hall_of_fame(self):
with open('test_data/hall_of_fame.html', 'r') as f:
teams, _ = ResourceLibraryParser.parse(f.read())
... |
41612 | from django.db import models
from djangae import patches # noqa
class DeferIterationMarker(models.Model):
"""
Marker to keep track of sharded defer
iteration tasks
"""
# Set to True when all shards have been deferred
is_ready = models.BooleanField(default=False)
shard_count = m... |
41652 | import sublime, sublime_plugin
from os.path import join as join_path, isdir
from os import mkdir
IS_WINDOWS = sublime.platform() == 'windows'
PATH_SEPARATOR = '\\' if IS_WINDOWS else '/'
EXTENSION = '.exe' if IS_WINDOWS else ''
class VlangBuilderCommand(sublime_plugin.WindowCommand):
def run(self, **kwargs):
... |
41661 | import sublime, sublime_plugin
import os
from ...libs import util
from ...libs import JavascriptEnhancementsExecuteOnTerminalCommand
class JavascriptEnhancementsGenerateJsdocCommand(JavascriptEnhancementsExecuteOnTerminalCommand, sublime_plugin.WindowCommand):
is_node = True
is_bin_path = True
def prepare_comm... |
41665 | import torch.nn as nn
from architectures.position_wise_feed_forward_net import PositionWiseFeedForwardNet
from architectures.multi_head_attention import MultiHeadAttention
from architectures.add_and_norm import AddAndNorm
class TransformerEncoderBlock(nn.Module):
def __init__(self, d_model, n_heads, d_ff, dropout... |
41674 | from collections import Counter, defaultdict
import matplotlib as mpl
import networkx as nx
import numba
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import seaborn as sns
from fa2 import ForceAtlas2
from scipy import sparse
def to_adjacency_matrix(net):
if sparse.issparse(net):
... |
41706 | import json
import logging
from django.urls import reverse
from seahub.test_utils import BaseTestCase
from tests.common.utils import randstring
from seahub.institutions.models import Institution, InstitutionAdmin
from seahub.profile.models import Profile
logger = logging.getLogger(__name__)
class AdminInstitutionUs... |
41717 | import numpy as np
def bowl(vs, v_ref=1.0, scale=.1):
def normal(v, loc, scale):
return 1 / np.sqrt(2 * np.pi * scale**2) * np.exp( - 0.5 * np.square(v - loc) / scale**2 )
def _bowl(v):
if np.abs(v-v_ref) > 0.05:
return 2 * np.abs(v-v_ref) - 0.095
else:
return ... |
41721 | load("//bazel/rules/cpp:object.bzl", "cpp_object")
load("//bazel/rules/hcp:hcp.bzl", "hcp")
load("//bazel/rules/hcp:hcp_hdrs_derive.bzl", "hcp_hdrs_derive")
def string_tree_to_static_tree_parser(name):
#the file names to use
target_name = name + "_string_tree_parser_dat"
in_file = name + ".dat"
outfile... |
41723 | import datetime
from django.core.cache import cache
from django.test import TestCase, override_settings
from django.utils import timezone
from wagtail.core.models import Page, Site
from wagtail.tests.utils import WagtailTestUtils
from tests.app.models import NewsIndex, NewsItem
def dt(*args):
return datetime.da... |
41800 | from _revkit import netlist, gate
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
def _to_qiskit(self, circuit=None, with_classical_register=False):
"""
Convert RevKit quantum circuit into Qiskit quantum circuit
:param qiskit.QuantumCircuit circuit: If not `None`, add gates to this circui... |
41845 | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from config import Config
def cuda_(var):
return var.cuda() if Config.use_gpu else var
class Net(nn.Module):
def __init__(self, state_dim, num_actions):
super(Net, self).__init__()
self.linear1 = nn... |
41865 | from wtforms import StringField
from flask_babel import lazy_gettext
from wtforms.validators import DataRequired
from flask_appbuilder.fieldwidgets import BS3TextFieldWidget
from flask_appbuilder.forms import DynamicForm
class TestForm(DynamicForm):
TestFieldOne = StringField(lazy_gettext('Test Field One'), valid... |
41903 | import numpy as np
class DOM:
"""
Object representing a discretized observation model. Comprised primarily by the
DOM.edges and DOM.chi vectors, which represent the discrete mask and state-dependent
emission probabilities, respectively.
"""
def __init__(self):
self.k = None
se... |
41918 | from __future__ import print_function
from itertools import product
import torch
import torch.nn as nn
import torch_mlu
from torch.nn import Parameter
import torch.nn.functional as F
import numpy as np
import sys
import os
import copy
import random
import time
import unittest
cur_dir = os.path.dirname(os.path.abspath(... |
41943 | import torch
import torch.nn as nn
__all__ = [
'ConcatEmbeddings',
'PassThrough',
'MeanOfEmbeddings',
]
class ConcatEmbeddings(nn.Module):
def __init__(self, fields):
super().__init__()
self.output_dim = sum([field.output_dim for field in fields.values()])
self.embedders = nn.... |
41948 | import json
import tempfile
from collections import OrderedDict
import os
import numpy as np
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from utils import BoxList
#from utils.pycocotools_rotation import Rotation_COCOeval
def evaluate(dataset, predictions, result_file, score_... |
41977 | import unittest
import update_logs
class UpdateLogsTest(unittest.TestCase):
def test_get_new_logs_with_more_next_logs(self):
self.assertEqual(
"56789",
update_logs.get_new_logs(prev_logs="01234", next_logs="0123456789"))
def test_get_new_logs_with_more_prev_logs(self):
... |
41995 | import time
import numpy as np
import utils.measurement_subs as measurement_subs
import utils.socket_subs as socket_subs
from .do_fridge_sweep import do_fridge_sweep
from .do_device_sweep import do_device_sweep
def device_fridge_2d(
graph_proc, rpg, data_file,
read_inst, sweep_inst=[], set_inst=[],
... |
42009 | import re
import numpy as np
import sympy as sp
import random as rd
from functools import reduce
NORMAL_VECTOR_ID = 'hyperplane_normal_vector_%s_%i'
NUM_NORMAL_VECS_ID = 'num_normal_vectors_%s'
CHAMBER_ID = 'chamber_%s_%s'
FVECTOR_ID = 'feature_vector_%s'
FVEC_ID_EX = re.compile(r'feature_vector_([\S]*)')
class Hype... |
42018 | import graph_ltpl.offline_graph.src.gen_edges
import graph_ltpl.offline_graph.src.gen_node_skeleton
import graph_ltpl.offline_graph.src.gen_offline_cost
import graph_ltpl.offline_graph.src.main_offline_callback
import graph_ltpl.offline_graph.src.prune_graph
|
42083 | import pandas as pd
from autogluon.utils.tabular.utils.savers import save_pd
from autogluon_utils.benchmarking.evaluation.preprocess import preprocess_openml
from autogluon_utils.benchmarking.evaluation.constants import *
def run():
results_dir = 'data/results/'
results_dir_input = results_dir + 'input/raw/... |
42092 | from tests.functional.services.policy_engine.utils.api.conf import (
policy_engine_api_conf,
)
from tests.functional.services.utils import http_utils
def get_vulnerabilities(
vulnerability_ids=[],
affected_package=None,
affected_package_version=None,
namespace=None,
):
if not vulnerability_ids... |
42095 | from flake8_aaa.line_markers import LineMarkers
from flake8_aaa.types import LineType
def test():
result = LineMarkers(5 * [''], 7)
assert result.types == [
LineType.unprocessed,
LineType.unprocessed,
LineType.unprocessed,
LineType.unprocessed,
LineType.unprocessed,
... |
42115 | import platform as platform_module
import pytest
from cibuildwheel.__main__ import get_build_identifiers
from cibuildwheel.environment import parse_environment
from cibuildwheel.options import Options, _get_pinned_docker_images
from .utils import get_default_command_line_arguments
PYPROJECT_1 = """
[tool.cibuildwhe... |
42143 | from __future__ import absolute_import, unicode_literals
from django.core.management.base import BaseCommand
from molo.core.models import ArticlePage
class Command(BaseCommand):
def handle(self, **options):
ArticlePage.objects.all().update(
featured_in_latest=False,
featured_in_la... |
42149 | from itertools import chain
from nose.tools import *
from hawkweed.monads.either import Either, Left, Right, is_right,\
is_left, is_either, either, lefts, rights, partition_eithers
from hawkweed.functional.primitives import identity
def test_right():
assert_equal(Right(10).bind(identity), 10)
def test_not... |
42177 | from openpathsampling.high_level.network import FixedLengthTPSNetwork
from openpathsampling.high_level.transition import FixedLengthTPSTransition
import openpathsampling as paths
class PartInBFixedLengthTPSTransition(FixedLengthTPSTransition):
"""Fixed length TPS transition accepting any frame in the final state.
... |
42190 | from collections import deque
import networkx as nx
import numpy as np
def random_subtree(T, alpha, beta, subtree_mark):
""" Random subtree of T according to Algorithm X in [1].
Args:
alpha (float): probability of continuing to a neighbor
beta (float): probability of non empty subtree
... |
42194 | from django.apps import AppConfig
class ClubADMConfig(AppConfig):
name = "clubadm"
verbose_name = "Клуб анонимных Дедов Морозов"
|
42237 | countries = {
"kabul": "afghanistan",
"tirana": "albania",
"alger": "algeria",
"fagatogo": "american samoa",
"andorra la vella": "andorra",
"luanda": "angola",
"the valley": "anguilla",
"null": "united states minor outlying islands",
"saint john's": "antigua and barbuda",
"buenos... |
42298 | import os
import shutil
import json
import pandas as pd
import ast
import numpy as np
from utils.read_convergence import plot_convergence, parse, get_cffl_best
fairness_keys = [
'standalone_vs_fedavg_mean',
'standalone_vs_rrdssgd_mean',
'standalone_vs_final_mean',
]
def collect_and_compile_performance(dirnam... |
42324 | import os
directory="/home/pi/Desktop/samplepacks/"
sampleList=[["test","test"]]
def main():
for file in os.listdir(directory):
fullPath = directory + file
if os.path.isdir(fullPath):
#print
#print "directory: ",file
#print fullPath
containsAif=0
#each folder in parent directory
for subfil... |
42356 | from typing import Optional
import tensorflow as tf
import tensorflow.keras.backend as K
from tensorflow.keras import Model
from tensorflow.keras.layers import Layer
import numpy as np
import rinokeras as rk
from rinokeras.layers import WeightNormDense as Dense
from rinokeras.layers import LayerNorm, Stack
class Ra... |
42364 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="iam-permissions-guardrails", # Replace with your own username
version="0.0.3",
author="<NAME>",
author_email="<EMAIL>",
description="IAM Permissions Guardrails module",
long_descripti... |
42415 | import hyperopt
import csv
import json
import traceback
import os.path
from pprint import pprint
import datetime
import time
import numpy.random
import threading
import queue
import copy
import tempfile
import random
import subprocess
import concurrent.futures
import tempfile
import functools
import math
import atexit
... |
42435 | from unittest import TestCase
import sys
sys.path.append("./AerialNavigation/rocket_powered_landing/")
from AerialNavigation.rocket_powered_landing import rocket_powered_landing as m
print(__file__)
class Test(TestCase):
def test1(self):
m.show_animation = False
m.main()
|
42469 | class SearchModule:
def __init__(self):
pass
def search_for_competition_by_name(self, competitions, query):
m, answer = self.search(competitions, attribute_name="caption", query=query)
if m == 0:
return False
return answer
def search_for_competition_by_code(self... |
42484 | from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
import logging
from libs.modules.FuseBlock import MakeFB
from .resnet_dilation import resnet50, resnet101, Bottleneck, conv1x1
BN_MOMENTUM = 0.1
logger = logging.getLogger(__name__)
def conv3x3(in_planes, out_plan... |
42499 | import time
from selenium import webdriver
from lxml import etree
driver = webdriver.PhantomJS(executable_path='./phantomjs-2.1.1-macosx/bin/phantomjs')
# 获取第一页的数据
def get_html():
url = "https://detail.tmall.com/item.htm?id=531993957001&skuId=3609796167425&user_id=268451883&cat_id=2&is_b=1&rn=71b9b0aeb233411c4f5... |
42582 | import urllib
from bs4 import BeautifulSoup
print ("Collecting data from IMDb charts....\n\n\n")
print ("The current top 15 IMDB movies are the following: \n\n")
response = urllib.request.urlopen("http://www.imdb.com/chart/top")
html = response.read()
soup = BeautifulSoup(html, 'html.parser')
mytd = soup.findAll("td",... |
42601 | from uuid import UUID
from datetime import datetime
def uuid_from_string(string):
return UUID('{s}'.format(s=string))
def format_timestamp(string):
if isinstance(string, str):
return datetime.strptime(string, '%Y-%m-%dT%H:%M:%S.%fZ')
if isinstance(string, datetime):
return string
|
42613 | import sys
from glob import glob
from serial import Serial, SerialException
import numpy as np
BAUD_RATE = 9600
PORT = 'COM5'
READ_TIMEOUT = 1
LOWER_BOUND = 0.01
UPPER_BOUND = 0.4
class SerialCommunication():
""" Manages the communication and sends the data to the Arduino """
def __init__(self):
s... |
42620 | import assets
import webbrowser
from PyQt5.Qt import QMessageBox
from PyQt5.QtNetwork import QNetworkDiskCache
from PyQt5.QtWebKitWidgets import QWebPage, QWebInspector
class WebPage(QWebPage):
def __init__(self):
super(WebPage, self).__init__()
self.inspector = QWebInspector()
self.inspector.setPage(self)
se... |
42624 | import sys
import time
import threading
import grpc
import numpy
import soundfile as sf
import tensorflow as tf
import _init_paths
import audioset.vggish_input as vggish_input
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc
tf.app.flags.DEFINE_integer... |
42685 | from __future__ import annotations
import json
import os
import shutil
import subprocess
import tempfile
import uuid
from abc import ABC, abstractmethod
from typing import Any, Union
from urllib.error import HTTPError
from urllib.request import urlopen, urlretrieve
import warnings
import meerkat as mk
import pandas a... |
42686 | import asyncio
import json
import zlib
import aiohttp
import errors
API_BASE = 'https://discordapp.com/api/v6'
CONFIG_FILE = json.load(open('data/config.json'))
TOKEN = CONFIG_FILE['token']
HEADERS = {'Authorization': 'Bot ' + TOKEN,
'User-Agent': 'DiscordBot (https://www.github.com/fourjr/dapi-bot,\
... |
42760 | from tensorflow.keras.layers import (Conv2D, Dense, Flatten, MaxPooling2D,
TimeDistributed)
def VGG16(inputs):
x = Conv2D(64,(3,3),activation = 'relu',padding = 'same',name = 'block1_conv1')(inputs)
x = Conv2D(64,(3,3),activation = 'relu',padding = 'same', name = 'bl... |
42761 | from ...schema_classes import SchemaClasses
ContainerType = SchemaClasses.sysflow.type.ContainerTypeClass
OID = SchemaClasses.sysflow.type.OIDClass
SFObjectState = SchemaClasses.sysflow.type.SFObjectStateClass
|
42774 | from .seg import seg
class cbs(seg):
'''
cbs file type extends from seg files
'''
_fileType = "cbs"
|
42784 | from pygments.lexer import RegexLexer
from pygments.token import Comment, Keyword, Name, Number, Operator, Punctuation, String, Text
__all__ = ["GraphQLLexer"]
class GraphQLLexer(RegexLexer):
"""
Pygments GraphQL lexer for mkdocs
"""
name = "GraphQL"
aliases = ["graphql", "gql"]
filenames = ... |
42790 | from copy import copy
import sqlite3
import pandas as pd
import pandas_to_sql
from pandas_to_sql.testing.utils.fake_data_creation import create_fake_dataset
from pandas_to_sql.conventions import flatten_grouped_dataframe
# table_name = 'random_data'
# df, _ = create_fake_dataset()
# df_ = pandas_to_sql.wrap_df(df, tab... |
42793 | from flask_restful import Api
class ViewInjector:
def __init__(self, app=None):
if app is not None:
self.init_app(app)
def init_app(self, app):
from app.views.blockchain import Node, Chain, Mine, Transaction
api = Api(app)
api.add_resource(Node, '/node')
... |
42826 | import time
import mxnet as mx
benchmark_dataiter = mx.io.ImageRecordIter(
path_imgrec="../data/test.rec",
data_shape=(1, 28, 28),
batch_size=64,
mean_r=128,
scale=0.00390625,
)
mod = mx.mod.Module.load('mnist_lenet', 35, context=mx.gpu(2))
mod.bind(
data_shapes=benchmark_dataiter.provide_data... |
42872 | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
dic = {}
for char in s:
dic[char] = dic.get(char,0)+1
res = []
for char in s:
dic[char] -= 1
if char not in res:
while res and char<res[-1] and dic[res[-1]]>0:
... |
42884 | import argparse
def merge(infiles, outfile):
setReads = set()
for infile in infiles:
with open(infile, "r") as fileIn:
for strLine in fileIn:
if strLine.startswith('@'):
continue
strSplit = strLine.split("\t")
if strSplit[... |
42930 | from ._kaldi_error import *
from ._timer import *
__all__ = [name for name in dir()
if name[0] != '_'
and not name.endswith('Base')]
|
43000 | import setuptools
setuptools.setup(
name="almond-cloud-cli",
version="0.0.0",
author="<NAME>",
author_email="<EMAIL>",
description="Command Line Interface (CLI) for Almond Cloud development and deployment",
url="https://github.com/stanford-oval/almond-cloud",
packages=setuptools.find_packag... |
43067 | import pickle
import numpy as np
import matplotlib.pyplot as plt
with open('./quadratic/eval_record.pickle','rb') as loss:
data = pickle.load(loss)
print('Mat_record',len(data['Mat_record']))
#print('bias',data['inter_gradient_record'])
#print('constant',data['intra_record'])
with open('./quadratic/evaluate_reco... |
43085 | from django.forms import TextInput
from django.forms.widgets import MultiWidget, RadioSelect
from django.template.loader import render_to_string
class MultiTextWidget(MultiWidget):
def __init__(self, widgets_length, **kwargs):
widgets = [TextInput() for _ in range(widgets_length)]
kwargs.update({"... |
43090 | import socket
def is_connectable(host, port):
sock = None
try:
sock = socket.create_connection((host, port), 1)
result = True
except socket.error:
result = False
finally:
if sock:
sock.close()
return result
|
43108 | from singlecellmultiomics.modularDemultiplexer.baseDemultiplexMethods import UmiBarcodeDemuxMethod
class chrom10x_c16_u12(UmiBarcodeDemuxMethod):
def __init__(self, barcodeFileParser, **kwargs):
self.barcodeFileAlias = '10x_3M-february-2018'
UmiBarcodeDemuxMethod.__init__(
self,
... |
43109 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# read CSV data into a "dataframe" - pandas can parse dates
# this will be familiar to R users (not so much matlab users)
df = pd.read_csv('data/SHA.csv', index_col=0, parse_dates=True)
Q = df.SHA_INFLOW_CFS # a pandas series (daily)
# Q = Q.resa... |
43115 | import unittest
from calculator import multiply
class TestSomething(unittest.TestCase):
def test_multiply(self):
self.assertEqual(6, multiply(2,3))
if __name__ == '__main__':
unittest.main()
|
43155 | from util.callbacks import callsback
from util.threads.timeout_thread import Timer
from util.primitives import Storage as S
from traceback import print_exc
import util.primitives.structures as structures
from .fbutil import trim_profiles, extract_profile_ids
import traceback
import simplejson
import facebookapi
import ... |
43162 | import configparser
import os
ApplicationDir = os.path.dirname(os.path.abspath(__file__))
HomeDir = os.path.expanduser('~')
CredentialDir = os.path.join(HomeDir, '.credentials')
if not os.path.exists(CredentialDir):
os.makedirs(CredentialDir)
CredentialFilePath = os.path.join(CredentialDir, 'CalSyncHAB.json')
Ca... |
43213 | from relex.predictors.relation_classification.relation_classifier_predictor import RelationClassifierPredictor
|
43268 | import datetime
import re
import time
from collections import namedtuple
from django.conf import settings
from django.core.management.base import BaseCommand
from trello import ResourceUnavailable, TrelloClient
from core.models import Event
# Create new command
class Command(BaseCommand):
help = 'Syncs event i... |
43291 | from setuptools import setup, find_packages
try:
import s3stat
doc = s3stat.__doc__
except ImportError:
doc = "The docs are only available when the package is already installed. Sorry for this."
setup(
name="s3stat",
version="2.3.1",
description='An extensible Amazon S3 and Cloudfront log ... |
43299 | import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import psoap
from psoap.data import lkca14, redshift, Chunk
from psoap import matrix_functions
from psoap import covariance
from psoap import orbit
# from matplotlib.ticker import FormatStrFormatter as FSF
# from matplotlib.tick... |
43322 | from slack_sdk import WebClient
from slack_bolt.app.app import SlackAppDevelopmentServer, App
from tests.mock_web_api_server import (
setup_mock_web_api_server,
cleanup_mock_web_api_server,
)
from tests.utils import remove_os_env_temporarily, restore_os_env
class TestDevServer:
signing_secret = "secret"
... |
43337 | import tensorflow as tf
if __name__ == "__main__":
with tf.Session() as sess:
game_dir = "Gobang"
model_dir = "model2_10_10_5"
batch = "11000"
# 初始化变量
sess.run(tf.global_variables_initializer())
# 获取最新的checkpoint,其实就是解析了checkpoint文件
latest_ckpt = tf.train.... |
43338 | from django.db import connection
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view()
def root(request):
return Response({"message": "Hello, from Yappa!",
"next step": "go to the next example: "
"connect you ... |
43391 | from .assembla import AssemblaPlatform
from .base import BasePlatform
from .bitbucket import BitbucketPlatform
from .friendcode import FriendCodePlatform
from .github import GitHubPlatform
from .gitlab import GitLabPlatform
# Supported platforms
PLATFORMS = [
# name -> Platform object
("github", GitHubPlatform... |
43445 | from pysmt.shortcuts import Symbol
from pysmt.typing import INT
h = Symbol("H", INT)
domain = (1 <= h) & (10 >= h)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.