code stringlengths 1 199k |
|---|
""" Math attributes
:Author: Jonathan Karr <karr@mssm.edu>
:Date: 2017-05-10
:Copyright: 2017, Karr Lab
:License: MIT
"""
from . import core
import numpy
import sympy
import json
import six
class NumpyArrayAttribute(core.LiteralAttribute):
""" numpy.array attribute
Attributes:
min_length (:obj:`int`): m... |
__author__ = 'brett'
from monopyly import *
from monopyly.utility import Logger
from monopyly.game.board import Board
from monopyly.squares.property import Property
from monopyly.squares.property_set import PropertySet
from monopyly.squares.station import Station
from monopyly.squares.street import Street
from monopyly... |
from ism.config import cfg
import numpy as np
class Voxelizer(object):
def __init__(self, grid_size, num_classes):
self.grid_size = grid_size
self.num_classes = num_classes
self.margin = 0.3
self.min_x = 0
self.min_y = 0
self.min_z = 0
self.max_x = 0
s... |
"""Tests for include cli command"""
import logging
from datetime import datetime
from click import Context
from click.testing import CliRunner
from housekeeper.cli.include import include
from housekeeper.cli.add import bundle_cmd
def test_include_files_creates_bundle_dir(populated_context: Context, cli_runner: CliRunne... |
from toothless.decorators import admin_handler, command_handler
from toothless.util import dispatch, humanise_list
@command_handler('list_commands')
def list_commands(bot, event, command, args):
idents = bot.state.commands.keys()
idents.sort()
for ident in idents:
command = bot.state.commands[ident]... |
import logging
log = logging.getLogger(__name__)
import re
import html
try:
unescape_html = html.unescape # pylint: disable=no-member
except AttributeError:
import html.parser
unescape_html = html.parser.HTMLParser().unescape
irc_format_pattern = re.compile(r'(\x03\d{1,2}(,\d{1,2})?)|[\x02\x03\x0F\x16\x1D\x1F]')
def... |
import hashlib
import logging
from Crypto.PublicKey import RSA
from tenet.message import (
Message,
DictTransport, MessageRouter, MessageSerializer, MessageTypes,
PeerOffline
)
log = logging.getLogger(__name__)
class Friend(object):
def __init__(self, address, key):
self.addr... |
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline i... |
from flask.ext.security import current_user
def remove_invalid_vars(variables):
filtered_variables = []
approved_variables = current_user.approved_variables()
for variable in variables:
if str(variable.id) in approved_variables:
filtered_variables.append(variable)
return filtered_var... |
from __future__ import division
import sys
import numpy as np
import pandas as pd
from multiprocessing import Pool
from matplotlib import pyplot as plt
def load_panel(a):
a = pd.read_pickle(a)
return a
def time_index(a):
a = a.reindex(index=a.index.to_datetime())
return a
def resamp(a):
a = a.resamp... |
import os
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.template.response import TemplateResponse
from django.views import generic
from django.core.files.storage import FileSystemStorage
from helper import helper
from django.http ... |
def sieve_of_erathosthenes(n):
factors = set()
primes = []
for i in range(2, n+1):
if i not in factors:
primes.append(i)
factors.update(range(i*i, n+1, i))
return primes
n = 600851475143
i = 0
primes = sieve_of_erathosthenes(100000)
while n > 1:
if n % primes[i] == 0:... |
from setuptools import setup, find_packages
setup(
name='python_connection_loader',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='1.0.0',
... |
'''
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
'''
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List... |
from flask import Flask
from flask import request
from rocketchat.api import RocketChatAPI
from os import environ
app = Flask(__name__)
def notify_rocketchat(app, release, release_summary, sha, user):
api.send_message(':new: *Deis({env})* {app} #{release} - {release_summary}'
.format(app=app, release=re... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('iiits', '0020_imageslider_researchcentreprofile'),
]
operations = [
migrations.AlterField(
model_name='faculty',
name='research_a... |
"""warcvalid - check a warc is ok"""
from __future__ import print_function
import os
import sys
import sys
import os.path
from optparse import OptionParser
from .warctools import WarcRecord, expand_files
parser = OptionParser(usage="%prog [options] warc warc warc")
parser.add_option("-l", "--limit", dest="limit")
parse... |
class AuthError(Exception):
pass
class BusyError(Exception):
pass |
from unittest import TestCase
from mock import patch, Mock
from pyEchosign import TransientDocument
from pyEchosign.classes.agreement import Agreement
from pyEchosign.classes.account import EchosignAccount
from pyEchosign.exceptions.internal import ApiError
class TestAccount(TestCase):
@classmethod
def setup_cl... |
import os
import logging
from logging import StreamHandler
from logging.handlers import RotatingFileHandler
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
MAIL_SERVER = 'smtp.googlema... |
"""
SQLite queue storage.
:author: David Siroky (siroky@dasir.cz)
:license: MIT License (see LICENSE.txt)
"""
import platform
import sqlite3
from binascii import b2a_hex, a2b_hex
from snakemq.message import Message, MAX_UUID_LENGTH
from snakemq.messaging import MAX_IDENT_LENGTH
from snakemq.storage import QueuesStorage... |
from unittest import TestCase
from Conundrum.caesar import encrypt, decrypt, decrypt_try_all
DECRYPTED_MSG = 'helloworld'
INDEX = 4
ENCRYPTED_MSG = 'lippsasvph'
class CaesarTestCase(TestCase):
def test_that_encrypt_works(self):
self.assertEqual(ENCRYPTED_MSG, encrypt(DECRYPTED_MSG, INDEX))
def test_that... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
from glow import *
glow('pydiv')
scene = canvas()
side = 4.0
thk = 0.3
s2 = 2*side - thk
s3 = 2*side + thk
wallR = box (pos=vec( side, 0, 0), size=vec(thk,s2,s3), color=color.red)
wallL = box (pos=vec(-side, 0, 0), size=vec(thk,s2,s3), color=color.red)
wallB = box (pos=vec(0, -side, 0), size=vec(s3,thk,s3), color=co... |
"""Module to connect and discover JUNOS devices."""
import sys
import re
import warnings
from jnpr.junos.op.phyport import PhyPortTable
from jnpr.junos.exception import ConnectRefusedError, ConnectAuthError
from napalm import get_network_driver
class NetworkDevice(object):
"""Class that connects and discovers JUNOS d... |
from django.db import migrations, models
import lametro.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('councilmatic_core', '0048_post_shape'),
]
operations = [
migrations.CreateModel(
name='SubjectGuid',
fields=[
('... |
from flask_table import Col, DateCol, DatetimeCol
from .forms import (StringField, DSDateField as DateField,
DSDateTimeField as DateTimeField, IntegerField)
def str_data_factory(name):
return data_types[name.lower()]
def data_factory(val=None, sql_type=None):
if sql_type.startswith('INTEGER'... |
import sys
import warnings
class LabelDictionary(dict):
'''This class implements a dictionary of labels. Labels as mapped to
integers, and it is efficient to retrieve the label name from its
integer representation, and vice-versa.'''
def __init__(self, label_names=[]):
self.names = []
fo... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
def physikum(apps, schema_editor):
Testat = apps.get_model("exoral", "Testat")
physikum = Testat(bezeichnung = "Physikum")
physikum.save()
Frage = apps.get_model("exoral", ... |
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
import sys # noqa: F40... |
from butter.product import Product
class PantryItem(Product):
def __init__(self, mode, pantry_name, sku, name=None):
super().__init__(sku, name)
self.mode = mode
self.pantry_name = pantry_name
@staticmethod
def from_product(product, pantry, mode):
return PantryItem(mode, pant... |
import requests
import csv
symbol = input('Enter a stock symbol: ').upper()
stock = dict( [
( 'name' , 'Excellent Co.' ),
( 'symbol' , symbol ),
( 'phone' , '800-YOU-GAIN' ),
( 'currentPrice' , '150' ),
( 'yearHigh' , '12' ),
( 'yearLow' , '5' ),
( 'marketCap' , '$100 Million' ),
( 'dayDollarV... |
def sort(array):
for i in range(0, len (array)):
min = i
for j in range(i + 1, len(array)):
if array[j] < array[min]:
min = j
array[i], array[min] = array[min], array[i] |
import json
from slackclient import SlackClient
import logging
log = logging.getLogger('luigi_slack')
log.setLevel(logging.DEBUG)
class ChannelNotFoundError(Exception):
pass
class ChannelListNotLoadedError(Exception):
pass
class SlackAPI(object):
def __init__(self, token, username='Luigi-slack Bot', as_user... |
from examples import *
def batch_atari():
cf = Config()
cf.add_argument('--i', type=int, default=0)
cf.add_argument('--j', type=int, default=0)
cf.merge()
games = [
'BreakoutNoFrameskip-v4',
# 'AlienNoFrameskip-v4',
# 'DemonAttackNoFrameskip-v4',
# 'MsPacmanNoFrameski... |
import os
from setuptools import setup, find_packages
from setuptools.extension import Extension
import numpy
from grslicer import VERSION
dev_mode = os.path.exists('dev')
if dev_mode:
from Cython.Distutils import build_ext
print('Development mode: Compiling Cython modules from .pyx sources.')
sources = ["g... |
from toontown.safezone import DistributedSZTreasure
from toontown.toonbase import ToontownGlobals
from direct.interval.IntervalGlobal import *
from pandac.PandaModules import Point3
Models = {ToontownGlobals.ToontownCentral: 'phase_4/models/props/icecream',
ToontownGlobals.DonaldsDock: 'phase_6/models/props/starfish_t... |
from functools import wraps
class MetaMachine(type):
def __new__(cls, name, bases, d):
state = d.get('initial_state')
if state == None:
for base in bases:
try:
state = base.initial_state
break
except AttributeError:
... |
__all__ = ['BackgroundAudio']
import alsaaudio, time
from array import array
from itertools import izip_longest
import multiprocessing
import logging
from logging_helper import *
ml = logging.getLogger('BA')
ml.addHandler(logging.NullHandler())
ml = LazyLoggerAdapter(ml)
def _chunks(n, iterable, padvalue=None):
ret... |
import operator
import warnings
from django.db import models
from django.db.models.base import ModelBase
from django.db.models.query import Q
from django.utils.translation import ugettext as _
from mptt2.fields import TreeForeignKey, TreeOneToOneField, TreeManyToManyField
from mptt2.managers import TreeManager
from mpt... |
import unittest
import finger
from datetime import datetime
EPOCH_TIME = datetime(1970, 1, 1)
EPOCH_OVERWORK = datetime(1970, 1, 1, 11, 0)
EPOCH_UNDERWORK = datetime(1970, 1, 1, 10, 0)
DAILY_USER_NAME = 0
DAILY_LOG_DATE = 1
DAILY_WEEK_NB = 2
DAILY_WORKED_HR = 3
DAILY_STATUS = 4
WEEKLY_USER_NAME = ... |
import numpy as np
import argparse
import cv2
from cnn.neural_network import CNN
from keras.utils import np_utils
from keras.optimizers import SGD
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
ap = argparse.ArgumentParser()
ap.add_argument("-s", "--save_model", type=int,... |
client_id_google = 'YOUR_GOOGLE_CLIENT_ID'
client_secret_google='YOUR_GOOGLE_CLIENT_SECRET'
client_id_github = 'YOUR_GITHUB_CLIENT_ID'
client_secret_github = 'YOUR_GITHUB_CLIENT_SECRET' |
"""
__MT_pre__SwcToEcuMapping.py_____________________________________________________
Automatically generated AToM3 syntactic object (DO NOT MODIFY DIRECTLY)
Author: levi
Modified: Sun Aug 9 23:45:38 2015
_________________________________________________________________________________
"""
from ASGNode import *
from A... |
from __future__ import absolute_import
from __future__ import print_function
from PyOpenWorm.data import DataUser
from .DataTestTemplate import _DataTest
from PyOpenWorm.cell import Cell
class CellTest(_DataTest):
ctx_classes = (Cell,)
def test_DataUser(self):
do = Cell('', conf=self.config)
sel... |
"Implements Model"
import numpy as np
from .costed import CostedConstraintSet
from ..nomials import Monomial
from .prog_factories import _progify_fctry, _solve_fctry
from .gp import GeometricProgram
from .sgp import SequentialGeometricProgram
from ..small_scripts import mag
from ..tools.autosweep import autosweep_1d
fr... |
from django.conf import settings
from rest_framework.settings import APISettings
USER_SETTINGS = getattr(settings, 'JWT_AUTH', None)
DEFAULTS = {
'JWT_APP_NAME': 'refreshtoken',
}
api_settings = APISettings(USER_SETTINGS, DEFAULTS, []) |
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azur... |
import argparse
import logging
import sys
import corpus
log = logging.getLogger(__name__)
def read_corpus(options):
with open(options.input, "rb") as f:
dec = corpus.TLVDecoder(f.read())
for tlv in dec:
print(tlv)
return ScriptRC.SUCCESS
def get_options():
parser = argparse.Argum... |
import boto3
from log import log
from time import sleep
ec2 = boto3.resource('ec2')
ec2client = boto3.client('ec2')
def start_instance(user_data_str, conf):
log("Requesting instance, %d bytes userdata" % (len(user_data_str)))
instances = ec2.create_instances(
DryRun=False,
ImageId=conf['machine-... |
from data.gen_fixtures import BASIC_USER as FIXTURE_USER, NON_FB_USER as NON_FB_FIXTURE_USER
from django.core.urlresolvers import reverse
from django.test import TestCase
STAFF_USER = {'email':'nick@jumo.com', 'pwd':'tester01'}
BASIC_USER = {'email':FIXTURE_USER['email'], 'pwd':FIXTURE_USER['password']}
NON_FB_USER = {... |
import tensorflow as tf
import numpy as np
import random
from param import *
class Model:
'''機械学習のモデル定義を管理するクラス
TensorFlowのSessionや学習済みモデルの保存・読込機能も持たせる
'''
def __init__(self):
''' 初期化処理(準コンストラクタ) '''
self.__setup_placeholder()
self.__setup_model()
self.__setup_ops()
... |
'''
implements simple substitution cipher
Author: James Lyons
Created: 2012-04-28
'''
from pycipher.base import Cipher
class SimpleSubstitution(Cipher):
"""The Simple Substitution Cipher has a key consisting of the letters A-Z jumbled up.
e.g. 'AJPCZWRLFBDKOTYUQGENHXMIVS'
This cipher encrypts a letter accor... |
"""
This module contains unit tests for the "StatusPacket" class.
"""
from pyax12.status_packet import StatusPacket
from pyax12.status_packet import StatusPacketError
from pyax12.status_packet import InstructionError
from pyax12.status_packet import InstructionChecksumError
from pyax12.status_packet import StatusChecks... |
"""
@file FWPWebsite.Google_App_Engine.exception_handlers
=====================================================
This module defines function used to handle common HTTP errors. These
functions are imported into [FWPWebsite.Google_App_Engine.request] and
passed to the WSGI application constructor.
... |
import _plotly_utils.basevalidators
class TicktextsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="ticktextsrc", parent_name="mesh3d.colorbar", **kwargs
):
super(TicktextsrcValidator, self).__init__(
plotly_name=plotly_name,
parent... |
a,b,c = {"1":1,"2":[1,2,3],"3":"string"},[1,2,3],"string"
a,b,c = b,c,a
d = c["2"]
f = d[1]
d[1] = 5
e = c["2"][1] |
from django.core import signing
from django.utils.encoding import smart_str
class TokenGenerator:
def _uid(self, user):
raise NotImplementedError
def generate(self, user, data=None):
"""
Django signer uses colon (:) for components separation
JSON_object:hash_first_component:hash_... |
import gtk
from . helpers import get_builder
class AboutDialog(gtk.AboutDialog):
__gtype_name__ = "AboutDialog"
def __new__(cls):
"""Special static method that's automatically called by Python when
constructing a new instance of this class.
Returns a fully instantiated AboutDialog object... |
import sys, os
sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定
import numpy as np
from collections import OrderedDict
from src.layers import *
from src.gradient import numerical_gradient
class MultiLayerNet:
"""全結合による多層ニューラルネットワーク
Parameters
----------
input_size : 入力サイズ(MNISTの場合は784)
hidden... |
import unittest
from matasano.util.converters import *
class ParsingTest(unittest.TestCase):
def test_hex_to_base64_standard(self):
# Regular hex string
hex_string = "deadbeef1234"
b64_string = "3q2+7xI0"
self.assertEqual(bytes_to_base64(hex_to_bytestr(hex_string)), b64_string)
d... |
import datetime as dt
import peewee as pw
from . import app, db
@db.register
class Category(pw.Model):
name = pw.CharField()
@db.register
class Pet(pw.Model):
created = pw.DateTimeField(default=dt.datetime.utcnow)
name = pw.CharField()
image = pw.CharField(null=True)
status = pw.CharField(choices=[
... |
import uuid
from django.db import models
class Other(models.Model):
pass
class EverythingModel(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField()
username = models.CharField(max_length=20, unique=True)
address = models.TextField()
o1 = models.ForeignKey(Other)
... |
from django.urls import path
from karspexet.economy import views
urlpatterns = [
path("", views.overview, name="economy_overview"),
path("<int:show_id>/", views.show_detail, name="economy_show_detail"),
path("create_voucher/", views.create_voucher, name="economy_create_voucher"),
path("discounts/", view... |
"""
Challenge #270 [Easy] Transpose the input text
https://www.reddit.com/r/dailyprogrammer/comments/4msu2x/challenge_270_easy_transpose_the_input_text/
Write a program that takes input text from standard input and outputs the text -- transposed.
Roughly explained, the transpose of a matrix
A B C
D E F
is given... |
import sys
import os
import re
import gevent
import requests
import signal
import requests
import apache_log_parser
import argparse
from gevent.queue import Queue
from gevent import monkey
from gevent.pool import Pool
monkey.patch_socket()
monkey.patch_ssl()
__version__ = '0.6'
DEFAULT_LOG_FORMAT = "%h %l %u %t \"%r\" ... |
"""
Main module with the bulk_update function.
"""
import itertools
from django.db import connections, models
from django.db.models.query import QuerySet
def _get_db_type(field, connection):
if isinstance(field, (models.PositiveSmallIntegerField,
models.PositiveIntegerField)):
# in... |
from Tkinter import *
import datetime
import re
import itertools
import os
root=Tk()
root.title(" DexEd - a (Dex)terous (Ed)itor")
root.wm_resizable(0,0)
convert_formats = ('%s','%.2e','%.3e','%.4e','%.5e','%.1f','%.3f','%.5f','%5i')
def print_2status(mtype,message):
today = datetime.datetime.now()
s = today.st... |
from tg.controllers.util import LazyUrl
class JSONLazyUrl(LazyUrl):
def __json__(self):
return str(self)
def json_lurl(base_url=None, params=None):
return JSONLazyUrl(base_url, params) |
from __future__ import annotations
import contextlib
from itertools import filterfalse
import re
import sys
import warnings
from . import assertsql
from . import config
from . import engines
from . import mock
from .exclusions import db_spec
from .util import fail
from .. import exc as sa_exc
from .. import schema
from... |
"""
Read a custom fasta file and create a custom GTF containing each entry
"""
import argparse
from itertools import groupby
import logging
logging.basicConfig(format='%(name)s - %(asctime)s %(levelname)s: %(message)s')
logger = logging.getLogger(__file__)
logger.setLevel(logging.INFO)
def fasta_iter(fasta_name):
"... |
from flask import Blueprint, current_app
main = Blueprint(
'main',
__name__
)
from . import errors
from . import views
from ...models import Permission
@main.app_context_processor
def inject_permissions():
return dict(permission=Permission) |
"""Test UptimeRobot sensor."""
from unittest.mock import patch
from pyuptimerobot import UptimeRobotAuthenticationException
from homeassistant.components.uptimerobot.const import COORDINATOR_UPDATE_INTERVAL
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant... |
from unittest import mock
import os
import pytest
import http.client as httplib
from vcr import VCR, mode, use_cassette
from vcr.request import Request
from vcr.stubs import VCRHTTPSConnection
from vcr.patch import _HTTPConnection, force_reset
def test_vcr_use_cassette():
record_mode = mock.Mock()
test_vcr = VC... |
""" core implementation of testing process: init, session, runtest loop. """
import re
import py
import pytest, _pytest
import os, sys, imp
try:
from collections import MutableMapping as MappingMixin
except ImportError:
from UserDict import DictMixin as MappingMixin
from _pytest.runner import collect_one_node
t... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRe... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import textwrap
import copy
import pickle
import future.standard_library.email as email
import future.standard_library.email.message as email_message
from future.standard_... |
import tkinter as tk
import math
import subprocess
import time
import threading
import tkinter as tk
import settings
import utils
from utils import toHex, shadeN
class Thought:
root=[]
canvas=[]
std_r = 50 # "standard" radius
r = 50 # default radius
fontSize = 12
cursorPos=(0,0) #need to track cursor position for... |
import unittest
import numpy
import pyaccel
import trackcpp
import models
class TestTwiss(unittest.TestCase):
def setUp(self):
self.accelerator = models.create_accelerator()
self.accelerator.cavity_on = True
self.accelerator.radiation_on = False
twiss, *_ = pyaccel.optics.calc_twiss(... |
"""Test metadata specification
"""
from pytest import fixture, raises
from smif.metadata import Coordinates, Spec
class TestSpec():
"""A Spec serves as metadata for a model input/parameter/output
Describes an Exchange item (OpenMI)
dtype - see numpy.dtypes
Quality (OpenMI) categorical
Quantity (Open... |
class Snake:
"""Domain class containing information about a snake and its evaluation, including its genetic encoding."""
def __init__(self, encoding):
self.encoding = encoding
self.score = 0
self.moves = 0
self.size = 0 |
"""
Cooley-Rupert-style business cycle figures for Backus-Ferriere-Zin paper,
"Risk and ambiguity in models of business cycles," Carnegie-Rochester-NYU
conference paper, April 2014.
FRED codes: ["GDPC1", "PCECC96", "GPDIC96", "OPHNFB"]
(gdp, consumption, investment, labor productivity)
Cooley-Rupert link: http://eco... |
from .factories import CleanModelFactory, UserFactory
__all__ = [CleanModelFactory, UserFactory] |
import re
import getpass
import urllib
import click
from gg.utils import error_out, info_out, is_github
from gg.state import save, read
from gg.main import cli, pass_config
from gg.builtins import bugzilla
from gg.builtins import github
from gg.builtins.branches.gg_branches import find
@cli.command()
@click.argument("b... |
from __future__ import absolute_import, division, print_function
from astropy.units import Unit
from ..core.sed import IntrinsicSED
from ...core.tools import introspection
from ...core.tools import filesystem as fs
sun_sed_path = fs.join(introspection.skirt_repo_dir, "dat", "SED", "Sun", "SunSED.dat")
Lsun = 3.839e26 *... |
import numpy as np
import copy
import collections
from . import arc
from . import entities
from .. import util
from ..nsphere import fit_nsphere
from ..constants import log
from ..constants import tol_path as tol
def fit_circle_check(points,
scale,
prior=None,
... |
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
import sys # noqa: F40... |
import re
def print_all(seq,type):
fn = lambda(x,y): x
if type=="js": fn = script_tag
def formatted_concat(x,y): return x+fn(y,"root")
return reduce(formatted_concat,seq,"")
def script_tag(url, base):
tag_template = "<script src=\"{__src__}\" type=\"text/javascript\"></script>\n"
if base == "root":
root = "/"
... |
from flask import Flask, render_template_string
from flask_sqlalchemy import SQLAlchemy
from flask_user import login_required, UserManager, UserMixin
class ConfigClass(object):
""" Flask application config """
# Flask settings
SECRET_KEY = 'This is an INSECURE secret!! DO NOT use this in production!!'
#... |
import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="color", parent_name="scattergl.selected.marker", **kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=... |
"""
Fitbit OAuth support.
This contribution adds support for Fitbit OAuth service. The settings
FITBIT_CONSUMER_KEY and FITBIT_CONSUMER_SECRET must be defined with the values
given by Fitbit application registration process.
By default account id, username and token expiration time are stored in
extra_data field, check... |
import datetime
import os
import sys
import log
import logging
import argparse
import math
from optimization_weight import *
from simple_af_theano import *
from data_provision_att_vqa import *
from data_processing_vqa import *
from configurations import get_configurations
def get_lr(options, curr_epoch):
if options... |
from __future__ import print_function
import io
import os
import subprocess
import sys
import contextlib
from distutils.command.build_ext import build_ext
from distutils.sysconfig import get_python_inc
from distutils import ccompiler, msvccompiler
try:
from setuptools import Extension, setup
except ImportError:
... |
"""
Created on Mon Feb 20 03:51:37 2017
@author: Aretas
"""
import argparse
import os
import re
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--vina_config_file',
help='choose a vina configuration file', required=True)
parser.add_argument('-vina', '--vina_location',
help='choose the vina directo... |
from flask import (Flask, g, jsonify, redirect, request)
from io import BytesIO
from random import choice
import os
import requests
from bot import SimpleBot
TELEGRAM_BOT_NAME = os.getenv('TELEGRAM_BOT_NAME')
TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
class ImageRelayBot(SimpleBot):
def __init__(self, tok... |
from __future__ import absolute_import
import numpy as np
import six
from . import backend as K
from .utils.generic_utils import serialize_keras_object
from .utils.generic_utils import deserialize_keras_object
class Initializer(Module):
"""Initializer base class: all initializers inherit from this class.
"""
... |
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
matplotlib.use('Agg')
import matplotlib.pyplot as plot
import inspect, math, mpmath, scipy, itertools
from scipy import special
dark_color = itertools.cycle(('green', 'red', 'goldenrod', 'blue', 'magenta', 'purple', 'gray... |
import re
b = "WILLIAM ALLEY AMERICAN BRANDS died"
c = "AMB"
d = "1996"
e = "66"
f = open('output_B3.txt','r').read()
if 'WILLIAM' in f:
if 'died' in f:
if '1996' in f:
if 'AMB' in f:
if '349631' in f:
if '66' in f:
print 1
else:
pr... |
from decimal import *
import getpass
import math
import os
import os.path
import platform
import sys
import time
from jsonrpc import ServiceProxy, json
BASE_FEE=Decimal("0.001")
def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("2000000... |
import datetime
import logging
from contextlib import contextmanager
_logger = logging.getLogger('pueuey')
def log(**data):
data = dict(data, lib='pueuey')
_logger.debug(" ".join([(k + '=' + v) for k, v in data.items()]))
@contextmanager
def log_yield(**data):
try:
t0 = datetime.datetime.now()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.