id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
124730 | import numpy as np
a_soll = np.zeros((1000,20), dtype=np.complex64)
for ind in range(a_soll.shape[0]):
for jnd in range(a_soll.shape[1]):
i = ind + 1
j = jnd + 1
a_soll[ind,jnd] = - i * 0.3 + 1j*( j*j + 0.4)
b_soll = np.zeros(1200, dtype=np.complex64)
for ind in range(b_soll.shape[0... |
124740 | hidden_dim = 128
dilation = [1,2,4,8,16,32,64,128,256,512]
sample_rate = 16000
timestep = 6080
is_training = True
use_mulaw = True
batch_size = 1
num_epochs = 10000
save_dir = './logdir'
test_data = 'test.wav' |
124784 | import argparse
import os
import json
import copy
import pickle
import sys
import multiprocessing as mp
from pathlib import Path
from typing import Dict, List
from tqdm import tqdm
from collections import defaultdict, Counter
import logging
logger = logging.getLogger("root") # pylint: disable=invalid-name
logger.setL... |
124800 | from collections import OrderedDict
from itertools import islice
from typing import List
from app.master.build import Build
from app.util.exceptions import ItemNotFoundError
class BuildStore:
"""
Build storage service that stores and handles all builds.
"""
_all_builds_by_id = OrderedDict()
@cla... |
124807 | import tensorflow as tf
from base_model import BaseModel
class LSTMNN(object):
"""
LSTM neural network class, inherits from BaseModel
"""
def train(self):
"""
Fit the LSTM neural network to the data
"""
raise NotImplementedError()
|
124848 | class Solution:
def mySqrt(self, x: int) -> int:
left, right = 0, x
while left <= right:
mid = left + (right - left) // 2
square = mid ** 2
if square <= x:
left = mid + 1
elif squ... |
124923 | collect_ignore = []
try:
import sklearn
except ImportError:
collect_ignore.append('compat/sklearn.py')
collect_ignore.append('compat/test_sklearn.py')
try:
import sqlalchemy
except ImportError:
collect_ignore.append('stream/iter_sql.py')
collect_ignore.append('stream/test_sql.py')
try:
im... |
125002 | import pytest
from stock_indicators import indicators
class TestVortex:
def test_standard(self, quotes):
results = indicators.get_vortex(quotes, 14)
assert 502 == len(results)
assert 488 == len(list(filter(lambda x: x.pvi is not None, results)))
r = results[13]
... |
125056 | import numpy as np
import os, pickle
from tqdm import tqdm
def get_word_emb(word2coef_dict, word, default_value):
return word2coef_dict.get(word, default_value)
def get_phrase_emb(word2coef_dict, phrase, default_value):
words = phrase.split(' ')
embs = [ get_word_emb(word2coef_dict, word, default_value) fo... |
125092 | import chardet
import csv
from dateutil.parser import parse
def get_encoding(ds_path: str) -> str:
""" Returns the encoding of the file """
test_str = b''
number_of_lines_to_read = 500
count = 0
with open(ds_path, 'rb') as f:
line = f.readline()
while line and count < number_of_lin... |
125136 | from django.shortcuts import get_object_or_404
from django.views.generic import RedirectView
from common.models import Allegation, AllegationCategory
from common.utils.mobile_url_hash_util import MobileUrlHashUtil
from share.models import Session
from url_mediator.services.session_builder import Builder, AllegationCri... |
125155 | from gym.envs.registration import register
register(
id="Pusher-v1",
entry_point="micoenv.mico_robot_env:MicoEnv",
kwargs={
"randomize_arm": True,
"randomize_camera": True,
"randomize_textures": True,
"randomize_objects": True,
"normal_textures": True,
"done_a... |
125197 | from docopt import docopt
from abbr import __main__
from abbr.core import main
_mocked_html = """
<html>
<table class="no-margin">
<tbody>
<tr>
<dir>
<span class="sf" />
<span class="sf" />
</dir>
<p class="desc">term1</p>
<td... |
125215 | from pubnub.endpoints.file_operations.file_based_endpoint import FileOperationEndpoint
from pubnub.enums import HttpMethod, PNOperationType
from pubnub.crypto import PubNubFileCrypto
from pubnub.models.consumer.file import PNDownloadFileResult
from pubnub.request_handlers.requests_handler import RequestsRequestHandler
... |
125233 | import unittest
import io
from sievelib.factory import FiltersSet
from .. import parser
class FactoryTestCase(unittest.TestCase):
def setUp(self):
self.fs = FiltersSet("test")
def test_get_filter_conditions(self):
"""Test get_filter_conditions method."""
orig_conditions = [('Sender'... |
125265 | from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import registry
reg: registry = registry()
Base = declarative_base()
class SomeAbstract(Base):
__abstract__ = True
class HasUpdatedAt:
updated_at = Co... |
125347 | import re
from .git2_types import Git2Type
from .git2_type_common import (
Git2TypeConstObject,
Git2TypeOutObject,
PAT1_STR,
PAT2_STR,
PAT3_STR,
)
class Git2TypeConstRebaseOptions(Git2TypeConstObject):
PAT = re.compile(PAT1_STR + "(?P<obj_name>rebase_options)" + PAT2_STR)
class Git2TypeOutRe... |
125368 | del_items(0x80122A40)
SetType(0x80122A40, "struct Creds CreditsTitle[6]")
del_items(0x80122BE8)
SetType(0x80122BE8, "struct Creds CreditsSubTitle[28]")
del_items(0x80123084)
SetType(0x80123084, "struct Creds CreditsText[35]")
del_items(0x8012319C)
SetType(0x8012319C, "int CreditsTable[224]")
del_items(0x801243BC)
SetTy... |
125399 | import traceback
import services # pylint: disable=import-error
from interactions.base.immediate_interaction import ImmediateSuperInteraction # pylint: disable=import-error,no-name-in-module
from singletons import DEFAULT # pylint: disable=import-error
from event_testing.results import TestResult # pylint: disab... |
125420 | import os,glob
filenames = [os.path.splitext(os.path.basename(f))[0] for f in glob.glob(os.path.dirname(__file__)+"/*.py")]
filenames.remove('__init__')
__all__ = filenames |
125490 | from simple_settings import settings
from simple_settings.utils import settings_stub
# Stub examples
with settings_stub(SOME_SETTING='foo'):
assert settings.SOME_SETTING == 'foo'
assert settings.SOME_SETTING == 'bar'
@settings_stub(SOME_SETTING='foo')
def get_some_setting():
return settings.SOME_SETTING
ass... |
125570 | class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
start, end = 0, len(nums)- 1
while start <= end:
mid = start + (end - start) // 2
if nums[mid] < target:
start =... |
125579 | import torch
from abc import abstractmethod
from numpy import inf
import numpy as np
class BaseTrainer:
"""
Base class for all trainers
"""
def __init__(self, model, criterion, metric_ftns, optimizer, config, fold_id):
self.config = config
self.logger = config.get_logger('trainer', conf... |
125591 | from re import compile, finditer
REGEX = compile(r'\{\{([a-zA-Z]+)\}\}')
REPLS = ('{{', '{'), ('}}', '}')
def create_template(s):
def my_template(**kwargs):
keys = {a.group(1): '' for a in finditer(REGEX, s)}
keys.update(kwargs)
return reduce(lambda a, kv: a.replace(*kv), REPLS, s).format... |
125640 | from pylayers.antprop.antenna import *
from pylayers.antprop.antvsh import *
import matplotlib.pylab as plt
from numpy import *
import pdb
"""
This test :
1 : loads a measured antenna
2 : applies an electrical delay obtained from data with getdelay method
3 : evaluate the antenna vsh coefficient with a d... |
125682 | class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
E = len(trust)
if E < N - 1:
return -1
trustScore = [0] * N
for a, b in trust:
trustScore[a - 1] -= 1
trustScore[b - 1] += 1
for index, t in enumerate(trustScore, 1... |
125724 | from javax.swing.event import ListSelectionListener
class IssueListener(ListSelectionListener):
def __init__(self, view, table, scanner_pane, issue_name, issue_param):
self.view = view
self.table = table
self.scanner_pane = scanner_pane
self.issue_name = issue_name
self.issu... |
125739 | import collections
import numbers
import torch
import torch.nn.functional as F
from types import SimpleNamespace as nm
from .bioes import entities_jie_bioes
from .viterbi import decode_bioes_logits, INFTY
EPSILON = 1.e-8
def token_and_record_accuracy(logits, labels):
'''Computes accuracy metric from logits and ... |
125793 | import os
import sys
__all__ = ['ENVS_AND_VALS']
# Exercises both namespaced and simple-named settings variables
ENVS_AND_VALS = [("TAPISPY_PAGE_SIZE", 9000),
("TAPISPY_LOG_LEVEL", "CRITICAL"),
("TENANT_DNS_DOMAIN", "tacc.dev"),
("TACC_PROJECT_NAME", "TACO_SUPERPOWER... |
125808 | expected_normal_output = """Title Release Year Estimated Budget
Shawshank Redemption 1994 $25 000 000
The Godfather 1972 $6 000 000
The Godfather: Part II 1974 $13 000 000
The Dark Knight 2008 $185 000 000
12 Angry Men 1957 ... |
125813 | import os
# src_dir = "/usr/lib/x86_64-linux-gnu"
src_dir = "/mnt/drive_c/datasets/kaju/opencv_libs"
# dst_dir = None
dst_dir = None
libname = "opencv"
# libversion = "1.58.0"
# leading . needed
src_libversion = ""
dst_libversion = ".4.0.0"
dry_run = True
if not dst_dir:
dst_dir = src_dir
files = os.listdir(src_d... |
125869 | import pytest
import base64
from mock import MagicMock
from volttrontesting.utils.utils import AgentMock
from volttron.platform.vip.agent import Agent
from volttroncentral.platforms import PlatformHandler, Platforms
from volttroncentral.agent import VolttronCentralAgent
@pytest.fixture
def mock_vc():
VolttronCent... |
125954 | import pandas as pd
import flexmatcher
# Let's assume that the mediated schema has three attributes
# movie_name, movie_year, movie_rating
# creating one sample DataFrame where the schema is (year, Movie, imdb_rating)
vals1 = [['year', 'Movie', 'imdb_rating'],
['2001', 'Lord of the Rings', '8.8'],
[... |
125963 | import os
import numpy as np
import pandas as pd
from collections import defaultdict
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
def tabulate_events(dir_path):
summary_iterators = [EventAccumulator(os.path.join(dir_path, dname)).Reload() for dname in os.listdir(dir_path)]
... |
125993 | import re
from uuid import UUID
from typing import Union
class BTUUID(UUID):
"""An extension of the built-in UUID class with some utility functions for converting Bluetooth UUID16s to and from UUID128s."""
_UUID16_UUID128_FMT = "0000{0}-0000-1000-8000-00805F9B34FB"
_UUID16_UUID128_RE = re.compile(
... |
126065 | from torch.nn.modules.loss import _Loss
import torch
from enum import Enum
from typing import Union
class Mode(Enum):
BINARY = "binary"
MULTICLASS = "multiclass"
MULTILABEL = "multilabel"
class Reduction(Enum):
SUM = "sum"
MEAN = "mean"
NONE = "none"
SAMPLE_SUM = "sample_sum" # mean by s... |
126095 | from setuptools import setup, find_packages
import re
# Get the version, following advice from https://stackoverflow.com/a/7071358/851699
VERSIONFILE="artemis/_version.py"
verstrline = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, verstrline, re.M)
if mo:
verstr =... |
126104 | from nlgen.cfg import CFG, PTerminal, PUnion
def test_simple_production_union():
cfg = CFG([
("S", PUnion([
PTerminal("foo"),
PTerminal("bar")
])),
])
expect = [("foo",), ("bar",)]
result = list(cfg.permutation_values("S"))
assert expect == result
def test... |
126150 | from __future__ import print_function
import os.path
import sys
import json
from collections import OrderedDict
from itertools import chain
from dmcontent import ContentLoader, utils
_base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def _get_questions_by_type(framework_slug, doc_type, questi... |
126152 | def get_context_user(context):
if 'user' in context:
return context['user']
elif 'request' in context:
return getattr(context['request'], 'user', None)
|
126195 | from importlib import import_module
from py2swagger.plugins import Py2SwaggerPlugin, Py2SwaggerPluginException
from py2swagger.introspector import BaseDocstringIntrospector
from py2swagger.utils import OrderedDict
class FalconMethodIntrospector(BaseDocstringIntrospector):
def get_operation(self):
"""
... |
126241 | import setuptools
import versioneer
from pathlib import Path
# Extract information from the README file and embed it in the package.
readme_path = Path(__file__).absolute().parent / "README.md"
with open(readme_path, "r") as fh:
long_description = fh.read()
setuptools.setup(
author="<NAME>",
author_emai... |
126244 | a=int(input("Input an integer :"))
n1=int("%s"%a)
n2=int("%s%s"%(a,a))
n3=int("%s%s%s"%(a,a,a))
print(n1+n2+n3)
|
126254 | from pydantic import validator, ValidationError, Field
from .types import BaseModel, Union, Optional, Literal, List
from typing import Dict
import pathlib
class ParasiticValues(BaseModel):
mean: int = 0
min: int = 0
max: int = 0
class Layer(BaseModel):
name: str
gds_layer_number: int
gds_dat... |
126317 | from django.test import TestCase
import pytest
from ...test_assets.utils import get_taxbrain_model
from ...test_assets.test_models import (TaxBrainTableResults,
TaxBrainFieldsTest)
from ...dynamic.models import DynamicBehaviorOutputUrl
from ...dynamic.forms import DynamicBehavi... |
126331 | import asyncio
import pytest
from panini.async_test_client import AsyncTestClient
from panini import app as panini_app
def run_panini():
app = panini_app.App(
service_name="async_test_client_test_error_handling",
host="127.0.0.1",
port=4222,
)
@app.listen("async_test_client.test... |
126348 | class Alphabet:
"""
Bijective mapping from strings to integers.
>>> a = Alphabet()
>>> [a[x] for x in 'abcd']
[0, 1, 2, 3]
>>> list(map(a.lookup, range(4)))
['a', 'b', 'c', 'd']
>>> a.stop_growth()
>>> a['e']
>>> a.freeze()
>>> a.add('z')
Traceback (most recent call last)... |
126397 | import tensorflow as tf
def deconvLayer(x,kernelSize,outMaps,stride): #default caffe style MRSA
with tf.variable_scope(None,default_name="deconv"):
inMaps = x.get_shape()[3]
kShape = [kernelSize,kernelSize,outMaps,inMaps]
w = tf.get_variable("weights",shape=kShape,initializer=tf.uniform_unit_scaling_initialize... |
126420 | from distutils.core import setup, Extension
m = Extension('tinyobjloader',
sources = ['main.cpp', '../tiny_obj_loader.cc'])
setup (name = 'tinyobjloader',
version = '0.1',
description = 'Python module for tinyobjloader',
ext_modules = [m])
|
126429 | import numpy as np
import pandas as pd
from tqdm import tqdm
from joblib import Parallel, delayed
import os
bitsize = 1024
total_sample = 110913349
data_save_folder = './data'
file = './data/%s_%s.npy' % (total_sample, bitsize)
f = np.memmap(file, dtype = np.bool, shape = (total_sample, bitsize))
def _sum(memmap... |
126437 | from typing import Any, Dict, List, Tuple
from streamlit_prophet.lib.utils.holidays import get_school_holidays_FR
COUNTRY_NAMES_MAPPING = {
"FR": "France",
"US": "United States",
"UK": "United Kingdom",
"CA": "Canada",
"BR": "Brazil",
"MX": "Mexico",
"IN": "India",
"CN": "China",
"... |
126438 | import sys, os
from read_struc import read_struc
from math import sin, cos
import numpy as np
def euler2rotmat(phi,ssi,rot):
cs=cos(ssi)
cp=cos(phi)
ss=sin(ssi)
sp=sin(phi)
cscp=cs*cp
cssp=cs*sp
sscp=ss*cp
sssp=ss*sp
crot=cos(rot)
srot=sin(rot)
r1 = crot * cscp + srot * sp
... |
126464 | import matplotlib.pyplot as plt
from cleanco import cleanco
from nltk.corpus import names, gazetteers
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.stem.lancaster import LancasterStemmer
from nltk.tokenize import TweetTokenizer
plt.style.use('ggplot')
import nltk
import scipy.sta... |
126502 | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import numpy.testing as npt
import pytest
import freud
matplotlib.use("agg")
class TestGaussianDensity:
def test_random_point_with_cell_list(self):
fftpack = pytest.importorskip("scipy.fftpack")
fft = fftpack.fft
fftshi... |
126507 | from os.path import basename, splitext
import cv2
import json
from src.img_utility import BBCor_to_pts, vertices_rearange
# return a list of BB coordinates [[x1, y1], [x2, y2]]
def CCPD_BBCor_info(img_path):
img_path = basename(img_path)
BBCor = img_path.split('-')[2].split('_')
return [map(int, BBCor[0... |
126508 | import numpy as np
import os
import warnings
from Input import Input
class InputFromData(Input):
"""
Used to draw random samples from a data file.
"""
def __init__(self, input_filename, delimiter=" ", skip_header=0,
shuffle_data=True):
"""
:param input_filename: path ... |
126564 | import json
import pytest
import simdjson
def with_buffer(content):
import numpy
parser = simdjson.Parser()
doc = parser.parse(content)
assert len(numpy.frombuffer(doc.as_buffer(of_type='d'))) == 10001
def without_buffer(content):
import numpy
parser = simdjson.Parser()
doc = parser.... |
126565 | from sequana.rnadiff import RNADiffResults, RNADiffAnalysis, RNADesign
from . import test_dir
import pytest
def test_design():
d = RNADesign(f"{test_dir}/data/rnadiff/design.csv")
assert d.comparisons == [('Complemented_csrA', 'Mut_csrA'), ('Complemented_csrA', 'WT'), ('Mut_csrA', 'WT')]
assert d.conditi... |
126588 | class AccountNotFoundError(Exception):
pass
class TransactionError(Exception):
pass
class AccountClosedError(TransactionError):
pass
class InsufficientFundsError(TransactionError):
pass
|
126620 | import unittest
import uuid
import py3crdt
from py3crdt.orset import ORSet
class TestORSet(unittest.TestCase):
def setUp(self):
# Create a ORSet
self.orset1 = ORSet(uuid.uuid4())
# Create another ORSet
self.orset2 = ORSet(uuid.uuid4())
# Add elements to orset1
sel... |
126659 | from sklearn.metrics import recall_score, roc_curve, auc
def specificity(y_true, y_pred):
return recall_score(y_true, y_pred, pos_label=0)
def sensitivity(y_true, y_pred):
return recall_score(y_true, y_pred, pos_label=1)
def balanced_accuracy(y_true, y_pred):
spec = specificity(y_true, y_pred)
sens... |
126668 | from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from rest_framework_json_api.relations import (
ResourceRelatedField,
SerializerMethodResourceRelatedField, SerializerMethodHyperlinkedRelatedField
)
from bluebottle.activities.utils import (
BaseActivitySe... |
126691 | import sys
sys.path.append('.') # NOQA
from src.datasets.preprocess import normalize
def main(root_path=None, arr_type='nii.gz', modality='mri'):
# save normalized npz arrays in root_path/normalized/
normalize(root_path, arr_type, modality)
if __name__ == '__main__':
from fire import Fire
Fire(main... |
126770 | from benchmark import Benchmark, benchmark
import astropy.units as u
import pytest
@benchmark(
{
"log.final.venus.TMan": {"value": 2679.27122, "unit": u.K},
"log.final.venus.TCore": {"value": 6365.71258, "unit": u.K},
"log.final.venus.RIC": {"value": 0.0, "unit": u.km},
"log.final.... |
126772 | class RetrievalMethod():
def __init__(self,db):
self.db = db
def get_sentences_for_claim(self,claim_text,include_text=False):
pass
|
126819 | from sentence_transformers import CrossEncoder
from .dataset import HardNegativeDataset
from torch.utils.data import DataLoader
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer
import tqdm
import os
import logging
logger = logging.getLogger(__name__)
def hard_negative_colla... |
126874 | import copy
import time
from collections import defaultdict, namedtuple
import kaa
from . import keybind, theme, modebase, menu
class DefaultMode(modebase.ModeBase):
DOCUMENT_MODE = True
MODENAME = 'default'
SHOW_LINENO = False
SHOW_BLANK_LINE = True
VI_COMMAND_MODE = False
KEY_BINDS = [
... |
126938 | from FrameLibDocs.utils import write_json, read_yaml
from FrameLibDocs.classes import qParseAndBuild, Documentation
def main(docs):
"""
Creates a dict for the Max Documentation system.
This dict contains is essential for maxObjectLauncher/Refpages to pull the right info.
"""
object_info = read_ya... |
127014 | import json
import string
from backports.tempfile import TemporaryDirectory
from django.test import override_settings
from django.urls import reverse
from django_webtest import WebTest, WebTestMixin
from hypothesis import given, settings
from hypothesis.extra.django import TestCase
from hypothesis.strategies import te... |
127029 | from biicode.common.utils.serializer import Serializer, SetDeserializer
from biicode.common.model.symbolic.reference import ReferencedDependencies
from biicode.common.model.declare.declaration import Declaration
class FinderResult(object):
SERIAL_RESOLVED_KEY = "r"
SERIAL_UNRESOLVED_KEY = "u"
SERIAL_UPDA... |
127040 | import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import BaggingRegressor
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.ensemble import AdaBoostRegressor
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble import RandomTreesEmbedding
fr... |
127069 | from __future__ import absolute_import
from builtins import zip
from builtins import range
from builtins import object
from nose.tools import (assert_equal, assert_not_equal, assert_almost_equal,
raises)
from nose.plugins.skip import Skip, SkipTest
from .test_helpers import (
true_func, asse... |
127089 | def coroutine(seq):
count = 0
while count < 200:
count += yield
seq.append(count)
seq = []
c = coroutine(seq)
next(c)
___assertEqual(seq, [])
c.send(10)
___assertEqual(seq, [10])
c.send(10)
___assertEqual(seq, [10, 20]) |
127095 | from __future__ import print_function
from math import pi,floor
print(int(((-330+1024)*pi/(6.0*2048.0))/(0.625*pi/180.0)))
#phi=[]
#for i in range(0,2048):
# p = int((i*pi/(6.0*2048.0)+15.0*pi/180.0)/(0.625*pi/180.0))
# p = int((i*2*pi/(6.0*2048.0))/(0.625*pi/180.0))
# phi.append(str(p))
#print('const ap... |
127106 | import psycopg2
from flask import g
from psycopg2 import errorcodes
class DuplicateRestaurantNameError(RuntimeError):
pass
class Restaurant:
def __init__(self, id, name):
self.id = id
self.name = name
@classmethod
def create(cls, name):
query = """
INSERT INTO
... |
127164 | from .. import rman_bl_nodes
from ..rfb_icons import get_bxdf_icon, get_light_icon, get_lightfilter_icon, get_projection_icon
from ..rman_constants import RMAN_BL_NODE_DESCRIPTIONS
def get_description(category, node_name):
description = None
for n in rman_bl_nodes.__RMAN_NODES__.get(category, list()):
... |
127178 | import numpy as np
import matplotlib.pyplot as plt
x,y = np.linspace(0,5,100),np.linspace(0,2,100)
X,Y = np.meshgrid(x,y)
U = X
V = Y*(1-Y)
speed = np.sqrt(U*U + V*V)
start = [[.3,.15], [0.3,1], [.3,1.5],[3,1.5]]
fig0, ax0 = plt.subplots()
strm = ax0.streamplot(x,y, U, V, color=(.75,.90,.93))
strmS = ax0.streamplot... |
127190 | from os.path import join
import numpy as np
import matplotlib as mpl
# For headless environments
mpl.use('Agg') # NOQA
import matplotlib.pyplot as plt
PLOT_CURVES = 'plot_curves'
def plot_curves(run_path):
"""Plot the training and validation accuracy over epochs.
# Arguments
run_path: the path to t... |
127201 | import numpy as np
from PIL import Image
import skimage
import skimage.transform
import scipy.io as io
import matplotlib.pyplot as plt
import utils.common_utils as cu
import scipy.io
def load_data(path, f):
img = np.array(Image.open(path))
img = skimage.transform.resize(img, (img.shape[0]//f,img.shape[1]//f), ... |
127211 | from snowddl.blueprint import DatabaseBlueprint, DatabaseIdent
from snowddl.parser.abc_parser import AbstractParser
database_json_schema = {
"type": "object",
"properties": {
"is_transient": {
"type": "boolean"
},
"retention_time": {
"type": "integer"
},... |
127226 | import torch
import torch.nn as nn
import numpy as np
import torch.distributions as TD
import scipy
import scipy.linalg
from copy import deepcopy
from multipledispatch import dispatch
from collections import Iterable
import sdepy
from .em import batchItoEuler
from .em_proxrec import torchBatchItoEulerProxrec
class OU_... |
127240 | import pytest
from vnep_approx import treewidth_model
from test_data.request_test_data import create_test_request, example_requests
from test_data.tree_decomposition_test_data import PACE_INPUT_FORMAT
@pytest.mark.parametrize("test_data", PACE_INPUT_FORMAT.items())
def test_conversion_to_PACE_format_works(test_data... |
127244 | from django import forms
from ..nospam import utils
from .fields import HoneypotField
class BaseForm(forms.Form):
def __init__(self, request, *args, **kwargs):
self._request = request
super(BaseForm, self).__init__(*args, **kwargs)
class AkismetForm(BaseForm):
akismet_fields = {
... |
127278 | import pandas as pd
import numpy as np
import os
from collections import Counter
from scipy.cluster.hierarchy import linkage, fcluster
from scipy.spatial.distance import squareform
def find_correlation_clusters(corr,corr_thresh):
dissimilarity = 1.0 - corr
hierarchy = linkage(squareform(dissimilarity), method... |
127299 | import argparse
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
import sys
sys.path.append('.')
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('res', type=str)
parser.add_argument('gt', type=str)
args = parser.parse_args()
return args
def main(... |
127311 | from django.contrib.auth.models import User
from core.models import UserProfile, CourseStatus, Course, ProviderProfile, TimelineItem
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'email')
class BioSerializ... |
127376 | from django.conf import settings
from django.views.generic import TemplateView
from daiquiri.core.views import ModelPermissionMixin
from .models import Record
class ManagementView(ModelPermissionMixin, TemplateView):
template_name = 'stats/management.html'
permission_required = 'daiquiri_stats.view_record'
... |
127386 | import pytest
from dbt.tests.util import run_dbt, check_relations_equal
snapshot_sql = """
{% snapshot snapshot_check_cols_new_column %}
{{
config(
target_database=database,
target_schema=schema,
strategy='check',
unique_key='id',
check_cols=var("... |
127396 | import numpy as np
import scipy.signal
__all__ = ['instant_parameters']
#-----------------------------------
def instant_parameters(signal, fs = None):
'''
Instant parameters estimation:
..math::
analitc_signal = hilbert(signal)
envelope = |analitc_signal|
phase = unwrap(angle(a... |
127427 | import imageio
import sys
if __name__ == '__main__':
if len(sys.argv) == 2:
_, filename = sys.argv
img = imageio.imread(filename).astype(dtype='float32')
print('DTYPE:', img.dtype)
print('SHAPE:', img.shape)
elif len(sys.argv) == 3:
_, filename, type = sys.argv
i... |
127461 | from torch_sparse import coalesce
def dense_to_sparse(tensor):
index = tensor.nonzero()
value = tensor[index]
index = index.t().contiguous()
index, value = coalesce(index, value, tensor.size(0), tensor.size(1))
return index, value
|
127471 | import os
import random
import numpy as np
import argparse
import logging
import pickle
from pprint import pformat
from exps.data import get_modelnet40_data_fps
from settree.set_data import SetDataset, OPERATIONS, flatten_datasets
import exps.eval_utils as eval
if __name__ == '__main__':
parser = argparse.Argu... |
127491 | import numpy
import h5py
import scipy.sparse
from pyscf import gto, scf, mcscf, fci, ao2mo, lib
from pauxy.systems.generic import Generic
from pauxy.utils.from_pyscf import generate_integrals
from pauxy.utils.io import (
write_qmcpack_wfn,
write_qmcpack_dense,
write_input
)
mol = gto.M(... |
127627 | import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
def plot_cca(image, objects_cordinates):
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(12, 12))
ax.imshow(image, cmap=plt.cm.gray)
for each_cordinate in objects_cordinates:
min_row, min_col, max_row, max_col = each_cordinate... |
127648 | comida = ["tacos", "pozole", "<NAME>", "pastel", "spaghetti", "gorditas"]
print("Acceder a los elementos de la lista individualmente")
print(comida[0])
print(comida[2])
print(comida[5])
print("Mostrar todos los elementos")
print(comida)
print()
print("Eliminar algun elemento")
del comida[3]
comida.pop()
print(comida... |
127661 | import os.path as osp
import sys
def add_path(path):
if path not in sys.path:
sys.path.insert(0, path)
# path
this_dir = osp.dirname(__file__)
# refer path
refer_dir = osp.join(this_dir, '..', 'data', 'ref')
sys.path.insert(0, refer_dir)
# lib path
sys.path.insert(0, osp.join(this_dir, '..'))
sys.pat... |
127676 | class Eval:
"""
Eval
"""
def __init__(self):
self.predict_num = 0
self.correct_num = 0
self.gold_num = 0
self.precision = 0
self.recall = 0
self.fscore = 0
def clear(self):
"""
:return:
"""
self.predict_num = 0
... |
127709 | import dico
client = dico.Client("YOUR_BOT_TOKEN")
client.on_ready = lambda ready: print(f"Bot ready, with {len(ready.guilds)} guilds.")
@client.on_message_create
async def on_message_create(message: dico.Message):
if message.content.startswith("!button"):
button = dico.Button(style=dico.ButtonStyles.PR... |
127726 | from contextlib import closing
from pathlib import Path
import pytest
from asyncio_extras import open_async
@pytest.fixture(scope='module')
def testdata():
return b''.join(bytes([i] * 1000) for i in range(10))
@pytest.fixture
def testdatafile(tmpdir_factory, testdata):
file = tmpdir_factory.mktemp('file')... |
127748 | from django.shortcuts import render
from django.core import serializers
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.conf import settings
import json
impo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.