id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11530897 | from rx.core import Observable
from rx.concurrency import timeout_scheduler
from rx.internal.utils import TimeInterval
from rx.internal import extensionmethod
@extensionmethod(Observable)
def time_interval(self, scheduler=None):
"""Records the time interval between consecutive values in an
observable sequence... |
11530966 | import torch
from .type_dist import CharacterTypeDist
from .token_dist import CharacterTokenDist
from .image_dist import CharacterImageDist
class CharacterModel(object):
"""
Sampling from and Scoring according to the graphical model. The model is
defined as P(Type, Token, Image) = P(Type)*P(Token | Type)... |
11530989 | from fastapi import Depends, HTTPException
from starlette.status import HTTP_401_UNAUTHORIZED
from starlette.requests import Request
from app.database.models import User
from app.dependencies import get_db
from app.internal.security.ouath2 import (
Session, get_jwt_token, get_authorization_cookie
)
from app.intern... |
11531024 | from .model import KerasModel
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten
from keras.layers import BatchNormalization, Dropout, Conv2D, MaxPooling2D
from keras.layers import Input, Dense, Dropout, Flatten
from keras.layers import merge, Conv2D, MaxPooling2D, Inpu... |
11531030 | from matrixio_hal import GPIO
import time
# new pin 0
pin0 = GPIO.Pin(0)
# set pin to output mode
pin0.mode = GPIO.MODE_OUT
while True:
# toggeling high(1) and low(0)
pin0.value ^= GPIO.VALUE_HIGH
time.sleep(0.5)
|
11531042 | import json
import re
from csv import writer
import requests
from bs4 import BeautifulSoup
def get_data():
agent = "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"
headers = {"User-Agent": agent} # Defining a user agent is necessary to the request
... |
11531062 | from typing import List, Optional
from sqlalchemy.orm.session import Session as SessionType
from sqlalchemy_cockroachdb import run_transaction # type: ignore
from src.db.main import Session
from src.db.models.team_match import TeamMatch, TeamMatchORM
def get_team_matches(
year: Optional[int] = None, event: Opt... |
11531063 | import tempfile
import pytest
import mxnet as mx
import os
import numpy as np
import numpy.testing as npt
from gluonnlp.models import get_backbone, list_backbone_names
from gluonnlp.utils.parameter import count_parameters
from gluonnlp.utils.lazy_imports import try_import_tvm
mx.npx.set_np()
def test_list_backbone_na... |
11531091 | from fastapi import Body, APIRouter
from fastapi.encoders import jsonable_encoder
from fastapi.security import HTTPBasicCredentials
from fastapi.responses import RedirectResponse
from passlib.context import CryptContext
from database.database import admin_collection, post_collection
from auth.jwt_handler import signJW... |
11531101 | from typing import List, Optional
from pydantic import PositiveInt
from rastervision.pipeline.config import (Config, register_config, ConfigError,
Field)
from rastervision.pipeline.utils import split_into_groups
from rastervision.core.data.scene_config import SceneConfig
from ... |
11531116 | import unittest
from gooey.gui.components.options import options
class TestPrefixFilter(unittest.TestCase):
def test_doc_schenanigans(self):
"""Sanity check that my docstring wrappers all behave as expected"""
@options._include_layout_docs
def no_self_docstring():
pass
... |
11531158 | from setuptools import setup, find_packages
from setuptools.command.install import install
import os.path
import sys
VERSION='2.3.3'
here = os.path.abspath(os.path.dirname(__file__))
readme_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'README.md')
try:
from m2r import parse_from_file
read... |
11531159 | import unittest
import mock
from utils import k8s_util
from kubernetes.client.models.v1_node import V1Node
from kubernetes.client.models.v1_node_list import V1NodeList
from kubernetes.client.models.v1_node_status import V1NodeStatus
from kubernetes.client.models.v1_node_address import V1NodeAddress
from kubernetes.clie... |
11531161 | from setuptools import find_packages, setup
setup(
name="varclr",
version="1.0",
author="<NAME>",
author_email="<EMAIL>",
license="MIT",
python_requires=">=3.6",
packages=find_packages(exclude=[]),
install_requires=[
"black>=21.10b0",
"gdown>=4.2.0",
"isort>=5.8.... |
11531183 | from textwrap import wrap
from decimal import Decimal
from django.template.loader import render_to_string
from django.db.models import Avg
from notifications import constants
from std_bounties.models import Bounty, Fulfillment
from bounties.utils import (
bounty_url_for,
profile_url_for,
shorten_address,
... |
11531234 | import io
class MeteredFile(io.BufferedRandom):
"""Implement using a subclassing model."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._read_bytes = 0
self._read_ops = 0
self._write_bytes = 0
self._write_ops = 0
def __enter__(self):... |
11531241 | import os
import pathlib
import inotify.adapters
import inotify.constants
from base_camera import BaseCamera
class CameraFile(BaseCamera):
@staticmethod
def frames():
filename = os.getenv('MOABFRAME', '/tmp/camera/frame.jpg')
dirname = os.path.dirname(filename)
pathlib.Path(dirname).m... |
11531262 | from ballet.validation.base import BaseValidator
from ballet.validation.common import ChangeCollector
class ProjectStructureValidator(BaseValidator):
def __init__(self, project):
self.change_collector = ChangeCollector(project)
def validate(self):
changes = self.change_collector.collect_chan... |
11531280 | from __future__ import annotations
from typing import Any, Dict, List, Optional, Union
from enum import Enum
from pydantic import BaseModel, Extra, Field, conint, constr
###################
# Package section #
###################
class Package(BaseModel):
class Config:
extra = Extra.forbid
name: s... |
11531284 | from __future__ import print_function, division
from sympy import zeros, eye, Symbol, solve_linear_system
N = 8
M = zeros(N, N + 1)
M[:, :N] = eye(N)
S = [Symbol('A%i' % i) for i in range(N)]
def timeit_linsolve_trivial():
solve_linear_system(M, *S)
|
11531294 | import os
import random
from colbert.utils.parser import Arguments
from colbert.utils.runs import Run
from colbert.evaluation.loaders import load_colbert, load_qrels, load_queries
from colbert.indexing.faiss import get_faiss_index_name
from colbert.ranking.retrieval import retrieve
from colbert.ranking.batch_retrieva... |
11531295 | from typing import Dict
import sys
from . import console
def get_imported_packages() -> Dict[str, str]:
"""
Returns a list of packages that have been imported, as a {name: version} dict.
"""
try:
# Should we vendor pkg_resources? See https://github.com/replicate/keepsake/issues/350
im... |
11531306 | from django.views import defaults
def bad_request_400_custom(
request,
exception,
template_name='core/400.html'
):
return defaults.bad_request(
request=request,
exception=exception,
template_name=template_name
)
def permission_denied_403_custom(
request,
e... |
11531310 | from typing import List, Optional
import re
import spacy
import nltk
import numpy as np
import tensorflow as tf
def load_glove(filepath: str):
"""Load GLoVe data"""
wv = {}
with open(filepath, 'rt') as f:
for line in f:
tokens = line.strip().split(' ')
wv[tokens[0]] = [float... |
11531359 | import json
from datetime import datetime
from os import path
from ralph.operations.changemanagement import jira
from ralph.operations.changemanagement.exceptions import IgnoreOperation
from ralph.operations.models import OperationStatus
from ralph.tests import RalphTestCase
class JiraProcessorTestCase(RalphTestCase... |
11531361 | from gzip import open as gopen
from re import search
from lxml import etree
from utility import dumpStruct, loadStruct, createPath
from structures import f_misc, langs
def extractAlignmentsRX(f_align, f_align_p, f_stats):
""" Extracts the alignments with regex.
Easier to parse HUN aligned files, which will ... |
11531373 | from pypureclient.flashblade import BucketReplicaLinkPost
# create a replica link from a specified local bucket, to a specified remote bucket
# on the remote corresponding to the remote credentials
local_bucket_names = ["localbucket"]
remote_bucket_names = ["remotebucket"]
remote_credentials_names = ["remote/credentia... |
11531391 | from urllib.parse import quote
from django.http import HttpResponseRedirect, JsonResponse
from django.views import generic
from jet_django import settings
from jet_django.mixins.cors_api_view import CORSAPIViewMixin
from jet_django.utils.backend import register_token, is_token_activated
class RegisterView(CORSAPIVi... |
11531405 | from .. import bp
from flask_login import login_required
from flask import render_template, redirect, url_for, flash, request
from app.lib.base.provider import Provider
from app.lib.base.decorators import admin_required
@bp.route('/logs/shell', methods=['GET'])
@login_required
@admin_required
def shell_logs():
pa... |
11531406 | import abc
import bisect
import contextlib
import heapq
import itertools
from typing import Iterable
import lucene
from java.lang import Double, Float, Number, Object
from org.apache.lucene import analysis, util
class Atomic(metaclass=abc.ABCMeta):
"""Abstract base class to distinguish singleton values from other... |
11531424 | from ..base import BaseModel
# https://vk.com/dev/objects/video
class Video(BaseModel):
id: int = None
owner_id: int = None
title: str = None
description: str = None
duration: int = None
photo_130: str = None
photo_320: str = None
photo_640: str = None
photo_800: str = None
d... |
11531450 | from os import path
from setuptools import setup, find_packages
with open("requirements.txt") as f:
requirements = f.read().splitlines()
with open(
path.join(path.abspath(path.dirname(__file__)), "README.md"), encoding="utf-8"
) as f:
long_description = f.read()
PACKAGE_KEYWORDS = [
"cisco",
"dna... |
11531452 | import tensorflow as tf
import numpy as np
import constant
grid_w = constant.GRID_W
grid_h = constant.GRID_H
def intensity_loss(gen_frames, gt_frames, l_num):
"""
Calculates the sum of lp losses between the predicted and ground truth frames.
@param gen_frames: The predicted frames at each scale.
@pa... |
11531516 | from pyrez.models import APIResponseBase
class Status(APIResponseBase):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.indicator = kwargs.get("indicator", '') or ''
self.description = kwargs.get("description", '') or ''
|
11531566 | from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV3
from directory_forms_api_client.forms import GovNotifyEmailActionMixin
from django.forms import Textarea
from django.template.loader import render_to_string
from django.utils.html import mark_safe
from great_components import forms
from ... |
11531649 | from octopus.arch.wasm.emulator import WasmSSAEmulatorEngine
# complete wasm module
file_name = "examples/wasm/samples/fib.wasm"
# read file
with open(file_name, 'rb') as f:
raw = f.read()
# run the emulator for SSA
emul = WasmSSAEmulatorEngine(raw, 'fib')
emul.emulate()
# visualization of the cfg with SSA
emu... |
11531668 | from itertools import permutations
from unittest import TestCase
from sipa import forms
from wtforms import Form, PasswordField, ValidationError
class PasswordComplexityValidatorTest(TestCase):
class TestForm(Form):
password = PasswordField()
def validate(self, validator, password):
form = s... |
11531672 | from glue import custom_viewer
from matplotlib.colors import LogNorm
from matplotlib.patches import Circle, Rectangle, Arc
from matplotlib.lines import Line2D
bball = custom_viewer('Shot Plot',
x='att(x)',
y='att(y)')
@bball.plot_data
def show_hexbin(axes, x, y):
axes... |
11531708 | from collections import namedtuple
from mwtypes import Timestamp
from articlequality.extractors import frwiki
def test_extractor():
Revision = namedtuple("Revisions", ['id', 'timestamp', 'sha1', 'text'])
class Page:
def __init__(self, title, namespace, revisions):
self.title = title
... |
11531727 | import os
import itertools
from abc import ABC, abstractmethod
from collections import namedtuple
from math import log
Run = namedtuple("Run", ["cross", "stats"])
def do_send(gen, past=None):
""" Functions as `next' for value-accepting generators.
"""
try:
cross = gen.send(past)
except StopIt... |
11531746 | from __future__ import print_function
import argparse
import datetime
import logging
import random
import threading
import time
try:
import queue
from queue import Queue
except ImportError:
import Queue as queue
from queue import Queue
import gpudb
from gpudb import GPUdbColumnProperty as GCP, GPUdbR... |
11531758 | import os
from concurrent import futures
import grpc
import time
import inference_service_pb2, inference_service_pb2_grpc
CHUNK_SIZE = 1024 * 1024 # 1MB
def get_file_chunks(filename):
with open(filename, 'rb') as f:
while True:
piece = f.read(CHUNK_SIZE);
if len(piece) == 0:
... |
11531853 | import torch
from torch import nn
import numpy as np
class ProjectPoint2Image(nn.Module):
"""Differentiable renderer for point cloud"""
def __init__(self, K, im_width, im_height, uv_only=False):
super(ProjectPoint2Image, self).__init__()
self.K = K
self.im_width = im_width
self.im_height = im_he... |
11531899 | BUILDDIR = '#build/release'
DISTDIR = '#Mitsuba.app'
CXX = 'icpc'
CC = 'icc'
CCFLAGS = ['-arch', 'i386', '-mmacosx-version-min=10.7', '-mfpmath=sse', '-isysroot', '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.7.sdk', '-O3', '-ipo... |
11531907 | import importlib.util
import os
import platform
import shutil
import subprocess
from pathlib import Path
from setuptools.command.build_ext import build_ext
from .build_ext_option import BuildExtOption, add_new_build_ext_option
from .cmake_extension import CMakeExtension
# These options are listed in `python setup.py... |
11531960 | from tests.utils import W3CTestCase
class TestFlexbox_Flex10N(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'flexbox_flex-1-0-N'))
|
11531969 | import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
# plotting Myanmar unicode characters with matplotlib
# Note: plotting syllables are not working with this program
# written by <NAME>, Visiting Professor, LST, NECTEC, Thailand
# ref: https://jdhao.github.io/2018/04/08/matplotlib-unicode-character/
... |
11531988 | import sys
import os
import argparse
import logging
import json
import time
import numpy as np
import openslide
import PIL
import cv2
import matplotlib.pyplot as plt
import math
import json
import logging
import time
import tensorflow as tf
import gzip
import timeit
from scipy import stats
from tensorflow.keras import... |
11531998 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import os
import json
import six
import requests
from .exceptions import RegistryError
# Module API
class Registry(object):
'''Allow loading Data Package... |
11532020 | import logging
import torch
import torch.distributed as dist
from torch.autograd import Variable
SMOOTH = 1e-6
logger = logging.getLogger("ActiveLearning")
def accuracy(dataloader, net, top_k=(1, 5), **kwargs):
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
net... |
11532026 | import numpy as np
from numpy.testing import assert_array_equal
from sklearn.datasets import load_digits
from deepforest import CascadeForestClassifier
toy_kwargs = {
"n_bins": 10,
"bin_subsample": 2e5,
"max_layers": 10,
"n_estimators": 1,
"criterion": "gini",
"n_trees": 100,
"max_depth":... |
11532029 | def ANTRuntime():
raise NotImplemented
def App(on_initialize, on_start, on_stop):
"""
Args:
on_initialize (Function): Callback handler invoked on application's initialization.
on_start (Function): Callback handler invoked when application starts.
on_stop (Function): Callback handler... |
11532050 | class Tasks(object):
def __init__(self, client):
self.client = client
def create_a_task(self, data):
"""
Create a new task
Args:
data:
Returns:
"""
return self.client._post("/dealTasks", json=data)
def retrieve_a_task(self, task_id):
... |
11532064 | from ctypes import POINTER, c_int, c_uint, c_uint64, c_void_p, c_char_p
from .dll import _bind
from .stdinc import SDL_bool
from .video import SDL_Window
# NOTE: I have no idea whether this module actually works
__all__ = [
"SDL_Vulkan_LoadLibrary", "SDL_Vulkan_GetVkGetInstanceProcAddr",
"SDL_Vulkan_UnloadLib... |
11532066 | import logging
import os
import example_app.static
from jivago.config.production_jivago_context import ProductionJivagoContext
from jivago.jivago_application import JivagoApplication
from jivago.lang.annotations import Override
from jivago.lang.registry import Registry
from jivago.wsgi.routing.router import Router
fro... |
11532073 | import unittest
from django.db import connection
from django.test import TestCase
from ..models import Person
@unittest.skipUnless(connection.vendor == 'postgresql', "Test only for PostgreSQL")
class DatabaseSequenceTests(TestCase):
def test_get_sequences(self):
with connection.cursor() as cursor:
... |
11532085 | from __future__ import absolute_import
from .legacy import (
create_message, create_gzip_message,
create_snappy_message, create_message_set,
CODEC_NONE, CODEC_GZIP, CODEC_SNAPPY, ALL_CODECS,
ATTRIBUTE_CODEC_MASK, KafkaProtocol,
)
API_KEYS = {
0: 'Produce',
1: 'Fetch',
2: 'ListOffsets',
... |
11532098 | from urllib.parse import urlparse
from privacyscanner.scanmodules import ScanModule
class ExampleScanModule(ScanModule):
name = 'example'
dependencies = []
required_keys = ['site_url']
def scan_site(self, result, meta):
"""Scans a site and adds more information to the result.
The pa... |
11532161 | import json
from pathlib import Path
from typing import Any, Dict, Union
from . import markers
__all__ = ["matplotlib_style", "markers"]
matplotlib_style: Dict[str, Dict[str, Union[str, Any]]] = json.loads(
(Path(__file__).parent / "matplotlib_style.json").read_text()
)
for _, value in matplotlib_style.items():... |
11532186 | import struct
def read_string(f, n=0):
if n == 0:
s = b''
while True:
c = f.read(1)
if c == b'\0':
break
s += c
else:
s = f.read(n)
s = s.partition(b'\0')[0]
try:
s = s.decode('ascii')
except:
s = s.decode('latin-1') #FIXME: This is a poor fallback
return s
... |
11532206 | from PyQt5.QtWidgets import QLineEdit, QDialog, QFileDialog, QWidget, QTreeWidget, QToolButton, QRadioButton, QMessageBox, QTreeWidgetItem, QTabWidget, QLabel, QCheckBox, QPushButton, QSpinBox
from os.path import basename
from PyQt5.QtGui import QIcon
from PyQt5.QtGui import QColor, QBrush
from PyQt5.QtCore import Qt
f... |
11532235 | import warnings
from scrapy.exceptions import ScrapyDeprecationWarning
warnings.warn("Module `scrapy.contrib.exporter` is deprecated, "
"use `scrapy.exporters` instead",
ScrapyDeprecationWarning, stacklevel=2)
from scrapy.exporters import *
from scrapy.exporters import PythonItemExporter
|
11532272 | import unittest
import numpy as np
from holoviews import NdOverlay, Element
class CompositeTest(unittest.TestCase):
"For testing of basic composite element types"
def setUp(self):
self.data1 = np.zeros((10, 2))
self.data2 = np.ones((10, 2))
self.data3 = np.ones((10, 2)) * 2
... |
11532309 | import os
from Deployment.ConsumerWorker import celery_worker_app
from Deployment.server_config import IS_TEST, OCR_TRITON_URL, OCR_TRITON_PORT
from Operators.ExampleTextDetectOperator import GeneralDBDetect
from Operators.ExampleTextRecognizeOperator import GeneralCRNN
from Operators.ExampleTextOrientationClassificat... |
11532313 | from typing import List, Optional
from autofit.mapper.prior_model.abstract import AbstractPriorModel
from autofit.non_linear.samples import Samples, Sample
class DrawerSamples(Samples):
def __init__(
self,
model: AbstractPriorModel,
parameter_lists: List[List[float... |
11532316 | import FWCore.ParameterSet.Config as cms
import FWCore.ParameterSet.VarParsing as VarParsing
process = cms.Process("bsvsbpix")
#prepare options
options = VarParsing.VarParsing("analysis")
options.register ('globalTag',
"DONOTEXIST",
VarParsing.VarParsing.multiplicity.singleton, #... |
11532359 | from monai.inferers import SlidingWindowInferer
import torch
from typing import Callable, Any
from loguru import logger
class SlidingWindowInferer(SlidingWindowInferer):
def __init__(self, *args, **kwargs):
self.logger = logger
super().__init__(*args, **kwargs)
def __call__(
self,
... |
11532365 | import pytari2600.memory.cartridge as cartridge
import unittest
import pkg_resources
class TestCartridge(unittest.TestCase):
def test_cartridge(self):
cart = cartridge.GenericCartridge(pkg_resources.resource_filename(__name__, 'dummy_rom.bin'), 4, 0x1000, 0xFF9, 0x0)
# Write should do nothing
... |
11532379 | from typing import Any
import pytest
from pydantic import BaseModel
from pydantic_factories import (
AsyncPersistenceProtocol,
ModelFactory,
SyncPersistenceProtocol,
)
class MyModel(BaseModel):
name: str
class MySyncPersistenceHandler(SyncPersistenceProtocol):
def save(self, data: Any, *args, ... |
11532383 | from pyspark.mllib.recommendation import ALS
from numpy import array
# Load and parse the data
data = sc.textFile("data/mllib/als/test.data")
ratings = data.map(lambda line: array([float(x) for x in line.split(',')]))
# Build the recommendation model using Alternating Least Squares
rank = 10
numIterations = 20
model ... |
11532412 | import unittest
import torch
import torch.nn
from torch.autograd import Variable
import memcnn.models.revop as revop
import numpy as np
import copy
class ReversibleOperationsTestCase(unittest.TestCase):
def test_reversible_block(self):
"""ReversibleBlock test
* test inversion Y = RB(X) and X = RB... |
11532455 | from setuptools import setup
# see https://stackoverflow.com/questions/14399534/reference-requirements-txt-for-the-install-requires-kwarg-in-setuptools-setup-py
setup(name='fuzzymatcher',
version='0.0.5',
description='Fuzzy match two pandas dataframes based on one or more common fields',
url='https:/... |
11532501 | import logging
from flask import current_app
from app.clients.sms.firetext import (
FiretextClient
)
logger = logging.getLogger(__name__)
class LoadtestingClient(FiretextClient):
'''
Loadtest sms client.
'''
def init_app(self, config, statsd_client, *args, **kwargs):
super(FiretextClie... |
11532503 | import os
import string
import random
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Embedding, GRU
from tensorflow.keras.losses import sparse_categorical_crossentropy
from tensorflow.keras.models import load_model
from matplotlib imp... |
11532519 | from typing_extensions import final
from typing import Any, cast
from .tensor import Tensor
from .tensor import TensorType
from .tensor import TensorOrScalar
def unwrap_(*args: Any) -> Any:
return tuple(t.raw if isinstance(t, Tensor) else t for t in args)
def unwrap1(t: Any) -> Any:
return t.raw if isinsta... |
11532598 | import numpy as np
import pytest
from neuraxle.base import ExecutionMode
from neuraxle.pipeline import Pipeline
from neuraxle.steps.flow import ReversiblePreprocessingWrapper
from neuraxle.steps.misc import TapeCallbackFunction, CallbackWrapper
from neuraxle.steps.numpy import MultiplyByN, AddN
from testing.steps.neur... |
11532601 | CONF_MAINNET = {
"fullnode": "https://api.trongrid.io",
"event": "https://api.trongrid.io",
}
# The long running, maintained by the tron-us community
CONF_SHASTA = {
"fullnode": "https://api.shasta.trongrid.io",
"event": "https://api.shasta.trongrid.io",
"faucet": "https://www.trongrid.io/faucet",
... |
11532647 | from typing import Type, TypeVar
from copy import deepcopy
from datapipelines import DataTransformer, PipelineContext
from ..core.championmastery import ChampionMasteryData, ChampionMasteryListData, ChampionMastery, ChampionMasteries
from ..dto.championmastery import ChampionMasteryDto, ChampionMasteryListDto
T = Ty... |
11532655 | import json
import sys
import iotbx.phil
from cctbx.miller.display import render_2d, scene
from dials.util import Sorry
from iotbx.gui_tools.reflections import get_array_description
from iotbx.reflection_file_reader import any_reflection_file
from scitbx.array_family import flex
class MultiplicityViewPng(render_2d):... |
11532663 | from .operators import *
from .soft_regression import Soft4DFlowRegression, SoftArg2DFlowRegression
|
11532664 | import torch
import torch.nn.functional as F
import torch.nn as nn
from Models.base_man import BaseMan
import torch_utils
from setting_keywords import KeyWordSettings
from thirdparty.head_cnns import PACRRPlaneMaxPooling
import time
import layers
from Models.base_man import AttentionType
class MultiModalAttentionNetw... |
11532670 | import struct
import sys
class WAL():
# http://www.cclgroupltd.com/the-forensic-implications-of-sqlites-write-ahead-log/
def __init__(self, f):
self.f=f
HEADER = ">LLLLLLLL"
size = struct.calcsize(HEADER)
data = self.f.read(size)
(self.signature, self.version, self.page_size, self.sequence, self.salt1, se... |
11532690 | import pymel.internal.factories as _factories
from . import general as _general
def fluidEmitter(*args, **kwargs):
"""
Creates an emitter object. If object names are provided or if objects are selected, applies the emitter to the
named/selected object(s)in the scene. Fluid will then be emitted from each. I... |
11532707 | import os
from pathlib import Path
import zipfile
DATA_FOLDER = os.path.join(os.path.dirname(__file__), "../../data/raw")
def main():
data_file = os.path.join(DATA_FOLDER, "2016-annual-report-xbrls.zip")
folder_name, _ = os.path.splitext(data_file)
if not Path(DATA_FOLDER).joinpath(folder_name).exists()... |
11532711 | import boto3
import sys
def new_redis_cluster(clusterID, instanceSize, cacheName):
new_cluster = boto3.client('elasticache')
new_cluster.create_cache_cluster(
CacheClusterId = clusterID,
AZMode='single-az',
NumCacheNodes = 1,
CacheNodeType = instanceSize,
Engine='redis',... |
11532735 | import numpy as np
from gensim import matutils
SLICE_SIZE = 5000 # Change this in case of Memory problems
class ClosestIndexes:
def __init__(self, similarities):
self.vectors = similarities
# Normalize just in case
norms = np.sqrt((self.vectors * self.vectors).sum(axis=1)).reshape(
... |
11532736 | class ApiConfig(object):
host_and_port = None
scheme = None
@classmethod
def splunkd_host_port(cls):
if not cls.host_and_port:
import splunk.clilib.cli_common as comm
ipAndPort = comm.getWebConfKeyValue('mgmtHostPort')
ip, port = ipAndPort.split(':')... |
11532781 | import cPickle
from thoonk.exceptions import *
from thoonk.feeds import Queue
class PythonQueue(Queue):
"""
A Thoonk.py addition, the PythonQueue class behaves the
same as a normal Thoonk queue, except it pickles/unpickles
items as needed.
Thoonk.py Implementation API:
put -- Add a Pyth... |
11532784 | from argparse import ArgumentParser
import torch
from model import get_openqa, add_additional_documents
from transformers.models.realm.modeling_realm import logger
from transformers.utils import logging
logger.setLevel(logging.INFO)
torch.set_printoptions(precision=8)
def get_arg_parser():
parser = ArgumentPa... |
11532786 | import typing
import torch
from . import module
class _GlobalPool(torch.nn.Module):
def forward(self, inputs):
return self._pooling(inputs).reshape(inputs.shape[0], -1)
class GlobalMaxPool1d(_GlobalPool):
"""Applies a 1D global max pooling over the last dimension.
Usually used after last `Con... |
11532805 | CAMVID = 'camvid'
KITTI = 'kitti'
camvid_color_map = {'Animal': (64, 128, 64), 'Archway': (192, 0, 128),
'Bicyclist': (0, 128, 192), 'Bridge': (0, 128, 64),
'Building': (128, 0, 0), 'Car': (64, 0, 128),
'CartLuggagePram': (64, 0, 192), 'Child': (192, 128, 64),
... |
11532831 | from .common import InfoExtractor
class MaoriTVIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?maoritelevision\.com/shows/(?:[^/]+/)+(?P<id>[^/?&#]+)'
_TEST = {
'url': 'https://www.maoritelevision.com/shows/korero-mai/S01E054/korero-mai-series-1-episode-54',
'md5': '5ade8ef53851b6a132c051... |
11532874 | from django.utils import simplejson
from django.http import HttpResponse
class JsonResponse(HttpResponse):
"""Return a Json Format."""
def __init__(self, data):
HttpResponse.__init__(self,
content=simplejson.dumps(data),
content_type='applica... |
11532886 | from dataclasses import dataclass, field as datafield
from typing import List
from pal.model.logical_operand import LogicalOperand
from pal.model.register_operand import RegisterOperand
@dataclass
class ExecutionContext():
""" Models the context under which an instruction may be executed """
execution_state:... |
11532928 | from ..app import app
from ..tools import ErrorResponse, OKResponse
from ..model.user import User
@app.http_get("/api2/user/{username}")
@app.authenticated
async def get_user_byname(request):
"""
Return a user by its username.
---
description: Return a user by its name.
tags:
- Users
pa... |
11532970 | import setuptools
with open("README.md", encoding='utf-8') as f:
long_description = f.read()
version = {}
with open('alkymi/version.py') as fp:
exec(fp.read(), version)
setuptools.setup(
name="alkymi",
description="alkymi - Pythonic task automation",
version=version['__version__'],
license="M... |
11532972 | import torch
import torch.nn.functional as F
from combinet.src.dataset.camvid import CLASS_WEIGHT_CAMVID
from combinet.src.dataset.bacteria import CLASS_WEIGHT_BACTERIA
from combinet.src.utils import nanmean
class StreamSegMetrics():
"""
Stream Metrics for Semantic Segmentation Task
"""
def __init__(... |
11532987 | import os
import subprocess
import networkx as nx
from attacksurfacemeter import utilities
from attacksurfacemeter.call import Call
from attacksurfacemeter.granularity import Granularity
from attacksurfacemeter.loaders.base_loader import BaseLoader
from attacksurfacemeter.loaders.stack import Stack
class CflowLoade... |
11533023 | from datetime import datetime
from json import JSONDecodeError
from rest_framework import status
from openbook_moderation.permissions import IsNotSuspended
from openbook_posts.models import Post
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.files.images import ... |
11533033 | import pytest
import sqlalchemy
import sqlalchemy.event
import sqlalchemy_fsm
from tests.conftest import Base
class EventModel(Base):
__tablename__ = 'event_model'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
state = sqlalchemy.Column(sqlalchemy_fsm.FSMField)
def __init__(self, *arg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.