id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4819420 | import json
import urllib
import sqlite3 as lite
from unidecode import unidecode
'''
last_ndb_no = '10909'
start = False
con = lite.connect('db')
with con:
cur = con.cursor()
cur.execute('select ndb_no,shrt_desc from food_des')
rows = cur.fetchall()
for row in rows:
ndb_no = row[0]
print ndb_n... |
4819454 | import unittest
from katas.kyu_5.airport_arrivals_departures_1 import flap_display
class FlapDisplayTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(flap_display(['CAT'], [[1, 13, 27]]), ['DOG'])
def test_equal_2(self):
self.assertEqual(
flap_display(['HELLO ... |
4819459 | import logging
import time
from unittest import TestCase
from unittest.mock import MagicMock
from databay import Record
from databay.support.buffers import Buffer
from test_utils import DummyException
class TestBuffers(TestCase):
def test_count_controller(self):
buffer = Buffer(count_threshold=10)
... |
4819475 | class recfilter(object):
lastval = 0
a = None
b = None
def __init__(self, fcoef, initval):
self.lastval = float(initval)
self.a = 1.0 - float(fcoef)
self.b = float(fcoef)
def apply(self, x):
self.lastval = self.a * float(x) + self.b * self.lastval
return sel... |
4819484 | from __future__ import unicode_literals
import uuid
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from star_ratings import get_star_ratings_rating_model_name
from star_ratings.models import AbstractBaseRating
class Foo(models.Model):
name = models.CharField(max_len... |
4819519 | import os
from typing import Optional, List, Callable, Tuple
from hetdesrun.adapters.exceptions import AdapterHandlingException
from hetdesrun.adapters.local_file.detect import (
get_local_files_and_dirs,
LocalFile,
local_file_from_path,
)
from hetdesrun.adapters.local_file.models import (
Structur... |
4819527 | from manimlib.imports import *
from my_projects.active_projects.mechanism.basic_component import *
class Test_Curve(Scene):
def construct(self):
s = 0.6
P2A, P3B, CD, AC = 1.5, 1., 2, 4
phi_A, phi_B, theta_BCD = PI/6, PI/4, PI/2
z0, z1, z2, z3 = 20, 45, 30, 20
# z0, z1, z... |
4819536 | def _jupyter_server_extension_paths():
return [{"module": "aws_glue_databrew_jupyter_extension"}]
def _jupyter_nbextension_paths():
return []
|
4819546 | from mmdet.models.losses import FocalLoss, SmoothL1Loss, binary_cross_entropy
from .chamfer_distance import ChamferDistance, chamfer_distance
__all__ = [
'FocalLoss', 'SmoothL1Loss', 'binary_cross_entropy', 'ChamferDistance',
'chamfer_distance'
]
|
4819559 | from setuptools import setup
def readme():
with open('README.md') as f:
return f.read()
setup(
name="aleph-alpha-client",
url="https://github.com/Aleph-Alpha/aleph-alpha-client",
author="<NAME>",
author_email="<EMAIL>",
packages=["aleph_alpha_client"],
setup_requires=['setuptools_s... |
4819584 | from __future__ import absolute_import
import re
from .cut import Cut
__all__ = [
'Categories',
]
class Categories(object):
"""
Implements a mechanism to ease the creation of cuts that describe
non-overlapping categories.
"""
#TODO: use pyparsing
CUT_REGEX = '[-+]?[0-9]*\.?[0-9]+([eE][-... |
4819608 | from zyglrox.core.utils import partial_trace
import tensorflow as tf
import numpy as np
# Phi+ state
psi = tf.reshape(tf.constant(1 / np.sqrt(2) * np.array([1,0,0,1])), (1,2,2))
rho_a = partial_trace(psi, keep=[0,], dims=[1,2,2])
sess = tf.Session()
print(sess.run(rho_a)) |
4819631 | from RecoTracker.FinalTrackSelectors.lwtnnESProducer_cfi import lwtnnESProducer as _lwtnnESProducer
trackSelectionLwtnn = _lwtnnESProducer.clone(
ComponentName = "trackSelectionLwtnn",
fileName = "RecoTracker/FinalTrackSelectors/data/LWTNN_network_10_5_X_v1.json",
)
|
4819632 | import torch.nn as nn
import torch.nn.functional as F
from torch import sigmoid
# define the NN architecture
class ConvAutoencoder(nn.Module):
def __init__(self, **kwargs):
super(ConvAutoencoder, self).__init__()
## encoder layers ##
# conv layer (depth from 1 --> 16), 3x3 kernels
s... |
4819723 | from collections import OrderedDict
from rpython.rlib import jit
from hippy.objects.arrayobject import new_rdict, W_RCellDictArrayObject
from hippy.objects.reference import W_Reference
class W_Vars(W_RCellDictArrayObject):
"""An array of variables."""
def __init__(self, space):
W_RCellDictArrayObj... |
4819778 | import argparse
import os
import json
from collections import defaultdict
from nltk.tokenize import wordpunct_tokenize
##############
# Below copied from the WikiSQL code
agg_ops = ['', 'MAX', 'MIN', 'COUNT', 'SUM', 'AVG']
cond_ops = ['=', '>', '<', 'OP']
##############
def construct_sql_graph(sql, table):
''... |
4819779 | import unittest
from pulsar.utils import security
from pulsar.utils.string import random_string
class TestSecurity(unittest.TestCase):
def testSalt(self):
s1 = security.gen_salt(10)
self.assertEqual(len(s1), 10)
self.assertNotEqual(security.gen_salt(10), s1)
s1 = security.gen_sal... |
4819860 | import math
import torch
import torch.nn.functional as F
from torch import nn, Tensor
from typing import List, Tuple, Dict, Optional
class ImageList(object):
"""
Structure that holds a list of images (of possibly
varying sizes) as a single tensor.
This works by padding the images to the s... |
4819874 | from typing import List, Optional, cast
from unittest import mock
from unittest.mock import patch
from uuid import uuid1
import pytest
from _pytest.fixtures import FixtureRequest
from _pytest.python import Metafunc
from alchemy_mock.mocking import UnifiedAlchemyMagicMock
from faker import Faker
from pytest_mock import... |
4819893 | from .formulas import get_mappings
from .workspace import workspace
from .workspace_structure import WorkspaceStructure
class Correspondence(WorkspaceStructure):
def __init__(
self,
object_from_initial,
object_from_target,
concept_mappings,
flip_target_object,
):
... |
4819903 | from .adam import *
from .spec import *
from .util import *
from .vars import *
from .minimise import *
|
4819914 | import mock
import pytest
from thundra.samplers import CompositeSampler
@pytest.fixture
def mocked_sampler():
def sampler(is_sampled=False):
m = mock.Mock(name='mocked_sampler')
m.is_sampled.return_value = is_sampled
return m
return sampler
def test_with_no_samplers():
cms = Co... |
4819920 | from beagle.edges import Edge
class AlertedOn(Edge):
__name__ = "Alerted On"
timestamp: int
def __init__(self) -> None:
super().__init__()
|
4819936 | import numpy as np
from scipy.optimize import minimize
from DCC_GARCH.GARCH.GARCH_loss import garch_process
class GARCH():
def __init__(self, p=1, q=1, max_itr=3, early_stopping=True):
# p the lag of r_t, q the lag of s_t
self.p = p
self.q = q
theta0 = [0.005] + [0.1 fo... |
4819949 | def check_resource_count(expected_count):
test.assertEqual(expected_count, len(reality.all_resources()))
example_template = Template({
'A': RsrcDef({}, []),
'B': RsrcDef({'a': '4alpha'}, ['A']),
'C': RsrcDef({'a': 'foo'}, ['B']),
'D': RsrcDef({'a': 'bar'}, ['C']),
})
engine.create_stack('foo', exam... |
4820013 | import numpy as np
import sys
import time
import shutil
import subprocess
import os
import pyflann
from IPython.core.debugger import set_trace
from Bio.PDB import *
struct_dir = "/home/gainza/lpdi_fs/masif_paper/masif/data/masif_ppi_search/data_preparation/01-benchmark_pdbs/"
benchmark_list_fn = "../benchmark_list.txt... |
4820066 | import os
import sys
import numpy as np
import pandas as pd
import pandas.util.testing as pdt
import unittest
sys.path.insert(0, os.path.abspath("../../"))
from specdal.spectrum import Spectrum
from specdal.collection import Collection
class GroupByTests(unittest.TestCase):
def setUp(self):
# total 36 spe... |
4820082 | from users.starlette_password.hashers import BasePasswordHasher, constant_time_compare
class PlainPasswordHasher(BasePasswordHasher):
"""
Used to have fast unit tests!
Not for production use!
"""
algorithm = "plain"
def salt(self):
return ""
def encode(self, password, salt):
... |
4820102 | import subprocess
from pathlib import Path
from datakit_project.exceptions import RepositoryFetchFailed
class Repository:
def __init__(self, path):
self.path = Path(path)
def info(self):
cmd = self._log_pretty_cmd()
output = self._syscall(cmd)
return self._prepare_repo_info... |
4820115 | import os
# Default paths for libraries, header files, binaries, etc.
home = os.environ.get('WINBREW_HOME', os.path.join(os.environ['LOCALAPPDATA'], 'WinBrew'))
formula_path = os.environ.get('WINBREW_PATH', os.path.join(home, 'formula'))
lib_path = os.path.join(home, 'lib')
include_path = os.path.join(home, 'include')... |
4820153 | import json
with open("terrain_texture.json") as file:
oldData=json.load(file)
with open("terrain_texture17.json") as file:
newData=json.load(file)
oldKeys=list(oldData["texture_data"].keys())
newKeys=list(newData["texture_data"].keys())
newBlocks = list(filter(lambda i: i not in oldKeys, newKeys))
for key ... |
4820181 | from mage.union_find.disjoint_set import DisjointSet
from tests.union_find.constants import Constants
import pytest
@pytest.fixture
def disjoint_set():
return DisjointSet(node_ids=Constants.IDs)
class TestInit:
def test_keys(self, disjoint_set):
assert all(i in disjoint_set.nodes.keys() for i in Co... |
4820183 | from .text_classification_instance import TextClassificationInstance, IndexedTextClassificationInstance
|
4820195 | from .lithology import m,n,romaa,dtmaa,umaa,ur_lith
__all__ = ['m',
'n',
'romaa',
'dtmaa',
'umaa',
'ur_lith',
]
|
4820213 | import torch.nn as nn
import torch
def make_optimizer(arg, model):
params = []
bn_param_set = set()
for name, module in model.named_modules():
if isinstance(module, (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)):
bn_param_set.add(name+".weight")
bn_param_set.add(name+".b... |
4820250 | import argparse
from ocdata.structure_sampler import StructureSampler
def parse_args():
parser = argparse.ArgumentParser(description='Sample adsorbate and bulk surface(s)')
parser.add_argument('--seed', type=int, default=None, help='Random seed for sampling')
# input and output
parser.add_argument(... |
4820264 | class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
i = 0
maxlen = 0
while i<len(s):
if s[i]==")":
i = i+1
continue
else:
l, f = self.find_longe... |
4820277 | import pytest
from notion.helpers import page_url_to_id
@pytest.mark.parametrize(('page_url', 'expected'), [
('https://notion.so/workspace/100500ddf', '100500ddf'),
('https://notion.so/workspace/100500ddf/', '100500ddf'),
('https://notion.so/workspace/100500ddf/?v=test', '100500ddf'),
('https://notio... |
4820286 | import os
import logging
from typing import Optional, Union
import yaml
from redis import Redis
from discord.ext.commands import Context, Command, Cog, Group
LOCALE_PATH = "locale/"
log = logging.getLogger(__name__)
def load_locale(path: str, cache: Redis) -> None:
with open(path) as f:
data = yaml.sa... |
4820293 | from baserow.core.registry import Registry
class BaserowFormulaFunctionRegistry(Registry):
name = "formula_function"
formula_function_registry = BaserowFormulaFunctionRegistry()
|
4820319 | import uvicorn
from config import get_config
# from utils.logger import create_logger
"""
Application is run from the root of the project directory with `python3 app/main.py`
`"create_app:app"` is the module passed to uvicorn, to keep live reload ability and path import structure
for the application.
"""
if __name_... |
4820320 | from django import template
from report.models import PageView
register = template.Library()
##
## On page template, increments the hit count to the URL, or creates it as 1.
##
@register.simple_tag(takes_context=True)
def trackPageView(context):
request = context['request']
try:
pvObj = PageView... |
4820370 | t = int(input())
for i in range(t):
l = []
n = int(input())
for i in range(n):
d = list(map(int, input().split()))
l.append(d)
p = []
for i in l:
for j in i:
p.append( (i[1]//(i[0]+1) )*i[2] )
print(max(p))
|
4820373 | from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy import Column, Integer
import logging
log = logging.getLogger("interactor.database.connection")
class Base:
# Metadata gets set by Sqlalchemy
metadata = None
# __repr_columns__ must be set by subclasses of Base
__... |
4820420 | import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'tp_utils'))
import platform
if platform.system() == 'Darwin':
import matplotlib
matplotlib.use('Agg')
import argparse
import datetime
import numpy as np
import tensorflow as tf
import provider
import copy
import models.tp8 as MODE... |
4820453 | from datetime import datetime
from functools import reduce
import pandas as pd
import pytz
def get_all_data_types(data):
print(data.keys())
return sorted(data['datasets'].keys())
def get_all_data_sources_for_data_type(data, datatype):
return sorted(data['datasets'][datatype].keys())
def get_all_data_t... |
4820468 | import numpy as np
max_interval_s = 60*60*24
min_interval_s = 30
def new_interval(current):
new_interval_s = current * 1.2
if new_interval_s > max_interval_s:
return max_interval_s
elif new_interval_s < min_interval_s:
return min_interval_s
else:
return new_interval_s
interva... |
4820491 | import gc
from typing import Callable
from ..init_helper import get_logger
logger = get_logger()
import torch
from ..operator import OperatorInterface
class UnaryOp(OperatorInterface):
"""
UnaryOp is called in the form of tensor_obj.op(args), we convert it
to a regular function call with "getattr(tens... |
4820499 | import logging
from starling_sim.basemodel.population.agent_population import AgentPopulation
class DictPopulation(AgentPopulation):
"""
Stores the agent populations of the simulation in Python dictionaries
Theses dicts are stored in a global dict
"""
def __init__(self, population_names):
... |
4820512 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="TLAF",
version="1.0",
author="<NAME> , <NAME>",
author_email="<EMAIL>, <EMAIL>",
# #Small Description about module
description="TLA is built using PyTorch, Transformers and several other State-of-the-A... |
4820537 | import obspython as _obs
import threading
import traceback
from . import data as _data
from . import _helper
class Future:
_NOTSET = object()
_EXCEPTION = object()
_INTERRUPT = object()
_WAITING = []
def __init__(self):
self._result = self._NOTSET
self._exception = None
se... |
4820602 | from computation.turing_machine.rule import (
DTM,
Direction,
DTMRulebook,
Tape,
TMConfiguration,
TMRule,
)
# increment binary number rulebook
rulebook = DTMRulebook(
[
TMRule(1, "0", 2, "1", Direction.RIGHT),
TMRule(1, "1", 1, "0", Direction.LEFT),
TMRule(1, "_", 2,... |
4820644 | from typing import TypeVar, Callable, Dict, Set, Any
from mopyx import rendering
from mopyx.computed_property import ComputedProperty
from mopyx.decorator_action import action
from mopyx.proxy_list import ListModelProxy
T = TypeVar("T")
def model(base: Callable[..., T]) -> Callable[..., T]:
class ModelProxy(bas... |
4820650 | import ast
from dataclasses import field
from functools import singledispatch
from reiz.ir import IR, Schema
from reiz.serialization.transformers import iter_properties
@singledispatch
def serialize(value, context):
message = f"Unexpected object for serialization: {value!r} ({type(value)})"
if context.flows_... |
4820658 | import os
import gdown
import tarfile
print('The script will download and extract the segment one by one')
#reply = input('[y] to confirm, others to exit: ')
#if reply != 'y':
# exit()
links = [
'https://drive.google.com/uc?id=14DNamenZsvZnb32NFBNkZCGene5D2oaE'
]
names = [
'a2d_annotation_with_instances.... |
4820672 | import calendar
from flask_appbuilder import ModelView
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_appbuilder.fields import AJAXSelectField
from flask_appbuilder.fieldwidgets import Select2AJAXWidget, Select2SlaveAJAXWidget
from wtforms import validators
from app import db, appbuilder
... |
4820675 | import subprocess
import sys
from workflow import Workflow3, ICON_INFO
def list_genymotion():
arg = wf.args[0].strip()
shell_cmd = "/usr/local/bin/VBoxManage list vms -l | grep '^Name:\|Hardware UUID:\|Log folder:' | tr -s ' '"
sys.stderr.write(shell_cmd + "\n")
result = subprocess.check_output(shell_... |
4820684 | from datetime import datetime, timedelta
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.template.defaultfilters import slugify
from django.core.urlresolvers import reverse
from taggit.managers import TaggableManager
from markupfield.fields import M... |
4820710 | from django.conf.urls import url
from .views import Dashboard, AccountList, AccountNew, AccountDelete, AccountEdit
from .views import TransactionList, TransactionNew, TransactionEdit, TransactionDelete
from .views import CategoryList, CategoryNew, CategoryEdit, CategoryDelete
from .views import TransactionCommentList, ... |
4820766 | from phon.mesh_objects.element_side_set import ElementSideSet
from phon.mesh_objects.element_side_set import ElementSide
def create_element_sides(mesh, mesh_dimension):
"""
Creates elements of mesh_dimension - 1 along the interfaces
between grains.
:param mesh: The mesh
:type: mesh: :class:`Mesh`... |
4820778 | from unittest.mock import Mock
from django.test import TestCase
from django.utils import timezone
from news.models import Article, Reporter
from django_query_capture import native_query_capture
class NativeQueryCaptureTests(TestCase):
def setUp(self) -> None:
Reporter.objects.create(full_name="target")
... |
4820787 | from string import Template
from django.contrib.contenttypes.models import ContentType
from django.db import ProgrammingError
from rest_framework import serializers
from rest_framework.serializers import SerializerMetaclass
FIELD_TPL = """\
@Field() $name: $type;\
"""
TPL = """
/////////////////////////////////... |
4820802 | import numpy as np
import tensorflow as tf
import tensorlight as light
def sse(outputs, targets, name=None):
"""Sum of squared error (SSE) between images.
Parameters
----------
outputs: Tensor [batch_size, ...] of type float32
The first tensor.
targets: Tensor [batch_size, ...] of type flo... |
4820804 | import unittest
import numpy as np
import pytest
import torch
from pfrl.nn import empirical_normalization
class TestEmpiricalNormalization(unittest.TestCase):
def test_small_cpu(self):
self._test_small(gpu=-1)
@pytest.mark.gpu
def test_small_gpu(self):
self._test_small(gpu=0)
def _... |
4820819 | import airflow.utils.operator_helpers
from dbnd._core.current import try_get_current_task_run
from dbnd._core.utils.uid_utils import get_airflow_instance_uid
from dbnd_airflow.tracking.dbnd_airflow_conf import extend_airflow_ctx_with_dbnd_tracking_info
def context_to_airflow_vars(context, in_env_var_format=False):
... |
4820830 | import pytest
pytest.importorskip("requests")
pytest.importorskip("requests.exceptions")
def test_load_module():
__import__("modules.contrib.weather")
|
4820903 | import collections
import numpy as np
from sklearn.metrics import mean_squared_error, precision_recall_curve, recall_score, precision_score
__author__ = "<NAME>"
__credits__ = "https://github.com/octo-technology/bdacore"
__license__ = "Apache 2.0"
def generalized_jaccard_similarity_score(y_true, y_pred):
""" Ge... |
4820907 | import tensorflow as tf
import tensorflow_addons as tfa
from tensorflow.keras import layers
def tfa_sampler(image, coords, mask=False):
''' Value sampler using tfa.image.resampler
Args:
image: tensor with shape (bs*h*w, h/i**2, w/i**2, 1)
coords: coordinates tensor with shape (bs*h*w,, 2r+1, 2r+1,... |
4820936 | from abc import abstractmethod, ABCMeta
from typing import List
from protoactor.cluster.member_status import MemberStatus
from protoactor.cluster.rendezvous import Rendezvous
from protoactor.cluster.round_robin import RoundRobin
class AbstractMemberStrategy(metaclass=ABCMeta):
@abstractmethod
def get_all_mem... |
4820964 | try:
from ustruct import unpack_from
except ImportError:
from struct import unpack_from
class Icon:
def __init__(self, filename, intensity_bits=4):
self.f = open(filename, 'rb')
self.intensity_bits = intensity_bits
self.frame = 0
chunk = bytearray(4)
self.f.readinto(chunk)
self.num_frames = chunk[0]
s... |
4820989 | import unittest
import programytest.externals as Externals
from programy.nlp.stemming import Stemmer
class StemmerTests(unittest.TestCase):
def test_stem_default(self):
stemmer = Stemmer()
self.assertIsNotNone(stemmer)
self.assertIsNotNone(stemmer._impl)
self.assertEqual("troubl"... |
4820993 | import random
class TTTGame(object):
_coords = [(x, y) for y in range(3) for x in range(3)]
_num_to_coord = dict([(n+1, c) for n, c in enumerate(_coords)])
_win_ways = (# Horizontal
set([1, 2, 3]),
set([4, 5, 6]),
set([7, 8, 9]),
# Verti... |
4821007 | import sys
from unittest.mock import Mock
_django_settings = None
def get_django_settings():
global _django_settings
if _django_settings is None:
sys.path.append("app/app")
# Mock out imports
sys.modules.update(
{
"django.utils.safestring": Mock(mark_safe=l... |
4821032 | import uuid
from globus_cli.login_manager import LoginManager
from globus_cli.parsing import command
from globus_cli.termio import FORMAT_TEXT_TABLE, formatted_print
from .._common import index_id_arg
TASK_FIELDS = [
("State", "state"),
("Task ID", "task_id"),
("Creation Date", "creation_date"),
("Co... |
4821063 | import os
from random import randint
import json
import time
import requests
import vk
# Настройки
with open('keys.json', 'r') as file:
VK_API_ACCESS_TOKEN = json.loads(file.read())['vk']['token']
with open('sets.json', 'r') as file:
GROUP_ID = json.loads(file.read())['vk']['group']
VK_API_VERSION = '5.95'
se... |
4821075 | version_info = (2, 0, 3)
version = '.'.join(str(n) for n in version_info[:3])
release = version + ''.join(str(n) for n in version_info[3:])
|
4821098 | import numpy as np
from scipy import stats
## function to simulate data and perform a t.test
def sim_ttest(mu1, mu2, sd, n1, n2):
x = stats.norm.rvs(loc = mu1, scale = sd, size = n1)
y = stats.norm.rvs(loc = mu2, scale = sd, size = n2)
return(stats.ttest_ind(x, y)[1])
## run the function 10,000 times
nsi... |
4821101 | import json
import logging
import os
# Get environment variables
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
# Configure logging
logger = logging.getLogger()
logger.setLevel(LOG_LEVEL)
def remove_policy(input_path: str, output_path: str):
"""Remove all IAM policies from a CloudFormation json template
... |
4821112 | import re
import logging
import Levenshtein
from functools import cache
from banal import ensure_list
from datetime import datetime
from itertools import combinations
from collections import defaultdict
from typing import Any, Dict, List, Optional, Tuple
from normality import latinize_text, stringify, slugify
log = lo... |
4821135 | from typing import List, Union, Dict
from ordered_set import OrderedSet
from modelindex.models.BaseModelIndex import BaseModelIndex
from modelindex.models.Result import Result
from modelindex.utils import full_filepath, load_any_file, lowercase_keys
class ResultList(BaseModelIndex):
"""ResultList is a list of R... |
4821199 | import sabre
class CustomReplacement(sabre.Replacement):
def check_replace(self, quality):
buffer = self.session.get_buffer_contents()
for i in range(2, len(buffer)):
if buffer[i] < quality:
# return -ve index from end of buffer
return i - len(buffer)
... |
4821243 | from . import BaseAnnotationDefinition
class Text(BaseAnnotationDefinition):
"""
can create a text annotation having two types (paragraph, block)
"""
type = "text_mark"
def __init__(self, text_type, start, end, label,
top=None, left=None, attributes=None, description=None):
... |
4821260 | from .checker import SetCookieChecker
from .notsecure import CookieNotSecureChecker
from .nothttponly import CookieNotHttpOnlyChecker
__all__ = ['SetCookieChecker','CookieNotSecureChecker', 'CookieNotHttpOnlyChecker']
|
4821275 | from layers import *
import tensorflow as tf
from tensorflow.contrib.distributions import RelaxedBernoulli
import numpy as np
digamma = tf.digamma
from digamma import digamma_approx as digamma_approx
lgamma = tf.lgamma
Euler = 0.577215664901532
def bbdropout(x, training,
alpha=1e-4, thres=1e-2, a_init=-1., ta... |
4821521 | import argparse
import csv
import sys
import time
import pyperclip
import scrapers
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise ... |
4821539 | import numpy as np
import tensorflow as tf
from .simple_replay_memory import SimpleDataSet
# util is used for AE
from .util import conv2d, linear
from ..base import BaseModel
from functools import reduce
from ..utils import onehot_actions
class AutoEncoder(BaseModel):
def __init__(self, name, sess, config):
... |
4821584 | import torch
import torch.nn.functional as F
from torch.autograd import Variable
from utils.utils import AverageMeter
import torchvision.utils as vutils
import numpy as np
import random
from datasets.transforms import normalize
def mix_data(x, use_cuda=True, prob=0.6):
'''Returns mixed inputs, pairs of targets, a... |
4821822 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import GradientBoostingRegressor
import sklearn
from sklearn.ensemble.gradient_boosting import LOSS_FUNCTIONS
X = np.array([1,2,3,4,8,9,10,11,15,16,17,18]).reshape(12,1)
Y = np.array([1,1,10,2,-4,-5,-10,-3,0,1,-1,5])
#Y = np.array([0,0,0,1,1,0,0,... |
4821866 | if __name__ == '__main__':
# print(ord("ß"))
# Thanks to https://stackoverflow.com/questions/319426/how-do-i-do-a-case-insensitive-string-comparison
# for i in range(0, 0x110000):
# ch = chr(i).upper()
# if "FLAG".find(ch) > -1:
# print(i, chr(i), ch)
# print("GG!!!!!... |
4821873 | import time
from utils.common.setup_helper import lprint
from utils.eval.localize import *
def eval_prediction(data_loaders, net, log, pair_type='ess'):
'''The function evaluates network predictions and prepare results for RANSAC and convenient accuracy calculation.
Args:
- data_loaders: a dict of data... |
4821875 | from datetime import datetime, timedelta
from .apitask import APITask
from evething import local_settings
from thing.models import ESIToken
from thing.tasks.esi import ESI_CharacterInfo
class ESI_CharacterUpdateSpawner(APITask):
name = "thing.esi.character_update_spawner"
def run(self):
... |
4821881 | from ._disjoint import DisjointSet
from ._comparator import Comparator
__all__ = [
"DisjointSet",
"Comparator"
]
|
4821896 | import cv2
import numpy as np
import os
def deprocess_image(x):
x = np.array(x)
x[..., 0] += 103.939
x[..., 1] += 116.779
x[..., 2] += 123.68
return x.astype(np.uint8)
def is_image(name):
return '.jpg' in name or '.png' in name
class FolderVideoReader:
def __init__(self, path):
... |
4821911 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import constant_op
from tensorflow.python.platform import test
from self_driving.segnet import evaluate
import tensorflow as tf
class EvaluateTest(test.TestCase):
def tes... |
4822025 | import sys
import os
from goatools.obo_parser import GODag
ROOT = os.path.dirname(os.path.abspath(__file__)) + "/data/"
def print_paths(paths, PRT=sys.stdout):
for path in paths:
PRT.write('\n')
for GO in path:
PRT.write('{}\n'.format(GO))
def chk_results(actual_paths, expected_path... |
4822026 | from __future__ import absolute_import, division, print_function
import os
import numpy as np
import h5py as h5
import re
import json
from glob import glob
from tqdm import trange
import shutil
import time
from multiprocessing import Process, Queue, current_process, freeze_support
class Frame(object):
pass
cl... |
4822036 | import models.net as net
import models.iadam_attention as iadam_attention
import bin.train_and_evaluate as train
# configure
# data_small.pkl is the small data for debugging purpose (10K training instances for UDC)
# data.pkl is the whole data (1M training instances for UDC)
conf = {
"data_name": "udc",
"d... |
4822051 | from deepfool import deepfool
import os
import numpy as np
import torch
from torch.utils.data import DataLoader
from PIL import Image
import torch.backends.cudnn as cudnn
import sys
from transform_file import transform, cut, convert
from targetmodel import MyDataset
def project_lp(v, xi, p):
if p==2:
pass... |
4822077 | import random
from pathlib import Path
from typing import Tuple
import glob
import numpy as np
import cv2
import torch
from torch.utils.data import Dataset
import torchvision.transforms as transforms
import torchvision.transforms.functional as TF
from ganslate.utils.io import make_dataset_of_files
# Config imports
f... |
4822114 | import json
import os.path
from unittest import skipIf
from samcli.lib.utils.resources import AWS_LAMBDA_FUNCTION
from tests.integration.sync.test_sync_code import TestSyncCodeBase, SKIP_SYNC_TESTS, TestSyncCode
from tests.integration.sync.test_sync_watch import TestSyncWatchBase
from tests.testing_utils import run_co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.