filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_0_2209 | from datetime import datetime
from utils.api import fetch_events
class Events:
def __init__(self):
self.items = []
def fetch(self, params):
self.items = []
params['pageToken'] = None
while True:
events = fetch_events(params)
if events and events.get('items'):
self.items.ex... |
the-stack_0_2211 | # globalprogramlib GUI example by PWRScript
# Import necessary libs
import tkinter
from globalprogramlib.v1 import Language, Translator
class App(tkinter.Tk):
def __init__(self, translator: Translator, *args, **kwargs) -> None:
"""
This class will take care of creating our application
Thi... |
the-stack_0_2213 | import matplotlib.pyplot as plt #import the library, any procedures with plt.* come form this lib
import numpy as np #imports numpy for standard deviation
trials = []
for i in range(1,31):
trials.append(i) #sets up the X axis
#Y axis
data = [2.5105, 2.5100, 2.5103, 2.5091, 2.5101, 2.5101, 2.5103, 2.5098, 2.5098, 2... |
the-stack_0_2214 | from astropy.time import Time
__all__ = [
"_checkTime"
]
def _checkTime(time, arg_name):
"""
Check that 'time' is an astropy time object, if not, raise an error.
Parameters
----------
time : `~astropy.time.core.Time`
arg_name : str
Name of argument in function.
Returns
-... |
the-stack_0_2215 | import datetime
from rest_framework import permissions, status
from rest_framework.decorators import (api_view,
authentication_classes,
permission_classes,
throttle_classes,)
from django.db.models.expr... |
the-stack_0_2216 | from concurrent.futures import ThreadPoolExecutor, as_completed
from time import time
import boto3
from botocore import UNSIGNED
from botocore.config import Config
from botocore.exceptions import ClientError
from .start_lambda_api_integ_base import StartLambdaIntegBaseClass
class TestParallelRequests(StartLambdaInt... |
the-stack_0_2217 | import asyncio
import time
def timed(fn, *args, **kwargs):
name = fn.__name__
times = []
last = before = time.time()
duration = 0
while duration < 1.0:
if asyncio.iscoroutinefunction(fn):
asyncio.run(fn(*args, **kwargs))
else:
fn(*args, **kwargs)
no... |
the-stack_0_2220 | import pytest
import math
import numpy as np
from pandas import read_table, DataFrame, Series
from catboost import Pool, CatBoost, CatBoostClassifier, CatBoostRegressor, CatboostError, cv
from catboost_pytest_lib import data_file, local_canonical_file, remove_time_from_json
import yatest.common
EPS = 1e-5
TRAIN_FI... |
the-stack_0_2223 | import turtle, random
rat = turtle.Turtle()
screen = turtle.Screen()
dot_distance = 75
#width = 5
height = 5
rat.penup()
screen.register_shape("NickCage.gif")
rat.shape("NickCage.gif")
def draw_a_star():
for i in range(5):
rat.pendown()
rat.forward(50)
rat.right(144)
rat.penup... |
the-stack_0_2224 | # -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/MedicationKnowledge
Release: R4
Version: 4.0.1
Build ID: 9346c8cc45
Last updated: 2019-11-01T09:29:23.356+11:00
"""
import sys
from . import backboneelement, domainresource
class MedicationKnowledge(domainresource.DomainResource):
"""... |
the-stack_0_2226 | #!/usr/bin/python3
import unittest
from base import TestBase
class LoginTest(TestBase):
def test_anonymous_login(self):
info = self.call('/user')
self.assertIsNone(info['user'])
def test_logged_in(self):
with self.client:
email = 'a@test.com'
self.login(email)... |
the-stack_0_2228 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
the-stack_0_2229 | """
Canny edge detection adapted from https://github.com/DCurro/CannyEdgePytorch
"""
import torch
import torch.nn as nn
import numpy as np
from scipy.signal.windows import gaussian
class CannyEdgeDetector(nn.Module):
def __init__(self,
non_max_suppression=True,
gaussian_filter_s... |
the-stack_0_2231 | import time
import orjson
import asyncio
import websockets
from typing import Optional
from enum import IntEnum
from dataclasses import dataclass
from dataclasses_json import dataclass_json
from websockets.exceptions import ConnectionClosedError, ConnectionClosed, ConnectionClosedOK
from athanor.app import Service
... |
the-stack_0_2233 | import inspect
from typing import Callable, Type
from open_mafia_engine.util.repr import ReprMixin
class MafiaError(Exception, ReprMixin):
"""Base class for Mafia exceptions."""
class MafiaAmbiguousTypeName(MafiaError):
"""The type name conficts with an existing name."""
def __init__(self, existing_ty... |
the-stack_0_2235 | '''
Manage the pipeline : reading the logs, parsing them and generating stats.
'''
import os
import time
from monilog.parser import Parser
from monilog.statistics import Statistics
from monilog.utils import init_logger
HIGH_TRAFFIC_DUR = 2*60
STAT_DUR = 10
MAX_IDLE_TIME = 5*60
class MonilogPipeline:
'''
Re... |
the-stack_0_2236 | import sys
sys.setrecursionlimit(500000)
class Solution:
# @param A : list of integers
# @return an integer
def solve(self, parents):
if not parents:
return 0
assert len(parents) >= 1
tree = make_tree(parents)
depth, max_dist = find_max_dist(tree)
return ... |
the-stack_0_2237 | """Documenter module docstring."""
import ast
import importlib
import inspect
import os
import re
import textwrap
from collections import namedtuple
from functools import lru_cache
from types import ModuleType
from typing import Any, Callable, Dict, GenericMeta, List, Optional, Pattern, Tuple, Type, Union
RECURSIVE_N... |
the-stack_0_2238 | import os
import asyncio
import pygame
import random
from functools import partial
import json
import asyncio
import websockets
import logging
import argparse
import time
from mapa import Map, Tiles
logging.basicConfig(level=logging.DEBUG)
logger_websockets = logging.getLogger("websockets")
logger_websockets.setLevel(... |
the-stack_0_2240 | from in_data import in_data
from random import choice
import operator
from GA import *
class main:
DeliveryPoints = in_data()
nth_population = 0
BestSolution = None
population= Inicial_Population(DeliveryPoints)
while nth_population < EndPoint:
nth_population+=1
Populat... |
the-stack_0_2241 | # coding=utf-8
# Copyright 2018 Google LLC & Hwalsuk Lee.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
the-stack_0_2244 | from Roteiro8.Roteiro8__funcoes import Grafo
grafo = Grafo()
for v in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']:
grafo.adicionaVertice(v)
for a, p in {'a-b': 9, 'a-g': 4,
'b-c': 6, 'b-g': 10, 'b-h': 7,
'c-d': 8, 'c-e': 12, 'c-f': 8,
'd-e': 14,
'e-f': 2,
... |
the-stack_0_2245 | from random import randint
from kivy.animation import Animation
from kivy.lang import Builder
from kivy.metrics import dp
from kivy.properties import Clock, NumericProperty, ListProperty
from kivy.uix.floatlayout import FloatLayout
Builder.load_file("uix/components/kv/confetti_rain.kv")
class ConfettiItem(FloatLay... |
the-stack_0_2248 | from __future__ import absolute_import
import argparse
import docker
import os
import random
import sys
import shutil
import traceback
from ann_benchmarks.datasets import get_dataset, DATASETS
from ann_benchmarks.constants import INDEX_DIR
from ann_benchmarks.algorithms.definitions import get_definitions, list_algorit... |
the-stack_0_2249 | import unittest
from tests._compat import patch, call
import requests_mock
from proxy_db.utils import download_file, get_domain
class TestDownloadFile(unittest.TestCase):
url = 'https://domain.com/'
def setUp(self):
super(TestDownloadFile, self).setUp()
self.session_mock = requests_mock.Mo... |
the-stack_0_2250 | import asyncio
import aiopg
import aiosqlite
from motor import motor_asyncio
import discordSuperUtils
async def database_test():
mongo_database = discordSuperUtils.DatabaseManager.connect(
motor_asyncio.AsyncIOMotorClient("con-string")["name"]
)
# Replace 'con-string' with the MongoDB connection... |
the-stack_0_2251 | from __future__ import print_function, absolute_import, division # makes these scripts backward compatible with python 2.6 and 2.7
from KratosMultiphysics import kratos_utilities
import KratosMultiphysics.KratosUnittest as KratosUnittest
from KratosMultiphysics.CoSimulationApplication.solver_wrappers.sdof.sdof_static... |
the-stack_0_2252 | from nltk import word_tokenize
from nltk.stem import PorterStemmer
from nltk.stem.snowball import SnowballStemmer
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from nltk.corpus import stopwords
import re
import nltk
... |
the-stack_0_2253 | from flask import request, jsonify, Blueprint
from app.models import Nonprofit, NonprofitSchema
api_blueprint = Blueprint('api', __name__,)
npschema = NonprofitSchema()
npschemas = NonprofitSchema(many=True)
def jsonsift(obj, attrlist):
''' Use a custom attribute list to filter attributes from the model object t... |
the-stack_0_2254 | # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not
# use this file except in compliance with the License. A copy of the License
# is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... |
the-stack_0_2255 | """
Test label generation for nodes.
"""
from map_machine.map_configuration import LabelMode
from map_machine.text import Label
from tests import SCHEME
__author__ = "Sergey Vartanov"
__email__ = "me@enzet.ru"
def construct_labels(tags: dict[str, str]) -> list[Label]:
"""Construct labels from OSM node tags."""
... |
the-stack_0_2256 | """Typing middleware."""
from typing import Any, Callable, Dict, Optional
import falcon
from falcon import Request, Response
from falcontyping.base import (PydanticBaseModel, TypedResource,
TypeValidationError)
from falcontyping.typedjson import DecodingError, ExternalSerializerExceptio... |
the-stack_0_2258 | import networkx as nx
import utils
import sys
import logging
import os
import uuid
def convert(args):
for graph in args.graphs:
if args.nocycles:
g=nx.DiGraph()
else:
g=nx.MultiDiGraph()
g.graph['paths']=[]
g.graph['path2id']=dict()
g.graph[... |
the-stack_0_2259 | from collections import Counter
from itertools import product
def count_letters(input_):
"""
Given an input_ like "abcdef" return a tuple with the result of the following rules
a letter appears exactly 2 times
a letter appears exactly 3 times
"""
counter = Counter(input_)
two_times = 0
... |
the-stack_0_2260 | """Cloud optical properties from ECHAM."""
from os.path import dirname, join
import numpy as np
import xarray as xr
from scipy.interpolate import interp1d
class EchamCloudOptics:
"""Interface to interpolate cloud optical properties used in ECHAM."""
def __init__(self):
self.database = xr.open_datase... |
the-stack_0_2262 | import os, pymysql, logging, matplotlib, sys
from logging.handlers import RotatingFileHandler
from flask import Flask
from config import app_config
from .utils.mattermostdriver import Driver
config_name = os.getenv('FLASK_CONFIG', 'default')
app = Flask(__name__)
# load the color list from the matplotlib
color_list ... |
the-stack_0_2264 | from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, Boolean
from sqlalchemy.orm import relationship
import datetime
from models.SessionWorkouts import SessionWorkouts
# from .SessionModel import Session
from database import Base
class Workout(Base):
__tablename__ = "workout"
id = Column(In... |
the-stack_0_2266 | #!/usr/bin/env python3
#
# This file is part of LiteX-Boards.
#
# Copyright (c) 2019 Antti Lukats <antti.lukats@gmail.com>
# Copyright (c) 2019 msloniewski <marcin.sloniewski@gmail.com>
# Copyright (c) 2019 Florent Kermarrec <florent@enjoy-digital.fr>
# SPDX-License-Identifier: BSD-2-Clause
import os
import argparse
... |
the-stack_0_2267 | import numpy as np
import matplotlib.pyplot as plt
from scipy import linalg
from simupy.systems import LTISystem
from simupy.systems.symbolic import DynamicalSystem, dynamicsymbols
from simupy.block_diagram import BlockDiagram
from sympy.tensor.array import Array
legends = [r'$x_1(t)$', r'$x_2(t)$', r'$x_3(t)$', r'$u(... |
the-stack_0_2269 | """Bit manipulation class."""
import math
from abc import abstractmethod
from copy import deepcopy
from typing import (
Any,
Container,
Iterable,
Iterator,
MutableSequence,
SupportsInt,
Tuple,
Union,
overload,
)
from biterator._biterators import biterate
from biterator.bits_exceptio... |
the-stack_0_2270 | import asyncio
import logging
from zof.event import load_event
LOGGER = logging.getLogger(__package__)
class Protocol(asyncio.SubprocessProtocol):
"""Implements an asyncio Protocol for parsing data received from oftr.
"""
def __init__(self, post_event):
self.post_event = post_event
self.... |
the-stack_0_2271 | """
WRITEME
"""
from __future__ import absolute_import, print_function, division
import logging
import theano
from theano import gof
import theano.gof.vm
from theano.configparser import config
from theano.compile.ops import _output_guard
from six import string_types
_logger = logging.getLogger('theano.compile.mode'... |
the-stack_0_2275 | '''
Written by Heng Fan
在ILSVRC_crops生成剪切之后的图片,成对,每一帧都有一个x和一个z。
如:
000000.00.crop.x.jpg
000000.00.crop.z.jpg
'''
import numpy as np
import os
import glob
import xml.etree.ElementTree as ET
import cv2
import datetime
'''
# default setting for cropping
'''
examplar_size = 127.0 # 模板z的尺寸
# instance_size = 255.0
instanc... |
the-stack_0_2276 | '''
Created on 22 Sep 2016
@author: andrew
'''
DATA_DIR = '/home/andrew/workspace/BKData/'
TESTS_DIR = DATA_DIR + 'tests/'
CIRCUIT_TEST_DIR = TESTS_DIR + 'circuit/'
CIRCUIT_ANGLE_TEST_DIR = CIRCUIT_TEST_DIR + 'angles/'
DEFAULT_CUTOFF = 1e-14
from yaferp.analysis import analyser
import cPickle
import scipy.sparse
impor... |
the-stack_0_2277 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
the-stack_0_2278 | from datetime import datetime
from enum import Enum
from functools import wraps
from typing import Union
import json
import pytz
class DatetimeFormats(Enum):
FULLDATETIME = '%Y-%m-%dT%H:%M:%S.%f%z'
DATE = '%Y-%m-%d'
YMDHMSmS = '%Y-%m-%dT%H:%M:%S.%f%z'
YMDHMS = '%Y-%m-%dT%H:%M:%S%z'
YMD = '%Y-%m-%d... |
the-stack_0_2279 | """Support for Aurora Forecast sensor."""
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import PERCENTAGE
from . import AuroraEntity
from .const import COORDINATOR, DOMAIN
async def async_setup_entry(hass, entry, async_add_entries):
"""Set up the sensor platform."""
coordi... |
the-stack_0_2280 | import csv
import os
from statistics import mean, median, quantiles
def process(fqp, resultsfile):
# gather the max per line of file of round 1
prev_fqp = fqp.replace("Round2", "Round1")
r1max = []
with open(prev_fqp, "r") as csvfile:
datareader = csv.reader(csvfile, delimiter=',')
t... |
the-stack_0_2281 | # Main differences in this ablation:
# - there is no optimism
# - the novelty Q is trained only between episodes
# - the novelty Q is trained on _logged_ novelty rewards, not live ones
import time
import os
import math
import pickle
import queue
from typing import Any
import numpy as np
import matplotlib.pyplot as pl... |
the-stack_0_2282 | #
# @lc app=leetcode id=445 lang=python
#
# [445] Add Two Numbers II
#
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for singly-linked list.
from LeetCode.Python.BaseListNode import MakeListNodes, PrintListNod... |
the-stack_0_2284 | import pyglet, math
from pyglet.window import key
from . import bullet, physicalobject, resources
class Player(physicalobject.PhysicalObject):
"""Physical object that responds to user input"""
def __init__(self, *args, **kwargs):
super(Player, self).__init__(img=resources.player_image, *args, **kwarg... |
the-stack_0_2287 | import numpy as np
def predict_one_vs_all(all_theta, X):
m = X.shape[0]
num_labels = all_theta.shape[0]
# You need to return the following variable correctly;
p = np.zeros(m)
# Add ones to the X data matrix
X = np.c_[np.ones(m), X]
# ===================== Your Code Here ================... |
the-stack_0_2289 | from typing import Dict, List, Optional, Tuple
from blspy import AugSchemeMPL, G2Element, PrivateKey
from kiwi.consensus.constants import ConsensusConstants
from kiwi.util.hash import std_hash
from kiwi.types.announcement import Announcement
from kiwi.types.blockchain_format.coin import Coin
from kiwi.types.blockchai... |
the-stack_0_2293 | import glob
import sys
import os
import xml.etree.ElementTree as ET
from random import random
def main(filename):
# ratio to divide up the images
train = 0.7
val = 0.2
test = 0.1
if (train + test + val) != 1.0:
print("probabilities must equal 1")
exit()
# get the... |
the-stack_0_2296 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
the-stack_0_2297 | import typing
from typing import Optional, Any
import gym
import gym_minigrid.minigrid
import numpy as np
import torch
from babyai.utils.format import InstructionsPreprocessor
from gym_minigrid.minigrid import MiniGridEnv
from core.base_abstractions.sensor import Sensor, prepare_locals_for_super
from core.base_abstra... |
the-stack_0_2298 | from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/webhooks/stripe', methods=['POST'])
def receive_stripe_webhook():
"""Receives a webhook payload from Stripe.
"""
# Try to parse a webhook payload, get upset if we couldn't
# parse any JSON in the body:
stripe_payloa... |
the-stack_0_2299 | import json
import sys
from wsgiref.simple_server import make_server
from . import NAME, VERSION, Kaa, KaaServer
from .openapi import OpenApi
from .server import Server
class Cli():
def __init__(self):
self.host = '127.0.0.1'
self.port = 8086
self.argv = sys.argv[:]
def execute(self... |
the-stack_0_2303 | from django.conf.urls import url
from . import views
app_name = 'twister'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^twist/$', views.TwistView.as_view(), name='twist'),
url(r'^domain/(?P<pk>.+)/$', views.DomainView.as_view(), name='domain'),
]
|
the-stack_0_2305 | from typing import List, NamedTuple, Tuple, Union
import geopandas as gpd
import gmsh
import numpy as np
import pandas as pd
import shapely.geometry as sg
from .common import FloatArray, IntArray, coord_dtype, flatten, separate
Z_DEFAULT = 0.0
POINT_DIM = 0
LINE_DIM = 1
PLANE_DIM = 2
class PolygonInfo(NamedTuple):... |
the-stack_0_2306 | """
Download ACS data and parse for uploading
"""
import os.path
import json
import grequests
import pandas as pd
from ntd import update_dollars
from carto import replace_data
import settings
def process_result(i, y, var, indexes, frames):
"""Transform downloaded result to data frame by year"""
result = pd.Da... |
the-stack_0_2307 | import warnings
from collections import namedtuple
from contextlib import suppress
import boto3
from botocore.exceptions import ClientError
from dagster import Array, Field, Noneable, ScalarUnion, StringSource, check
from dagster.core.events import EngineEventData, MetadataEntry
from dagster.core.launcher.base import... |
the-stack_0_2308 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Provides endpoint and web page for simple search API."""
import os
import json
from typing import Iterable, Iterator
from flask import Flask, render_template, abort, jsonify
from webargs.flaskparser import use_kwargs
from webargs import fields
FIELD_NAMES = ['job_hist... |
the-stack_0_2309 | from functools import partial
import trw
import torch.nn as nn
import torch
class Net(nn.Module):
def __init__(self):
super().__init__()
self.encoder_decoder = trw.layers.AutoencoderConvolutional(
2,
1,
[8, 16, 32],
[32, 16, 8, 1], # make sure we a... |
the-stack_0_2310 | import time
import hashlib
import matplotlib.pyplot as plot
from passlib.hash import b
import random
import argon
# Random salt generation
def ransalt():
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
chars = []
for i in range(16):
chars.append(rando... |
the-stack_0_2311 | #!/usr/bin/env python3
import os
import math
from numbers import Number
from cereal import car, log
from common.numpy_fast import clip
from common.realtime import sec_since_boot, config_realtime_process, Priority, Ratekeeper, DT_CTRL
from common.profiler import Profiler
from common.params import Params, put_nonblockin... |
the-stack_0_2313 | """
Methods for computing confidence intervals.
"""
import scipy.special as special
import numpy as np
import pandas as pd
import scipy.stats as stats
def z_effect(ci_low, ci_high):
"""
Compute an effect score for a z-score.
Parameters
----------
ci_low :
Lower bound of the confidence in... |
the-stack_0_2314 | from django.test import TestCase
from mock import patch, MagicMock
from model_mommy import mommy
from dbaas.tests.helpers import DatabaseHelper
from logical.models import Database
from notification.tasks import check_database_is_alive
@patch('logical.models.Database.update_status', new=MagicMock())
@patch('notifica... |
the-stack_0_2315 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 15 12:48:54 2019
@author: James Kring
@email: jdk0026@auburn.edu
"""
import sys
sys.path.insert(0, '/home/cth/cthgroup/Python/recon')
from recon_input import InputClass
import click
# =============================================================================
# Exa... |
the-stack_0_2316 | from code_pipeline.tests_generation import RoadTestFactory
from time import sleep
from swat_gen.road_gen import RoadGen
import logging as log
from code_pipeline.validation import TestValidator
from code_pipeline.tests_generation import RoadTestFactory
from scipy.interpolate import splprep, splev, interp1d, splrep
from ... |
the-stack_0_2318 | from botocore.exceptions import ClientError
# Stores found values to minimize AWS calls
PARAM_CACHE = {}
current_region = None
def get_special_param(client, func, param):
print('Getting info for func: {}, param: {}'.format(func, param))
if param in PARAM_CACHE:
return PARAM_CACHE[param]
if para... |
the-stack_0_2319 | # Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
the-stack_0_2320 | from django.contrib.auth.models import User
from image_loader.image.models import MainImage, Image
from image_loader.plan.models import UserPlan, Plan
from rest_framework.test import APITestCase
from django.urls import reverse
from django.core.files import File
class TestAPI(APITestCase):
@classmethod
def setUpTes... |
the-stack_0_2321 | from django.test import TestCase
from django.test.client import Client
from wagtail.wagtailredirects import models
def get_default_site():
from wagtail.wagtailcore.models import Site
return Site.objects.filter(is_default_site=True).first()
def get_default_host():
return get_default_site().root_url.split... |
the-stack_0_2323 | import logging
import pytest
log = logging.getLogger("dexbot")
log.setLevel(logging.DEBUG)
@pytest.fixture()
def worker(strategybase):
return strategybase
@pytest.mark.mandatory
def test_init(worker):
pass
@pytest.mark.parametrize('asset', ['base', 'quote'])
def test_get_operational_balance(asset, worke... |
the-stack_0_2324 | """
Please see
https://computationalmindset.com/en/neural-networks/ordinary-differential-equation-solvers.html#ode1
for details
"""
import numpy as np
import matplotlib.pyplot as plt
import torch
from torchdiffeq import odeint
ode_fn = lambda t, x: torch.sin(t) + 3. * torch.cos(2. * t) - x
an_sol = lambda t : (1./2... |
the-stack_0_2325 | #!/usr/bin/env python2
# coding: utf-8
import re
from collections import defaultdict
from pykit.dictutil import FixedKeysDict
from .block_id import BlockID
from .block_desc import BlockDesc
from .block_group_id import BlockGroupID
from .block_index import BlockIndex
from .replication_config import ReplicationConfig... |
the-stack_0_2326 | # Copyright 2010-2021, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and ... |
the-stack_0_2327 | from typing import Union
from pyrogram.types import Message, Audio, Voice
async def convert_count(count):
if int(count) == 1:
x = "First"
elif int(count) == 2:
x = "Second"
elif int(count) == 3:
x = "Third"
elif int(count) == 4:
x = "Fourth"
elif int(count) == 5:
... |
the-stack_0_2328 | from absl import app, flags, logging
from absl.flags import FLAGS
import cv2
import os
import numpy as np
import tensorflow as tf
from modules.evaluations import get_val_data, perform_val
from modules.models import ArcFaceModel
from modules.utils import set_memory_growth, load_yaml, l2_norm
flags.DEFINE_string('cfg_... |
the-stack_0_2330 | # This file is execfile()d with the current directory set to its containing dir.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
#
# All configuration values have a default; values that are comme... |
the-stack_0_2331 | import json
import urllib
import aiohttp
from aiocache import cached
client_session = None
@cached(ttl=3600)
async def get_ios_cfw():
"""Gets all apps on ios.cfw.guide
Returns
-------
dict
"ios, jailbreaks, devices"
"""
async with client_session.get("https://api.appledb.dev/main.js... |
the-stack_0_2333 | import uuid
from django.db import models
from core.models.base import StandardModel
from core.models.base import CaseInsensitiveNamedModel
from core.models import Material
from core.models import Source
from core.models import SampleType
from core.models import Storage
from core.models import Project
from core.models i... |
the-stack_0_2334 | # improvement_meta.py
# author: Ahmed Bin Zaman
# since: 02/2021
"""Module for improving the fitness of a conformation.
This module provides functionalities like local search to improve the
current fitness of a given conformation. The bookkeeping is for
metamorphic proteins with four native structures.
Available Clas... |
the-stack_0_2335 | import logging
from datetime import datetime
import xml.etree.ElementTree as ET
from indra.statements import *
from indra.statements.statements import Migration
from indra.statements.context import MovementContext
from indra.util import UnicodeXMLTreeBuilder as UTB
logger = logging.getLogger(__name__)
class CWMSEr... |
the-stack_0_2337 | import logging
import re
import typing as t
import requests
from . import const
HOST = "https://{endpoint}.api.pvp.net"
# Commonly used types (for type hints)
Params = t.Dict[str, str]
JSON = t.Dict[str, t.Any]
l = logging.getLogger(__name__)
api_key = None # type: str
########################################... |
the-stack_0_2338 | #!/usr/bin/env python3
import random
import os
import asyncpg
from quart import Quart, jsonify, make_response, request, render_template
app = Quart(__name__)
GET_WORLD = "select id,randomnumber from world where id = $1"
UPDATE_WORLD = "update world set randomNumber = $2 where id = $1"
@app.before_serving
async def... |
the-stack_0_2339 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib as ml
import matplotlib.pyplot as plt
import _settings
import os.path
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from matplotlib import colors, ticker, cm
from math import log10
def logspace_for(... |
the-stack_0_2341 | import pandas as pd
import numpy as np
import random
import logging
import cv2
import sys
sys.path.append("../DataProcessing/")
from ImageTransformer import ImageTransformer
class DataProcessor:
@staticmethod
def ProcessTrainData(trainPath, image_height, image_width, isGray = False, isExtended=False):
... |
the-stack_0_2342 | # engine/reflection.py
# Copyright (C) 2005-2020 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Provides an abstraction for obtaining database schema information.
Usage No... |
the-stack_0_2345 | # Copyright 2016 Raytheon BBN Technologies
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
__all__ = ['Averager']
import time
import iterto... |
the-stack_0_2346 | import os
import argparse
import pandas as pd
def combine_ftype(on_private):
# Content_2_index = {
# 0: "Empty",
# 1: "Pasta",
# 2: "Rice",
# 3: "Water"
# }
if on_private:
vggish_path = './filling_type/vggish/predictions/200903163404/ftype_private_test_agg_vggish.cs... |
the-stack_0_2349 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
the-stack_0_2350 | import falcon
import simplejson as json
import mysql.connector
import config
from datetime import datetime, timedelta, timezone
from core import utilities
from decimal import Decimal
import excelexporters.spacestatistics
class Reporting:
@staticmethod
def __init__():
pass
@staticmethod
def on... |
the-stack_0_2352 | import logging
from boto3.resources.action import ServiceAction, WaiterAction
from boto3.resources.params import create_request_parameters
from botocore import xform_name
from aioboto3.resources.response import AIOResourceHandler, AIORawHandler
logger = logging.getLogger(__name__)
class AIOServiceAction(ServiceAct... |
the-stack_0_2353 | """The test provides the basic capabilities to run numerous property tests."""
from datetime import timedelta
from datetime import datetime
import functools
import traceback
import shutil
import random
import os
import numpy as np
from property_auxiliary import distribute_command_line_arguments
from property_auxiliar... |
the-stack_0_2354 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('message', '0002_message_date'),
]
operations = [
migrations.RemoveField(
model_name='message',
name=... |
the-stack_0_2356 | """Tests for chebyshev module.
"""
from __future__ import division, absolute_import, print_function
import numpy as np
import numpy.polynomial.chebyshev as cheb
from numpy.polynomial.polynomial import polyval
from numpy.testing import (
assert_almost_equal, assert_raises, assert_equal, assert_,
run_module_sui... |
the-stack_0_2357 | # Copyright 2019 NREL
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distribu... |
the-stack_0_2358 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
#
# Copyright 2009, Benjamin Kampmann <ben.kampmann@gmail.com>
# Copyright 2014, Hartmut Goebel <h.goebel@crazy-compilers.com>
# Copyright 2018, Pol Canelles <canellestudi@gmail.com>
from t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.