id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
400014 | import os
from win32com.client import Dispatch
import logging
logging.basicConfig()
logger = logging.getLogger('coreFunctions_PS')
logger.setLevel(logging.WARNING)
class PsCoreFunctions(object):
def __init__(self):
super(PsCoreFunctions, self).__init__()
# self.psApp = Dispatch('Photoshop.Applicat... |
400057 | from typing import Union
import numpy as np
from observer.base_observer import BaseObserver
from shape.point_2d import Point2D
class ClosestVertexSelector(BaseObserver):
def __init__(self, editor: 'MapBasedCalibrator'):
super().__init__(editor)
def find_closest_vertex_to_mouse(
self, mo... |
400066 | from setuptools import setup, find_namespace_packages
from pathlib import Path
long_description = (Path(__file__).parent / "README.md").read_text()
setup(
name="icolos",
maintainer="<NAME>, <NAME>",
version="1.9.0",
url="https://github.com/MolecularAI/Icolos",
packages=find_namespace_packages(wher... |
400069 | import os
from datetime import datetime, timedelta, timezone
import tempfile
from django.db import transaction
import boto3
import pytz
from google.transit import gtfs_realtime_pb2
from busshaming.models import Trip, TripDate, TripStop, RealtimeEntry, Route, Stop
from busshaming.enums import ScheduleRelationship
S3... |
400074 | from collections import defaultdict
from itertools import groupby, product
import numpy as np
import pandas as pd
from scipy.stats import hmean, spearmanr
from statsmodels.stats.proportion import proportion_confint
import wordfreq
from conceptnet5.util import get_support_data_filename
from conceptnet5.vectors import ... |
400079 | import numpy as np
import minimal_pytorch_rasterizer
import torch
from torch import nn
import nvdiffrast.torch as dr
class UVRenderer(torch.nn.Module):
def __init__(self, H, W, faces_path='data/uv_renderer/face_tex.npy',
vertice_values_path='data/uv_renderer/uv.npy'):
super().__init__()
... |
400133 | import os
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, "README.rst"), encoding="utf-8") as f:
long_description = "\n" + f.read()
if __name__ == "__main__":
setup(
name="paragraph",
use_scm_version=True,
author="<NAME>",
... |
400157 | from compressor.conf import settings
from compressor.filters import CompilerFilter
class ClosureCompilerFilter(CompilerFilter):
command = "{binary} {args}"
options = (
("binary", settings.COMPRESS_CLOSURE_COMPILER_BINARY),
("args", settings.COMPRESS_CLOSURE_COMPILER_ARGUMENTS),
)
|
400179 | import copy
import typing
from commercetools.platform import models
class Paginator:
"""This paginator uses the offset kwarg for retrieving the pages
Example::
paginator = Paginator(client.products.query, sort=["id asc"])
for product in paginator:
print(product)
paginat... |
400199 | from __future__ import print_function, division, absolute_import
import json
from collections import OrderedDict
from functools import partial
from os.path import basename
from future import standard_library
from littleutils import DecentJSONEncoder, withattrs, group_by_attr
standard_library.install_aliases()
impor... |
400245 | from django.core.management import BaseCommand
from importer import models
from importer.tasks import find_and_run_next_batch_chunks
from workbaskets.validators import WorkflowStatus
def run_batch(batch: str, status: str, username: str):
import_batch = models.ImportBatch.objects.get(name=batch)
find_and_run... |
400285 | from icevision.all import *
def _test_dl(x, y, recs):
assert len(recs) == 1
assert recs[0].img is None
assert x.shape == torch.Size([1, 3, 64, 64])
assert recs[0].segmentation.class_map is not None
assert recs[0].segmentation.class_map.num_classes == 32
if y is not None:
assert y.sha... |
400304 | from .state import *
from .target_selection import *
from .gpu_status import *
from .download_button import *
from .ps_process import *
from .run_proteinsolver import *
from .structure import *
|
400309 | from typing import Tuple, Callable, Optional, cast
from ..model import Model
from ..config import registry
from ..types import Floats1d, Floats2d
from ..initializers import glorot_uniform_init, zero_init
from ..util import get_width, partial
InT = Floats2d
OutT = Floats2d
@registry.layers("Linear.v1")
def Linear(
... |
400320 | import math
import sys
import coloredlogs
from pyvox.parser import VoxParser
coloredlogs.install(level='DEBUG')
m = VoxParser(sys.argv[1]).parse()
img = m.to_dense()
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
cm = ListedColormap(np.array(m.palette, dtype='f')/25... |
400390 | from posixpath import split
import pytest
from tasrif.processing_pipeline import SplitOperator
from tasrif.processing_pipeline.processing_operator import ProcessingOperator
class NotProcessingOperator:
pass
def test_error_is_raised_when_split_operators_are_not_ProcessingOperators(mocker):
with pytest.rais... |
400470 | import plotly
import plotly.graph_objects as go
from plotly.graph_objs.scatter import Line
from plotly.subplots import make_subplots
import plotly.express as px
import ipywidgets
from ipywidgets.widgets import Layout, HBox, VBox
from ipywidgets.embed import embed_minimal_html
import pandas as pd
import os,sys
import co... |
400539 | import os, shutil
dir_path = os.path.dirname(os.path.realpath(__file__))
source = '/readme.md'
destinations = [
'/js/logipar/readme.md',
# '/python/pip/readme.md'
]
for d in destinations:
shutil.copyfile("{}{}".format(dir_path, source), "{}{}".format(dir_path, d))
|
400556 | import os
import re
import time
from itertools import chain
from errbot import BotPlugin, re_botcmd
from errbot.core import ErrBot
from slack_sdk.errors import SlackApiError
import config_template
from lib import ApproveHelper, create_sdm_service, MSTeamsPlatform, PollerHelper, \
ShowResourcesHelper, ShowRolesHelp... |
400559 | import pytest
from dbt.tests.util import run_dbt
from tests.functional.simple_snapshot.fixtures import models_slow__gen_sql
test_snapshots_changing_strategy__test_snapshot_sql = """
{# /*
Given the repro case for the snapshot build, we'd
expect to see both records have color='pink'
in their most recent r... |
400614 | import unittest
from craft_ai import Client, errors as craft_err
from . import settings
from .utils import generate_entity_id
from .data import valid_data, invalid_data
class TestGetContextStateSuccess(unittest.TestCase):
"""Checks that the client succeeds when retrieving an agent's current state
with OK in... |
400697 | from __future__ import with_statement # this is to work with python2.5
#!/usr/bin/env python
# import everything so that a session looks like tpips one
from pyps import workspace
with workspace("properties2.f",deleteOnClose=True) as w:
#Get foo function
foo1 = w.fun.FOO1
foo2 = w.fun.FOO2
foo3 = w.fun.FOO3
foo4 ... |
400728 | import hashlib
import re
import time
from urllib import parse
from app.thirdparty.oneforall.common.query import Query
class NetCraft(Query):
def __init__(self, domain):
Query.__init__(self)
self.domain = domain
self.module = 'Dataset'
self.source = 'NetCraftQuery'
self.add... |
400754 | import torch
import numpy as np
from torch.utils.data import Dataset
import os, glob
import re
import cv2
import math
from random import shuffle
import torch.nn.functional as F
from torchvision import transforms
from tqdm import tqdm
from PIL import Image
import scipy.io as io
import matplotlib.pyplot as plt
import m... |
400781 | from __future__ import absolute_import
import struct
import random
from . import *
_len = len
_type = type
try:
long(0)
except:
long = int
default_xid = lambda: long(random.random()*0xFFFFFFFF)
def _obj(obj):
if isinstance(obj, bytes):
return obj
elif isinstance(obj, tuple):
return eval(o... |
400787 | import ezc3d
import xarray as xr
from ._constants import EXPECTED_VALUES, MARKERS_ANALOGS_C3D
from .utils import is_expected_array
def test_ezc3d():
c3d = ezc3d.c3d(f"{MARKERS_ANALOGS_C3D}")
is_expected_array(xr.DataArray(c3d["data"]["points"]), **EXPECTED_VALUES[65])
is_expected_array(xr.DataArray(c3d["... |
400872 | import praw
from prawcore.exceptions import ServerError
from logger import log
import json
import Config
import os
from pathlib import Path
logger = log('reddit')
def get_user_subscriptions():
users = []
empty_users = []
subs = {}
erroredUsers = []
i = 1
with open('../shared/nsfw_subs.json', 'r') as f:
nsfw... |
400888 | import os
import pandas as pd
import calendar
import datetime as dt
import requests
URL = "https://earthquake.usgs.gov/fdsnws/event/1/query.csv?starttime={start}&endtime={end}&minmagnitude=2.0&orderby=time"
for yr in range(2000, 2019):
for m in range(1, 13):
if os.path.isfile('{yr}_{m}.csv'.format(yr=yr, ... |
400894 | import os
import yaml
from .test_utils import CliTestCase, skip_if_environ
class BuildAndLintTestCase(CliTestCase):
def test_build_and_lint(self):
with self._isolate():
self._check_exit_code(_init_command())
self._check_lint(exit_code=0)
def test_build_and_lint_with_macros(... |
400935 | class Solution:
def subsetsWithDup(self, nums: List[int], sorted: bool = False) -> List[List[int]]:
if not nums: return [[]]
if len(nums) == 1: return [[], nums]
if not sorted: nums.sort()
pre_lists = self.subsetsWithDup(nums[:-1], sorted=True)
all_lists = [i + [nums[-1]] for... |
400951 | import FWCore.ParameterSet.Config as cms
pfAllMuons = cms.EDFilter("PFCandidateFwdPtrCollectionPdgIdFilter",
src = cms.InputTag("pfNoPileUp"),
pdgId = cms.vint32( -13, 13),
makeClones = cms.bool(True)
)
pfAllMuonsClones = cms.EDProducer("PFCandidateProductFromFwdPtrProducer",
... |
400966 | import os,random,glob
import argparse
import numpy as np
parser = argparse.ArgumentParser()
parser.description='please enter two parameters a and b ...'
parser.add_argument("-p", "--path", help="A list of paths to jpgs for seperate",
type=str,
default= '/mnt/data9/independent_raw... |
400970 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import mxnet as mx
from mxnet import ndarray as nd
import random
import argparse
import cv2
import time
import sklearn
from sklearn.decomposition import PCA
from easydict import EasyDict as ... |
400975 | from datetime import datetime
from typing import Dict, List, Optional
from pydantic import BaseModel
from common_osint_model.models import ShodanDataHandler, CensysDataHandler, BinaryEdgeDataHandler, Logger
from common_osint_model.models.http import HTTPComponent
from common_osint_model.models.ssh import SSHComponent... |
400976 | import numpy as np
import matplotlib.pyplot as plt
from FEM.Torsion2D import Torsion2D
from FEM.Mesh.Geometry import Geometry
G = 1
phi = 1
geometria = Geometry.loadmsh('Mesh_tests/Web_test.msh')
O = Torsion2D(geometria, G, phi)
O.solve()
plt.show()
|
400992 | from kadot.models import CRFExtractor
# Find the city in a weather related query
train = {
"What is the weather like in Paris ?": ('Paris',),
"What kind of weather will it do in London ?": ('London',),
"Give me the weather forecast for Berlin please.": ('Berlin',),
"Tell me the forecast in New York !":... |
400997 | from __future__ import absolute_import, division, print_function
from cctbx.xray import ext
from cctbx.array_family import flex
from libtbx.test_utils import approx_equal
from libtbx.math_utils import iceil
from itertools import count
import sys
from six.moves import range
from six.moves import zip
class random_inputs... |
401007 | from instructionexecutor import InstructionExecutor
from optimizer import Optimizer
from tracereader import EffectReader, TraceReader
from ceptions import TimeoutException
import signal, sys
def handler(signum, frame):
raise TimeoutException("timeout")
class OptimizerTester:
def __init__(self, line, debug):
re... |
401037 | from elasticsearch import Elasticsearch
import json
import re
from utils.constant import WIKIPEDIA_INDEX_NAME
es = Elasticsearch(timeout=300)
core_title_matcher = re.compile('([^()]+[^\s()])(?:\s*\(.+\))?')
core_title_filter = lambda x: core_title_matcher.match(x).group(1) if core_title_matcher.match(x) else x
def ... |
401064 | from flask import Flask, render_template, request, jsonify
from urlparse import urljoin
from werkzeug.contrib.atom import AtomFeed
import os
from bs4 import BeautifulSoup
import os
import datetime
import html2text
app = Flask(__name__)
app.debug=True
def make_external(url):
return urljoin(request.url_root, url)
... |
401072 | import time
from datetime import date
from unittest import mock, skip
from django.test import override_settings
from selenium.webdriver.common.keys import Keys
from mainapp.models import Person
from mainapp.tests.live.chromedriver_test_case import ChromeDriverTestCase
from mainapp.tests.live.helper import (
MockM... |
401082 | from imutils import face_utils
import dlib
import cv2
import numpy as np
pre_trained_model = 'classifier/shape_predictor_68_face_landmarks.dat'
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(pre_trained_model)
video = cv2.VideoCapture('video/somi.mp4')
while video.read():
_, image_... |
401112 | import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import unittest
from unittest.mock import Mock, patch
import DWF
class FakeResponse:
def __init__(self):
pass
def raise_for_status(self):
pass
def json(self):
return []
# This method will be used by t... |
401115 | import traceback
def agency_slug(agency_name):
return '#' + ''.join(agency_name.split()) + '#'
def user_input(prompt):
try:
return raw_input(prompt)
except NameError:
return input(prompt)
def error_info(e):
return "%s: %s" % (e, traceback.format_exc().replace("\n", "\\n "))
|
401175 | import numpy as np
import pytest
from robogym.envs.rearrange.ycb import make_env
@pytest.mark.parametrize("mesh_scale", [0.5, 1.0, 1.5])
def test_mesh_centering(mesh_scale):
# We know these meshe stls. are not center properly.
for mesh_name in ["005_tomato_soup_can", "073-b_lego_duplo", "062_dice"]:
... |
401176 | import cv2
import glob as gb
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--img_file', default='results', type=str)
parser.add_argument('--video_name', default='dancetrack.avi', type=str)
parser.add_argument('--suffix', default='png', type=str)
parser.add_argument('--show_height', default=5... |
401212 | import logging
from typing import List
from homeassistant.helpers.entity import Entity
from gehomesdk import ErdCode, ErdApplianceType
from .washer import WasherApi
from .dryer import DryerApi
from ..entities import GeErdSensor, GeErdBinarySensor
_LOGGER = logging.getLogger(__name__)
class WasherDryerApi(WasherApi,... |
401278 | import os
from fnmatch import fnmatch
def ignore(source_file, config):
file_name = os.path.basename(source_file)
if config['ignore'] is True or \
config['ignore'] and any(pattern for pattern in config['ignore'] if fnmatch(file_name, pattern)):
return
return config
ignore.defaults = ... |
401323 | import pytest
from geomdl import ray
from geomdl.ray import Ray, RayIntersection
def test_ray_intersect():
r2 = Ray((5.0, 181.34), (13.659999999999997, 176.34))
r3 = Ray((19.999779996773235, 189.9998729810778), (19.999652977851035, 180.00009298430456))
t0, t1, res = ray.intersect(r2, r3)
assert res !=... |
401383 | r"""
Unique factorization domains
"""
#*****************************************************************************
# Copyright (C) 2008 <NAME> (CNRS) <<EMAIL>>
#
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#***********************************... |
401483 | from __future__ import print_function
from __future__ import division
from skvideo.io import VideoCapture, VideoWriter
import sys
cap_filename, wr_filename = sys.argv[1], sys.argv[2]
cap = VideoCapture(cap_filename)
cap.open()
print(str(cap.get_info()))
retval, image = cap.read()
wr = VideoWriter(wr_filename, 'H26... |
401517 | from django.utils.translation import gettext_lazy as _
from rest_framework import decorators, response
from rest_framework import serializers as rf_serializers
from rest_framework import status, viewsets
from waldur_core.core import exceptions as core_exceptions
from waldur_core.core import validators as core_validato... |
401571 | from pathlib import Path
def relative_to_abs_path(relative_path):
dirname = Path(__file__).parent
try:
return str((dirname / relative_path).resolve())
except FileNotFoundError:
return None
prefix = relative_to_abs_path('../resources/')+"/"
device_cmd_fpath = relative_t... |
401603 | from __future__ import print_function, division
import sys,os
qspin_path = os.path.join(os.getcwd(),"../")
sys.path.insert(0,qspin_path)
from quspin.basis import spin_basis_1d
from quspin.basis import spin_basis_general
from quspin.basis import basis_int_to_python_int
import numpy as np
from itertools import product
... |
401606 | import pytest
# integration tests requires nomad Vagrant VM or Binary running
def test_initiate_garbage_collection(nomad_setup):
nomad_setup.system.initiate_garbage_collection()
def test_dunder_str(nomad_setup):
assert isinstance(str(nomad_setup.system), str)
def test_dunder_repr(nomad_setup):
assert ... |
401608 | import matplotlib
#
import numpy
import math
import pylab as plt
import h5py
import itertools
#
#plt.ion()
default_events = 'vq_output_hattonsenvy_3k/events_3000_d.h5'
events_2 = 'ca_model_hattonsenvy_105yrs_3km/events_3000.hdf5'
def quick_figs(vc_data_file=default_events, fnum_0=0, events_start=0, events_end=None, m... |
401729 | from builtins import object
import factory
from bluebottle.statistics.models import Statistic
class StatisticFactory(factory.DjangoModelFactory):
class Meta(object):
model = Statistic
type = 'manual'
title = factory.Sequence(lambda n: 'Metric {0}'.format(n))
value = None
sequence = facto... |
401750 | from dataclasses import dataclass
@dataclass(frozen=True)
class VertexData:
__slots__ = ["lat", "lon"]
lat: float
lon: float
def __repr__(self) -> str:
return "{} {}".format(self.lat, self.lon)
@dataclass(frozen=True)
class Vertex:
__slots__ = ["id", "data"]
id: int
data: Vertex... |
401751 | from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPool2D, UpSampling2D
def autoencoder():
input_shape=(784,)
model = Sequential()
model.add(Dense(64, activation='relu', input_shape=input_shape))
model.add(Dense(784, activation='sigmoid'))
return model
def deep_autoenco... |
401789 | import torch
class BaseMatcher:
def __init__(self, matcher_cfg):
self.matcher_cfg = matcher_cfg
self.device = torch.device(
"cuda" if torch.cuda.is_available() else "cpu"
)
self.n_fails = 0
def match(self, s1: torch.Tensor, s2: torch.Tensor):
raise NotImple... |
401795 | from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
ext_modules = [
Extension(
name='toolkit.utils.region',
sources=[
'toolkit/utils/region.pyx',
'toolkit/utils/src/region.c',
],
include_dirs=[
... |
401810 | import torch
from torch.utils import data
from transformers import AutoTokenizer
from .augment import Augmenter
# map lm name to huggingface's pre-trained model names
lm_mp = {'roberta': 'roberta-base',
'distilbert': 'distilbert-base-uncased'}
def get_tokenizer(lm):
if lm in lm_mp:
return AutoT... |
401818 | import bpy
import json
from bpy.props import PointerProperty
from ...nodes.BASE.node_base import RenderNodeBase
def update_node(self, context):
self.execute_tree()
class RSNodeTaskInfoInputsNode(RenderNodeBase):
'''A simple input node'''
bl_idname = 'RSNodeTaskInfoInputsNode'
bl_label = 'Task Info(E... |
401819 | import os
import time
from speech_tools import *
import numpy as np
from multiprocessing import Pool
datasets_dir = "datasets"
output_root_dir = "datasets_splitted"
divs = 64
def process(folder):
sampling_rate = 22050
num_mcep = 36
frame_period = 5.0
n_frames = 128
X=[]
for f... |
401842 | import numpy as np
from scipy.special import gammaln, psi
# TODO: define distribution base class
class Discrete(object):
def __init__(self, p=0.5*np.ones(2)):
assert np.all(p >= 0) and p.ndim == 1 and np.allclose(p.sum(), 1.0), \
"p must be a probability vector that sums to 1.0"
self.p... |
401843 | from django.utils.duration import duration_string
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from resources.api.base import TranslatedModelSerializer
from ..models import Order, OrderLine, Product
class ProductSerializer(TranslatedModelSerializer):
id = serial... |
401858 | import argparse
import time
# terminal run: python test.py 3, 4
parser = argparse.ArgumentParser(description = 'This is a summation method.')
parser.add_argument('a')
parser.add_argument('b')
args = parser.parse_args()
a = int(args.a)
b = int(args.b)
# print('begin 1s:')
# time.sleep(1)
def sum():
return a + b
r... |
401865 | from . import links
from .allocator import use_mempool_in_cupy_malloc, use_torch_in_cupy_malloc
from .datasets import TransformDataset
from .links import TorchModule
from .parameter import ChainerParameter, LinkAsTorchModel, Optimizer
from .tensor import asarray, astensor, to_numpy_dtype
from .device import to_chainer_... |
401867 | from corehq.util.validation import is_url_or_host_banned
from corehq.util.urlvalidate.ip_resolver import CannotResolveHost
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
def form_clean_url(url):
try:
if is_url_or_host_banned(url):
raise Va... |
401870 | from FreeTAKServer.model.FTSModel.fts_protocol_object import FTSProtocolObject
class Archive(FTSProtocolObject):
@staticmethod
def drop_point():
# while the tag exists in the CoT structure no known content exists
pass |
401874 | def palindrome(s):
s=s.replace(" ",'')
reverse=s[::-1]
if s==reverse:
return True
else:
return False
|
401890 | import contextlib
import time
_timing_db = []
def record(timing_information):
"""
Add a timing record to a global database.
:param timing_information: a dictionary in the format
{"command": "command line string",
"time_start": unix epoch timestamp,
"time_end": unix epoch timestamp... |
401923 | import asyncio
from typing import Any
from behave import given, then, when # type: ignore
from behave.api.async_step import async_run_until_complete # type: ignore
from mqtt_io.modules.gpio import InterruptEdge, PinDirection
from mqtt_io.server import MqttIo
# pylint: disable=function-redefined,protected-access
#... |
401980 | from track import Track
import pandas as pd
import tempfile
import pkg_resources
import re
import os.path
#hg19_track_path = pkg_resources.resource_filename('deepmosaic', 'resources/hg19_seq.h5')
#hg38_track_path = pkg_resources.resource_filename('deepmosaic', 'resources/hg38_seq.h5')
# The directory containing this ... |
401995 | import unittest
from grip.model import Package, Version
class TestPackage(unittest.TestCase):
def test_name_sanitizer(self):
pkg = Package('Django_module', '1.0')
self.assertEqual(pkg.name, 'django-module')
def test_version(self):
pkg = Package('pkg', '1.0')
self.assertEqual(p... |
402010 | import random
from processor import CharacterProcessor
class Race(CharacterProcessor):
def process(self):
""" Pick the character's race, randomly. """
self.character.race = random.choice(['Dwarf', 'Elf', 'Halfling', 'Human'])
if self.character.race == 'Dwarf':
self.character.sc... |
402030 | import unittest
from slack_sdk.oauth.state_store import FileOAuthStateStore
class TestFile(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_instance(self):
store = FileOAuthStateStore(expiration_seconds=10)
self.assertIsNotNone(store)
def ... |
402037 | import os
import gzip
import numpy as np
import matplotlib.pyplot as plt
def load_mnist():
dir_path = "mnist_datas"
files = ["train-images-idx3-ubyte.gz",
"train-labels-idx1-ubyte.gz",
"t10k-images-idx3-ubyte.gz",
"t10k-labels-idx1-ubyte.gz"]
# download mnist datas
... |
402054 | import torch
import numpy as np
from torch import Tensor
_MEL_BREAK_FREQUENCY_HERTZ = 700.0
_MEL_HIGH_FREQUENCY_Q = 1127.0
def mel_to_hertz(mel_values):
"""Converts frequencies in `mel_values` from the mel scale to linear scale."""
return _MEL_BREAK_FREQUENCY_HERTZ * (
np.exp(np.array(mel_values) / _MEL_HI... |
402086 | LONG_TIMEOUT = 30.0 # For wifi scan
SHORT_TIMEOUT = 10.0 # For any other command
DEFAULT_MEROSS_HTTP_API = "https://iot.meross.com"
DEFAULT_MQTT_HOST = "mqtt.meross.com"
DEFAULT_MQTT_PORT = 443
DEFAULT_COMMAND_TIMEOUT = 10.0
|
402118 | from pymtl import *
from lizard.bitutil import clog2, bit_enum
from lizard.util.rtl.method import MethodSpec
from lizard.util.rtl.interface import Interface, UseInterface
CMPFunc = bit_enum(
'ALUFunc',
None,
'CMP_EQ',
'CMP_NE',
'CMP_LT',
'CMP_GE',
)
class ComparatorInterface(Interface):
de... |
402139 | import moviepy.editor as mp
import speech_recognition as sr
import wave
import contextlib
from moviepy.editor import VideoFileClip, TextClip, CompositeVideoClip
import sys
def get_audio(filename):
video = mp.VideoFileClip(filename)
video.audio.write_audiofile("audio.wav")
def get_file_length(audiofile):
... |
402150 | import os
import sys
import torch
import torch.nn as nn
import math
from models.common import conv3x3, conv3x3_bn_relu, inconv, up, down, outconv, weights_init
from torch.nn import functional as F
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
__all__ = ['ResNe... |
402151 | from tensorboardX import SummaryWriter
import os
class Logger:
def __init__(self, *, log_dir, config):
self.writer = SummaryWriter(log_dir, write_to_disk=True)
self.config = config
def log_training(
self,
*,
training_metric_translation,
training_metric_orientat... |
402166 | import sys
import numpy as np
import lutorpy as lua
try:
import torchfile
except ImportError:
torchfile = None
if torchfile is None:
raise ImportError("Please, do pip install torchfile.")
import os
import sys
import time
import cv2
TFEAT_PATCH_SIZE = 32
TFEAT_DESC_SIZE = 128
TFEAT_BATCH_SIZE = 1000
STATS_FN... |
402170 | from django.test import TestCase
from .models import Board, Post, Comment
class BoardsTests(TestCase):
def test_no_boards(self):
"""
Tests if the 'boards' endpoint is responding and
if the response initially contains no boards
"""
resp = self.client.get('/nchan/boards/')
... |
402191 | import json
import math
import os
import shutil
import torch
from . import Callback
__all__ = ['ModelCheckpoint']
class ModelCheckpoint(Callback):
"""
Model Checkpoint to save model weights during training. 'Best' is determined by minimizing (or maximizing) the value found under monitored_log_key in the l... |
402198 | import numpy as np
from np_ml import Perceptron
if __name__ == '__main__':
print("--------------------------------------------------------")
print("Perceptron simple example!")
print("example in Statistical Learning Method(《统计学习方法》)")
print("--------------------------------------------------------")
... |
402231 | from django.db import models
from busshaming.enums import ScheduleRelationship
class TripDate(models.Model):
trip = models.ForeignKey('Trip')
date = models.DateField(db_index=True)
added_from_realtime = models.BooleanField(default=False)
# Has it had the stats calculation script run.
is_stats_ca... |
402241 | from btcproxy import ProxiedBitcoinD
from ephemeral_port_reserve import reserve
from concurrent import futures
import os
import pytest
import tempfile
import logging
import shutil
TEST_DIR = tempfile.mkdtemp(prefix='lightning-')
TEST_DEBUG = os.getenv("TEST_DEBUG", "0") == "1"
# A dict in which we count how often ... |
402254 | import time
from typing import Optional
import pyperclip
from platypush.backend import Backend
from platypush.message.event.clipboard import ClipboardEvent
class ClipboardBackend(Backend):
"""
This backend monitors for changes in the clipboard and generates even when the user copies a new text.
Require... |
402261 | from flask import Flask, jsonify
from flask_cors import CORS, cross_origin
from aci import aci
from deploy import deploy
from host import hosts
from iso import isos
from monitor import monitor
from network import networks
from server import servers
from setting import setting
from disks import disks
app = Flask(__name... |
402291 | import re
import copy
import numpy as np
import joblib
from sklearn.utils.metaestimators import _BaseComposition
from sklearn.base import BaseEstimator, TransformerMixin
from chariot.transformer.text.base import TextNormalizer, TextFilter
from chariot.transformer.token.base import TokenFilter, TokenNormalizer
from char... |
402298 | from sqlalchemy import Column, DateTime, Enum, Integer, String
from sqlalchemy.sql.schema import ForeignKey, UniqueConstraint
from virtool.pg.base import Base
from virtool.pg.utils import SQLEnum
class ArtifactType(str, SQLEnum):
"""
Enumerated type for possible artifact types
"""
sam = "sam"
b... |
402319 | from modify_host_origin_request_header import app
def test_event():
return {
"Records": [
{
"cf": {
"request": {
"headers": {
"host": [
{
"... |
402321 | import os
import numpy as np
import matplotlib.pyplot as plt
import pylab
def get_data(filename):
#print("retrieving data from " + filename)
loss_save = []
with open(filename, 'r') as f:
for line in f:
line = line.rstrip()
if line.startswith("unit:"):
unit = line.split(':')[1]
elif ... |
402326 | import torch
import torch.nn as nn
from ..registry import LOSSES
@LOSSES.register_module
class HausdorffLoss(nn.Module):
def __init__(self, loss_weight=1.0):
super(HausdorffLoss, self).__init__()
self.weight = loss_weight
def forward(self, set1, set2):
"""
Compute the Averaged... |
402332 | import json
import math
import os
import numpy as np
# Constants ---
tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),
(44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),
(148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),
... |
402378 | import sqlite3
try:
DBCONN = sqlite3.connect("..\\WSUS_Update_Data.db",
check_same_thread=False, isolation_level=None)
DBCONN.execute("pragma journal_mode=wal")
DBCONN.execute("pragma synchronous=NORMAL")
DBCONN.commit()
DBCONN.close()
except sqlite3.Error as erro... |
402394 | import copy
import json
import logging
from collections import OrderedDict
from typing import Dict, Tuple, List
from allennlp.common.file_utils import cached_path
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.fields import Field, TextField, SequenceLabelField, MetadataField
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.