id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
491738 | import os
from pathlib import Path
from time import sleep
from boucanpy.core import logger
from boucanpy.core.utils import storage_dir
from boucanpy.cli.base import BaseCommand
from boucanpy.api_client import ApiClient
from boucanpy.http.manager import HttpServerManager
class HttpServer(BaseCommand):
name = "http... |
491792 | import re
import pandas as pd
from cowidev.utils.clean import clean_count
from cowidev.utils.web.scraping import get_soup
from cowidev.vax.utils.incremental import enrich_data, increment
from cowidev.utils.clean.dates import localdate
import datetime
def read(source: str) -> pd.Series:
soup = get_soup(source)
... |
491849 | from . import statefulfunction
from .statefulfunction import *
__all__ = list(statefulfunction.__all__)
|
491880 | import os,os.path,shutil
import numpy as np
import pickle
import dmdd
import dmdd_efficiencies as eff
def check_min_mass(element='fluorine', Qmin=1., v_esc=544., v_lag=220., mx_guess=1.):
experiment = dmdd.Experiment('test',element,Qmin, 40.,100., eff.efficiency_unit)
res = experiment.find_min_mass(v_esc=v_e... |
491885 | import gensim
import random
import logging
# configuration
trains = "../../temp_results/word2vec_hindi.txt"
create = 1
topn = 10
data_folder = '../data/word2vec_evaluation/'
TARGET_SYN = data_folder+'syntactic.questions.txt'
TARGET_SEM_OP = data_folder+'semantic_op.questions.txt'
TARGET_SEM_BM = data_folder+'se... |
491908 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributions as D
from torch import Tensor
from .functions import *
from .common import *
class ActorCritic(nn.Module):
def __init__(self,
in_dim,
out_actions,
hidden_dim=400,
... |
491926 | import doxygen_basic_notranslate
import inspect
import string
import sys
import comment_verifier
comment_verifier.check(inspect.getdoc(doxygen_basic_notranslate.function),
r"""\brief
Brief description.
The comment text
\author Some author
\return Some number
\sa function2"""
)
comment_verifier.check(inspect.getd... |
491931 | import random
try:
random = random.SystemRandom()
except NotImplementedError:
pass
def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'0123456789'):
return '... |
491947 | from django.test import TestCase
from ..importer import Importer
class ImporterTestCase(TestCase):
def test_load(self):
""" Test that the loaded attribute is changed appropriately when the
importer is loaded.
"""
importer = Importer('module')
self.assertFalse(importer.loa... |
491970 | import os
import subprocess
try:
from munkicon import worker
except ImportError:
from .munkicon import worker
# Keys: 'mac_os_python_path'
# 'mac_os_python_ver'
# 'munki_python_path'
# 'munki_python_symlink'
# 'munki_python_ver'
# 'official_python3_path'
# 'official_python3... |
491980 | import sys
def main(input_filename):
test_cases = open(input_filename, 'r')
for test in test_cases:
test = test.strip()
word = list(test.split(' ')[0])
mask = list(test.split(' ')[1])
result = []
for m, w in zip(mask, word):
if m == '1':
resul... |
491987 | def sum_zero(n):
zero_sum_array = []
counter = 1
if n % 2 != 0:
zero_sum_array.append(0)
n -= 1
while n:
zero_sum_array.append(counter)
zero_sum_array.append(-counter)
counter += 1
n -= 2
return zero_sum_array
|
492077 | from torchsso.utils.logger import Logger # NOQA
from torchsso.utils.inv_cupy import inv # NOQA
from torchsso.utils.cholesky_cupy import cholesky # NOQA
from torchsso.utils.accumulator import TensorAccumulator # NOQA
|
492112 | import copy
import itertools
from functools import reduce
import numpy as np
from narwhal.cast import AbstractCast, Cast
def count_casts(castlikes):
""" Given an iterable of Casts and CastCollections, count the number of
individual Casts. """
n = 0
for c in castlikes:
if isinstance(c, AbstractC... |
492134 | import json
import sys
with open('reports/servers/index.json') as file_:
report = json.load(file_)
failures = sum(value['behavior'] == 'FAILED' for value in report['websockets'].values())
if failures > 0:
sys.exit(1)
else:
sys.exit(0)
|
492139 | import argparse
from preprocess import preprocess
import os
from pathlib import Path
import wave
import numpy as np
import unicodedata
import random
from tqdm import tqdm
import re
import yaml
import sys
import librosa
## Fairseq ์คํ์ผ๋ก ๋ณํํ๊ธฐ
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argumen... |
492157 | from typing import List
from lib import Migrations, MigrationsConfig
from cli import MigrationsCli
__version__: str = '0.0.4'
__all__: List[str] = [
'Migrations',
'MigrationsConfig',
'MigrationsCli'
]
|
492189 | import copy
import random
from dataclasses import dataclass
from pathlib import Path
import pandas as pd
from joblib import dump, load
from tqdm import tqdm
from deepform.data.add_features import LABEL_COLS, pq_index_and_dir
from deepform.document import Document
from deepform.logger import logger
@dataclass(frozen... |
492207 | import gzip
import os
from typing import Optional, Dict
from kgx.cli.cli_utils import prepare_output_args, prepare_input_args # type: ignore
from kgx.transformer import Transformer # type: ignore
from kg_covid_19.transform_utils.transform import Transform
class GocamTransform(Transform):
"""
GocamTransform... |
492228 | from compiler.errors import TypedSyntaxError
from compiler.static.types import (
TYPED_INT8,
TYPED_INT16,
PRIM_OP_DIV_INT,
PRIM_OP_ADD_INT,
)
from .common import StaticTestBase
try:
import cinderjit
except ImportError:
cinderjit = None
class BinopTests(StaticTestBase):
def test_pow_of_in... |
492285 | from mayan.apps.events.classes import EventModelRegistry
from mayan.apps.testing.tests.base import BaseTestCase
from ..models import DownloadFile, SharedUploadedFile
from ..settings import (
setting_download_file_expiration_interval,
setting_shared_uploaded_file_expiration_interval
)
from .mixins import Downl... |
492300 | import unittest
from kafka.tools.protocol.requests import ArgumentError
from kafka.tools.protocol.requests.offset_commit_v2 import OffsetCommitV2Request
class OffsetCommitV2RequestTests(unittest.TestCase):
def test_process_arguments(self):
val = OffsetCommitV2Request.process_arguments(['groupname', '16',... |
492306 | import asyncio
from aiokafka import AIOKafkaProducer, AIOKafkaConsumer
from aiokafka.helpers import create_ssl_context
from kafka.structs import TopicPartition
context = create_ssl_context(
cafile="./ca-cert", # CA used to sign certificate.
# `CARoot` of JKS store container
certfile="... |
492314 | from caresjpsutil import PythonLogger
#This is the module that writes output file from a template
##thoughts: write copied part first, then write changeble part
HEADER = '''
&ADMS_HEADER
Comment = "This is an ADMS parameter file"
Model = "ADMS"
Version = 5.2
FileVersion = 8
Complete = 1
/
'... |
492333 | import inspect
import operator
from functools import reduce
from typing import Any, Optional
from rest_framework.fields import empty
from rest_framework.request import Request
from .param_settings import ParamSettings
from rest_typed.utils import inspect_complex_type
def get_nested_value(dic: dict, path: str, fallb... |
492352 | from llvm.core import Type
void = Type.void()
char = Type.int(8)
short = Type.int(16)
int = Type.int(32)
int16 = short
int32 = int
int64 = Type.int(64)
float = Type.float()
double = Type.double()
# platform dependent
def _determine_sizes():
import ctypes
# Makes following assumption:
# sizeof(py_ssize_t... |
492375 | from setuptools import setup, find_packages
import versioneer
DISTNAME = 'mynn'
DESCRIPTION = 'A pure-Python neural network library'
LICENSE = 'MIT'
AUTHOR = '<NAME>'
AUTHOR_EMAIL = '<EMAIL>'
URL = 'https://github.com/davidmascharka/MyNN'
CLASSIFIERS = [
"Development Status :: 4 - Beta",
"License :: OSI Appr... |
492376 | import numpy as np
import heapq
from operator import itemgetter
from copy import copy
class SDRRL(object):
def __init__(self, numState, numHidden, numAction, initMinWeight, initMaxWeight):
self._numState = numState
self._numHidden = numHidden
self._numAction = numAction
... |
492409 | import torch.nn as nn
import torch.nn.functional as F
from base.base_net import BaseNet
class CIFAR10_LeNet(BaseNet):
def __init__(self, rep_dim=256, bias_terms=False):
super().__init__()
self.rep_dim = rep_dim
self.pool = nn.MaxPool2d(2, 2)
# Encoder network
self.conv1... |
492417 | from .MultimodalManipulationDataset import MultimodalManipulationDataset
from .MultimodalManipulationDataset_robust import MultimodalManipulationDataset_robust
from .ProcessForce import ProcessForce
from .ToTensor import ToTensor
|
492464 | import gym
import torch
from load_policy import load_policy
from model import Agent
from train import BehavioralCloning, DAgger, Eval
class Config():
seed = 3
envname = 'Humanoid-v2'
env = gym.make(envname)
method = 'DA' # BC: Behavioral Cloning DA: DAgger
device = torch.device('cuda')
expert... |
492473 | from typing import Callable
class ForWithProgress:
def __init__(self, total: int, every_nth: int, run_both_on_every: bool, run_on_start: bool):
self._total = total
self._every_nth = every_nth
self._run_both_on_every = run_both_on_every
self._run_on_start = run_on_start
def eve... |
492475 | from django.contrib import admin
from . import models
@admin.register(models.Model)
class ModelAdmin(admin.ModelAdmin):
list_display = ("name",)
|
492500 | import numpy as np
from ba3l.ingredients.ingredient import Ingredient
# credit: https://github.com/iBelieveCJM/Tricks-of-Semi-supervisedDeepLeanring-Pytorch/blob/master/utils/ramps.py
def pseudo_rampup(T1, T2):
def warpper(epoch):
if epoch > T1:
alpha = (epoch - T1) / (T2 - T1)
i... |
492505 | import torch
from typing_extensions import TypedDict
class ConfigMap(TypedDict):
rank : int
local_rank : int
world_size : int
local_size : int
calc_stream : torch.cuda.Stream
load_stream : torch.cuda.Stream
load_event : torch.cuda.Event
barrier_stream : torch.cuda.Stream
loss_scale... |
492515 | def gather_writable_check_list(hook, check_list, **kwargs):
pass
def before_project_updated(hook, project_uploader, **kwargs):
pass
def after_project_updated(hook, project_uploader, **kwargs):
pass
def before_resource_group_updated(hook, resource_group_uploader, **kwargs):
pass
def after_resource_gr... |
492536 | import os
from numpy.testing import assert_allclose
from glue_geospatial.data_factory import is_geospatial, geospatial_reader
DATA = os.path.join(os.path.dirname(__file__), 'data')
def test_geospatial(tmpdir):
assert not is_geospatial(os.path.join(DATA, 'plain.tif'))
assert is_geospatial(os.path.join(DATA... |
492540 | from datetime import date
from gazette.spiders.base.imprensa_oficial import ImprensaOficialSpider
class BaMunizFerreiraSpider(ImprensaOficialSpider):
name = "ba_muniz_ferreira"
allowed_domains = ["pmmunizferreiraba.imprensaoficial.org"]
start_date = date(2014, 12, 1)
end_date = date(2021, 1, 19)
... |
492593 | import argparse
import numpy as np
import os
import tensorflow as tf
import time
import pickle
import scipy.io
import skimage.transform
import matplotlib.pyplot as plt
import augmentation as augm
import evaluation
import tensorboard as tb
from datetime import datetime
np.set_printoptions(suppress=True, precision=4)
... |
492620 | import math
import numpy as np
import matplotlib.pyplot as plt
from porousmedialab.phcalc import Acid
import seaborn as sns
from matplotlib.colors import ListedColormap
sns.set_style("whitegrid")
def custom_plot(lab, x, y, ttl='', y_lbl='', x_lbl=''):
plt.figure()
ax = plt.subplot(111)
plt.plot(x, y, lw... |
492628 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import constant_op
from tensorflow.python.platform import test
from self_driving.segnet import segnet_vgg
import tensorflow as tf
import numpy as np
NUM_CLASSES = 11
class Poo... |
492629 | from napari.components.cursor import Cursor
def test_cursor():
"""Test creating cursor object"""
cursor = Cursor()
assert cursor is not None
|
492647 | from starGen import *
import numpy as np
import sys, os, traceback
from timeout import timeout, TimeoutError
from common import *
from scipy.optimize import linear_sum_assignment
time = int(os.getenv("TIMEOUT",30))
error = os.getenv("ERROR", 5)
required = int(os.getenv("REQUIRED",10))
def grade(guess, actual):
co... |
492685 | from docxcompose.utils import xpath
class StructuredDocumentTags(object):
"""Structured Document Tags (aka Content Controls)"""
def __init__(self, doc):
self.doc = doc
def tags_by_alias(self, alias):
"""Get Structured Document Tags by alias."""
return xpath(
self.doc.... |
492691 | import asyncio
import datetime
import os
import pytz
import re
import logging
from logging.handlers import TimedRotatingFileHandler
import discord
from discord.ext import commands
from utils import customchecks, sql, punishmentshelper
workDir = os.getcwd()
logDir = os.path.join(workDir, "logs")
if not os.path.exist... |
492708 | from scipy import interpolate
from cached_property import cached_property
import numpy as np
try:
import matplotlib.pyplot as plt
except:
plt = None
from devito import Dimension
from devito.function import SparseTimeFunction
__all__ = ['PointSource', 'Receiver', 'Shot', 'WaveletSource',
'RickerSou... |
492727 | import os
from typing import List
from unittest import TestCase
from message_passing_nn.data.data_preprocessor import DataPreprocessor
from message_passing_nn.model.trainer import Trainer
from message_passing_nn.infrastructure.file_system_repository import FileSystemRepository
from message_passing_nn.usecase.grid_sear... |
492754 | import sqlite3
import os
def do_migration(conf):
db_path = os.path.join(conf.data_dir, "lbrynet.sqlite")
connection = sqlite3.connect(db_path)
cursor = connection.cursor()
cursor.executescript("alter table blob add last_announced_time integer;")
cursor.executescript("alter table blob add single_an... |
492783 | import datetime
import logging
import threading
from . import util
class Cache:
def __init__(self):
self._cache = {}
self._lock = threading.Lock()
def get(self, key):
with self._lock:
entry = self._cache.get(key)
if not entry:
return None
... |
492841 | from typing import Union
import numpy as np
from experiments.utils import sample_uniform_weights
from simulation.outcome_generators import (OutcomeGenerator,
generate_outcome_tcga)
class TCGASimulator(OutcomeGenerator):
def __init__(
self,
id_to_graph_d... |
492871 | from torch import nn as nn
from torch.nn import functional as F
class ConvLayer(nn.Module):
def __init__(self, n_inputs, n_outputs, kernel_size, stride, conv_type, transpose=False):
super(ConvLayer, self).__init__()
self.transpose = transpose
self.stride = stride
self.kernel_size =... |
492890 | import operator
import numpy
import numba
class Dependent(object):
def __init__(self, **available):
self.available = available
def __getitem__(self, where):
return self.available[where]
@numba.extending.typeof_impl.register(Dependent)
def _Dependent_typeof(val, c):
return DependentType(l... |
492902 | from gym_kuka_mujoco.utils.kinematics import forwardKin, inverseKin, identity_quat
from gym_kuka_mujoco.utils.quaternion import mat2Quat
import numpy as np
def hole_insertion_samples(sim, nsamples=10, range=(0, 0.05)):
# The points to be transformed.
pos = np.array([0., 0., 0.])
peg_body_id = sim.model.bod... |
492937 | from mypy.nodes import SymbolTableNode
from mypy.plugin import AnalyzeTypeContext
from mypy.types import Instance
from mypy.types import Type as MypyType
from mypy.types import UnionType
from typing_extensions import final
from classes.contrib.mypy.semanal.variadic_generic import (
analize_variadic_generic,
)
from... |
492940 | import numpy as np
import cv2
import os
SRC_VIDEOS_DIR = '/home/deepano/workspace/dataset/roadSign/video'
DIST_FRAME_DIR = '/home/deepano/workspace/dataset/roadSign/frame'
def get_frame(src_video_dir, dist_frame_dir, fps):
for _file in os.listdir(src_video_dir):
video_file = os.path.join(src_video_dir, _file)
pr... |
492948 | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
try:
from wagtail.admin import urls as wagtailadmin_urls
from wagtail.core import urls as wa... |
492994 | from pathlib import Path
from typing import Union
import cv2
import numpy as np
def load_rgb(file_path: Union[str, Path]) -> np.ndarray:
image = cv2.imread(str(file_path))
return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
images = {
"with_faces": {
"image": load_rgb("tests/data/13.jpg"),
"... |
493002 | from pyanp.priority import *
import numpy as np
from scipy.stats.mstats import gmean
a = np.array([
[1, 2, 5],
[1/2, 1, 3],
[1/5, 1/3, 1]
])
print(pri_eigen(a))
vals = [
[2, 5/3],
[2*3, 5],
[3, 5/2]
]
means = [gmean(row) for row in vals]
b = utmrowlist_to_npmatrix(means)
print(b)
print(means)
... |
493022 | import hypothesis as hp
from hypothesis import strategies as st
import time
import pypeln as pl
import cytoolz as cz
MAX_EXAMPLES = 10
@hp.given(nums=st.lists(st.integers()))
@hp.settings(max_examples=MAX_EXAMPLES)
def test_flat_map_square(nums):
def _generator(x):
yield x
yield x + 1
yie... |
493039 | from django.apps import AppConfig
class DatasetsConfig(AppConfig):
name = 'datasets'
verbose_name = 'Scaleout Datasets'
|
493065 | import requests.packages
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
|
493084 | from cv2 import cv2
import numpy as np
from keras_squeezenet import SqueezeNet
from keras.optimizers import Adam
from keras.utils import np_utils
from keras.layers import Activation, Dropout, Convolution2D, GlobalAveragePooling2D
from keras.models import Sequential
import tensorflow as tf
import os
IMG_SAVE_... |
493090 | import tensorflow as tf
from avb.decoders import get_reconstr_err, get_decoder_mean, get_interpolations
from avb.utils import *
from avb.ops import *
from avb.validate import run_tests
from avb.validate.ais import AIS
from avb.iaf import IAFVAE, apply_iaf
from tqdm import tqdm
import time
import ipdb
def test(encoder,... |
493157 | import milan
import exponential
import hepmass
import estimator
import cvx_estimator
import gauss_estimator
import time
import pandas as pd
import numpy
import math
def main():
ps = numpy.linspace(0, 1, 21)
ps[0] = 0.01
ps[-1] = 0.99
k = 7
datasets = {
"milan": milan.data,
"exponent... |
493181 | import numpy as np
from scipy.stats import norm
def black_scholes(t=40, r=4.00, v=32.00, K=60, St=62, type='c'):
"""
Parameters:
K : Excercise Price
St: Current Stock Price
v : Volatility in percentage
r : Risk free rate in percentage
t : Time to expiration in days
type: Type of option... |
493222 | from flask import session, request, render_template
from app import app, LINK, get_url
from requests import post
from json import loads
@app.route('/sys_sign_in', methods=['POST'])
def signin():
x = request.form
if not all([i in x for i in ('login', 'pass')]):
return render_template('message.html', cont='3')
r... |
493227 | from styx_msgs.msg import TrafficLight
import numpy as np
import rospkg
import os
import rospy
import tensorflow as tf
import cv2
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image
class TLClassifier(object):
def __init__(self):
#TODO load classifier
self.color_th = 15
... |
493240 | import logging
import os
import signal
import yaml
import time
from flask import Flask, jsonify, request
from gevent.pywsgi import WSGIServer
from triggerflow.service import storage
from triggerflow.service.worker import Worker
from triggerflow import eventsources
import threading
app = Flask(__name__)
app.debug = Fal... |
493301 | from .version import __version__
from .core import *
from .topology import *
from .exterior import *
from .printing import *
|
493323 | import ajenti
from ajenti.api import *
from ajenti.plugins import *
ajenti.edition += '+vh'
info = PluginInfo(
title='Ajenti V Virtual Hosting',
description='Adds easy web hosting management to Ajenti',
icon='globe',
dependencies=[
PluginDependency('main'),
PluginDependency('services... |
493333 | from layout import ListInfoData
from layout import FieldMetadata
class ListInfoItemMetadata:
# private final ListInfoData infoData
# private String variableName
#
def __init__(self, infoData, _type, value):
self.infoData = infoData
self.type = _type
self.value = value
self.variab... |
493339 | import json
import os
class Config:
def __init__(self):
if self.exists():
print("Loading the config.json")
self.read()
else:
print("config.json file doesn't exist")
self.config = {}
def package_root_path(self, value=None):
if value is no... |
493412 | from PyQt5.QtCore import QModelIndex, QRect
from PyQt5.QtWidgets import QAbstractItemView
from inselect.lib.inselect_error import InselectError
from inselect.lib.utils import debug_print
from inselect.gui.roles import PixmapRole, RectRole, MetadataValidRole
from inselect.gui.utils import update_selection_model
from .... |
493414 | import math
from seamless.highlevel import Context, Cell
import json
ctx = Context()
ctx.pi = math.pi
ctx.doubleit = lambda a: 2 * a
ctx.doubleit.hash_pattern = {"*": "#"}
ctx.doubleit.a = ctx.pi
ctx.twopi = ctx.doubleit
ctx.translate()
graph = ctx.get_graph()
print(json.dumps( graph, indent=2, sort_keys=True))
json.d... |
493449 | from builtins import range
from mrq.helpers import ratelimit
import time
def test_helpers_ratelimit(worker):
worker.start_deps()
assert ratelimit("k3", 1, per=1) == 1
assert ratelimit("k3", 1, per=1) == 0
assert ratelimit("k3", 1, per=1) == 0
for i in range(0, 10):
r = ratelimit("k", 10... |
493467 | import torch.nn as nn
class PoseDecoder(nn.Module):
def __init__(self, input_channels):
super().__init__()
self.nl = nn.ReLU()
self.squeeze = nn.Conv2d(input_channels, 256, 1)
self.conv_1 = nn.Conv2d(256, 256, 3, 1, 1)
self.conv_2 = nn.Conv2d(256, 256, 3, 1, 1)
self... |
493474 | import numpy as np
import os
from PIL import Image
from keras.preprocessing import image
def preprocess_input(x):
x = x.astype(np.float32)
x /= 255.
return x
def decode_output(x):
x = x.astype(np.float32)
x *= 255.
return x
def make_paths_from_directory(root):
input_paths = []
for dir... |
493491 | import numpy as np
import random
import config
class DataProvider:
def __init__(self, nparray_path):
print('Load data for STN ...')
self.imgs_trans = np.load(nparray_path + 'SE_transformed_imgs_with_W.npy')
img_embd_sz_arr = np.load(nparray_path + 'img_embd_sz.npy')
self.feed_size... |
493519 | from django.contrib import admin
from django.db import models
from django.forms import TextInput
from django.utils.safestring import mark_safe
from ..core.admin import DittoItemModelAdmin
from .models import Account, Photo, Photoset, User
@admin.register(Account)
class AccountAdmin(admin.ModelAdmin):
list_displa... |
493530 | import logging
from collections import defaultdict
from typing import Dict, List, Sequence, Any, Optional, Union, cast
from .encoding import flip_bloom_filter
from .pprlindex import PPRLIndex, ReversedIndexResult
from .signature_generator import generate_signatures
from .stats import reversed_index_per_strategy_stats,... |
493569 | import argparse
import math
from datetime import datetime
import h5py
import numpy as np
import tensorflow as tf
import socket
import importlib
import os
import sys
import os.path
from os import path
import json
import pickle
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR) # model
sys.p... |
493674 | import os, sys
import subprocess
TOOLS_DIR = "tools"
def RunCommand(cmds):
ret = 0
cmds[0] = "{}/{}/{}.py".format(os.getcwd(), TOOLS_DIR, cmds[0])
if os.path.exists(cmds[0]):
cmds.insert(0, "python3")
ret = subprocess.call(cmds)
else:
print("Invalid command: ", cmds... |
493679 | import numpy as np
from .util import zero_pad, format_json
from .grouping import group_rows
from .constants import log, _log_time
_MIN_BIN_COUNT = 20
_TOL_FREQ = 1e-3
def rotationally_invariant_identifier(mesh, length=6, as_json=False, json_digits=None):
'''
Given an input mesh, return a vector or string th... |
493691 | Runtime.createAndStart("sweety", "Sweety")
sweety.chatBot.startSession("default", "wikiTestFR")
sweety.chatBot.setPredicate("default","name","unknow")
wdf = Runtime.createAndStart("wikiDataFetcher", "WikiDataFetcher")
wdf.setLanguage("fr")
wdf.setWebSite("frwiki")
# Add route from webKitSpeechRecognition to Program ... |
493781 | import os
from test.podman_testcase import PodmanTestCase
import podman
from podman import FoldedString
pod = None
class TestPodsCtnrs(PodmanTestCase):
@classmethod
def setUpClass(cls):
# Populate storage
super().setUpClass()
@classmethod
def tearDownClass(cls):
super().tear... |
493825 | from .blocks import conv_block
from .transform_block import transformation_block
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow as tf
def get_shape_segmentation_model(num_points: int, num_classes: int) -> keras.Model:
input_points = keras.Input(shape=(num_points, 3))
# Po... |
493865 | import zlib
import sys
import argparse
print('\033[0;32m'+"Zlib file decompressor : " + '1.0' + " Updated: " + 'May 15, 2018' +'\033[0;39m')
parser = argparse.ArgumentParser(description='\033[0;31m'+'Decompress a zlib file'+'\033[0;39m')
parser.add_argument("-input", metavar='file', type=str, default="file.zlib"... |
493876 | import nltk
sentences1 = nltk.corpus.treebank.tagged_sents()[17]
print(nltk.ne_chunk(sentences1, binary=True))
sentences2 = nltk.corpus.treebank.tagged_sents()[7]
print(nltk.ne_chunk(sentences2, binary=True))
print(nltk.ne_chunk(sentences2))
|
493934 | from tool.runners.python import SubmissionPy
class EvqnaSubmission(SubmissionPy):
def rotate_trig(self, u, v, angle):
if angle == 90:
return -v, u
elif angle == 180:
return -u, -v
elif angle == 270:
return v, -u
def run(self, s):
instruction... |
493964 | import importlib
import pytest
from zope.interface import Interface
from pyramid.testing import Configurator
from pyramid.httpexceptions import HTTPNotFound
from clld.db.models.common import Contribution, ValueSet, Language, Language_files
from clld.interfaces import IMapMarker, IDataTable
from clld.web.adapters.down... |
493986 | import requests.api
from requests.auth import HTTPBasicAuth
from amqpstorm.compatibility import urlparse
from amqpstorm.management.exception import ApiConnectionError
from amqpstorm.management.exception import ApiError
class HTTPClient(object):
def __init__(self, api_url, username, password, timeout):
se... |
493999 | import json
import os
from termcolor import cprint
import colorama
from pyvoc import pyvoc
from pyvoc.check_config import check_config_dir, config_dir_path
from pyvoc.settings import USER_GROUP_ENTRIES_LIMIT
colorama.init()
# create an empty vocabulary group file
def create_new_vocab_group(group_path, group_number)... |
494015 | import time
# time.time() return the time in seconds since the epoch as a floating point number
def chour(t):
hour = t / 3600
print("The number of hours has passed since epoch is %f" % hour)
def cminute(t):
minute = t / 60
print("The number of minutes has passed since epoch is %f" % minute)
def cseconds(t):
se... |
494032 | import cvcomm
class ControlVault2:
NAME = 'Broadcom ControlVault 2'
turn_on_seq1 = [
"10 2f 04 00",
"10 2f 1d 03 05 90 65",
"10 2f 2d 00",
"10 2f 11 01 f7",
"01 27 fc 0c 08 00 01 00 01 00 00 00 00 00 00 00",
]
turn_on_seq2 = [
"10 20 00 01 01",
"10 20 01 02 01 00",
"10 20 02 67 01 b9 64 01 00 ff f... |
494044 | from __future__ import absolute_import
from django.conf import settings
from appconf import AppConf
class AjaxAppConf(AppConf):
AJAX_AUTHENTICATION = 'ajax.authentication.BaseAuthentication'
|
494046 | from typing import Dict, Any
from .module import Module
from .parameter import Parameter
_dict_methods = ['__setitem__', '__getitem__', '__delitem__', '__len__', '__iter__', '__contains__',
'update', 'keys', 'values', 'items', 'clear', 'pop']
class ModuleDict(Module, dict): # use dict for auto-comp... |
494063 | import tensorflow as tf
class SmoothL1Loss(tf.Module):
"""Smooth L1 loss.
Args:
beta (float, optional): The threshold in the piecewise function.
Defaults to 1.0.
loss_weight (float, optional): The weight of loss.
"""
def __init__(self, beta=1.0, loss_weight=1.0):
... |
494075 | import os
import sys
import numpy as np
from torch.utils.data import Dataset
Cross_Subject = [1, 2, 4, 5, 8, 9, 13, 14, 15, 16, 17, 18, 19, 25, 27, 28, 31, 34, 35, 38]
class NTU60Subject(Dataset):
def __init__(self, root, meta, frames_per_clip=23, step_between_clips=2, num_points=2048, train=True):
super(... |
494089 | import random
from CellModeller.Regulation.ModuleRegulator import ModuleRegulator
from CellModeller.Biophysics.BacterialModels.CLBacterium import CLBacterium
from CellModeller.GUI import Renderers
import numpy
import math
N0 = 10
def setup(sim):
# Set biophysics, signalling, and regulation models
biophys = CL... |
494093 | from collections import deque
import gym
import numpy as np
from gym import spaces, logger
from gym.utils import seeding
class SnakeAction(object):
LEFT = 0
RIGHT = 1
UP = 2
DOWN = 3
class BoardColor(object):
BODY_COLOR = np.array([0, 0, 0], dtype=np.uint8)
FOOD_COLOR = np.array([0, 255, 0]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.