id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9982254 | import os
import moderngl.next as mgl
import numpy as np
from objloader import Obj
from PIL import Image
from pyrr import Matrix44
import data
from window import Example, run_example
class CrateExample(Example):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.ctx = mgl.create_conte... |
9982262 | import warnings
from functools import reduce
import cv2
import numpy as np
import tensorflow as tf
def compose(*funcs):
if funcs:
return reduce(lambda f, g: lambda *a, **kw: g(f(*a, **kw)), funcs)
else:
raise ValueError('Composition of empty sequence not supported.')
#---------... |
9982277 | import os
import math
import argparse
import cv2
import numpy as np
import megengine as mge
from megengine import jit
from config import config
import dataset
import network
import misc_utils
import visual_utils
def inference(args):
@jit.trace(symbolic=False)
def val_func():
pred_boxes = net(net.inpu... |
9982282 | import numpy as np
from collections import defaultdict
from scipy.stats import multivariate_normal
from scipy.spatial.distance import cdist
_HEATMAP_THRESH = 0.0027
_2D_MAH_DIST_THRESH = 3.439
_SMALL_VAL = 1e-14
def two_d_iou(box, boxes):
"""Compute 2D IOU between a 2D bounding box 'box' and a list
:param b... |
9982329 | from .certstream import CertStreamUpdateMessage
from .domain import Domain
from .rule import Rule
from .verdiction import DomainWithVerdiction
__all__ = ["Rule", "Domain", "DomainWithVerdiction", "CertStreamUpdateMessage"]
|
9982334 | from tests.utils import W3CTestCase
class TestMaxWidth(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'max-width-'))
|
9982345 | import random
import numpy as np
import tensorflow as tf
from replay_buffer import ReplayBuffer
class NeuralQLearner(object):
def __init__(self, session,
optimizer,
q_network,
state_dim,
num_actions,
batch_size=... |
9982352 | from django.shortcuts import render
from .models import Student, Teacher
from django.db import connection
from django.db.models import Q
# Part 2
#################################################################
################
# Simple OR
################
def student_list_(request):
posts = Student.objects.al... |
9982361 | from hamcrest import assert_that
from allure_commons_test.report import has_test_case
from allure_commons_test.result import has_step
from allure_commons_test.result import with_status
from allure_commons_test.result import has_status_details
from allure_commons_test.result import with_message_contains
from allure_comm... |
9982374 | import torch
import torch.nn as nn
from .vit import (
_make_pretrained_vitb_rn50_384,
_make_pretrained_vitl16_384,
_make_pretrained_vitb16_384,
forward_vit,
)
def _make_encoder(
backbone,
features,
use_pretrained,
groups=1,
expand=False,
exportable=True,
hooks=None,
us... |
9982375 | import torch
import torch.nn as nn
import torchvision
import numpy as np
import math
import webcolors
import cv2
import gdown
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from torch.nn.init import _calculate_fan_in_and_fan_out, _no_grad_normal_
STANDARD_COLORS = [
'LawnGreen', 'LightBlue' ,... |
9982383 | from tqdm import *
import numpy as np
import os
import json
import h5py
import sys
caffe_python = '/home/liqing/Desktop/program/caffe/python'
sys.path.insert(0, caffe_python)
import caffe
caffe.set_mode_gpu()
caffe.set_device(1)
model_dir = "/home/liqing/Desktop/program/ResNet-152/"
model_def = model_di... |
9982386 | from __future__ import print_function, division
from PyAstronomy import pyaC
from PyAstronomy.pyasl import _moduleImportStatus
_modules = ["astroTimeLegacy", "airtovac", "aitoffLegacy", "folding", \
"keplerOrbit", "inTransit", "statTest", "binning", "smooth", \
"planet_Teq", "planck", "planetPhas... |
9982389 | from __future__ import print_function
import os
import sys
import tempfile
import gc
import unittest
import gevent
from gevent import fileobject
import gevent.testing as greentest
from gevent.testing.sysinfo import PY3
from gevent.testing.flaky import reraiseFlakyTestRaceConditionLibuv
from gevent.testing.skipping im... |
9982429 | import unittest
import singer.statediff as statediff
from singer.statediff import Add, Remove, Change
class TestPaths(unittest.TestCase):
def test_simple_dict(self):
self.assertEqual(
[(('a',), 1),
(('b',), 2)],
statediff.paths({'a': 1, 'b': 2}))
def test_nested_... |
9982430 | import os
from .properties import PropFileSavePath
from Qt import QtWidgets
class _element_widget(QtWidgets.QWidget):
def __init__(self):
super(_element_widget, self).__init__()
self.layout = QtWidgets.QHBoxLayout(self)
self.layout.setContentsMargins(0, 0, 0, 0)
class NodePublishWidget... |
9982434 | import logging
import random
import pytest
from pytest import fixture, mark
from dbnd import config
from dbnd._core.constants import CloudType, SparkClusters
from dbnd._core.errors import DatabandRunError
from dbnd._core.settings import EnvConfig
from dbnd.testing.helpers_pytest import assert_run_task
from dbnd_aws.... |
9982448 | from interfax.documents import Documents
from interfax.response import Document
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
class TestDocuments(object):
def setup_method(self, method):
self.client = Mock()
self.documents = Documents(self.client)
def... |
9982459 | import csv
from datetime import datetime
import re
import urlparse
from scrapy.utils.url import urljoin_rfc
from scrapy.conf import settings
from scrapy.spider import Spider
from scrapy.http import Request
from scrapy.selector import HtmlXPathSelector
from scrapy import log
from onderwijsscrapers.items import OwinspV... |
9982489 | from rest_framework import serializers
from .models import Contact, User
class AddFriendSerializer(serializers.Serializer):
email = serializers.EmailField(max_length=255)
class ContactSerializer(serializers.ModelSerializer):
"""
used to serializer contact model
"""
private_mode = serializers.Bo... |
9982509 | from barril.units import UnitDatabase
from docutils import nodes
from docutils.statemachine import ViewList
from sphinx.util import nested_parse_with_titles
from sphinx.util.docutils import SphinxDirective
class ListAllUnits(SphinxDirective):
def run(self):
rst = ViewList()
unit_database = UnitDat... |
9982515 | description = 'Flow cell'
group = 'optional'
tango_base = 'tango://phys.kws3.frm2:10000/kws3/'
devices = dict(
flowcell_m = device('nicos.devices.entangle.Sensor',
description = 'balance readout',
tangodevice = tango_base + 'sartorius/balance',
unit = 'g',
fmtstr = '%.3f',
),
... |
9982517 | from sys import argv
from context import Instpector, endpoints
def get_timeline(**options):
instpector = Instpector()
if not instpector.login(user=options.get("user"), password=options.get("password")):
return
timeline = endpoints.factory.create("timeline", instpector)
comments = endpoints.fac... |
9982518 | from pyranges.multithreaded import pyrange_apply_single
def _to_rle(ranges, value_col=None, strand=True, rpm=False, **kwargs):
try:
from pyrle.methods import coverage
from pyrle import PyRles
except ImportError:
raise Exception(
"Using the coverage method requires that pyr... |
9982570 | from __future__ import unicode_literals
import sys
import traceback
import time
from traitlets import Unicode, Undefined
from uuid import uuid4
from ipykernel.kernelbase import Kernel
from .coqtop import Coqtop, CoqtopError
from .renderer import Renderer, HTML_ROLLED_BACK_STATUS_MESSAGE, TEXT_ROLLED_BACK_STATUS_MESSA... |
9982587 | from typing import Optional, List, Dict, Any
import numpy as np
import torch
import torch.nn as nn
# Hydra and OmegaConf
from hydra.conf import dataclass, MISSING, field
# Project Imports
from hydra.core.config_store import ConfigStore
from slam.common.geometry import compute_normal_map, projection_map_to_points
fr... |
9982601 | from typing import Text
from ... import _test
from .aoharu_battle_confirm import AoharuBattleConfirmScene
from ...single_mode import Context
import pytest
@pytest.mark.parametrize(
"name",
tuple(
i.stem
for i in (
(_test.DATA_PATH / "single_mode").glob("aoharu_battle_confirm_menu_*... |
9982603 | from flask_cors import CORS
from . import api
cors = CORS()
def init_app(app):
"""
Application extensions initialization.
"""
for extension in (
cors,
api,
):
extension.init_app(app)
|
9982615 | import autosar
def setup():
ws = autosar.workspace(version="4.2.2")
#Application Types
dataTypePackage=ws.createPackage('ApplicationTypes', role='DataType')
dataConstraintPackage = dataTypePackage.createSubPackage('DataConstrs', role='DataConstraint')
compuMethodPackage = dataTypePackage.cre... |
9982647 | from typing import Dict
from botocore.waiter import Waiter
class AuditReportCreated(Waiter):
def wait(self, CertificateAuthorityArn: str, AuditReportId: str, WaiterConfig: Dict = None):
pass
class CertificateAuthorityCSRCreated(Waiter):
def wait(self, CertificateAuthorityArn: str, WaiterConfig: Dict... |
9982711 | from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class IsisL1PSNPDU(Base):
__slots__ = ()
_SDM_NAME = 'isisL1PSNPDU'
_SDM_ATT_MAP = {
'CommonHeaderIntradomainRoutingProtocolDiscriminator': 'isisL1PSNPDU.isisHeader.commonHeader.intradomainRoutingProtocolDiscriminator-... |
9982747 | from boa3.builtin import public
@public
def main() -> int:
a = [1, 2, 3, 4, 1, 1, 0]
return a.count(1)
|
9982759 | from .. import log
import sys, site, os
libsubdir = 'lib'
prefixes = list(site.PREFIXES)
if hasattr(site, 'getuserbase'):
prefixes.append(site.getuserbase())
for prefix in prefixes:
libdir = os.path.join(prefix, libsubdir)
if not os.path.exists(os.path.join(libdir, 'libmkl_rt.so.1')):
continue
log.set_outp... |
9982760 | from django.views.generic import TemplateView
from pydotorg.mixins import FlagMixin
# NOTE: Many aspects of 'membership' such as adjusting a user profile, signup,
# etc are handled in the users app
class Membership(FlagMixin, TemplateView):
""" Main membership landing page """
flag = 'psf_membership'
... |
9982793 | import socketio
from app.api.api_v1.router.websocket.server import ServerNamespace
sio = socketio.AsyncServer(async_mode='asgi',cors_allowed_origins='*')
sio.register_namespace(ServerNamespace('/server',))
socket_app = socketio.ASGIApp(sio)
|
9982807 | import argparse
import pickle
from math import floor, ceil
import numpy as np
import cv2
import seaborn as sns
from pathlib import Path
import ruptures as rpt
from zsvision.zs_utils import loadmat
def get_CP_dict(feature_dict, vid_list):
"""
Function for CP Baseline
Calculate changepoints for whole epsio... |
9982823 | from abc import ABC
import cv2
from gbvision.models.system import EMPTY_PIPELINE
from .opencv_window import OpenCVWindow
from .wrapper_window import WrapperWindow
class WrapperOpenCVWindow(OpenCVWindow, WrapperWindow, ABC):
"""
a basic window that displays a feed from a camera
:param wrap_object: the o... |
9982846 | from ..libmp.backend import xrange
# TODO: should use diagonalization-based algorithms
class MatrixCalculusMethods(object):
def _exp_pade(ctx, a):
"""
Exponential of a matrix using Pade approximants.
See <NAME>, <NAME> 'Matrix Computations',
third Ed., page 572
TODO:
... |
9982849 | import typing as t
import functools
import click
from flask.cli import ScriptInfo
from flask.cli import AppGroup
from flask_postgres.types import PostgresUri
try:
import rich_click
except ImportError:
rich_click = None
from flask_postgres import config
__use_rich_click = config.get("FLASK_POSTGRES_RICH_CL... |
9982862 | import checkout_sdk as sdk
from checkout_sdk import HTTPClient
from checkout_sdk.payments import PaymentsClient
from tests.base import CheckoutSdkTestCase
class CheckoutApiTests(CheckoutSdkTestCase):
def test_init_checkout_api(self):
api = sdk.get_api()
self.assertTrue(isinstance(api.payments, P... |
9982863 | import csv
import operator
from my_montage_maker import *
import math
from PIL import Image
in_file = "/Users/myazdaniUCSD/Documents/kiev-instagram/results/kmeans_hog/Kmeans_RGB_HOG_lat_long_65.csv"
image_path = "/Users/myazdaniUCSD/Documents/kiev-instagram/good_data/all_images/"
output_path = "/Users/myazdaniUCSD/Doc... |
9982866 | from . import util
import os
import numpy as np
import random
import sys
from alphafold.common import protein
from alphafold.model import data
from alphafold.model import config
from alphafold.model import model
from typing import Any, List, Mapping, NoReturn
from absl import logging
def set_config(
use_templa... |
9982870 | import addfips
import os
import pandas as pd
import datetime
ageVariables = {
'DATE': 'date_stamp',
'AGE_RANGE': 'age_group',
'AR_TOTALCASES': 'cnt_confirmed',
'AR_TOTALPERCENT': 'pct_confirmed',
'AR_NEWCASES': 'cnt_confirmed_new',
'AR_NEWPERCENT': 'pct_confirmed_new',
'AR_TOTALDEATHS' : 'cnt_death',
'AR_NEWDE... |
9982904 | import numpy as np
from gym import spaces
class EpsilonWrapper(object):
def __init__(self, env, attrs=('distance_threshold', 'rotation_threshold'), compute_reward_with_internal=None):
"""Attrs is list of attributes (strings like "distance_threshold"). Only valid ones are used. """
self.env = env
... |
9982906 | import unittest
from deepdialog.transformer.preprocess.batch_generator import BatchGenerator, ENCODER_INPUT_NODE, DECODER_INPUT_NODE
class TestBatchGenerator(unittest.TestCase):
def test_vocab_size(self):
batch_generator = BatchGenerator()
self.assertEqual(batch_generator.vocab_size, 8000)
de... |
9982921 | from googlecontroller import GoogleAssistant
host = "192.168.0.4" #again your google homes ip
home = GoogleAssistant(host=host)
home.serve_media("Victory.mp3", "C:/Users/Dray-Cyber/Documents/GitHub/googlecontroller/examples")
|
9982930 | import sys
import os
import math
if __name__ == '__main__':
def eprint(message):
print(message, file=sys.stderr)
if len(sys.argv) != 3:
eprint("Syntax: {} <colorfile> <output>".format(sys.argv[0]))
sys.exit(1)
codes = []
with open(sys.argv[1]) as file:
line_number = 0
... |
9982952 | import os, sys, json, operator
DECL_PUBLIC = 0x000001
DECL_PRIVATE = 0x000002
DECL_PROTECTED = 0x000004
DECL_INTERNAL = 0x000008
DECL_VIRTUAL = 0x000100
DECL_OVERRIDE = 0x000200
DECL_ABSTRACT = 0x000400
DECL_FINAL = 0x000800
DECL_EXTERN = 0x001000
DECL_EXTENSION = 0x002000
DECL_DE... |
9982962 | import os, sys, time
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from reader import batch_patcher as patcher
from network.WideResNet.WideResNet import *
from network.DenseNet.DenseNet import *
os.environ['TF_CPP_MIN_LOG_L... |
9982976 | from enum import Enum
import json
import logging_util
import requests
# reference beepscore Remy / TVService.swift
# https://github.com/beepscore/Remy/blob/master/Remy/TVService.swift
# instantiate at module level, not class level
# https://stackoverflow.com/questions/22807972/python-best-practice-in-terms-of-logging... |
9983044 | import pandas as pd
import os
from configparser import ConfigParser, NoOptionError, NoSectionError
from datetime import datetime
import statistics
import numpy as np
import glob
from simba.drop_bp_cords import *
from simba.rw_dfs import *
configini = r"Z:\Classifiers\Attack_071520\Attack\project_folder\proje... |
9983078 | import mlsql_model
import mlsql
from sklearn.svm import SVC
clf = SVC(verbose=2)
mlsql.sklearn_configure_params(clf)
X, y = mlsql.sklearn_all_data()
clf.fit(X, y)
X_test, y_test = mlsql.get_validate_data()
if len(X_test) > 0:
testset_score = clf.score(X_test, y_test)
print("mlsql_validation_score:%f" % tes... |
9983097 | import os
import pickle
from ffthompy.tensorsLowRank.homogenisation import (homog_Ga_full_potential,
homog_GaNi_full_potential,
homog_Ga_sparse,
homog_GaNi_sparse)... |
9983117 | import asyncio
from typing import List
from dotlock.dist_info.dist_info import CandidateInfo, PackageType
from dotlock.dist_info.sdist_handling import get_local_package_requirements
from dotlock.exceptions import VCSException
from dotlock.tempdir import temp_working_dir
def clone_command(vcs_url: str) -> List[str]:
... |
9983159 | from django.db import models
from django.utils.timezone import now
from blockcypher.constants import COIN_CHOICES, COIN_SYMBOL_MAPPINGS
from emails.trigger import send_and_log
class AddressSubscription(models.Model):
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
unsubscribed_at = model... |
9983163 | import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
# data
def create_data():
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['label'] = iris.target
df.columns ... |
9983228 | from dataclasses import dataclass
from typing import Callable
from typing import Union
import pytest
from phantom import Phantom
from phantom import get_bound_parser
from phantom.base import AbstractInstanceCheck
from phantom.base import BoundError
from phantom.base import PhantomMeta
from phantom.predicates import b... |
9983248 | import utils.decisions_constants as log
from game.ai.strategies.main import BaseStrategy
from mahjong.tile import TilesConverter
from utils.test_helpers import tiles_to_string
class CommonOpenTempaiStrategy(BaseStrategy):
min_shanten = 1
def should_activate_strategy(self, tiles_136, meld_tile=None):
... |
9983268 | from __future__ import print_function
# Usage python train_with_labels_three_fold.py number_of_data_parts_divided NEPDF_pathway number_of_category
# command line in developer's linux machine :
# module load cuda-8.0 using GPU
#srun -p gpu --gres=gpu:1 -c 2 --mem=20Gb python train_with_labels_three_foldx.py 9 /home... |
9983306 | def extractTheLazy9(item):
"""
# TheLazy9
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
tagmap = [
('HTG', 'I was Reincarnated as a Thief Gir... |
9983307 | import os
import glob
import numpy as np
import argparse
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.keras.callbacks import ReduceLROnPlateau, EarlyStopping, CSVLogger
from tensorflow.python.keras.applications.inception_v3 import preprocess_input
from tensorflow.python.keras.preproce... |
9983327 | import datetime
import json
import time
import pytz
import requests
from .logger import logger
def get_time() -> datetime.datetime:
tz = pytz.timezone('Asia/Shanghai')
return datetime.datetime.now(tz)
class MsgSender:
__last_time : datetime.datetime = get_time()
def __init__(self, url: str, qid: int, to: int):... |
9983345 | import traceback
from abc import ABC
from copy import deepcopy
from itertools import chain
from inspect import getmembers, isroutine
from functools import wraps
import pyarrow as pa
def feature(pyarrow_type=None, is_helper=False, exceptions=None, **type_args):
exceptions = exceptions or tuple()
exceptions = ... |
9983359 | PATCH_RANGE = {
"2.6": list(range(13)),
"3.0": list(range(16)),
"3.2": list(range(23)),
"3.2-suse11": list(range(20)),
"3.2-ubuntu18": list(range(20, 23)),
"3.2-ubuntu16": list(range(7, 23)),
"3.2-ubuntu12": list(range(20)),
"3.2-sunos5": list(range(15)),
"3.2-debian8": list(range(8,... |
9983368 | from opera.parser.tosca.v_1_3.relationship_type import RelationshipType
class TestParse:
def test_full(self, yaml_ast):
RelationshipType.parse(yaml_ast(
# language=yaml
"""
derived_from: relationship_type
description: My desc
metadata:
... |
9983378 | import flowio
import numpy
f = flowio.FlowData('001_F6901PRY_21_C1_C01.fcs')
n = numpy.reshape(f.events, (-1, f.channel_count))
|
9983420 | import snitch
from snitch import explicit_dispatch
from snitch.constants import DEFAULT_CONFIG
from tests.app.events import DUMMY_EVENT
@snitch.dispatch(DUMMY_EVENT, config=DEFAULT_CONFIG)
def dispatch_dummy_event(actor, trigger, target):
pass
def dispatch_explicit_dummy_event(actor, trigger, target):
expli... |
9983523 | class Config:
_is_gtr = False
_is_gts = False
_image_size = (360, 360)
_preview_size = (210, 210)
@staticmethod
def setGtrMode(gtr):
Config._is_gtr = gtr
if Config._is_gtr == 47:
Config._image_size = (454, 454)
Config._preview_size = (266, 266)
i... |
9983526 | from lru_cache import Node, LRUCache
import unittest
class TestNode(unittest.TestCase):
def test_instantiates(self):
"""
Instantiates a new version of Node
"""
node = Node()
self.assertIsInstance(node, Node)
def test_instantiates_with_default_none(self):
"""
... |
9983560 | from arekit.common.entities.base import Entity
class RuSentRelEntity(Entity):
""" Annotated entity in RuSentRel corpus.
Provides bounds, i.e. char indices in related sentence.
"""
def __init__(self, id_in_doc, e_type, char_index_begin, char_index_end, value):
assert(isinstance(id_in_doc, ... |
9983579 | import sys
from core import colors
errorstr = "["+colors.bold+colors.red+"err"+colors.end+"] "
infostr = "["+colors.bold+colors.blue+"inf"+colors.end+"] "
warningstr = "["+colors.bold+colors.yellow+"war"+colors.end+"] "
successstr = "["+colors.bold+colors.green+"suf"+colors.end+"] "
def print_error(message, start="",... |
9983588 | from abc import ABC, abstractmethod
from collections import OrderedDict
import numpy as np
class TensorInfo:
def __init__(self, _name, _shape, _description):
self.name = _name
self.shape = _shape
self.description = _description
def tensor_check(self, _to_input_tensor, _limit_check=No... |
9983601 | import json
import numpy as np
import matplotlib.pyplot as plt
def compare_models():
"""
Compares multiple saved models and creates comparison plot.
"""
with open('logs/attack/results', 'r') as json_file:
data = json.load(json_file)['result']
n_groups = len(data)
fig, ax = pl... |
9983608 | import numpy as np
import os
import torch
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
def plot_training_loss(minibatch_losses, num_epochs, averaging_iterations=100, custom_label=''):
iter_per_epoch = len(minibatch_losses) // num_epochs
plt.figure()
ax1 = plt.subplot(1, 1, 1)
... |
9983612 | from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import TemplateView
from rest_framework import routers
from user_profile.views import UserViewSet
router = routers.DefaultRouter()
router.register(r'user', UserViewSet,)
urlpatterns = [
url(r'^admin/', include(ad... |
9983626 | import os
import pathlib
import uuid
import pandas as pd
import pytest
import yaml
from airflow.hooks.base import BaseHook
from airflow.models import DAG, Connection, DagRun
from airflow.models import TaskInstance as TI
from airflow.utils import timezone
from airflow.utils.db import create_default_connections
from air... |
9983628 | import psycopg2
import json
#
from bridgebots import Deal
class HandDao:
def __init__(self):
self.connection = psycopg2.connect("dbname=bridge user=bridgebot host=localhost password=<PASSWORD>")
def close(self):
self.connection.close()
def get_processed_files(self):
with self.co... |
9983631 | import json
import os
import eth_account
from eth_keyfile import create_keyfile_json, decode_keyfile_json
from eth_keys import keys
from eth_utils import decode_hex, encode_hex, remove_0x_prefix
def to_string(value):
if isinstance(value, bytes):
return value
if isinstance(value, str):
return ... |
9983664 | foo = "foo"
bar = "bar"
baz = "baz"
# When `__all__` is not defined, names starting with underscore is not imported with `from <module> import *`
_qux = "qux"
|
9983705 | import copy
class Matcher(object):
def __init__(self):
self.matcher = []
return super().__init__()
def add(self, key, value):
self.matcher.append((key, value))
def find(self, phrase):
matches = []
for match in self.matcher:
if " " + str(match[1]) + " "... |
9983717 | import io
import requests
import argparse
import numpy as np
import pandas as pd
import shapely.geometry
import geopandas as gpd
import matplotlib.pyplot as plt
from zipfile import ZipFile
from shapely.geometry.polygon import Polygon
from shapely.geometry.multipolygon import MultiPolygon
EUROSTAT_BASE_URL = "https://... |
9983732 | import multiprocessing
import pandas as pd
from dask import dataframe as dd
from rubicon_ml.domain.utils import uuid
def _log_all_to_experiment(experiment):
ddf = dd.from_pandas(pd.DataFrame([0, 1], columns=["a"]), npartitions=1)
for _ in range(0, 4):
experiment.log_metric(uuid.uuid4(), 0)
... |
9983748 | import statsmodels.nonparametric._smoothers_lowess
import statsmodels.nonparametric.linbin
import statsmodels.tsa.kalmanf.kalman_loglike
import statsmodels.tsa.regime_switching._hamilton_filter
import statsmodels.tsa.statespace._statespace
|
9983759 | import json
import os
import boto3
print('Loading function')
def init():
print('init() enter')
my_config = json.loads(os.environ['botoConfig'])
from botocore import config
config = config.Config(**my_config)
global personalize
personalize = boto3.client('personalize', config=config)
def la... |
9983802 | from pumapy.utilities.workspace import Workspace
import math
import numpy as np
def size_check(size):
if not (isinstance(size, tuple) and len(size) == 3):
raise Exception("Error, invalid size, must be tuple of size 3")
if size[0] <= 0:
raise Exception("Error, invalid size, must be >= 0")
i... |
9983813 | from django.test import override_settings
from rest_framework import serializers
from rest_framework_serializer_extensions import utils
from rest_framework_serializer_extensions.serializers import (
ExpandableFieldsMixin
)
from tests import models
from tests.base import SerializerMixinTestCase
"""
START TEST SER... |
9983816 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(name='eansearch',
description='A Python class for EAN and ISBN name lookup and validation using the API on ean-search.org',
long_description=long_description,
long_description_content_type="text/ma... |
9983828 | from enum import Enum
class filterChoices(Enum):
CONTAINS = 'contains'
NOT_CONTAINS = 'notcontains'
EQUAL = 'equal'
NOT_EQUAL = 'notequal'
GREATER_THAN = 'greater_than'
GREATER_THAN_EQUAL_TO = 'greater_than_equal_to'
LESS_THAN = 'less_than'
LESS_THAN_EQUAL_TO = 'less_than_equal_to'
... |
9983847 | import argparse
import os
import numpy as np
from tqdm import tqdm
import matplotlib
matplotlib.use('agg') # use matplotlib without GUI support
import matplotlib.pyplot as plt
import torch
import torch.optim as optim
from lib.models.unet import UNet
from lib.utils.net_utils import load_checkpoint
from lib.utils.dat... |
9983881 | import os, coreapi, coreschema
import requests
import numpy as np
from rest_framework import permissions
from rest_framework import viewsets, generics, filters, renderers
from rest_framework.views import APIView
from rest_framework.reverse import reverse
from gwasdb.models import Phenotype, Study, Genotype
from gwasd... |
9983894 | from pykeg.core.management.commands.common import RunnerCommand
class Command(RunnerCommand):
help = "Runs background task queue workers."
pidfile_name = "kegbot_run_all.pid"
def add_arguments(self, parser):
super(Command, self).add_arguments(parser)
parser.add_argument(
"--gu... |
9983912 | import numpy as np
from tqdm import tqdm
from scipy.io import wavfile
import os, csv
import tensorflow as tf
import pickle
from helper import *
from network_model import *
from dataloader import *
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
import argparse
'... |
9983974 | import math
import operator as op
from functools import reduce
def memoize(f):
"""memoization decorator for a function taking one or more arguments"""
class memodict(dict):
def __getitem__(self, *key):
return dict.__getitem__(self, key)
def __missing__(self, key):
ret ... |
9983986 | import collections
d = collections.OrderedDict({'one': 1, 'two':2, 'three':3})
print(d['one'])
print(d['two'])
print(d['three'])
e = collections.OrderedDict(d)
print(e['one'])
print(e['two'])
print(e['three'])
#d = collections.OrderedDict(one=1, two=2, three=3)
#print(d['one'])
#print(d['two'])
#print(d['three'])
|
9984008 | import nengo
from nengo.processes import Piecewise
from nengo.utils.numpy import rms
def test_integrator(Simulator, plt, seed):
model = nengo.Network(seed=seed)
with model:
inputs = {0: 0, 0.2: 1, 1: 0, 2: -2, 3: 0, 4: 1, 5: 0}
input = nengo.Node(Piecewise(inputs))
tau = 0.1
T... |
9984048 | from typing import Any
import torch
from pytorch_lightning import LightningModule
from torch.nn import functional as F
from transformers import AdamW, get_linear_schedule_with_warmup, VisualBertModel
from typing import Optional
from src.datamodules.datasets.dataset_output import DatasetOutput
from src.models.modules.vi... |
9984052 | import bpy
# print all objects
for obj in bpy.data.objects:
print(obj.name)
# print all scene names in a list
print(bpy.data.scenes.keys())
# remove mesh Cube
if "Cube" in bpy.data.meshes:
mesh = bpy.data.meshes["Cube"]
print("removing mesh", mesh)
bpy.data.meshes.remove(mesh)
# write images int... |
9984093 | import os
import importlib
class Platform:
def __init__(self):
self.plugin_list = self.get_all_plugin()
def load_plugins(self,driver, name, args):
for filename in self.plugin_list:
if filename == name:
pluginName = os.path.splitext(filename)[0]
... |
9984095 | from math import floor
def check_closers(input_str):
OPENS = ('(', '<', '[', '{')
CLOSES = (')', '>', ']', '}')
expected = []
valid = True
for char in input_str:
if char in OPENS:
idx = OPENS.index(char)
expected.append(CLOSES[idx])
elif char in CLOSES:
if expect... |
9984114 | from collections import defaultdict
from caching.base import CachingMixin, CachingManager
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.db import models... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.