content stringlengths 5 1.05M |
|---|
"""API Client module for handling requests and responses."""
import requests
import datetime
from .exceptions import (
PygitaException,
ServerConnectionError,
BadRequestError,
UnauthorisedError,
RequestFailedError,
ServerError,
AuthorizationError,
)
from .constants import (
TOKEN_VALIDIT... |
print('='*30)
print(' 10 TERMOS DE UMA PA ')
print('='*30)
primeiro = int(input('Primeiro termo: '))
razão = int(input('Razão: '))
décimo = primeiro + (10 - 1) * razão
for c in range(primeiro, décimo + razão, razão):
print(f'{c}', end=' -> ')
print('THE END') |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from mephisto.data_model._db_backed_meta import (
MephistoDBBackedMeta,
MephistoDataModelComponentMixin,
)
from... |
# Copyright 2022 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... |
from .network import ServerSocket
import sys
import time
import threading
import json
from concurrent.futures import ThreadPoolExecutor
import logging
import argparse
lag = 0
class Server(object):
def __init__(self, host, port, max_con=100, refuse=200):
self.host = host
self.port = port
se... |
"""Tests for `flask_image_search` package."""
import logging
import os
import numpy as np
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" # noqa
import pytest
import zarr
from sqlalchemy.sql.expression import func
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatte... |
from django import forms
from .models import Customer
class DealerAddCustForm(forms.ModelForm):
cust_email = forms.CharField()
cust_address = forms.CharField()
fname = forms.CharField()
lname = forms.CharField()
phone = forms.CharField()
notes = forms.CharField()
vin = forms.CharField()
... |
from django.shortcuts import redirect, render, HttpResponseRedirect, reverse
from twitteruser.models import Uzer
from authentication.forms import LoginForm, SignUpForm
from django.contrib.auth import login, logout, authenticate
# Create your views here.
def signup_view(request):
if request.method == 'POST':
... |
# -*- coding: UTF-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from marionette.by import By
from marionette.marionette import Actions
from marionette.wait impo... |
# Copyright 2018 Spotify AB. 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 applicable law or ag... |
from __future__ import absolute_import, division, print_function
from cctbx.array_family import flex
from libtbx import adopt_init_args
import mmtbx.refinement.real_space
from mmtbx.refinement.real_space import individual_sites
import math, sys
from cctbx import maptbx
import scitbx.math
import mmtbx.idealized_aa_resid... |
"""Default model package."""
import base64
import os
from arduinozore.settings import path
from yaml import SafeLoader
from yaml import YAMLObject
from yaml import dump
from yaml import safe_load
class Model(YAMLObject):
"""Model default class."""
yaml_tag = u'!Model'
yaml_loader = SafeLo... |
#!/usr/bin/env python
"""
This program takes a command line argument n (positive integer) and prints the nth fibonacci number.
"""
#
### INSTRUCTOR COMMENT:
# See the sequences file for my main comments, which are repeated here.
# Also, imports should be done at the top of the file, ideally, except for
# specific impo... |
import hashlib
import hmac
import time
class BitfinexAuth:
def __init__(self, api_key: str, secret_key: str):
self.api_key = api_key
self.secret_key = secret_key
def generate_auth_payload(self):
nonce = self._make_nonce()
auth_payload = 'AUTH{nonce}'.format(nonce=nonce)
... |
import json
from decimal import Decimal
from os import PathLike
from typing import Any, Tuple, Iterable, Union
import requests
__all__ = [
'tuplify',
'json_loadf',
'json_loadr',
'json_loads',
]
def tuplify(value: Any) -> Tuple:
if value is None:
return ()
if isinstance(value, Tuple):... |
import logging
log = logging.getLogger(__name__)
def get_answers_tree(project, snapshot=None):
values = {}
valuesets = {}
# first we loop over all values of this snapshot
# the values are gathered in one nested dict {attribute_id: set_index: collection_index: value}
# additionally all values wi... |
import json
from .reader import Reader
from .register import add_reader
@add_reader
class JSON(Reader):
extensions = ["json"]
def loads(self, string, **options):
return json.loads(string, **options)
|
from model.contact import Contact
from model.group import Group
import random
def test_del_contact_to_group(app, orm, db):
if len(db.get_contact_list()) == 0:
app.contact.create(Contact(first_name="Test_name", middle_name="Test_middle_name", last_name="Test_last_name",
a... |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.15.0)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x3d\xdf\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x01\xea\x... |
# Basic OOP
class Student:
"""
THe Student class defines a student in terms of full name, sex and gpa.
"""
def __init__(self, first_name, last_name, sex, gpa):
self.first_name = first_name
self.last_name = last_name
self.sex = sex
self.gpa = gpa
def get_name(... |
# -*- coding: utf-8 -*-
"""
rsc.py
======
Context decorator for producing figures which is ready to publish
in Royal Society of Chemistry.
Reference:
RSC Authour Guidelines
EPS format for image file are used, because of its high quality and working
in actual physical size rahter than pixel unit.
"""
from .gene... |
'''
Author: Mahnoor Anjum
Description:
Intersection Test
Reference:
www.geeksforgeeks.org
For a given point triplet (A, B, C),
we can determine the orientation by
inspecting at the sign of the cross product of AB × BC
If AB × BC > 0, counterclockwise.
If AB... |
import os
import torch
def get_step_from_checkpoint(fname):
return int(fname.split("_")[0][1:])
def load_model_from_cpd(Model,chekpoint_dir):
if not os.path.exists(chekpoint_dir):
return 1
checkpoints=os.listdir(chekpoint_dir)
newest_step=1
newest_model_fname=""
f... |
"""
Exercise: using strides to create fake dimensions
==================================================
Use strides to create fake dimensions.
"""
import numpy as np
from numpy.lib.stride_tricks import as_strided
x = np.array([1, 2, 3, 4], dtype=np.int8)
#
# Mini-exercise:
#
# 1. How to create a new array that sh... |
import unittest
from aoc2020.day_2 import *
class ParseRowTestCase(unittest.TestCase):
def setUp(self):
self.rows = [
"1-3 a: abcde",
"1-3 b: cdefg",
"2-9 c: ccccccccc",
]
def test_parse_row(self):
result = list(map(lambda x: parse_row(x), self.rows... |
"""Provide common Renault fixtures."""
import contextlib
from types import MappingProxyType
from typing import Any
from unittest.mock import patch
import pytest
from renault_api.kamereon import exceptions, schemas
from renault_api.renault_account import RenaultAccount
from homeassistant.components.renault.const impor... |
# coding=utf-8
from __future__ import print_function
import sys
import traceback
import os
def decode(examples, model, args, verbose=False, **kwargs):
if verbose:
print('evaluating %d examples' % len(examples))
was_training = model.training
model.eval()
if args.lang == 'wikisql':
fr... |
from kernel_tuner import tune_kernel
import numpy
import argparse
import json
def generate_code(tuning_parameters):
code = \
"__global__ void fct_ale_b1_vertical(const int maxLevels, const int * __restrict__ nLevels, const <%REAL_TYPE%> * __restrict__ fct_adf_v, <%REAL_TYPE%> * __restrict__ fct_plus, <%RE... |
# Generated by Django 2.2.6 on 2019-10-20 09:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('award', '0003_project_collaborators'),
]
operations = [
migrations.AlterField(
model_name='project',
name='tag',
... |
# Su Doku
import os
import numpy as np
from itertools import chain
def solve():
with open(os.path.join("..", "data", "p096.txt"), encoding="utf-8") as f:
rows = np.delete(np.array(f.readlines()), slice(None, None, 10))
sudokus = np.split(np.genfromtxt(rows, np.uint8, delimiter=[1] * 9),
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from utils import normalize
from utils import compute_bleu_rouge
import json
import logging
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/... |
# import the logging library
import logging
# django modules
from django.contrib.auth.decorators import login_required, permission_required
from django.db.transaction import atomic
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render, redirect
# my models
from places.models import Pla... |
from datetime import datetime
from scrapy import Request
from scrapy.http import TextResponse
from scrapy.utils.test import get_crawler
from kingfisher_scrapy.base_spider import BaseSpider
class ExpectedError(Exception):
pass
def response_fixture(meta=None, url_path='', **kwargs):
if meta is None:
... |
"""
Copyright (c) 2020 Chris Ohk
I am making my contributions/submissions to this project solely in our
personal capacity and am not conveying any rights to any intellectual
property of any third parties.
"""
import pyYahtzee
def test_player_roll_dices():
player = pyYahtzee.Player()
player.roll_dices(True)... |
# ---------------------------------------------------------------------
# inv.interface application
# ---------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Third... |
#!/usr/bin/env python3
# encoding=utf8
import traits.observation.api as ob_api
import traits.observation.events as ob_evt
import traits.observation.expression as ob_exp
from traits.api import *
from .i1_util import *
def __refer_sth():
return HasTraits, TraitType, ob_api, ob_evt, ob_exp
|
import glob
import os
import pathlib
import plistlib
import sqlite3
import json
from scripts.artifact_report import ArtifactHtmlReport
from scripts.ilapfuncs import logfunc, tsv, timeline, is_platform_windows
def get_healthFlights(files_found, report_folder, seeker):
file_found = str(files_found[0])
db = sqlite3.... |
#imports section
import json
import sys
import requests
#function return Ticker Data for EUR market for passed currency
#inputs are
#currency - name of currency for getting ticker data
#return JSON string with Ticker Data
def getTickerData(self, currency):
#wrapped in try_catch
try:
#pushing http reque... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
import re
import argparse
from random import shuffle
from .amr_utils import write_to_file
from .var_free_amrs import delete_wiki, delete_amr_variables, single_line_convert
'''Script that augments the data to get the best AMR permutation based on word order
INPUT SHOULD... |
import rigidbody3d
import numpy
def restitutionCoefficient():
cor = rigidbody3d.cor()
ncollisions = rigidbody3d.numCollisions()
assert cor.shape == (ncollisions,)
for col_idx in range( 0, ncollisions ):
indices = rigidbody3d.collisionIndices( col_idx )
assert indices[0] <= 2
assert indices[1] == -1... |
import requests
from bs4 import BeautifulSoup
SITE_NAME = 'programmers'
SITE_URL = 'https://programmers.co.kr/'
SITE_LOGIN_FORM = {
'utf8': '',
'authenticity_token': '',
'user[email]': '',
'user[password]': '',
'button': '',
}
"""
"""
with requests.Session() as sess:
req = sess.get(SITE_URL ... |
from itertools import product
from dataclasses import dataclass
from typing import Optional
from pathlib import Path
import numpy as np
import pandas as pd
from .meta import GRMMeta
@dataclass()
class GRMOutputs:
meta: GRMMeta
a_array: np.ndarray
b_array: np.ndarray
t_array: np.ndarray
level_mea... |
import os
import cgi
import json
import urllib.parse
import urllib.request
from typing import Any, List, Mapping, Iterable
from pathlib import Path
from functools import partial
from collections import defaultdict
import aiohttp
import parfive
import astropy.units as u
from astropy.table import TableAttribute
from as... |
from dymos.transcriptions.common.timeseries_output_comp import TimeseriesOutputCompBase
class SolveIVPTimeseriesOutputComp(TimeseriesOutputCompBase):
"""
Class definition for SolveIVPTimeseriesOutputComp.
Parameters
----------
**kwargs : dict
Dictionary of optional arguments.
"""
... |
#!/usr/bin/python2
import time
def format_time(t):
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(t))
if __name__ == "__main__":
print format_time(time.time()) |
# Copyright 2016-2021 Blue Marble Analytics LLC.
#
# 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 ag... |
from exception import InvalidPasswordException, InvalidUserNameException, NotLoggedInErrorException, \
NotPermittedErrorException, PermissionErrorException
from model import Authenticator, Authorizor
authenticator = Authenticator()
authorizor = Authorizor(authenticator)
authenticator.add_user("tuan", "tuan123hah... |
#by sandakelum priyamantha
from pytube import YouTube,Playlist
import os
from tkinter import *
import tkinter as tk
def make_folder():
home = os.path.expanduser("~")
path = os.path.join(home,"Videos")
path_to_y2v = os.path.join(path,"y2v")
try:
os.mkdir(path_to_y2v)
except:
# print("folder allr... |
_base_ = [
"./_base_/models/faster_rcnn_r50_fpn.py",
"./_base_/datasets/visdrone_dataset.py",
"./_base_/default_runtime.py",
]
gpu_count = 1
batch_size = 2
epoch_count = 12
class_label_count = 12
model = {"roi_head": {"bbox_head": {"num_classes": class_label_count}}}
gpu_ids = range(gpu_count)
data = {"sa... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 26 11:55:32 2021
@author: Diloz
"""
import cv2
import numpy as np
import pandas as pd
from scipy import ndimage
from scipy import optimize
import matplotlib.pylab as plt
from joblib import Parallel, delayed
from Detect_colorChecker import paralell_search
i... |
# These classes implement a doctest runner plugin for nose, a "known failure"
# error class, and a customized TestProgram for NumPy.
# Because this module imports nose directly, it should not
# be used except by nosetester.py to avoid a general NumPy
# dependency on nose.
import os
import doctest
import nose
from no... |
import numpy as np
import scipy.io as sio
np.random.seed(0)
VGG_MEAN = [103.939, 116.779, 123.68]
import os
import tensorflow as tf
import cv2
import json
from collections import namedtuple
from tqdm import tqdm
def read_mat(path):
return np.load(path)
def write_mat(path, m):
np.save(path, m)
def read_id... |
from launcher import Task
import json
import os
import argparse
import pprint
class ConfigureTask(Task):
name = 'configure'
def __init__(self, args):
self.args = args
self.data_dir = os.path.join(os.path.abspath(args["data_dir"]),
args["dataset"])
... |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Alstec.24xx.get_version
# ---------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# --------------------------------------------------------... |
# -*- coding: utf-8 -*-
import pytest
import sys
import random
from sfm.timer import DateTimeTimer
import mongoengine
from mongoengine_mate import ExtendedDocument
py_ver = "%s.%s" % (sys.version_info.major, sys.version_info.minor)
user_col_name = "user_%s" % py_ver
class User(ExtendedDocument):
_id = mongoeng... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸 (Blueking) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may... |
import hassapi as hass
import globals
#
# App to send notification when a sensor changes state
#
# Args:
#
# sensor: sensor to monitor e.g. sensor.upstairs_smoke
# idle_state - normal state of sensor e.g. Idle
# turn_on - scene or device to activate when sensor changes e.g. scene.house_bright
# Release Notes
#
# Versi... |
import time
from datetime import datetime
from dateparser import parse
def parse_timestamp(timestamp, utc=False):
if utc:
return datetime.utcfromtimestamp(timestamp)
else:
return datetime.fromtimestamp(timestamp)
def datetime_to_timestamp(dt):
return time.mktime(dt.timetuple())
def dat... |
Lines = [
'Needs more Assault Vest.',
'Only with Assault Vest equipped.',
'Yes, because you have an Assault Vest.',
'#BT approved.',
"I don't like it, there's no Assault Vest.",
"Doesn't seem like there's any Assault Vest here, so probably not.",
'If Assault Vest is included: Unquestionably ... |
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import sys
sys.path.append(".")
import warnings
warnings.filterwarnings('ignore', category=DeprecationWarning)
warnings.filterwarnings('ignore', category=FutureWarning)
import numpy as np
from datasets import DataSet
import utils
import likelihoods
from sdt_rff_gpu im... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def detectCycle(head: ListNode) -> ListNode:
def getInstance(head):
fast = head
slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast =... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Class that implements the MQTT server (broker).
"""
import tornado.gen
import tornado.ioloop
import tornado.locks
from slugify import slugify
from wotpy.codecs.enums import MediaTypes
from wotpy.protocols.enums import Protocols, InteractionVerbs
from wotpy.protocols.... |
'''
Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in your array.
For example, the length of your array of zeros n=10. Your list of que... |
import numpy as np
class MSE:
@staticmethod
def f(y, a):
return np.mean(0.5 * np.sum(np.square(y - a), axis=0))
@staticmethod
def df_da(y, a):
"""Return partial derivative wrt `a` (element-wise)."""
return a - y
class CrossEntropy:
@staticmethod
def f(y, a):
... |
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.cross_validation import train_test_split
df_train = pd.read_csv('../input/train.csv')
df_test = pd.read_csv('../input/test.csv')
usecols = []
for c in df_train.columns:
if 'cont' in c:
usecols.append(c)
x_train = df_train[usecols]
... |
# 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
# distributed under the ... |
from bs4 import BeautifulSoup
import logging
from nltk import tokenize
from ArticlesDataDownloader.text_utilities import format_text_and_split_into_sentences
def science_direct_html_to_json(textHTML):
logger = logging.getLogger("scienceDirectHtmlToJson")
logger.info("Start readig ScienceDirect file")
... |
import marshal
import mmap
import os
import os.path
import sys
import logging
# from profilehooks import profile
from cog.cache import Cache
import xxhash
RECORD_SEP = b'\xFD'
UNIT_SEP = b'\xAC'
class TableMeta:
def __init__(self, name, namespace, db_instance_id, column_mode):
self.name = name
... |
import gym
from gym import error, spaces, utils
from gym.utils import seeding
import os
import numpy as np
import random
from itertools import permutations
from gym.spaces import Discrete, Box
"""
Simple example for environment tests
"""
class SimpleCorridor(gym.Env):
actions = []
action_obj = []
action_lis... |
import numpy as np
def load_data():
postingList = [
['my', 'dog', 'has', 'flea', 'help', 'please'],
['maybe', 'not', 'take', 'him', 'to', 'park', 'stupid'],
['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],
['stop', 'posting', 'stupid', 'worthless', 'garbage']
]
... |
import unittest
import os
from FSharp.lib.fsac.server import Server
from FSharp.lib import const
import sublime
THIS_DIR = os.path.dirname(os.path.dirname(__file__))
DATA_DIR = os.path.join(sublime.packages_path(), 'FSharp_Tests/data')
class ServerTests(unittest.TestCase):
def __init__(self, *args, **kwargs):... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import pdc.apps.compose.models
class Migration(migrations.Migration):
dependencies = [
('compose', '0007_auto_20151120_0336'),
('package', '0007_auto_20151208_1011'),
]
operations = ... |
import npyscreen
class MainList(npyscreen.MultiLineAction):
def __init__(self, *args, **keywords):
super(MainList, self).__init__(*args, **keywords)
self.name = "Main List"
def display_value(self, vl):
return "|{:^76}|".format(str(vl))
def actionHighlighted(self, act_on_this, ke... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Flask-APIBlueprint
-------------
Route inheritance for Flask Blueprints.
"""
try:
from setuptools import setup, find_packages
except ImportError:
from disutils.core import setup
try:
with open('LONG_DESCRIPTION.rst') as f:
long_description = f.r... |
# -*- coding: utf-8 -*-
# Root directory where all data can be found : str
ROOT_DIRECTORY = r'';
# Type of platform in use : str
# Examples: 'airplane', 'uav'
PLATFORM = 'airplane';
# Sensor used to make the acquisition : str
# Examples: 'LiDAR', 'UX5HP_RGB15mm', 'EBEEX_MSREM'
SENSOR = 'LiDAR';
# Name of... |
#!/usr/bin/env python
import sys, glob
sys.path.insert(0, './gen-py')
sys.path.insert(0, glob.glob('../../lib/py/build/lib.*')[0])
from ThriftTest.ttypes import *
from thrift.transport import TTransport
from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol
import unittest
import time
class... |
# For compat
from .hdemucs import HDemucs
WDemucs = HDemucs
|
from .elasticsearch import ElasticSearch
from . import register
try:
from requests_aws4auth import AWS4Auth
enabled = True
except ImportError:
enabled = False
class AmazonElasticsearchService(ElasticSearch):
@classmethod
def name(cls):
return "Amazon Elasticsearch Service"
@classmeth... |
import pandas as pd
import pytest
from operational_analysis.toolkits import reanalysis_downloading as rd
def test_get_dataset_names():
dataset_names = {"merra2": "nasa_merra2_global", "era5": "ecmwf_era5_v2"}
assert rd._get_dataset_names("merra2") == dataset_names["merra2"]
assert rd._get_dataset_names(... |
#
# Builtin Definitions
#
from __future__ import absolute_import
from .Symtab import BuiltinScope, StructOrUnionScope, CppClassScope
from .Code import UtilityCode
from .TypeSlots import Signature
from . import PyrexTypes
from . import Options
# C-level implementations of builtin types, functions and methods
iter... |
"""
wordpress_username_enumeration.py
Copyright 2011 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distribut... |
from django.db import models
class YearsOfExperience(models.Model):
text = models.CharField(max_length=100)
def __str__(self):
return self.text
|
import pytest
from rotkehlchen.exchanges.coinbasepro import Coinbasepro
from rotkehlchen.tests.utils.factories import make_api_key, make_api_secret
class MockCoinbasepro(Coinbasepro):
pass
@pytest.fixture(scope='session')
def coinbasepro_passphrase():
return 'supersecretpassphrase'
@pytest.fixture(scope=... |
# -*- coding: utf-8 -*-
"""
Benchmarking script to make sure the porting of the code to Python
produces correct results and compare the execution times.
Based on example: Commands/Steps.py
Created on Sun Apr 19 13:18:33 2020
@author: Leonard.Doyle
"""
import numpy as np
import matplotlib.pyplot as plt
from LightP... |
# Copyright (C) 2017 TU Dresden
# Licensed under the ISC license (see LICENSE.txt)
#
# Authors: Gerald Hempel, Andres Goens
import sys
import numpy as np
from hydra.utils import instantiate
from mocasin.representations import MappingRepresentation
import mocasin.util.random_distributions.lp as lp
from mocasin.util i... |
#!/usr/bin/env python
import logging
import os
from json.decoder import JSONDecodeError
from typing import Dict, List, Optional, Union
import requests
from gevent.lock import Semaphore
from rotkehlchen import typing
from rotkehlchen.logging import RotkehlchenLogsAdapter
from rotkehlchen.utils import rlk_jsondumps, rl... |
"""New table for notes
Revision ID: 6fe71f4f1aba
Revises: 9c829c41652e
Create Date: 2021-03-21 11:33:27.533851
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "6fe71f4f1aba"
down_revision = "9c829c41652e"
branch_labels = None
depends_on = None
def upgrade():
... |
import os.path
class Arguments(object):
def __init__(self,
json_dict):
self.positionals = json_dict["positionals"] if "positionals" in json_dict else []
self.options = json_dict["options"] if "options" in json_dict else {}
@property
def to_list(self):
result = []
... |
"""
pdb.py
Open pdb files
"""
import numpy as np
def open_pdb(file_location):
"""
Open and read the pdb file from a .pdb file.
The pdb file must specify the atom elements in the last column and follow the conventions outlines in the PDB format specification
Parameters
----------
file locat... |
from sqlalchemy import Column, ForeignKey, Integer, String, UniqueConstraint
from sqlalchemy.orm import object_session, relationship
from sqlalchemy.sql.functions import current_timestamp
from .Base import Base
from .SnapshotAssociation import SnapshotAssociation
from .Symbol import Symbol
from .Timestamp import Times... |
#!/usr/bin/env python3
# encoding=utf8
"""Android UI Automate"""
import uiautomator2
import ppadb.client
class RemoteAndroidUI:
def __init__(self):
self._adb = ppadb.client.Client()
self._devices_dict = {}
self.get_devices()
self._remote_ui: uiautomator2.Device or None = None
... |
#!/usr/bin/env python
# -*- coding: utf-8
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
# Timothy Berkelbach <tim.berkelbach@gmail.com>
#
import sys
import json
import ctypes
import warnings
import numpy as np
import scipy.linalg
import scipy.misc
import scipy.special
import scipy.optimize
import pyscf.lib.par... |
import sys
sys.path.append("../..")
from sdf import *
### Define new types of Nodes
class Node(GenericNode):
def __init__(self,name,theType,inLength,outLength):
GenericNode.__init__(self,name)
self.addInput("i",theType,inLength)
self.addOutput("o",theType,outLength)
class Sink(GenericS... |
import numpy as np
import torch
from torch import nn
import radam # pip install git+https://github.com/LiyuanLucasLiu/RAdam/
from run_nerf import DEBUG
import nerf
import os
import contextlib
# https://github.com/lioryariv/idr/blob/main/code/model/implicit_differentiable_renderer.py
class ImplicitNetwork(nn.Module):... |
# -*- coding: utf-8 -*-
# Copyright (c) 2022 Intel Corporation
#
# 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... |
"""
This module handles interactions with the OpenWeather api
"""
import os
from typing import Dict
import requests
from server.utils.logger import log_exception
OPEN_WEATHER_API_URL = "https://api.openweathermap.org/data/2.5"
def fetch_weather(lat: float, long: float) -> Dict[str, any]:
"""
Fetches the c... |
from rest_framework import permissions
from instructeurs.models import Administration
class AdministrationPermission(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permi... |
import torch
from deep_privacy import logger
import pathlib
def _get_map_location():
if not torch.cuda.is_available():
logger.warn(
"Cuda is not available. Forcing map checkpoint to be loaded into CPU.")
return "cpu"
return None
def load_checkpoint_from_url(model_url: str):
i... |
from .types.CMakeVariable import CMakeVariable
from .types.VariableCollection import VariableCollection
class CMakeLangs(VariableCollection):
"""CMake Language related variables"""
CMAKE_C_COMPILE_FEATURES = ()
CMAKE_C_EXTENSIONS = ()
CMAKE_C_STANDARD = ()
CMAKE_C_STANDARD_REQUIRED = ()
CMAKE... |
#!/usr/bin/python3
"""
Context Manager
---------------
Redo a transaction handler task in such a way that there is no necessity to wrap
each action requiring a transaction into a separate function.
E.g. in the following code snippet there are 3 actions wrapped into a
transaction, including nested transactions:
.. cod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.