id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
163971 | import mock
import yaml
from boto3.session import Session
from botocore.exceptions import ClientError
from botocore.exceptions import NoCredentialsError
from botocore.exceptions import NoRegionError
from botocore.exceptions import EndpointConnectionError
from st2tests.base import BaseSensorTestCase
from sqs_sensor im... |
163985 | import os
import tqdm
import logging
import torch
import torch.nn as nn
from torch import optim
from torch.utils.data import DataLoader, TensorDataset
from transformers import BertTokenizer
from agents.utils import Statistics
from agents.optim_schedule import ScheduledOptim
from .soft_masked_bert import SoftMaskedBer... |
163992 | import unittest
import os
from thunderbolt.client.local_directory_client import LocalDirectoryClient
class TestLocalDirectoryClient(unittest.TestCase):
def setUp(self):
self.client = LocalDirectoryClient('.', None, None, use_cache=False)
def test_to_absolute_path(self):
source = './hoge/hoge/... |
164029 | r"""
Manifold Subsets Defined as Pullbacks of Subsets under Continuous Maps
"""
# ****************************************************************************
# Copyright (C) 2021 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Pu... |
164030 | import functools
from btypes.big_endian import *
import gx
from j3d.material import *
import j3d.string_table
import logging
logger = logging.getLogger(__name__)
index8 = NoneableConverter(uint8,0xFF)
index16 = NoneableConverter(uint16,0xFFFF)
class Header(Struct):
magic = ByteString(4)
section_size = uint3... |
164031 | from itertools import chain
from uuid import uuid4
from django.db.models.signals import post_save, pre_save
from main import models as edd_models
from . import models
def campaign_check(sender, instance, raw, using, **kwargs):
# make sure there is a UUID set
if instance.uuid is None:
instance.uuid ... |
164035 | import util as u
import re
import StringIO
def get_reg(invoke_param):
"""Return the parameter registry list"""
if invoke_param == '':
return
reg_list = re.finditer(r'(v|p)\d{1,3}', invoke_param)
for reg_value in reg_list:
yield reg_value.group()
def is_range(invoke_type):
"""Rang... |
164053 | from behave import given, when, then
from pages.dashboard import dashboard
@then(u'Dashboard Status shows correct values for row "{row}"')
def step_impl_dashboard_status(context, row):
dashboard.verify_status(row)
@then(u'Clicking on Status Refresh should refresh status component')
def step_impl_status_refresh(... |
164054 | from unittest import IsolatedAsyncioTestCase
events = []
class Test(IsolatedAsyncioTestCase):
def setUp(self):
events.append("setUp")
async def asyncSetUp(self):
self._async_connection = await AsyncConnection()
events.append("asyncSetUp")
async def test_response(self):
... |
164062 | from dask.distributed import Client
import dask.array as da
import dask_ml
import dask_bigquery
import numpy as np
client = Client("localhost:8786")
x = da.sum(np.ones(5))
x.compute()
|
164063 | from datequarter import DateQuarter
if __name__ == "__main__":
quarter1 = DateQuarter(2019, 1)
quarter2 = DateQuarter(2018, 4)
print(list(DateQuarter.between(quarter1, quarter2)))
|
164074 | import uuid
from djongo import models
from node.blockchain.inner_models import Block as PydanticBlock
from node.core.models import CustomModel
class PendingBlock(CustomModel):
_id = models.UUIDField(primary_key=True, default=uuid.uuid4)
number = models.PositiveBigIntegerField()
hash = models.CharField(... |
164118 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^upload/$', views.ImageUploadView.as_view(), name='upload'),
url(r'^md2html/$', views.MarkdownToHTML.as_view(), name='md2html'),
]
|
164120 | from pylagrit import PyLaGriT
import numpy
x = numpy.arange(0,10.1,1)
y = x
z = [0,1]
lg = PyLaGriT()
mqua = lg.gridder(x,y,z,elem_type='hex',connect=True)
mqua.rotateln([mqua.xmin-0.1,0,0],[mqua.xmax+0.1,0,0],25)
mqua.dump_exo('rotated.exo')
mqua.dump_ats_xml('rotated.xml','rotated.exo')
mqua.paraview()
|
164128 | import os
import datetime
from typing import Dict, Optional, Any, List
from markdown_subtemplate import caching as __caching
from markdown_subtemplate.infrastructure import markdown_transformer
from markdown_subtemplate.exceptions import ArgumentExpectedException, TemplateNotFoundException
from markdown_subtemplate im... |
164143 | from .statistics_diff import (
SmoothFRStatistic, SmoothKNNStatistic, MMDStatistic, EnergyStatistic)
from .statistics_nondiff import FRStatistic, KNNStatistic
__all__ = ['SmoothFRStatistic', 'SmoothKNNStatistic', 'MMDStatistic',
'EnergyStatistic', 'FRStatistic', 'KNNStatistic']
|
164184 | import os, argparse, cPickle
from shutil import copyfile
import numpy as np
import cPickle
from nibabel import load as load_nii
import nibabel as nib
from scipy import ndimage
from nolearn.lasagne import NeuralNet, BatchIterator, TrainSplit
from nolearn_utils.hooks import SaveTrainingHistory, PlotTrainingHistory, Early... |
164214 | import argparse
from unittest import TestCase
import pytest
from pytorch_lightning import Trainer
from pl_bolts.models.rl.double_dqn_model import DoubleDQN
from pl_bolts.models.rl.dqn_model import DQN
from pl_bolts.models.rl.dueling_dqn_model import DuelingDQN
from pl_bolts.models.rl.noisy_dqn_model import NoisyDQN
f... |
164219 | from django.conf import settings
from rest_framework.authentication import TokenAuthentication
from rest_framework.authtoken.models import Token
from rest_framework.exceptions import AuthenticationFailed
from datetime import timedelta
from django.utils import timezone
# this return left time
def expires_at(token):
... |
164253 | import numpy as np
class RunningScore(object):
def __init__(self, n_classes):
self.n_classes = n_classes
self.confusion_matrix = np.zeros((n_classes, n_classes))
@staticmethod
def _fast_hist(label_true, label_pred, n_class):
mask = (label_true >= 0) & (label_true < n_class)
... |
164259 | import h2o
from h2o.exceptions import H2OResponseError
from tests import pyunit_utils
import tempfile
from collections import OrderedDict
from h2o.grid.grid_search import H2OGridSearch
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def test_frame_reload():
work_dir = tempfile.mkdtemp()
iris = h2o... |
164288 | from tests.util import match_object_snapshot
from tests.analyzer.util import analyze
input = """
list:
- value
- value
- value
- value
- value
""".strip()
def test_list_item_analysis():
analysis = analyze(input)
assert match_object_snapshot(analysis, 'tests/analyzer/snapshots/list_item_analysis... |
164291 | from contextlib import contextmanager
import logging
from pkg_resources import parse_version
import sys
import time
from pykafka.exceptions import RdKafkaStoppedException, ConsumerStoppedException
from pykafka.simpleconsumer import SimpleConsumer, OffsetType
from pykafka.utils.compat import get_bytes
from pykafka.util... |
164314 | import sys
import subprocess
import commands
import os
import six
import copy
import argparse
import time
from utils.stream import stream_by_running as get_stream_m
from utils.args import ArgumentGroup, print_arguments, inv_arguments
from finetune_args import parser as finetuning_parser
from extend_pos import extend_w... |
164387 | from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
APP = ['src/clippy.py']
DATA_FILES = []
OPTIONS = {
'iconfile': 'clipboard.icns'
}
setup(
name="clippy",
version="0.0.1",
author="<NAME>",
author_email="<EMAIL>",
description="Clipboard manager us... |
164432 | from geode.vector import *
from numpy import *
def test_register():
random.seed(217301)
for _ in xrange(10):
for d in 2,3:
X0 = random.randn(10,d)
t = random.randn(d)
A = random.randn(d,d)
r,_ = linalg.qr(A)
if linalg.det(r)<0:
r[0] = -r[0]
X1 = t + Matrix(r)*X0
... |
164451 | def helper(N):
if (N <= 2):
print ("NO")
return
value = (N * (N + 1)) // 2
if(value%2==1):
print ("NO")
return
s1 = []
s2 = []
if (N%2==0):
shift = True
start = 1
last = N
while (start < last):
if (shift):
... |
164459 | from collections import namedtuple
import xml.etree.ElementTree as ET
OPERA_TIMESTAMP_FORMAT = "%Y%m%dT%H:%M:%S"
def parse_receipts_xml(receipt_xml_data):
tree = ET.fromstring(receipt_xml_data)
return map(receipt_to_namedtuple, tree.findall('receipt'))
def receipt_element_to_dict(element):
"""
Turn... |
164471 | from typing import Any, Callable, List, Optional, Sequence, Type, TypeVar, Union
from visions.relations import IdentityRelation, InferenceRelation
from visions.types.type import VisionsBaseType
T = TypeVar("T")
def process_relation(items: Union[dict, Type[VisionsBaseType]]) -> IdentityRelation:
if isinstance(it... |
164476 | from typing import Tuple, Union
from Crypto.Cipher.AES import MODE_ECB
from Crypto.Cipher.AES import new as new_aes_ctx
from Crypto.Cipher.PKCS1_OAEP import new as new_pkcs1_oaep_ctx
from Crypto.Hash import SHA256
from Crypto.PublicKey.RSA import import_key as import_rsa_key
from enum import IntEnum
from json import du... |
164533 | import io
import re
from rich.console import Console, RenderableType
from rich.__main__ import make_test_card
from ._card_render import expected
re_link_ids = re.compile(r"id=[\d\.\-]*?;.*?\x1b")
def replace_link_ids(render: str) -> str:
"""Link IDs have a random ID and system path which is a problem for
r... |
164563 | from setuptools import setup
from pppd import __version__ as version
def long_description():
description = open('README.rst').read()
try:
description += '\n\n' + open('CHANGELOG.rst').read()
except:
pass
return description
setup(
name='python-pppd',
version=version,
url='h... |
164588 | from openpyxl import load_workbook
xlsx_file = "E:\\hello-git-sourcetree\\R_GO\\Python_RPA\\"
xlsx = load_workbook(xlsx_file+"result.xlsx", read_only =True)
sheet=xlsx.active
print(sheet['A25'].value)
print(sheet['B1'].value)
row = sheet['1']
for data in row:
print(data.value)
xlsx=load_workbook(xlsx_file+"resu... |
164612 | from rest_framework import serializers
from .models import Notification
from users.serializers import UserProfileSerializer
from feed.serializers import MumbleSerializer
from article.serializers import ArticleSerializer
from discussion.serializers import DiscussionSerializer
class NotificationSerializer(serializers.M... |
164623 | import sqlite3
conexion = sqlite3.connect('RandUser.db')
cursor = conexion.cursor()
cursor.execute('''
CREATE TABLE Users(
Gender TEXT NOT NULL,
First TEXT NOT NULL,
Last TEXT NOT NULL,
Location TEXT NOT NULL,
Email TEXT NOT NULL)
''')
conexion.close()
|
164638 | import os
import glob
import random
import numpy as np
import torchaudio as T
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.distributed import DistributedSampler
def create_dataloader(params, train, is_distributed=False):
dataset = AudioDataset(params, train)
return DataLoader(
... |
164759 | import logging
import math
logging.basicConfig(level=logging.DEBUG,
handlers=[logging.FileHandler('logs.log', 'a', 'utf-8')],
format="%(asctime)s %(levelname)-6s - %(funcName)-8s - %(filename)s - %(lineno)-3d - %(message)s",
datefmt="[%Y-%m-%d] %H:%M:%S - ",
... |
164770 | from typing import Any, Mapping, Optional, Union
import copy
import os
import re
import yaml
from machinable.errors import ConfigurationError
from machinable.utils import sentinel, unflatten_dict, update_dict
class Loader(yaml.SafeLoader):
def __init__(self, stream, cwd="./"):
if isinstance(stream, str)... |
164790 | import time
import numpy as np
from PIL import Image as pil_image
from keras.preprocessing.image import save_img
from keras import layers
from keras.applications import vgg16
from keras import backend as K
import matplotlib.pyplot as plt
def normalize(x):
"""utility function to normalize a tensor.
# Argument... |
164869 | TASKS = {
"binary_classification": 1,
"multi_class_classification": 2,
"entity_extraction": 4,
"extractive_question_answering": 5,
"summarization": 8,
"single_column_regression": 10,
"speech_recognition": 11,
}
DATASETS_TASKS = ["text-classification", "question-answering-extractive"]
|
164913 | from pudzu.charts import *
from pudzu.sandbox.bamboo import *
df = pd.read_csv("datasets/flagsfictional.csv")
data = pd.DataFrame(list(generate_batches([dict(row) for _,row in df.iterrows()], 3)))
fg, bg="black", "#EEEEEE"
default_img = "https://s-media-cache-ak0.pinimg.com/736x/0d/36/e7/0d36e7a476b06333d9fe9960... |
164923 | from a10sdk.common.A10BaseClass import A10BaseClass
class RoleList(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param role: {"description": "Role in a given partition", "format": "string", "minLength": 1, "maxLength": 32, "type": "string", "$ref": "/axapi/v3/rba/role... |
164941 | from pathlib import Path
# set home dir for default
HOME_DIR = str(Path.home())
DEFAULT_MODEL_DIR = os.path.join(HOME_DIR,'arabicnlp_models')
|
164954 | from fabric.colors import green as _green, yellow as _yellow, red as _red
from settings import cloud_connections, DEFAULT_PROVIDER
from ghost_log import log
from ghost_tools import get_aws_connection_data
from libs.blue_green import get_blue_green_from_app
from libs.ec2 import create_ec2_instance
COMMAND_DESCRIPTION... |
164968 | import json
from shared import get_session_for_account, send_notification
from policyuniverse.policy import Policy
def audit(resource, remediate=False):
is_compliant = True
if resource["type"] != "sqs":
raise Exception(
"Mismatched type. Expected {} but received {}".format(
... |
164979 | import numpy as np
#I'm dumb, so I'm reducing the problem to 2D so I can see what's happening
##Make fake data
# an N x 5 array containing a regular mesh representing the stimulus params
stim_params=np.mgrid[10:25,20:22].reshape(2,-1).T
# an N x 3 array representing the output values for each simulation run
stimnum=... |
164988 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^list/$', views.targets_listing, name='crits-targets-views-targets_listing'),
url(r'^list/(?P<option>\S+)/$', views.targets_listing, name='crits-targets-views-targets_listing'),
url(r'^divisions/list/$', views.divisions_listing, na... |
164993 | import sys
import os
import json
import copy
import multiprocessing
if len(sys.argv) < 5:
print "Usage: python grid_search.py [model_template_file] [parameters_config] [process_number] [run_dir]"
model_tpl_file = sys.argv[1]
param_conf_file = sys.argv[2]
proc_num = int(sys.argv[3])
run_dir = sys.argv[4]
if not o... |
165009 | import jellyfish
import time
from difflib import SequenceMatcher
def getStringSimilarity(s1, s2):
return jellyfish.jaro_winkler(s1, s2)
def getStringsimilarity_difflib(s1,s2):
return SequenceMatcher(None, s1, s2).ratio()
def getInputData(path):
fin = open(path, "r", encoding="utf8")
data = []
... |
165064 | import os
import tensorflow as tf
from functools import partial
from random import shuffle
def _get_shard_dataset(record_path, split='train'):
pattern = os.path.join(record_path, split + "*")
files = tf.data.Dataset.list_files(pattern)
return files
def _decode_jpeg(image_buffer, size, scope=None):
w... |
165068 | from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from botocore.paginate import Paginator
from botocore.waiter import Waiter
from typing import Union
from typing import List
class Client(BaseClient):
def associate_node(self, ServerName: str, NodeName: str, EngineAttributes... |
165079 | from django.core.management.base import BaseCommand
from django_q.models import Schedule
class Command(BaseCommand):
help = "Setups up all background tasks"
def handle(self, *args, **options):
Schedule.objects.get_or_create(
func='news.tasks.get_news',
schedule_type='D',
... |
165094 | from django.apps import AppConfig
class ApiConfig(AppConfig):
name = 'series_tiempo_ar_api.apps.api'
|
165123 | from datetime import datetime, date
from django.urls import reverse
from django.contrib.gis.geos import Point
from rest_framework.test import APITestCase
from rest_framework import status
from robber import expect
import pytz
from data.factories import PoliceUnitFactory, OfficerFactory, OfficerHistoryFactory, Office... |
165134 | from . import metadata
from .client import ServiceClient
from .constants import DEFAULT_HOSTNAME, DEFAULT_PROTOCOL
def login(token: str, hostname: str = DEFAULT_HOSTNAME, protocol: str = DEFAULT_PROTOCOL, verify: bool = True) -> str:
"""Make a login request to SaaS."""
client = ServiceClient(f"{protocol}://{h... |
165143 | from odoo.tests.common import TransactionCase
class TestProductTemplate(TransactionCase):
def test_name_search(self):
partner = self.env['res.partner'].create({
'name': 'Azure Interior',
})
seller = self.env['product.supplierinfo'].create({
'name': partner.id,
'price': 1... |
165146 | import os
import shutil
import subprocess
import time
from bw_plex import LOG
TYPES = {'cut': 0,
'mute': 1,
'scene marker': 2,
'commercial break': 3}
TYPES.update(dict((v, k) for (k, v) in TYPES.items()))
def db_to_edl(item, type=3):
elds = {}
if (item.correct_theme_start and
... |
165167 | import imp
import sys
def new_module(name):
"""
Do all of the gruntwork associated with creating a new module.
"""
parent = None
if '.' in name:
parent_name = name.rsplit('.', 1)[0]
parent = __import__(parent_name, fromlist=[''])
module = imp.new_module(name)
sys.modules[... |
165201 | import asyncio
import logging
from collections import deque
from contextlib import asynccontextmanager
from functools import wraps
logger = logging.getLogger(__name__)
class AcurlSessionWrapper:
def __init__(self, session):
self.__session = session
self.__callback = None
self.additional_m... |
165241 | from unittest import TestCase
from dexpy.simplex_centroid import build_simplex_centroid
from dexpy.eval import det_xtxi
from dexpy.model import make_quadratic_model
import numpy as np
import patsy
class TestSimplexCentroid(TestCase):
@classmethod
def test_d_optimality(cls):
answer_d = [ 2.513455e3, 2.... |
165271 | from django.test import TestCase, override_settings
from hunts.models import Hunt
from puzzles.models import Puzzle
from .models import ChatRoom
from .service import ChatService
from .fake_service import FakeChatService
@override_settings(
CHAT_DEFAULT_SERVICE="DEFAULT",
CHAT_SERVICES={
"DEFAULT": Cha... |
165291 | import pytest
from simple_zpl2 import ZPLDocument
def test_comment():
zdoc = ZPLDocument()
zdoc.add_comment('Testing Comment')
assert zdoc.zpl_bytes == b'^XA\n^FXTesting Comment^FS\n^XZ'
|
165292 | import numpy as np
import time
from multiprocessing import Pool, cpu_count
import sys
sys.path.append('..')
from numpyVectorization.motion_gauss import simulateParticles_loop
# How do we pass multiple arguments via pool? Use wrapper functions! Note:
# lambda functions will NOT work for this purpose
def wrapper_fun(ar... |
165317 | import dash_core_components as dcc
import dash_html_components as html
from dash_docs import styles
from dash_docs import reusable_components as rc
layout = html.Div(children=[
rc.Markdown('''
# Deploying Dash Apps
By default, Dash apps run on `localhost` - you can only access them on your
own machine... |
165354 | import numpy as np
import pyCubbyFlow
from pytest import approx
from pytest_utils import *
cnt = 0
def test_grid2():
global cnt
a = pyCubbyFlow.VertexCenteredScalarGrid2(resolution=(3, 4),
gridSpacing=(1, 2),
gridOr... |
165379 | import random
import scipy
import numpy as np
import h5py
class DataLoader(object):
def __init__(self, cfg):
self.cfg = cfg
self.augment = cfg.data_augment
def get_data(self, mode='train'):
h5f = h5py.File('./classification/DataLoaders/mnist_background.h5', 'r')
self.x_test = ... |
165403 | from django.views import View
from django import http
from uxhelpers.utils import json_response
import json
import logging
logger = logging.getLogger(__name__)
LEVELS = {
'CRITICAL': 50,
'ERROR': 40,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0
}
class LogPostView(View):
def pos... |
165419 | from django.contrib import admin
from .models import Article
from .models import Tag
from .models import Author
from .models import Affiliation
# Register your models here.
admin.site.register(Article)
admin.site.register(Tag)
admin.site.register(Author)
admin.site.register(Affiliation)
|
165433 | import base64
from django.http import HttpResponse
from django.test import TestCase
from django.test.client import RequestFactory
from django.test.utils import override_settings
from regcore_write.views import security
def _wrapped_fn(request):
return HttpResponse(status=204)
def _encode(username, password):
... |
165455 | from kango.buildsteps import BuildStepBase
class BuildStep(BuildStepBase):
def pre_pack(self, output_path, project_path, info, args):
pass
|
165495 | import itertools
from typing import Any
from typing import Dict
from typing import Optional
from typing import Union
import dask.dataframe as dd
import holoviews as hv
import numpy as np
import pandas as pd
from bokeh.models import HoverTool
from sid.colors import get_colors
from sid.policies import compute_pseudo_eff... |
165519 | import os.path as op
import inspect
__all__ = ["get_fname", "with_name"]
def get_fname(subses_dict, suffix,
tracking_params=None, segmentation_params=None):
split_fdwi = op.split(subses_dict["dwi_file"])
fname = op.join(subses_dict["results_dir"], split_fdwi[1].split('.')[0])
if tracking_p... |
165528 | from django.conf.urls.defaults import *
urlpatterns = patterns('wouso.games.quiz.views',
url(r'^$', 'index', name='quiz_index_view'),
url(r'^cat/(?P<id>\d+)/$', 'category', name='quiz_category_view'),
url(r'^(?P<id>\d+)/$', 'quiz', name='quiz_view'),
)
|
165545 | from settings_local import (
BITCOIND_TEST_MODE,
BITCOIND_RPC_USERNAME,
BITCOIND_RPC_PASSWORD,
BITCOIND_RPC_PORT,
BITCOIND_RPC_HOST,
BITCOIND_TEST_RPC_USERNAME,
BITCOIND_TEST_RPC_PASSWORD,
BITCOIND_TEST_RPC_HOST,
BITCOIND_TEST_RPC_PORT,
ORACLE_ADDRESS,
ORGANIZATION_ADDRESS,
... |
165571 | import numpy as np
import random
import tensorflow as tf
import matplotlib.pyplot as plt
from AirSimClient import *
import sys
import time
import random
import msvcrt
np.set_printoptions(threshold=np.nan)
# if true, use Q-learning. Else, use SARSA
qlearning = True
readWeights = True # read in saved weights to resume ... |
165578 | class HtmlWriter():
def __init__(self, filename):
self.filename = filename
self.html_file = open(self.filename, 'w')
self.html_file.write(
"""<!DOCTYPE html>\n""" + \
"""<html>\n<body>\n<table border="1" style="width:100%"> \n""")
def add_element(self, co... |
165591 | from .ini_reader import INIReader
from .. import config_validator
from pagewalker.utilities import error_utils
from pagewalker.config import config
class CookiesConfigParser(INIReader):
def __init__(self):
super(CookiesConfigParser, self).__init__(config.custom_cookies_file)
self.config_types = co... |
165601 | from torch.cuda.amp import GradScaler
from utils.loss_accumulator import LossAccumulator
from torch.nn import Module
import logging
from trainer.losses import create_loss
import torch
from collections import OrderedDict
from trainer.inject import create_injector
from utils.util import recursively_detach, opt_get
logg... |
165629 | import os
from platform import node
from app.project_type.project_type import ProjectType
from app.util.conf.configuration import Configuration
from app.util.log import get_logger
class Directory(ProjectType):
"""
Example API call to invoke a directory-type build.
{
"type": "directory",
"... |
165639 | import logging.handlers
import os.path
from popupdict.gtk import GLib
logger = logging.getLogger('popupdict')
formatter = logging.Formatter('[%(asctime)s.%(msecs)03d] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(... |
165667 | from django.contrib.auth import models as auth_models
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
class BaseUserManager(auth_models.BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise Value... |
165701 | import tensorflow as tf
import numpy as np
from keras import backend as K
from keras.models import Sequential, model_from_json
from keras.layers import Lambda
from tensorflow.python.framework import ops
from scipy.ndimage.interpolation import zoom
import keras
import tempfile
import os
def loss_calculation(x, categor... |
165727 | from pyunicorn.timeseries import RecurrencePlot
import numpy as np
from statistics import median
import time
# Measure the times (in ms) of evaluating an expression n times
def measuretime(f, n, *args):
t = [0]*n
res = f(*args)
for n in range(n):
t0 = time.time()
f(*args)
t[n] = tim... |
165753 | class MyClass():
"This is my second class"
a = 10
def func(self):
print('Hello')
# create a new MyClass
ob = MyClass()
class Model(BaseModel):
age: int,
first_name = 'John'
last_name: NoneStr = None
signup_ts: Options[datetime] = None
list_of_ints: List[int]
class Addition:
... |
165825 | import re
from flask import abort
from .validation import get_validation_errors
def validate_framework_agreement_details_data(framework_agreement_details, enforce_required=True, required_fields=None):
errs = get_validation_errors(
'framework-agreement-details',
framework_agreement_details,
... |
165874 | import torch
import ipdb
from copy import deepcopy
import random
def modify_sentence(ids, min_change=2, prob=0.1, k=2):
def _random_deletion(rids):
num_deletion = max(min_change, int(prob*len(rids)))
delete_idx = random.sample(range(len(rids)), num_deletion)
n_ids = [rids[i] for i in range... |
165893 | DOCUMENT_MAPPING = [
{
'name': 'title',
'pattern': '<{}> dc:title|rdfs:label ?title .',
'type': 'string'
},
{
'name': 'journalTitle',
'pattern': """?journal vivo:publicationVenueFor <{}> ;
rdfs:label ?journalTitle .""",
'type':... |
165917 | import os
def prepare_videos(
videos, extension, start, duration, kinect_mask=True, width=1920, height=1080
):
video_start_secs = start % 60
video_start_mins = start // 60
print(f"Dumping frames and segmenting {len(videos)} input videos")
for i, video in enumerate(videos):
try:
... |
165925 | from collections import defaultdict
class Graph:
def __init__(self,V,directed=False):
self.V = V
self.directed = directed
self.graph = defaultdict(list)
def add_edge(self,a,b):
self.graph[a].append(b)
if not self.directed:
self.graph[b].append(a)
def color_greedy(self):
result = [-1]*self.V
... |
165947 | import contextlib
from typing import Any, Dict, Iterable, Optional
import discord
import iso8601
import validators
from redbot.core import commands
from redbot.vendored.discord.ext import menus
class GenericMenu(menus.MenuPages, inherit_buttons=False):
def __init__(
self,
source: menus.PageSource... |
165975 | from inspect import getfullargspec
from typing import Union, List, Optional
import operator
from collections import namedtuple
Patch = namedtuple('Patch', ['var'])
match_err = object()
class Pattern:
def match(self, expr):
raise NotImplemented
def __repr__(self):
return self.__str__()
cl... |
165977 | import logging
from ledfxcontroller.devices import Device
import voluptuous as vol
import numpy as np
import sacn
import time
_LOGGER = logging.getLogger(__name__)
class E131Device(Device):
"""E1.31 device support"""
CONFIG_SCHEMA = vol.Schema({
vol.Required('host'): str,
vol.Required('univer... |
166010 | n = int(raw_input())
data = [int(i) for i in raw_input().split()]
data = sorted(data)
ans = 0
for i in xrange(0, n, 2):
if data[i] != data[i + 1]:
print str(data[i]),
i -= 1
ans += 1
if ans != 2:
print str(data[n-1]) + " ",
|
166026 | from datetime import datetime, timezone
import json
import falcon
from sikr import settings
class APIInfo(object):
"""Show the main information about the API like endpoints, version, etc.
"""
def on_get(self, req, res):
payload = {
"version": {
"api_version": settin... |
166028 | import os
import time
import datetime
import tensorflow as tf
from PIL import Image
import numpy as np
import argparse
import json
from util import *
# parse args
argParser = argparse.ArgumentParser(description="runs validation and visualizations")
argParser.add_argument("-f",dest="showFlow",action="store_true")
argP... |
166034 | from os import path
from queue import Queue
from sys import stderr
from threading import Thread
from time import sleep
from typing import Callable, List, NamedTuple, Optional, Sequence, Text
from psutil import AccessDenied, NoSuchProcess, Popen, Process
from psutil._pslinux import popenfile
from .progress import Outp... |
166073 | from flask_login import current_user
from depc.controllers.teams import TeamController
class TeamPermission:
@classmethod
def _get_team(cls, team_id):
obj = TeamController._get(filters={"Team": {"id": team_id}})
# Add the members of the team
team = TeamController.resource_to_dict(obj... |
166103 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst', 'r') as f:
long_description = f.read()
setup(name='PyGnuplot',
py_modules=['PyGnuplot'],
version='0.11.16',
license='MIT',
description='Python Gnuplot wrapper',
long... |
166214 | import unittest
import qnet
import qnetu
import numpy
import mytime
import netutils
import estimation
import yaml
import StringIO
import pwfun
import distributions
import sampling
import arrivals
import qstats
import queues
import test_qnet
from scipy import integrate
from numpy import random
import arrivals
import... |
166230 | import torch
from torch import nn
from torch.nn import functional as F
import math
class Network(nn.Module):
def __init__(self, num_actions, image_channels, vec_size, cnn_module, hidden_size=256,
dueling=True, double_channels=False):
super().__init__()
self.num_actions = num_ac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.