code stringlengths 1 199k |
|---|
import unittest
from contented.app import Application
class AppTests(unittest.TestCase):
def test_load_app(self):
app = Application({})
self.assertTrue(hasattr(app, "settings"))
self.assertTrue(hasattr(app, "content_map"))
self.assertTrue(hasattr(app, "request_processors")) |
import pathlib
from typing import Union
import lxml.etree
def save_as_xml(
element_tree: Union[lxml.etree._Element, lxml.etree._ElementTree],
filepath: Union[str, pathlib.Path],
pretty_print: bool = True) -> None:
"""save ElementTree in the file as XML
Args:
element_tree ... |
import mysql.connector
import xlrd
import xlsxwriter
import os
from mysql.connector import errorcode
from datetime import datetime
EXCEL_NAME = '20170223_4.0.1_feedback_result_py'
DB_NAME = 'zl_crash'
config = {
'user': 'root',
'password': '123456',
'host': '127.0.0.1',
'database': 'zl_crash',
}
class R... |
from ._excel import ExcelXlsTableWriter, ExcelXlsxTableWriter
from ._pandas import PandasDataFramePickleWriter
from ._sqlite import SqliteTableWriter |
import cookielib
import urllib2
import urllib
import json
import time
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
def INITCOOKIES():
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.... |
from .httpclient import HTTPClient
from .models import Video, Show
__all__ = ['Funimation']
class Funimation(object):
def __init__(self):
super(Funimation, self).__init__()
self.http = HTTPClient('http://www.funimation.com/',
[('User-Agent', 'Sony-PS3')])
# def... |
from behave import *
import os
import subprocess
import glob
import re
import shutil
DNF_FLAGS = ['-y', '--disablerepo=*', '--nogpgcheck']
RPM_INSTALL_FLAGS = ['-Uvh']
RPM_ERASE_FLAGS = ['-e']
def _left_decorator(item):
""" Removed packages """
return u'-' + item
def _right_decorator(item):
""" Installed pa... |
from __future__ import unicode_literals
from django.conf import settings
from django.db import models
from grapevine import generics
from grapevine.models.base import GrapevineModel
from model_utils.managers import PassThroughManager
from .querysets import WelcomeEmailQuerySet
class WelcomeEmail(generics.EmailSendable,... |
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nlcd.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application() |
from fish_bundles.version import __version__ |
import requests
import csv
response = requests.get('http://onesearch.cuny.edu/PrimoWebServices'
'/xservice/search/brief?'
'&institution=KB'
'&query=any,contains,obama'
'&query=facet_rtype,exact,books'
... |
"""
This is pure Python implementation of comb sort algorithm.
Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz
Dobosiewicz in 1980. It was rediscovered by Stephen Lacey and Richard Box in 1991.
Comb sort improves on bubble sort algorithm.
In bubble sort, distance (or gap) between ... |
from django.forms import widgets
from django.template.loader import render_to_string
from django.utils.translation import gettext_lazy as _
from .conf import settings
class PlacesWidget(widgets.MultiWidget):
template_name = 'places/widgets/places.html'
def __init__(self, attrs=None):
_widgets = (
... |
from django.shortcuts import render, HttpResponseRedirect, redirect
from django.contrib.auth.decorators import login_required
from django.views.generic.edit import CreateView
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.forms.models import inlineformset_... |
import sct_utils as sct
import os
contrast = 't2'
path = '/Users/benjamindeleener/data/data_testing/test/'
path_output_seg = '/Users/benjamindeleener/data/spinal_cord_segmentation_data/test/labels/'
path_output_im = '/Users/benjamindeleener/data/spinal_cord_segmentation_data/test/data/'
size = '80'
def generate_data_li... |
"""This example samples from a simple bivariate normal distribution."""
import jass.mcmc as mcmc
import jass.samplers as samplers
import numpy as np
import scipy.stats as stats
import triangle
import matplotlib.pyplot as pl
normal_rv = stats.multivariate_normal(cov=np.identity(2))
initial = [0.0, 0.0]
sampler = sampler... |
from difflib import get_close_matches
import os
from pathlib import Path
def _safe(fn, fallback):
try:
return fn()
except OSError:
return fallback
def _get_all_bins():
return [exe.name
for path in os.environ.get('PATH', '').split(':')
for exe in _safe(lambda: list(Pat... |
"""
test
~~~~
Flask-CORS is a simple extension to Flask allowing you to support cross
origin resource sharing (CORS) using a simple decorator.
:copyright: (c) 2014 by Cory Dolphin.
:license: MIT, see LICENSE for more details.
"""
from tests.base_test import FlaskCorsTestCase, AppConfigTest
from ... |
import os, sys
import datetime
import iris
import iris.unit as unit
import iris.analysis.cartography
import numpy as np
from iris.coord_categorisation import add_categorised_coord
diag = 'avg.5216'
cube_name_explicit='stratiform_rainfall_rate'
cube_name_param='convective_rainfall_rate'
pp_file_path='/projects/cascade/p... |
import random
def drawBoard(board):
# This function prints out the board that it was passed.
# "board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' ... |
"""
@file async_multicast.py
@author Woong Gyu La a.k.a Chris. <juhgiyo@gmail.com>
<http://github.com/juhgiyo/pyserver>
@date March 10, 2016
@brief AsyncMulticast Interface
@version 0.1
@section LICENSE
The MIT License (MIT)
Copyright (c) 2016 Woong Gyu La <juhgiyo@gmail.com>
Permission is hereby granted, free ... |
"""
Author: Lloyd Moore <lloyd@workharderplayharder.com>
Usage:
print perm("01", 2)
> ["00", "01", "10", "11"]
print perm("abcd", 2)
> [ 'aa', 'ab', 'ac', 'ad',
'ba', 'bb', 'bc', 'bd',
'ca', 'cb', 'cc', 'cd',
'da', 'db', 'dc', 'dd' ]
"""
def perm(chars, m, wrd="", wrds=[]):
if len(wrd) == m: return wrd
... |
"""gui systems to manage actions
"""
import os
from sftoolbox.content import ActionContent, PanelContent
from sftoolboxqt import qtgui, qtcore
from sftoolboxqt.tree import PanelsModel, PanelsTreeWidget
class ActionsTreeWidget(qtgui.QTreeWidget):
"""tree widget holding actions
"""
def startDrag(self, dropAct... |
import logging
from pyvisdk.exceptions import InvalidArgumentError
log = logging.getLogger(__name__)
def VmfsDatastoreCreateSpec(vim, *args, **kwargs):
'''This data object type is used when creating a new VMFS datastore, to create a
specification for the VMFS datastore.'''
obj = vim.client.factory.create('n... |
import av
import logging
import random
import sys
import time
import warnings
from livestreamer import Livestreamer
from experiments.test_detecting_in_lol_or_not import get_classifier, process_image
from ocr import ocr_image
logging.getLogger("libav.http").setLevel(logging.ERROR)
warnings.filterwarnings("ignore", categ... |
import sys
import remote_core as core
import radio_lights
def main(argv):
config = core.load_config()
lights_config_names = {"1":"door_light", "2":"desk_light", "3": "shelf_light"}
if len(argv) == 1 and len(argv[0]) == 2:
if argv[0] == "an":
argv = ["1n", "2n", "3n"]
elif argv[0] == "af":
argv = ["1f", "2... |
"""Base64 content transfer encoding per RFCs 2045-2047.
This module handles the content transfer encoding method defined in RFC 2045
to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit
characters encoding known as Base64.
It is used in the MIME standards for email to attach images, audio, and text
... |
"""
下载后的漫画整理模块
====================
请参考注释部分的整理步骤。
"""
from __future__ import print_function, unicode_literals
import os, re
import shutil
import random, string
from hcomic.lib.filetool.files import WinDir, FileCollection
from hcomic.lib.filetool.winzip import zip_everything_in_a_folder
from hcomic.lib.logger import EZL... |
from __future__ import print_function
import time, json
with open("stats.json") as f:
data_s = f.read()
now = time.time()
data = json.loads(data_s)
if now < data["valid_until"]:
valid = "valid"
else:
valid = "EXPIRED"
age = now - data["created"]
print("age: %d (%s)" % (age, valid))
print(data_s) |
from concurrent.futures import ThreadPoolExecutor
import grpc
import pytest
from crawler.services import Library
import crawler_pb2_grpc
@pytest.fixture(name='grpc_client', scope='session', autouse=True)
def setup_grpc_client():
server = grpc.server(ThreadPoolExecutor(max_workers=4))
crawler_pb2_grpc.add_Librar... |
import os
import sys
from IPython.terminal.embed import InteractiveShellEmbed
from mongoalchemy.session import Session
HERE = os.path.abspath(os.path.dirname(__file__))
ROOT = os.path.join(HERE, '..')
sys.path.append(ROOT)
from server.model.user import User # noqa
from server.model.notification import Notification # ... |
def suma(a, b):
return a+b
def resta(a, b):
return a+b |
"""
Created on Tue May 31 10:57:02 2016
@author: noore
"""
import bioservices.kegg
import pandas as pd
kegg = bioservices.kegg.KEGG()
cid2name = kegg.list('cpd')
cid2name = filter(lambda x: len(x) == 2, map(lambda l : l.split('\t'), cid2name.split('\n')))
cid_df = pd.DataFrame(cid2name, columns=['cpd', 'names'])
cid_df... |
"""The tests for the Graphite component."""
import socket
import unittest
from unittest import mock
import blumate.core as ha
import blumate.components.graphite as graphite
from blumate.const import (
EVENT_STATE_CHANGED,
EVENT_BLUMATE_START, EVENT_BLUMATE_STOP,
STATE_ON, STATE_OFF)
from tests.common import... |
"""Init and utils."""
from zope.i18nmessageid import MessageFactory
_ = MessageFactory('dakhli.sitecontent')
def initialize(context):
"""Initializer called when used as a Zope 2 product.""" |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('testproducts', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ProductRequest',
fields=[
... |
from datasift import (
DataSiftUser,
DataSiftDefinition,
DataSiftStream,
DataSiftStreamListener
) |
__author__ = 'bdeutsch'
import re
import numpy as np
import pandas as pd
def get_cards(filename):
# Open the file
with open(filename) as f:
mycards = []
oppcards = []
for line in f:
# Generate my revealed card list
m = re.search('name=(.+)id.+to FRIENDLY HAND', li... |
"""
Created on 1 May 2019
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
https://www.sensirion.com/en/environmental-sensors/particulate-matter-sensors-pm25/
https://bytes.com/topic/python/answers/171354-struct-ieee-754-internal-representation
Firmware report:
89667EE8A8B34BC0
"""
import time
from scs_core.d... |
from polyphony import testbench
def loop_var01():
for i in range(10):
pass
return i
@testbench
def test():
loop_var01()
test() |
"""38. Count and Say
https://leetcode.com/problems/count-and-say/description/
The count-and-say sequence is the sequence of integers with the first five
terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, ... |
import os
massFile = 'AWTMass-2003.dat'
newFile = os.path.join('..', 'nmrfreq', 'masstable.py')
def main():
with open(massFile, 'r') as file:
massDict = extractMasses(file)
writeToFile(newFile, massDict, massFile)
def extractMasses(file):
massdict = {}
for line in file:
line = adjustLine... |
import json
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from rest_framework.test import force_authenticate
from rest_framework import status
from rest_framework.authtoken.models import Token
from core.models import Profile, User
from api.views import ProfileDetail
from api.seriali... |
from test_framework.test_framework import AureusTestFramework
from test_framework.util import *
from binascii import a2b_hex, b2a_hex
from hashlib import sha256
from struct import pack
def check_array_result(object_array, to_match, expected):
"""
Pass in array of JSON objects, a dictionary with key/value pairs
... |
__author__ = 'Yuvv'
OS_PROJECT_DOMAIN_ID = 'default'
OS_USER_DOMAIN_ID = 'default'
OS_PROJECT_NAME = 'admin'
OS_TENANT_NAME = 'admin'
OS_USERNAME = 'admin'
OS_PASSWORD = 'yuvv'
OS_AUTH_URL = 'http://controller:5000/v2.0/'
OS_IDENTITY_API_VERSION = 3
OS_IMAGE_API_VERSION = 2
OS_AUTH_VERSION = 3
'''
keystone = ksclient.C... |
__author__ = 'Yacine Haddad'
__email__ = 'yhaddad@cern.ch'
__version__ = '2.0.0' |
"""Error codes for JavaScript style checker."""
__author__ = ('robbyw@google.com (Robert Walker)',
'ajp@google.com (Andy Perelson)')
def ByName(name):
"""Get the error code for the given error name.
Args:
name: The name of the error
Returns:
The error code
"""
return globals()[name]
FILE... |
import pytest, sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../")
from unittest import TestCase
from pylogic.case import Case
class TestBaseOperand(TestCase):
def test_eq_case(self):
case1 = Case("parent", "homer", "bart")
case2 = Case("parent", "homer", "bart")
as... |
"""A program to detect Process Linkage Networks using
Simulated Annealing.
"""
import collections
import itertools
import sys
from convutils import convutils
import bpn.cli
import bpn.structures
from defaults import (
SUPERDEBUG,
SUPERDEBUG_MODE,
LINKS_FIELDNAMES,
PARAMETERS_FIELDNAMES,
... |
import os
import csv
import time
import random
import operator
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data as mnist_input_data
def main():
# Test classification using the following code:
#
# classifier = Classifier("model.pb")
# dataset = KatakanaDataSet()
... |
from django.shortcuts import render
from django.views import View
class SiteUpdateNotifier(View):
def get(self, request):
pass |
"""
make_a_star_cluster.py creates a model star cluster,
which can then be used in N-body simulations or for other purposes.
It requires AMUSE, which can be downloaded from http://amusecode.org or
https://github.com/amusecode/amuse.
Currently not feature-complete yet, and function/argument names are
subject to change.
... |
from setuptools import setup, find_packages
setup(
name="tomorrow",
version="0.2.4",
author="Madison May",
author_email="madison@indico.io",
packages=find_packages(
exclude=[
'tests'
]
),
install_requires=[
"futures >= 2.2.0"
],
description="""
... |
import os
import MySQLdb
import logging
_log = logging.getLogger('thanatos')
def execute_sql(sql, db_connection, fetch='all'):
"""
:param sql:
:param db_connection:
:param fetch: A string of either 'all' or 'one'.
:return:
"""
cursor = db_connection.cursor()
cursor.execute(sql)
if fe... |
__version__ = "0.0.2"
from .samplesubmod import * |
from w3lib.html import remove_tags
from requests import session, codes
from bs4 import BeautifulSoup
class Student:
_hours = 0
_wage = 0
_tax_rate = 18
_cost = 20
def __init__(self, hours, wage, cost):
self._hours = hours
self._wage = wage
self._cost = cost
def _get_real_... |
"""
Automatically test a given treewidth solver:
./autotest-tw-solver.py path/to/my/solver
The test is run on some corner cases, and on graphs were past PACE submissions
exhibited bugs.
Optional argument:
--full run test on all graphs with min-degree 3 and at most 8 vertices
Requires python3-networkx
Copyrigh... |
from common.persistence import from_pickle
NWORDS = from_pickle('../data/en_dict.pkl')
print(len(NWORDS))
print(NWORDS['word'])
print(NWORDS['spell'])
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def edits1(word):
s = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [a + b[1:] for a, b in s if b]
t... |
"""
mpstest7.py
A test of manipulating matrix product states with numpy.
2014-08-25
"""
import numpy as np
import matplotlib.pyplot as plt
from cmath import *
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
def main():
test3()
def test3():
""" Test MPS conversion functions by computing fidelit... |
from __future__ import (print_function, unicode_literals, absolute_import,
division)
import json
import re
import six
import sys
channel_name_re = re.compile('\A[-a-zA-Z0-9_=@,.;]+\Z')
app_id_re = re.compile('\A[0-9]+\Z')
pusher_url_re = re.compile('\A(http|https)://(.*):(.*)@(.*)/apps/(... |
import contextlib
import functools
import socket
import ssl
import tempfile
import time
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Hashable,
Iterable,
Iterator,
List,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
import pytest
from... |
PLACES = ["Virginia", "Lexington", "Washington", "New York"] |
from onlineticket.generated.ticket import Ticket
from onlineticket.section import SectionParser
class TicketParser:
def parse(self, filename):
parsed = self._parse_kaitai(filename)
return self._map(parsed)
def _parse_kaitai(self, filename):
return Ticket.from_file(filename)
def _map(... |
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
import docker
@python_2_unicode_compatible
class DockerServer(models.Model):
name = models.CharField(max_length=255, unique=True)
version = models.CharField(max_length=255, default=... |
from flask import Blueprint
main = Blueprint('main', __name__)
from . import errors, views
from ..models import Permission
@main.app_context_processor
def inject_permissions():
return dict(Permission=Permission) |
from .models import Donor
from django.forms import ModelForm, TextInput
class DonorForm(ModelForm):
class Meta:
model = Donor
fields = [
"email",
"donation_date",
"phone_number",
"address",
"observations"
]
widgets = {
'donation_date': TextInput(attrs={'class': 'form-control'}),
... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('courses', '0012_userlesson'),
]
operations = [
migrations.AddField(
model_name='exercise',
name=... |
import argparse, json
import boto3
from boto.mturk.connection import MTurkConnection
from boto.mturk.qualification import *
from jinja2 import Environment, FileSystemLoader
"""
A bunch of free functions that we use in all scripts.
"""
def get_jinja_env(config):
"""
Get a jinja2 Environment object that we can use to... |
import json
import requests
import logging
logger = logging.getLogger(__name__)
import warnings
import time
import sys
from counterpartylib.lib import config
from counterpartylib.lib import util
from counterpartylib.lib import exceptions
from counterpartylib.lib import backend
from counterpartylib.lib import database
C... |
from django import forms
from giza.models import Giza
class GizaEditForm(forms.ModelForm):
"""Giza edit form"""
class Meta:
"""Meta for GizaEditForm"""
model = Giza
exclude = ('user',)
def __init__(self, *args, **kwargs):
"""Init"""
self.user = kwargs.pop('user', None... |
"""
Project-wide application configuration.
DO NOT STORE SECRETS, PASSWORDS, ETC. IN THIS FILE.
They will be exposed to users. Use environment variables instead.
See get_secrets() below for a fast way to access them.
"""
import os
"""
NAMES
"""
PROJECT_SLUG = 'lunchbox'
PROJECT_FILENAME = 'lunchbox'
REPOSITORY_NAME = '... |
import theano
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from sklearn import cross_validation, metrics, datasets
from neupy import algorithms, layers, environment
environment.reproducible()
theano.config.floatX = 'float32'
mnist = datasets.fetch_mldata('MNIST original')
target_scaler = OneHotEnc... |
import numpy as np
import tensorflow as tf
from .module import Module
class RBFExpansion(Module):
def __init__(self, low, high, gap, dim=1, name=None):
self.low = low
self.high = high
self.gap = gap
self.dim = dim
xrange = high - low
self.centers = np.linspace(low, hi... |
from __future__ import unicode_literals
import django.contrib.auth.validators
from django.db import migrations, models
import users.managers
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations... |
import os
DIRNAME = os.path.dirname(__file__)
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}
}
INSTALLED_APPS = (
"django.contrib.auth",
"django.contrib.contenttypes",
"pqauth.pqauth_django_server"
)
SECRET_KEY = "chicken butt"
PQAUTH_SERVER_KEY = os.path.join(DIRNAME, "... |
from twitter import *
import simplejson
import serial
import datetime
import time
import threading
QUIT = 0
prevtweet = ""
def centerstring(string,width):
""" Pad a string to a specific width """
return " "*((width-len(string))/2)+string
def padstring(string,width):
"""pad a string to a maximum length"""
if len... |
import pymongo
import yaml
import utils
from utils import SupplyResult
from utils.tech import get_dev_channel, short_sleep
subreddit = 'all'
t_channel = '@r_channels'
SETTING_NAME = 1
def send_post(submission, r2t):
config_filename = 'configs/prod.yml'
with open(config_filename) as config_file:
config =... |
def diff_int(d=0.01*u.cm,a=0.001*u.cm,wl=400*u.nm):
'''
function that returns the intensity of a double slit interference pattern
'''
theta = arange(-10,10,1e-5)*u.degree
x = pi*a*sin(theta)/wl*u.radian
xnew = x.decompose()
i_single = (sin(xnew)/xnew)**2
y = pi*d*sin(theta)/wl*u.radian
... |
'''
本文件中包含的是CTA模块的回测引擎,回测引擎的API和CTA引擎一致,
可以使用和实盘相同的代码进行回测。
'''
from datetime import datetime, timedelta
from collections import OrderedDict
from itertools import product
import pymongo
import json
import os
import cPickle
import csv
from ctaBase import *
from ctaSetting import *
from eventEngine import *
from vtConstan... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import json
import time
def keys(filename):
with open(filename) as f:
secret_keys = json.load(f)
return secret_keys
def access_listpage(secret_keys, driver):
driver.get("https://wine.wul.waseda.ac.jp/patroninfo*jpn")
... |
from flask import Flask, session, render_template, url_for, redirect, request, flash, g
from flask.ext import assets
import pyxb
import json
import json
import os
import paypalrestsdk
app = Flask(__name__)
paypal_client_id = "AacMHTvbcCGRzaeuHY6i6zwqGvveuhN4X_2sZ2mZJi76ZGtSZATh7XggfVuVixzyrRuG-bJTLOJIXltg"
paypal_clien... |
from .proc_base import ProcBase
class ProcMaps(ProcBase):
'''Object represents the /proc/[pid]/maps file.'''
def __init__(self, pid):
'''
Read file by calling base class constructor
which populates self.content. This file is
already ASCII printable, so no further
parsing ... |
"""
Reduce samples that have too high energies by comparing
between the same group of samples.
The group is defined according to the name of directory before the last 5 digits.
For example, the directory `smpl_XX_YYYYYY_#####` where `#####` is the
last 5 digits and the group name would be `smpl_XX_YYYYY`.
Usage:
redu... |
from os import makedirs
from os.path import join
from posix import listdir
from django.conf import settings
from django.core.management.base import BaseCommand
from libavwrapper.avconv import Input, Output, AVConv
from libavwrapper.codec import AudioCodec, NO_VIDEO
from 匯入.族語辭典 import 代碼對應
class Command(BaseCommand):
... |
import numpy as np
import numpy.random as rng
import theano
import theano.tensor as T
from theano.tensor.nnet import conv2d
minibatch = 3
image_height,image_width = 28,28
filter_height,filter_width = 3,3
n_filters = 1
n_channels = 1
n = 1/(np.sqrt(image_height*image_width))
X = T.tensor4(name='X')
X_shape = (minibatch,... |
from .max import max
from pyramda.private.asserts import assert_equal
def max_test():
assert_equal(max([1, 3, 4, 2]), 4) |
import __settings__
from __settings__ import INSTALLED_APPS
assert hasattr(__settings__, 'BASE_DIR'), 'BASE_DIR required'
INSTALLED_APPS += (
'post',
) |
import _plotly_utils.basevalidators
class MetaValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(self, plotly_name="meta", parent_name="surface", **kwargs):
super(MetaValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwa... |
from typing import List
from backend.common.cache_clearing import get_affected_queries
from backend.common.manipulators.manipulator_base import ManipulatorBase
from backend.common.models.cached_model import TAffectedReferences
from backend.common.models.media import Media
class MediaManipulator(ManipulatorBase[Media]):... |
import _plotly_utils.basevalidators
class SeparatethousandsValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self,
plotly_name="separatethousands",
parent_name="scattermapbox.marker.colorbar",
**kwargs
):
super(SeparatethousandsValidator, self).__ini... |
from .health_evaluation import HealthEvaluation
class ApplicationsHealthEvaluation(HealthEvaluation):
"""Represents health evaluation for applications, containing health
evaluations for each unhealthy application that impacted current aggregated
health state.
:param aggregated_health_state: Possible val... |
import chainer
from chainer import cuda
import chainer.utils
class Send(chainer.Function):
"""Send elements to target process."""
def __init__(self, comm, peer_rank, peer_tag):
chainer.utils.experimental('chainermn.functions.Send')
self.comm = comm
self.peer_rank = peer_rank
self... |
from bottle import Bottle, run
app = Bottle()
@app.route('/')
def index():
return 'PService Running'
run(
app, # Run |app| Bottle() instance
host = '0.0.0.0',
port = 8080,
reloader = True, # restarts the server every time edit a module file
d... |
from __future__ import absolute_import, print_function, division
from petl.test.helpers import ieq
from petl.util import expr, empty, coalesce
from petl.transform.basics import cut, cat, addfield, rowslice, head, tail, \
cutout, skipcomments, annex, addrownumbers, addcolumn, \
addfieldusingcontext, movefield, s... |
import os
import re
import sys
vowels = set(('a','e','i','o','u','A','E','I','O','U'))
consonant_re = re.compile(r'([bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]+)([a-zA-Z]*)(.*)?')
original = sys.stdin.read()
piglatin = []
for word in original.split():
# there are different rules if it starts with a vowel
if wo... |
try:
import electrum_arg as electrum
from electrum_arg.bitcoin import TYPE_ADDRESS, var_int, msg_magic, Hash, verify_message, public_key_to_p2pkh, EncodeAES, DecodeAES
from electrum_arg.i18n import _
from electrum_arg.keystore import Hardware_KeyStore
from ..hw_wallet import HW_PluginBase
from e... |
import argparse
import os
import simplejson as json
import grpc
from google.protobuf.json_format import MessageToJson
from qrl.core import config
from qrl.core.AddressState import AddressState
from qrl.crypto.xmss import XMSS
from qrl.core.txs.Transaction import Transaction
from qrl.core.txs.TransferTransaction import ... |
import sys
from PyFBA import lp, log_and_message
def reaction_bounds(reactions, reactions_with_upsr, media, lower=-1000.0, mid=0.0, upper=1000.0, verbose=False):
"""
Set the bounds for each reaction. We set the reactions to run between
either lower/mid, mid/upper, or lower/upper depending on whether the
... |
from .create2 import *
from .factory import *
__all__ = ["FactoryCreate", "FactorySimulation"] |
"""This file should be used to run the flask app with something like Gunicorn.
For example: gunicorn -b 0.0.0.0:8000 ocspdash.web.wsgi:app
This file should NOT be imported anywhere, though, since it would instantiate the app.
"""
from ocspdash.web import create_application
app = create_application() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.