id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9817594 | from .lars import Lars
from .lamb import Lamb
from .radam import RAdam
from .ralars import RaLars
from .tadam import TAdam
from .adabelief import AdaBelief
from .adamp import AdamP
from . import wrapper
|
9817675 | from typing import TypeVar
from .base_event import Event
from ..filters import can_trace_type
class ExecutionCursor:
function_name: str
file: int
line: int
def __init__(self, file: int, line: int, function_name: str):
self.function_name = function_name
self.file = file
self.l... |
9817676 | import argparse
import template
import os.path
import easydict
### See option.py for detailed information.
args = easydict.EasyDict({
'debug': False,
'template': '.',
'degradation': False,
# Hardware specifications
'n_threads': 0,
'cpu': False,
'n_GPUs': 1,
'seed': 1,
# Data sp... |
9817679 | from HABApp.core import Items
from HABApp.core.items import BaseValueItem
from HABApp.mqtt.mqtt_interface import publish
class MqttBaseItem(BaseValueItem):
pass
class MqttItem(MqttBaseItem):
"""A simple item that represents a topic and a value"""
@classmethod
def get_create_item(cls, name: str, ini... |
9817741 | import os
import zipfile
from .metadata import Metadata
from .util import hash_zip
class MetadataNotFoundError(Exception):
"""
Thrown when no metadata was found in the data container loaded
"""
class DataContainer:
"""
Represents a data container which holds both data and metadata.
Responsibi... |
9817759 | import pytest
from plenum.common.constants import NYM, NODE
from plenum.common.txn_util import get_type, set_type, get_payload_data, \
get_from, get_req_id, get_seq_no, get_txn_id, \
get_txn_time, get_version, get_digest, get_protocol_version, get_payload_digest
from plenum.common.util import SortedDict
@pyt... |
9817803 | import random
from Helpers import colours
KAREN_ADDITIONS_ANIMATED = {
"wave" : "<a:wave:787761464697421835>",
"tada" : "<a:tada:787761454564114444>",
"thumbsdown" : "<a:thumbsdown:787762156316917761>",
"thumbsup" : "<a:thumbsup:787762147630514216>",
"alert" : "<a:alart:787764293256347648>"... |
9817812 | from . import actions # NOQA
from . import encentry # NOQA
from . import encyclopaedia # NOQA
from . import entry_sorting # NOQA
from . import labels # NOQA
|
9817823 | from least_squares import gauss_LS_mpc
###path of file of optical MPC-formatted observations
filename = '../example_data/mpc_eros_data.txt'
###body name
bodyname = 'Eros'
###vector of line numbers in observations file to be used for preliminary orbit determination using Gauss method
obs_arr = [1, 14, 15, 24, 32, 37,... |
9817853 | import sys
import pytest
from mvlearn.embed.base import BaseEmbed
from numpy.testing import assert_equal
def test_base_embed():
base = BaseEmbed()
base.fit(Xs=None, y=None)
base.transform(Xs=None)
base.fit_transform(Xs=None, y=None)
|
9817865 | import datetime as dt
import re
import pytest
import pytz
import stix2
from .constants import CAMPAIGN_ID, NOTE_ID
CONTENT = (
'This note indicates the various steps taken by the threat'
' analyst team to investigate this specific campaign. Step'
' 1) Do a scan 2) Review scanned results for identified '... |
9817892 | import re;
from .cBugTranslation import cBugTranslation;
aoBugTranslations = [
# ASan build related -> Ignored
cBugTranslation(
azs0rbAdditionalIrrelevantStackFrameSymbols = [
rb".*!`anonymous namespace'::Create", # Part of skia
rb".*!base::debug::BreakDebugger",
rb".*!base::debug::CollectGDI... |
9817937 | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_nginx_service(host):
nginx_service = host.service('nginx')
assert nginx_service.is_running
assert nginx_service.is_enabled... |
9817952 | import io
from bs4 import BeautifulSoup
import urllib.request as ulibr
# wikipedia url
base_url = "https://en.wikipedia.org/wiki/"
# this function creates name suitable for searching
def create_name(first, last):
if first is None and last is None:
return "error"
first = first[0].capitalize() + first... |
9817974 | from rest_framework import viewsets
from knockout import metadata
from app import serializers, models
class PersonViewSet(viewsets.ModelViewSet):
serializer_class = serializers.PersonSerializer
metadata_class = metadata.KnockoutMetadata
queryset = models.Person.objects.all()
class TaskViewSet(viewsets.... |
9817995 | import os
import random
import pickle
import pytrec_eval
from eval.eval_bm25_coliee2021 import read_label_file
from analysis.ttest import measure_per_query
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import matplotlib
from analysis.compare_bm25_dpr import read... |
9818015 | import time
import pytest
@pytest.fixture(scope='session')
def aiolib():
return ('asyncio', {'use_uvloop': False})
@pytest.fixture
def ts():
return time.time()
@pytest.fixture
async def client(asgi):
from asgi_tools.tests import ASGITestClient
client = ASGITestClient(asgi)
async with client.... |
9818027 | from ncvoter.known_cities import KNOWN_CITIES
# Code, Label, Description
STATUS_FILTER_CHOICES = [
('A', 'Active', "are actively registered"),
('D', 'Denied', "were denied registration"),
('I', 'Inactive', "have inactive registrations"),
('R', 'Removed', "have had their registration removed"),
('S'... |
9818071 | from ..broker import Broker
class VlanBroker(Broker):
controller = "vlans"
def show(self, **kwargs):
"""Shows the details for the specified vlan.
**Inputs**
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` True
| ... |
9818080 | from django.db import models
from django.conf import settings
import stripe
STRIPE_SECRET_KEY = getattr(settings, 'STRIPE_SECRET_KEY')
stripe.api_key = STRIPE_SECRET_KEY
class CardManager(models.Manager):
def new(self, token, payment_profile):
if token and payment_profile.user.is_employer:
cus... |
9818140 | import sublime
import os
import json
import webbrowser
def get_gists_cache(settings):
cache_dir = os.path.join(settings["workspace"], ".cache", "gists.json")
if not os.path.isfile(cache_dir): return
return json.loads(open(cache_dir).read())
def add_gists_to_cache(gists):
"""Add gist the caches"""
... |
9818207 | import json
import re
import time
import bs4
from ..Empty import Album, Singer, Song, Result, BaseAlbum, SearchMusic, MusicInfo, Lyric
from ..Utils import net_get as _g, net2_session
from ..Utils import _MIN_TO_MM
_MUSIC_BD_SEARCH_HEADERS = {
# ":authority": "music.taihe.com",
# ":method": "GET",
# ":path"... |
9818287 | import asyncio
import atexit
import random
import time
import types
import uuid
from pathlib import Path
import aiohttp
import tqdm # type: ignore
from yarl import URL
from gd.api.recording import Recording, RecordingEntry
from gd.async_utils import get_running_loop, maybe_coroutine, shutdown_loop
from gd.converter... |
9818390 | from biogeme import *
from headers import *
from nested import *
from loglikelihood import *
from statistics import *
#import random
cons_bus = Beta('bus cons',0,-10,10,0)
cons_mrt = Beta('MRT cons',0,-10,10,0)
cons_privatebus=Beta('private bus cons',0,-10,10,0)
cons_drive1=Beta('drive alone cons',0,-10,10,1)
cons_sha... |
9818391 | import random
import numpy as np
import nltk
import sklearn
import keras
import json
import scipy
from collections import defaultdict
import gen_util
import keras
random.seed(1337)
path="../big_domain_desc/"
maxlen=120
offset1=100 #we increase the training examples.
set_mode='train1'
num_train=900
num_valid=100
top... |
9818399 | from plex.core.idict import idict
from plex.interfaces.core.base import Interface
class PlaylistsInterface(Interface):
path = 'playlists'
def all(self, type=15, sort=None, playlist_type=None, smart=None):
response = self.http.get('all', query=[
('type', type),
('sort', sort),
... |
9818404 | import mwtypes
from ..errors import MalformedXML
from .user import User
class Revision(mwtypes.Revision):
"""
Revision metadata and text. See :class:`mwtypes.Revision` for a
description of fields.
"""
@classmethod
def from_element(cls, element):
id = None
timestamp = None
... |
9818449 | from __future__ import annotations
from typing import *
from collections import defaultdict
from itertools import takewhile, accumulate
from operator import itemgetter
import logging
import random
import uuid
import os
import time
import pickle
import torch
from torch import optim
from torch.optim.optimizer import Opt... |
9818453 | import subprocess
import os
import os.path
import uuid
import logging
import random
import requests
DEVNULL = open(os.devnull, 'w')
def fetch_relays(limit=100):
url = 'https://onionoo.torproject.org/details'
params = dict(
limit=limit,
)
res = requests.get(url, params=params)
... |
9818464 | class MovingAverageStrategyState:
def __init__(self):
self._long_open: bool = False
self._short_open: bool = False
self._position: int = 0
@property
def long_open(self) -> bool:
return self._long_open
@long_open.setter
def long_open(self, value: bool) -> None:
... |
9818465 | import json
import torch
from torch import nn
from torch.autograd.function import Function
import torch.nn.functional as F
import numpy as np
from detectron2.modeling.roi_heads.fast_rcnn import fast_rcnn_inference
from detectron2.modeling.roi_heads.roi_heads import ROI_HEADS_REGISTRY, StandardROIHeads
from detectron2.... |
9818467 | import torch
num_list = [str(i) for i in range(0, 10)]
def _getattr(obj, key):
stage = key.rsplit('.')
for i in stage:
if i[0] in num_list:
obj = obj[int(i)]
else:
obj = getattr(obj, i)
return obj
def _isinstance(obj, cls_list):
flag_list = [isinstance(obj, c... |
9818470 | from collections import OrderedDict
import numpy as np
from env.base import BaseEnv
from env.transform_utils import sample_quat
class TwoJacoEnv(BaseEnv):
def __init__(self, xml_path, **kwargs):
super().__init__(xml_path, **kwargs)
# env info
self.ob_shape = OrderedDict([("right_arm", 9 ... |
9818528 | from eth_tools import Contract, address
from nose.tools import assert_equal
from pyethereum import tester as t
INITIALIZE = 0
SET_CONFIGURATION = 1
BUY_TICKET = 2
GET_TICKET_OWNER = 3
GET_TICKET_NUMBERS = 4
TRANSFER_TICKET = 5
CHECK_WINNERS = 6
CLAIM_WINNINGS = 7
GET_BALANCE = 8
SET_PAYOUTS = 9
WITHDRAW = 10
START_LOT... |
9818547 | import json
import pandas as pd
import numpy as np
all_intents_data = pd.DataFrame()
all_intents_full_data = pd.DataFrame()
for intent in ['AddToPlaylist', 'BookRestaurant', 'GetWeather', 'PlayMusic', 'RateBook', 'SearchCreativeWork',
'SearchScreeningEvent']:
with open("./nlu-benchmark/2017-06-cust... |
9818552 | import uuid
def convert_tx_id(tx_id):
"""
Converts the guid tx_id to string of 16 characters with a dash between every 4 characters
:param tx_id: tx_id to be converted
:return: String in the form of xxxx-xxxx-xxxx-xxxx
"""
return (tx_id[:4] + '-' + tx_id[4:])[:19]
def convert_tx_id_for_boxes... |
9818578 | from types import SimpleNamespace
dashboard_fields = SimpleNamespace(
description="description",
html_file="html_file",
id="id",
name="name",
project="project",
categories="categories")
dashboard_post_properties = {
dashboard_fields.name: {
"type": "string",
"description": ... |
9818580 | from pathlib import Path
import json
import logging
from typing import List, Any, Tuple, Optional, Dict, Iterable
import toolz as tz
from .core import UserScopeSettings, ScopeSettings, CodeElement, CallPosType, Node
from . import serialize
from .custom_typing import CheckableOptional, CheckableDict, CheckableTuple, Ch... |
9818608 | import numpy as np
import os, glob
from tqdm import tqdm
from natsort import natsorted
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', required=True, help='base directory where data is placed')
opt = parser.parse_args()
modes = ['sky_train', 'sky_test']
for ia, mode in enumerate(m... |
9818629 | from rest_framework import serializers
import pytz
from shared.serializer import NoNullSerializer
from .coaccused_serializer import CoaccusedSerializer
class TRRSerializer(NoNullSerializer):
id = serializers.IntegerField()
to = serializers.SerializerMethodField()
taser = serializers.NullBooleanField()
... |
9818640 | from typing import List
import numpy as np
__author__ = "@de-code"
"""
Utility class, from:
https://github.com/elifesciences/sciencebeam-trainer-delft/blob/develop/sciencebeam_trainer_delft/utils/numpy.py
"""
def concatenate_or_none(arrays: List[np.array], **kwargs) -> np.array:
if arrays[0] is None:
r... |
9818644 | from rkd_harbor.test import BaseHarborTestClass
class TestRedirectToWWWFeature(BaseHarborTestClass):
"""Functional tests to check NGINX template feature - redirection from WWW to non-WWW hostname
It's about a label: `org.riotkit.redirectFromWWW: true`
"""
def test_redirects_from_www_to_non_www(self)... |
9818673 | import torch
from padl.utils import same
def test_same():
t = same.tolist()
assert t(torch.tensor([1, 2, 3])) == [1, 2, 3]
t = same[0]
assert t([1, 2, 3]) == 1
t = same[:2]
assert t([1, 2, 3]) == [1, 2]
|
9818746 | from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from collections import defaultdict
import random as r
import math as m
import numpy as np
from keras import backend as K
from random import Random
INTERVENTION_SIM_THRESHOLD=0.1
MAXLEN = 50
SEED=314159 # first digits... |
9818758 | import cv2
import dlib
from imutils import face_utils
# face detector
face_detect = dlib.get_frontal_face_detector()
# facial landmarks detector
face_marks = dlib.shape_predictor("./utils/shape_predictor_68_face_landmarks.dat")
def get_face(gray):
"""
Arguments:
gray: grayscale image array
Returns... |
9818782 | import os
import threading, queue
import traceback
from typing import List
from flask import Flask, json, request
import torch
import requests
from waitress import serve
from dotenv import load_dotenv
import cv2
import numpy as np
from insightface.app import FaceAnalysis
app = FaceAnalysis(name='antelopev2')
app.prepa... |
9818850 | def get_data(name):
if name == "request_list":
return request_list
elif name == "result_list":
return result_list
elif name == "info_list":
return info_list
elif name == "asset_info_list":
return asset_info_list
elif name == "score_list":
return score_list
r... |
9818877 | import requests
from datetime import datetime, timedelta
from requests.auth import HTTPBasicAuth
from django.db.models import Count
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from rest_f... |
9818903 | from django.test import TestCase
from wagtailmenus.models import ChildrenMenu
from wagtailmenus.tests import base, utils
Page = utils.get_page_model()
class ChildrenMenuTestCase(TestCase):
def get_test_menu_instance(self):
return ChildrenMenu(parent_page=Page(), max_levels=3)
class TestGetSubMenuTemp... |
9818932 | import abc
from hummingbot.core.web_assistant.connections.data_types import WSRequest
class WSPreProcessorBase(abc.ABC):
"""An interface class that enables functionality injection into the `WSAssistant`.
The logic provided by a class implementing this interface is applied to a request
before it is sent ... |
9818997 | from molotov import scenario, global_setup
@global_setup()
def init_test(args):
raise Exception("BAM")
@scenario(weight=100)
async def fail(session):
raise Exception("I am failing")
|
9819005 | import jax
import jax.numpy as np
import optax
import tensorflow_datasets as tfds
from jax import jit, random, vmap
from utils.meta_learn import DEFAULT_RESOLUTION, process_example
def meta_train(
model,
params,
coords,
ds,
ds_val,
batch_size,
outer_lr=1e-5,
inner_lr=0.01,
inner_s... |
9819050 | import os, cv2, shutil
import numpy as np
import argparse
def read_coords(coord_file):
coord_data, inds_pos = [], []
assert os.path.exists(coord_file), "File does not exist! %s"%coord_file
with open(coord_file, 'r') as f:
for ind, line in enumerate(f.readlines()):
x_coord = int(line.str... |
9819052 | import numpy as np
import time
from multiprocessing import Pool
from scipy.optimize import minimize
###STAGE 2###
import sys
from config import CODE_DIRECTORY
sys.path.append(CODE_DIRECTORY)
# User settings for CUSP
import settings
from set_settings import *
from cusp_demo_utils import *
# Load the optimized VQE par... |
9819141 | import os
import platform
import sys
import uuid
from ..version_info import *
try:
from .. import minipsutil
TOTAL_PHYMEM = minipsutil.total_memory()
NUM_CPUS = minipsutil.cpu_count()
except ImportError:
TOTAL_PHYMEM = 0
NUM_CPUS = 0
def _tup_to_flat_str(tup):
tmp_list = []
for t in tup:
if... |
9819162 | from .base_client import BaseDicomClient # noqa
from .pynetdicom_client import PynetDicomClient # noqa
from .dcmtk_client import DcmtkDicomClient # noqa
from .filesystem_dev_client import FilesystemDicomClient # noqa
from .utils import dataset_attribute_fetcher, copy_dicom_attributes, dicom_file_iterator # noqa
|
9819170 | import click
import cupy
from dask import array as da
from dask.distributed import Client
from dask.utils import parse_bytes
from dask_cuda import LocalCUDACluster
@click.command(context_settings=dict(ignore_unknown_options=True))
@click.option(
"--enable-nvlink/--disable-nvlink",
default=False,
help="E... |
9819223 | from seaworthy.stream._timeout import stream_timeout
def _last_few_log_lines(container):
return container.logs(tail=100).decode('utf-8')
def stream_logs(container, timeout=10.0, **logs_kwargs):
"""
Stream logs from a Docker container within a timeout.
:param ~docker.models.containers.Container cont... |
9819241 | from .utils import validate_str
import re
@validate_str
def isphone(value, locale='en-US'):
"""
Return whether or not given value is valid mobile number according to given locale. Default locale is 'en-US'.
If the value is valid mobile number, this function returns ``True``, otherwise ``False``.
Suppo... |
9819254 | import logging
import os
import sys
import re
import datetime
import urllib3
import shutil
import hashlib
import urllib
sys.path.append( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) )
from utils.get_doc_text import get_doc_text
from utils.sam_utils import schematize_opp
from utils.request_utils impo... |
9819295 | class SMS_store:
def __init__(self):
self.message = []
self.view_state = []
def add_new_arrival(self, from_number, time_arrived, text_of_SMS):
self.message.append((from_number, time_arrived, text_of_SMS))
self.view_state.append(False)
def message_count(self):
retur... |
9819323 | from pycqed.measurement import measurement_control as mc
import adaptive
from pycqed.instrument_drivers.meta_instrument.LutMans import flux_lutman as flm
from pycqed.instrument_drivers.virtual_instruments import noise_parameters_CZ_new as npCZ
from pycqed.simulations import cz_superoperator_simulation_new_functions a... |
9819395 | import subprocess
process = subprocess.Popen(['ls', '-ltr'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(process.communicate())
process = subprocess.Popen(['echo', 'Pankaj'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=None)
print(process.communicate())
process = subprocess.Popen(['ping', '-c 1... |
9819428 | from galois import *
from coding import *
#17
g = [
[1, 0, 0, 1, 1, 0],
[0, 1, 0, 0, 1, 1],
[0, 0, 1, 1, 0, 1]
]
g = Matrix(data=g).to_GF(2)
c = LinearBlockCode(g)
ws = [0, 0, 1, 0, 0, 1,
0, 1, 1, 0, 0, 0,
0, 0, 0, 1, 1, 0,
1, 0, 0, 0, 0, 1]
ws = [FFE(i,2) for i in ws]
words = c.decode(ws)
print words
#19
... |
9819450 | description = 'setup for the execution daemon'
group = 'special'
devices = dict(
Auth = device('nicos.services.daemon.auth.list.Authenticator',
# the hashing maybe 'md5' or 'sha1'
hashing = 'md5',
passwd = [('guest', '', 'guest'),
... |
9819459 | from openprocurement.api.utils import get_now, handle_store_exceptions, context_unpack
from openprocurement.api.auth import extract_access_token
from openprocurement.api.constants import SANDBOX_MODE, TZ, NORMALIZE_SHOULD_START_AFTER
from openprocurement.tender.core.procedure.context import get_now
from openprocurement... |
9819481 | import textwrap
import csv
import argparse
from collections import defaultdict
import sys
from jinja2 import Environment, FileSystemLoader
import os
import consts
encoding = sys.getfilesystemencoding()
EXEC_DIR = os.path.dirname(unicode(__file__, encoding))
def save_or_print_json(json_str, outdir, json_name):
i... |
9819495 | from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from api import views
urlpatterns = [
path('api/', views.ApiList.as_view(), name='ApiList'),
path('api/<int:pk>/', views.ApiDetail.as_view(), name='ApiDetail'),
]
urlpatterns = format_suffix_patterns(urlpatterns) |
9819510 | from fabric.api import local
# Automate the release
def release():
local("python setup.py sdist register upload")
local("python2.5 setup.py bdist_egg register upload")
local("python2.6 setup.py bdist_egg register upload")
local("python2.7 setup.py bdist_egg register upload") |
9819581 | import cv2
def variance_of_laplacian(image):
# compute the Laplacian of the image and then return the focus
# measure, which is simply the variance of the Laplacian
return cv2.Laplacian(image, cv2.CV_64F).var()
def is_blurry(image, threshold):
# Convert to grayscale, and compute the
# focus measur... |
9819614 | ACTIONS = (
'const',
'exception',
'extends',
'include',
'oneway',
'optional',
'required',
'throws',
'typedef',
)
BOOL = (
'false',
'true'
)
DISALLOW = (
"BEGIN",
"END",
"__CLASS__",
"__DIR__",
"__FILE__",
"__FUNCTION__",
"__LINE__",
"__METHOD__",
"__NAMESPACE__",
"abstract",
... |
9819620 | from copy import copy
NL_type = 'NEWLINE'
INDENT_type = 'INDENT'
DEDENT_type = 'DEDENT'
PAREN_OPENERS = 'LPAR', 'LBRACE', 'LSQB'
PAREN_CLOSERS = 'RPAR', 'RBRACE', 'RSQB'
class Tok():
def __init__(self, type=None, value=None, lexer=None):
self.type = type
self.value = value
self.lineno = N... |
9819638 | import pytest
from polog.errors import LoggedError, IncorrectUseOfTheDecoratorError, DoubleSettingError, AfterStartSettingError, RewritingLogError
errors = [LoggedError, IncorrectUseOfTheDecoratorError, DoubleSettingError, AfterStartSettingError, RewritingLogError]
def test_multiraise():
"""
Проверяем, что ... |
9819665 | from os import popen
from pickle import dumps as serialize, loads as unserialize
from math import sqrt
# Exceptions
class AutomataError(Exception):
pass
# Single Attributes Get/Set
def genGetMethod(attr):
def getMethod(self):
return getattr(self, attr)
return getMethod
def genSetMethod(attr,... |
9819669 | import csv
from collections import OrderedDict
import os, shutil
import codecs
def create_dir(dirpath):
p = os.path.normpath(os.path.expanduser(dirpath))
if not os.path.isdir(p):
os.makedirs(p)
return p
def clean_create_dir(dirpath):
if os.path.isdir(dirpath):
shutil.rmtree(dirpath)
... |
9819686 | from setuptools import setup, find_packages
setup(
name='Graphino',
version='0.1',
packages=find_packages(),
url='https://github.com/salvaRC/Graphino',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
description='A Graph neural network for long range and ENSO forecasting.'
) |
9819690 | import numpy as np
import pytest
from respy.config import CHAOSPY_INSTALLED
from respy.config import EXAMPLE_MODELS
from respy.config import INDEXER_INVALID_INDEX
from respy.config import KEANE_WOLPIN_1994_MODELS
from respy.config import KEANE_WOLPIN_1997_MODELS
from respy.pre_processing.model_checking import check_mo... |
9819700 | import numpy as np
from scipy.linalg import hadamard
import math
def ht_filtering_hadamard(group_3D, nSx_r, kHard, chnls, sigma_table, lambdaHard3D, doWeight):
kHard_2 = kHard * kHard
weight_table = np.array([0.] * chnls)
coef_norm = math.sqrt(nSx_r)
coef = 1.0 / nSx_r
for n in range(kHard_2 * chn... |
9819704 | import re
from urllib.parse import urlsplit, urlunsplit
from django.core.exceptions import ValidationError
from django.forms.widgets import TextInput
from django.utils.translation import gettext_lazy as _, ngettext_lazy
from django.forms.fields import CharField
from streamfield.validators import RelURLValidator
from s... |
9819751 | song_library = [("Phantom Of The Opera", "<NAME>"),
("Knocking On Heaven's Door", "Guns N' Roses"),
("Captain Nemo", "<NAME>"),
("Patterns In The Ivy", "Opeth"),
("November Rain", "Guns N' Roses"),
("Beautiful", "<NAME>"),
("Mal's Song", "<NAME>")]
artists = set()
for so... |
9819766 | import os
import cv2
import numpy as np
def pad_to_square(image):
"""
Pad image to square shape.
"""
height, width = image.shape[:2]
if width < height:
border_width = (height - width) // 2
image = cv2.copyMakeBorder(image, 0, 0, border_width, border_width,
... |
9819773 | fibSequence = [0,1]
def Fibonacci(n):
if n<0:
print("Outside bounds")
elif n<= len(fibSequence):
return fibSequence[n-1]
else:
print("Solving for {}".format(n))
fibN = Fibonacci(n-1) + Fibonacci(n-2)
fibSequence.append(fibN)
return fibN
print(F... |
9819805 | from unittest import mock
from django import test
from tethys_services.backends.arcgis_portal import ArcGISPortalOAuth2
@test.override_settings(
OAUTH_CONFIG={
'SOCIAL_AUTH_ARCGIS_PORTAL_URL': 'https://my.test.arcgis/portal'
}
)
class ArcGISPortalBackendTest(test.SimpleTestCase):
def setUp(self):
... |
9819841 | import sys
import os.path
sys.path.append(os.path.abspath(os.pardir))
from disaggregator import weather
import datetime
import settings
import unittest
import pandas as pd
class WeatherTestCase(unittest.TestCase):
def setUp(self):
pass
def test_remove_low_outliers_df(self):
base = datetime.da... |
9819879 | import requests
import json
ACCEPTED_CHEMBL_LIST = [
"CHEMBL1201247",
"CHEMBL88",
"CHEMBL53463",
"CHEMBL1201585",
"CHEMBL1201585",
"CHEMBL1351",
"CHEMBL3545252",
"CHEMBL185",
"CHEMBL83",
"CHEMBL1444",
"CHEMBL53463",
"CHEMBL88",
"CHEMBL306601",
"CHEMBL1399",
"... |
9819884 | from easydict import EasyDict
cfg = EasyDict()
cfg.batch_size = 16
cfg.epoch = 200
cfg.learning_rate = 1e-2
cfg.momentum = 0.9
cfg.weight_decay = 1e-4
cfg.patience = 25
cfg.inference_threshold = 0.75
cfg.transunet = EasyDict()
cfg.transunet.img_dim = 512
cfg.transunet.in_channels = 3
cfg.transunet.out_channels = 128
... |
9819901 | import numpy as np
import tensorflow as tf
from model import GCN_LPA
def print_statistics(features, labels, adj):
n_nodes = features[2][0]
n_edges = (len(adj[0]) - labels.shape[0]) // 2
n_features = features[2][1]
n_labels = labels.shape[1]
labeled_node_rate = 20 * n_labels / n_nodes
n_intra_... |
9819923 | from sqlalchemy import Sequence, Column, UniqueConstraint, Integer, String
from models.database import Base
shop_seq = Sequence('stream_id_seq')
class News(Base):
__tablename__ = 'news'
id = Column(Integer, shop_seq, primary_key=True, server_default=shop_seq.next_value())
link = Column(String(255))
... |
9820038 | import unittest
import six
import requests
from tests.bandwidth.helpers import get_account_client as get_client
from tests.bandwidth.helpers import create_response, AUTH, headers
if six.PY3:
from unittest.mock import patch, MagicMock
builtins = 'builtins'
else:
from mock import patch, MagicMock
builtins... |
9820046 | import utime
from hwconfig import LED, BUTTON
# Light LED when (and while) a BUTTON is pressed
while 1:
LED.value(BUTTON.value())
# Don't burn CPU
utime.sleep_ms(10)
|
9820051 | import requests
import bs4
res = requests.get('https://www.ploggingdev.com')
res.raise_for_status()
#print(res.text)
print("{} bytes".format(len(res.text)))
print("HTTP status code: {}".format(res.status_code))
print("response object type: {}".format(type(res)))
mysite = open("mysite.html", "wb")
print("Writing the... |
9820067 | from tir import Webapp
import unittest
class PCOXDIV(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.SetTIRConfig(config_name="User",value="PCO1")
inst.oHelper.SetTIRConfig(config_name="Password",value="a")
inst.oHelper.Setup('SIGAP... |
9820072 | import bge
import serial
import math
from math import *
import mathutils
a=0.0 # variable to adjust jaw
def read_serial():
global a
scene = bge.logic.getCurrentScene() # Get the whole bge scene
source = scene.objects # Helper vars for convenience
a=a+1
main_arm = source.get('Armature')
... |
9820106 | from utils.bert import bert_utils
from utils.bert import bert_modules
import numpy as np
import collections
import copy
import json
import math
import re
import six
import tensorflow as tf
from loss import loss_utils
# from task_module.global_batch_norm import batch_norm_relu
try:
from task_module.contrastive_util... |
9820164 | import torch
from torch import nn
from utils.data.structures.bounding_box import BoxList
# TODO get the predicted maskiou and mask score.
class MaskIoUPostProcessor(nn.Module):
"""
Getting the maskiou according to the targeted label, and computing the mask score according to maskiou.
"""
def __init__... |
9820169 | if __name__ != '__main__':
raise ImportError('This is not a module, but a script.')
import sys, os, socket
test_root = os.path.dirname(os.path.abspath(__file__))
os.chdir(test_root)
sys.path.insert(0, os.path.dirname(test_root))
sys.path.insert(0, test_root)
try:
server = sys.argv[1]
port = int(sys.arg... |
9820208 | import random
name = input("YOUR NAME PLAYER !? ")
diff=str(input("SELECT DIFFICULTY : EASY STANDARD OR HARD \n")) # difficulty level for the player.
print("GOOD LUCK ! ", name)
if diff == 'EASY':
easy_words=['apple','papaya','orange','banana','kiwi','strawberry','cherry'] # if difficulty is easy, then list of... |
9820212 | from datetime import datetime
from unittest import mock
import pytest
from crowdin_api.api_resources.reports.enums import (
ContributionMode,
Currency,
Format,
GroupBy,
SimpleRateMode,
Unit,
)
from crowdin_api.api_resources.reports.resource import ReportsResource
from crowdin_api.requester impo... |
9820215 | from django.conf.urls import url
from twobuntu.images import views
urlpatterns = [
url(r'^view/(?P<id>\d+)/$', views.view, name='view'),
url(r'^upload/$', views.upload, name='upload'),
]
|
9820229 | from magma import Bit, Out
from loam import Part
class Joystick(Part):
name = 'joystick'
IO = ["SELECT", Out(Bit),
"UP", Out(Bit),
"DOWN", Out(Bit),
"LEFT", Out(Bit),
"RIGHT", Out(Bit)]
def __init__(self, name='Joystick', board=None):
super(Joystic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.