code stringlengths 1 199k |
|---|
from .models import SpeedCurveCore
class Deployment(SpeedCurveCore):
"""Deployment class."""
def _update_attributes(self, json):
self.id = json.get('deploy_id')
self.tests_completed = json.get('tests-completed')
self.status = json.get('status')
self.site_id = json.get('site_id')
... |
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from django.core.management import execute_manager
try:
import tests.settings
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory")
sys.exit(1)
if _... |
import subprocess
class SystemCommands(object):
def __init__(self, command):
self.command = command
def execute_command(self):
if self.command == "get_hostname":
s_out = subprocess.Popen(['hostname'], stdout=subprocess.PIPE)
output = s_out.communicate()[0]
elif se... |
'''
antsy: Sweet interpolated ANSI strings
Repo: https://github.com/willyg302/antsy
'''
import os
import re
import sys
__version__ = '0.1.0'
VERSION = tuple(map(int, __version__.split('.')))
PY2 = sys.version_info[0] == 2
if not PY2:
import functools
reduce = functools.reduce
def is_a_tty():
return hasattr(sys.stdou... |
import math
from typing import (
Iterable,
cast,
Union,
List,
Dict,
Callable,
Tuple,
Set,
Optional,
)
import logging
from ezdxf.addons.drawing.config import (
Configuration,
ProxyGraphicPolicy,
HatchPolicy,
)
from ezdxf.addons.drawing.backend import BackendInterface
from ... |
from django.dispatch import Signal
email_address_already_invited = Signal(providing_args=['email_address'])
email_address_already_in_team = Signal(providing_args=['email_address'])
sent_invite_to_email_address = Signal(providing_args=['email_address']) |
import inspect
__all__ = ['on', 'when']
def on(param_name):
def f(fn):
dispatcher = Dispatcher(param_name, fn)
return dispatcher
return f
def when(param_type):
# f - actual decorator
# fn - decorated method, i.e. visit
# ff - fn gets replaced by ff in the effect of applying @when dec... |
from unittest import TestCase
from historia.pops.models.inventory import Inventory, NoInventorySpaceException
from historia.economy.enums.resource import Good
class TestInventory(TestCase):
def test_inventory_list(self):
inv = Inventory(10)
inv.set(Good.grain, 5, 1.5)
self.assertTrue(inv.add... |
from boto.s3.connection import S3Connection
from django.apps import AppConfig
from django.conf import settings
from django.core.files.storage import (
default_storage,
get_storage_class,
)
class MozyConfig(AppConfig):
name = 'mozy.apps.core'
def ready(self):
S3Connection.DefaultHost = settings.A... |
import urlparse
from django.contrib.auth.models import User
from django.contrib.sites.models import RequestSite
from django.http import QueryDict
def get_mutable_query_dict(params=None):
params = params or {}
q = QueryDict('')
q = q.copy()
q.update(params)
return q
def get_full_url(request, path=Non... |
description = ">> make catalogue from table"
import os
from argparse import ArgumentParser
import lsc
import numpy.ma as np
from numpy import pi, newaxis
import astropy.units as u
from astropy.table import Table
from astropy.coordinates import SkyCoord
from astropy.io import ascii
import matplotlib.pyplot as plt
from d... |
"""Given an unsorted array of integers where every integer appears
exactly twice, except for one integer which appears only once. Implement
an algorithm that finds the integer that appears only once."""
def find_odd_integer(integers):
"""The time complexity of this algorithm is
O(N), where N is the number of in... |
import sys
if sys.version_info[:2] >= (2, 7):
import unittest
else:
try:
import unittest2 as unittest
except ImportError:
raise ImportError("The unittest2 package is needed to run the tests.")
del sys
import icarus.scenarios as workload
class TestYCBS(unittest.TestCase):
@classmethod
... |
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.conf import settings
from democracylab.emails import send_volunteer_application_email
class Command(BaseCommand):
def handle(self, *args, **options):
from civictechprojects.models import VolunteerRelation
... |
import numpy as np
import copy
import scipy.interpolate as interpolate
class tensor:
def __init__(self, A=None, eps=1e-14):
if A is None:
self.core = 0
self.u = [0, 0, 0]
self.n = [0, 0, 0]
self.r = [0, 0, 0]
return
N1, N2, N3 = A.shape
... |
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
class TerminalApp(CMSApp):
name = _("Terminal")
urls = ["djangocms_terminal.urls"]
apphook_pool.register(TerminalApp) |
from AppKit import NSScroller, NSColor, NSAttributedString, NSMenuItem, NSShadowAttributeName, NSShadow, \
NSForegroundColorAttributeName, NSFont, NSFontAttributeName, NSSmallControlSize, NSView
import vanilla
class OpenTypeControlsView(vanilla.ScrollView):
def __init__(self, posSize, callback):
self._c... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yak.settings.development")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import os.path
import setuptools
MODULE_NAME = "pytablereader"
REPOSITORY_URL = f"https://github.com/thombashi/{MODULE_NAME:s}"
REQUIREMENT_DIR = "requirements"
ENCODING = "utf8"
pkg_info = {}
def get_release_command_class():
try:
from ... |
from scrapy import Spider
from scrapy.selector import Selector
from hackernews.items import HackerNewItem
class HackerNewsSpider(Spider):
name = "hackernews"
allowed_domains = ["news.ycombinator.com"]
start_urls = [
"http://news.ycombinator.com/",
]
def parse(self,response):
sel = Se... |
import os
import numpy as np
import pandas
from pandas.io import sql as psql
from time import strptime
from math import floor
import sqlite3 as lite
from apsimRegions.preprocess import fileio
def create_tables(masterDbConn, gridLut):
'''
Creates each of the tables in the master run database.
Parameters
... |
from netpyne import specs
from netpyne.batch import Batch
''' Example of evolutionary algorithm optimization of a network using NetPyNE
2 examples are provided: 'simple' and 'complex'
In 'simple', 3 parameters are optimized to match target firing rates in 2 populations
In 'complex', 6 parameters are optimized to match ... |
import sys
from websocket import create_connection
from json import *
ws = create_connection("ws://localhost:9003")
shortSurvivors = ["TCGA.19.2624", "TCGA.12.0657", "TCGA.06.0140", "TCGA.06.0402", "TCGA.41.4097", "TCGA.06.0201",
"TCGA.14.3476", "TCGA.32.1976", "TCGA.06.0213", "TCGA.19.0962", "TCGA.02... |
import numpy as np
from scipy.stats.stats import pearsonr
import matplotlib.pyplot as plt
rootdir = "/home/banua/xprmt/xprmt-icacsis16/"
dataset = 'zoo'
fname = rootdir+dataset+"/"+dataset+"_table_True.csv"
data = np.loadtxt(fname, delimiter="\t", dtype=str, usecols=(1, 2))
data = np.array(data).astype(np.float)
x = da... |
from pe7 import sieve_of_eratosthenes
def sum_primes(n):
result = 2
odds = sieve_of_eratosthenes(n)
for i, isPrime in enumerate(odds):
if isPrime:
result += 2*i + 3
return result
def main():
print sum_primes(int(2e6))
if __name__ == '__main__':
main() |
from flask import Blueprint, render_template
site = Blueprint('site', __name__, template_folder="../templates")
@site.route("/")
def index():
return render_template("index.html") |
import logging
from verlib import NormalizedVersion as Version, IrrationalVersionError
from pypi_notifier.extensions import db
from pypi_notifier.models.repo import Repo
from pypi_notifier.models.package import Package
from pypi_notifier.models.util import JSONType
logger = logging.getLogger(__name__)
class Requirement... |
dicto={}
with open('/tmp/a') as f:
for line in f:
s_line = line.rstrip()
try:
a=dicto[s_line]
except KeyError:
dicto[s_line]=0
pass
dicto[s_line]+=1
print dicto |
from headers import *
class RNN(object):
def __init__(self,layers,cost,Y,learning_rate,update_type=RMSprop(),clipnorm=0.0):
self.settings = locals()
del self.settings['self']
self.layers = layers
self.L2_sqr = theano.shared(value=np.float32(0.0))
for i in range(1, len(layers)):
layers[i].connect(layers[i-... |
"""
This module contains classes and functions for working with chemical reactions.
From the `IUPAC Compendium of Chemical Terminology
<http://dx.doi.org/10.1351/goldbook>`_, a chemical reaction is "a process that
results in the interconversion of chemical species".
In ChemPy, a chemical reaction is called a Reaction o... |
from configservice.exceptions import BusinessRuleViolation, ConfigServiceError
class ConfigProviderNotFound(ConfigServiceError):
def __init__(self, provider_type):
self.provider_type = provider_type
code = 'CONFIG_PARSE_ERROR'
details = {
'provider_type': self.provider_type
... |
import os
for i in range(53):
filename = "ex"+str(i)+".py"
f = open(filename, "w") |
__author__ = 'nickmab'
import nickmab.async_util.threads as thr
from _utils import expect_specific_err as _expect_specific_err
"""To be run by executing py.test in the parent dir"""
def _gen():
yield 1
def test_funcwrap_no_args():
f = lambda: 1
fw = thr.FuncWrap(f)
fw.run()
assert fw.result == 1
def... |
"""
Created on April 28, 2016
@author: Peter Styk <peter@styk.tv>
"""
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
class Settings(object):
# full arguments object passed
args = None
def __init__(self, args):
"""
Constructor
"""
self.a... |
from tornado import gen
from tornado.escape import json_encode
from tornado.web import asynchronous
from base_handler import BaseHandler
class IndexesDatabaseHandler(BaseHandler):
@asynchronous
@gen.engine
def get(self, datid):
database_name = yield gen.Task(self.client_for('postgres').select_scalar... |
"""timeman: Simple time management types
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='timeman',
# Versions shou... |
PACKAGE_ROOT = 'debian'
VERSION_REGEX = r'^v(\d\.\d\.\d$)'
STARTING_VERSION = '0.0.0'
VIRTUAL_ENV_PATH = 've' |
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline impo... |
from socket import socket, AF_INET, SOCK_STREAM, error
from select import select
import sys
from settings import PORT, BUFSIZE, MAGIC_NUM, BROADCAST_MSG
from utils import create_broadcast_socket
def broadcast_data(sock, msg, clients):
for client in clients:
if client != sock:
try:
... |
import numpy as np
import pandas as pd
from hagelslag.util.munkres import Munkres
class ObjectMatcher(object):
"""
ObjectMatcher calculates distances between two sets of objects and determines the optimal object assignments
based on the Hungarian object matching algorithm. ObjectMatcher supports the use of ... |
import os
from nose.tools import eq_
from douglas.plugins import tags
from douglas.tests import PluginTest
class TagsTest(PluginTest):
def setUp(self):
PluginTest.setUp(self, tags)
def test_get_tagsfile(self):
cfg = {'datadir': self.datadir}
eq_(tags.get_tagsfile(cfg),
os.pat... |
from flask import Flask, request
import couchdb, json, datetime
app = Flask(__name__)
server = couchdb.Server()
db = server['test']
headers = {'Content-Type': 'application/json'}
Weekly = {'S': 0, 'M': 0, 'T': 0, 'W': 0, 'R': 0, 'F': 0, 'Sa': 0, 'Tot': 0}
Goals = {'Daily': 24, 'Weekly': 150}
def dayToIndex(day):
sw... |
r"""
===============================================================================
Submodule -- diffusive_conductance
===============================================================================
"""
import scipy as sp
def conduit_conductance(physics, phase, network, throat_conductance,
thro... |
import mock
import pytest
from pyVmomi import vim, vmodl
from vcdriver.exceptions import (
NoObjectFound,
TooManyObjectsFound,
TimeoutError,
IpError,
)
from vcdriver.helpers import (
get_all_vcenter_objects,
get_vcenter_object_by_name,
timeout_loop,
validate_ip,
validate_ipv4,
va... |
"""Module providing views for the folderish content page type"""
import json
from Acquisition import aq_inner
from Products.Five.browser import BrowserView
from plone import api
class ShowRoomView(BrowserView):
""" Show room default view """
def render(self):
return self.index()
def __call__(self):
... |
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 .entity import Entity
from .service import Service
class EscalationPolicy(Entity):
"""PagerDuty escalation policy entity."""
STR_OUTPUT_FIELDS = ('id', 'name',)
TRANSLATE_QUERY_PARAM = ('name',)
def services(self):
"""Fetch all instances of services for this EP."""
ids = [ref['id'] ... |
import logging
import tornado.web
from muniments import errors
logger = logging.getLogger(__name__)
class BaseSchedulerHandler(tornado.web.RequestHandler):
def prepare(self):
logger.info('STARTING: %s %s', self.request.method, self.request.uri)
def on_finish(self):
logger.info('STOPPING: %s %s',... |
from flask import Flask, render_template
from dymo_kanban_labels.lib import jira_api
from dymo_kanban_labels.lib.dymo import JiraLabel
app = Flask(__name__)
@app.route("/")
def home():
return "You have contacted the DKL."
@app.route("/api/preview/issue/<issue_key>", methods=['GET'])
def preview_issue(issue_key):
... |
__version__ = "v3.5.0-dev" |
import web
import karesansui
from karesansui.lib.rest import Rest, auth
class HostBy1Report(Rest):
@auth
def _GET(self, *param, **params):
host_id = self.chk_hostby1(param)
if host_id is None: return web.notfound()
self.view.host_id = host_id
return True
urls = (
'/host/(\d+)... |
from __future__ import print_function
from IPython.display import HTML
from six.moves.urllib.parse import quote
from dark.fastq import FastqReads
def NCBISequenceLinkURL(title, field=None, delim='|'):
"""
Given a sequence title, like
"acc|GENBANK|AY516849.1|GENBANK|42768646 Homo sapiens",
return the... |
from typing import Callable, Dict, List, Optional, Union, TypeVar, cast
from functools import partial
from .ast import (
ArgumentNode,
BooleanValueNode,
ConstArgumentNode,
ConstDirectiveNode,
ConstValueNode,
DefinitionNode,
DirectiveDefinitionNode,
DirectiveNode,
DocumentNode,
En... |
import threading
import wx
from ..module import message
import packet
class Network:
def __init__(self, parent):
""" Initialize Network class """
# var init
self.thread_stop = True
self.socket_list = []
self.id_list = {}
# Inherit
self.server = parent
... |
class Constraint:
def __init__(self): pass
def process_new_value(self): pass
def process_forget_value(self): pass
class Connector:
def __init__(self):
self.value = None
self.informant = None
self.constraints = []
@staticmethod
def for_each_except(exception, bln, items):
... |
__version__ = "7.2.0" |
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Text, TypeDecorator
from sqlalchemy.orm import backref, relation
from . import Base, db_adapter
from datetime import datetime
from hackathon.util import get_now
import json
from pytz import utc
from dateutil import parser
def relationship(*arg, **kw)... |
from .MediaPlayer import MediaPlayer |
import addressbook_pb2
filepath=u'./addressbook.db'
addressbook=addressbook_pb2.AddressBook()
for item in xrange(0,10):
person=addressbook.person.add()
person.id=1234+item
person.name="John Doe"+str(item)
person.email="jdoe@example.com"+str(item)
phone=person.phone.add()
phone.number="555-4321"+... |
"""
globals() と locals() のサンプルです。
"""
from trypython.common.commoncls import SampleBase
from trypython.common.commonfunc import pr
global_variable01 = 'hello world from global'
class Sample(SampleBase):
def exec(self):
self.access_globalvariable_without_globalcall()
self.access_globalvariable_with_g... |
'''
Android target, based on python-for-android project
'''
import sys
if sys.platform == 'win32':
raise NotImplementedError('Windows platform not yet working for Android')
ANDROID_API = '14'
ANDROID_MINAPI = '8'
ANDROID_SDK_VERSION = '21'
ANDROID_NDK_VERSION = '9c'
APACHE_ANT_VERSION = '1.9.4'
import traceback
imp... |
import urllib
import urllib2
import re
import os
import sys
import logging
import pprint
from database import Database
from orderedset import OrderedSet
class Download:
def __init__(self, config, database):
self.config = config
self._dbh = Database(database)
if not os.path.exists(self.config... |
import sublime
import sublime_plugin
import os
import time
import json
from .salesforce.lib.panel import Printer
COMPONENT_METADATA_SETTINGS = "component_metadata.sublime-settings"
TOOLING_API_SETTINGS = "toolingapi.sublime-settings"
EXT_DICT = {
'application': '.app',
'controller': 'controller.js',
'compon... |
class DataSet:
def __init__(self, data_reader, data_writer = None):
self.reader = data_reader
self.writer = data_writer
self.latest = []
def collect(self):
value = self.reader.read_value()
was_added = self.add(value)
print value
# write value if it was acc... |
from django.conf.urls import url
from . import views
app_name = "polls"
urlpatterns = [url(r"^$", views.IndexView.as_view(), name='index'),
url(r"^(?P<pk>[0-9]+)/$", views.DetailView.as_view(), name="detail"),
url(r"^(?P<pk>[0-9]+)/results/$", views.ResultsView.as_view(), name="results"),
... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yablist.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import numpy
import pytest
from numpy.testing import assert_allclose
from fgivenx.parallel import parallel_apply
def f(x):
return x**3
def test_parallel_apply():
array = numpy.linspace(-1, 1, 100)
with pytest.raises(TypeError):
parallel_apply(f, array, wrong_argument=None)
with pytest.raises(Val... |
'''
CLASS: BaseHandler.py
FOR: This class defines the Base for rendering HTML files.
CREATED: 15 December 2013
MODIFIED: 15 December 2013
LOGS:
'''
import jinja2
import webapp2
import os
import logging
from DataStore import *
import Cookies
import json
template_dir = os.path.join(os.path.dirname(__file... |
'''
This module gets the number of completers who did each activity
'''
import csv
from datetime import datetime
from collections import defaultdict
import sys
from common.base_edx import EdXConnection
connection = EdXConnection('tracking' )
collection = connection.get_access_to_collection()
with open('csv_files/McGill... |
"""
WSGI config for north_american_hipster project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.cor... |
import smtplib
import socket
from email.mime.text import MIMEText
from flask import request, render_template, Response, jsonify
from core import app, project_relative_location, config
import token_gen
@app.route('/')
def home():
return render_template('home.html')
@app.route('/robots.txt')
def robots():
return ... |
from click.testing import CliRunner
from unittest import mock
from zeusci.cli import create_venv
from zeusci.cli import get_builder
from zeusci.cli import init_cmd
from zeusci.cli import start_cmd
from zeusci.cli import status_cmd
from zeusci.cli import stop_cmd
import pytest
@mock.patch('zeusci.cli.venv')
def test_get... |
import re
from datetime import timedelta
from urlparse import urlparse
from functools import wraps
from django.core.cache import cache
from django.utils.importlib import import_module
from fandjango.settings import FACEBOOK_APPLICATION_CANVAS_URL
from fandjango.settings import FACEBOOK_APPLICATION_DOMAIN
from fandjango... |
"""Start a mqtt gateway."""
import asyncio
from contextlib import contextmanager
import logging
import socket
import sys
import click
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_mqtt import AsyncMQTTGateway, MQTTGateway
... |
data = [
"""\
0000000500000001b2116ff20000001000002eb255f106760000000600000001000000d000003bc4\
000001fd000003e800e971b800000000000001fd0000000000000002000000010000009000000001\
00000552000000040000008001005e311af56c9ced6213d608004500054034d940003a117b3ad460\
b312e9311af5090a090a052c00004700651ee36d579e13dc65de7811377a... |
"""
Created on Fri Aug 18 16:42:41 2017
@author: m75380
https://www.elastic.co/guide/en/elasticsearch/reference/current/multi-fields.html
$ ./bin/elasticsearch
queries = self.current_queries
new_res = dict()
source_idxs = self.current_queries[0].history_pairs.keys()
for idx in source_idx... |
"""
A script for generating the project-playbills tasks.
"""
import json
import argparse
from helpers import get_task, mkdist, set_config_dir, write_json
from helpers import get_manifest, load_markdown
def get_share_url(manifest_url, canvas_index):
"""Return the BL Universal Viewer URL"""
share_url_base = manif... |
import os
import sys
def check_verbosity():
dir = os.path.dirname(__file__)
abs_path = os.path.join(dir, '../../verbosity')
try:
with open(abs_path, 'r') as verbosity:
VERBOSITY = int(verbosity.readline()) # Verbosity level
SVERBOSITY = list(
map(lambda x: x.s... |
'''VMSS Editor - Azure VM Scale Set management tool'''
import json
import os
import sys
import threading
import tkinter as tk
from time import sleep, strftime
from tkinter import messagebox
import subscription
import vmss
btnwidth = 14
entrywidth = 15
if os.name == 'posix': # Mac OS
geometry1 = '700x140'
geome... |
#sbaas
from SBaaS_base.sbaas_base_query_update import sbaas_base_query_update
from SBaaS_base.sbaas_base_query_drop import sbaas_base_query_drop
from SBaaS_base.sbaas_base_query_initialize import sbaas_base_query_initialize
from SBaaS_base.sbaas_base_query_insert import sbaas_base_query_insert
from SBaaS_base.sbaas_ba... |
import csv
import json
json_data = open('/home/bwaters/School/CS484/yelp-restaurant-classifiers/json/business.json')
data = json.load(json_data)
csv_list = []
with open('categories.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in reader:
for col in row:
... |
import urllib3
import json
def get_pool_manager():
return urllib3.PoolManager()
def post(location, data, headers={"Content-Type": "application/json"}):
http = get_pool_manager()
encoded_data = json.dumps(data).encode('utf-8')
r = http.request('POST', location, body=encoded_data, headers=headers)
ret... |
"""
Module for rendering bonds
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import time
import logging
import functools
import vtk
import numpy as np
from . import baseRenderer
from . import povrayWriters
from .. import utils
from .. import _rendering
from ...filtering import bonds... |
from msrest.serialization import Model
class X12SchemaReference(Model):
"""X12SchemaReference.
:param message_id: The message id.
:type message_id: str
:param sender_application_id: The sender application id.
:type sender_application_id: str
:param schema_version: The schema version.
:type s... |
"""empty message
Revision ID: 0034 add send_after to emails
Revises: 0033 drop tickets.old_event_id
Create Date: 2019-10-09 16:30:23.342044
"""
revision = '0034 add send_after to emails'
down_revision = '0033 drop tickets.old_event_id'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands aut... |
from django.utils.encoding import force_str
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
import magic
from .models.attachment import POSTAL_CONTENT_TYPES
def get_content_type(scan):
scan.seek(0)
content_type = magic.from_buffer(scan.read(1024), mime=T... |
from .H2O import H2O |
from flask import current_app, render_template
from flask.ext.mail import Message
from . import mail, celery
@celery.task
def send_async_email(msg):
mail.send(msg)
def send_email(to, subject, template, **kwargs):
app = current_app._get_current_object()
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] ... |
import logging
def click_progress_listener(progressbar):
def listen(m):
progressbar.pos = m.progress * progressbar.length
progressbar.label = m.message
progressbar.update(0)
if m.is_done:
progressbar.render_finish()
return listen
def log_listener(log:logging.Logger=No... |
print ("Let's calculate some area:")
from math import pi
from time import sleep
from datetime import datetime
now = datetime.now()
print "Starting the calculator ..."
print "Current time: %s/%s/%s %s:%s" % (now.month, now.day, now.year, now.hour, now.minute)
sleep(1)
hint = "Don't forget to include the correct units! \... |
import unittest
import copy
from player import Player
class TestPlayer(unittest.TestCase):
def setUp(self):
self.player = Player()
self.cards = [
{
"rank": "10",
"suit": "hearts"
},
{
"rank": "J",
"su... |
'''ATM-> Will have to make c_graph_from_string for each statement, and
combinde it all into a single c_graph'''
from network_base import *
from network_classes import *
def clean_number(string):
tmp = list(string)
to_kill = []
allowed = ['1','2','3','4','5','6','7','8','9','0','.']
for i in xrange(0,len(tmp)):
... |
# -*- coding: UTF-8 -*-
from flask import Flask, render_template, request, jsonify
import json
import MySQLdb
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/addinfo', methods=['GET'])
def addinfo():
name = request.args.get('name')
#stdNum = request.args... |
from zen.fabric.service_client import ServiceClient
class InteractiveServiceClient(ServiceClient):
''' Interactive Service Client
Service Client for GUI's and other interactive processes
'''
pass |
"""
Django settings for django_get_started project.
"""
from os import path
PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__file__)))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = (
'localhost',
'anextraspace.azurewebsites.net',
)
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGER... |
import types
print "Initializing Co8 Persistent Data module"
def buildPath(fname):
print "modules\\ToEE\\save\\" + fname + ".co8"
"""Helper function to construct the save path"""
return "modules\\ToEE\\save\\" + fname + ".co8" # modified for TemplePlus
def isNone(obj):
if type(obj) == types.NoneType:
... |
'''Filter configuration and execution; result and attribute caching.
There are two caches, both accessible via key lookups in the same
Redis database.
Result cache:
'result:' + murmur(
' '.join(
murmur(
' '.join(
SHA256(filter code),
filter... |
"""
================================================
ABElectronics Delta-Sigma Pi V2 8-Channel ADC
Version 1.0 Created 09/05/2014
Version 1.1 16/11/2014 updated code and functions to PEP8 format
Requires python smbus to be installed
================================================
"""
class DeltaSigma:
# internal v... |
from django.db import models
from django.core.validators import MinValueValidator
from edc_base.model.fields import IsDateEstimatedField, OtherCharField
from edc_constants.choices import YES_NO, YES_NO_NA
from td_list.models import PriorArv
from ..maternal_choices import PRIOR_PREG_HAART_STATUS
from .maternal_crf_model... |
from boxbranding import getBoxType
from time import localtime, mktime
from datetime import datetime
import xml.etree.cElementTree
from os import path
from enigma import eDVBSatelliteEquipmentControl as secClass, \
eDVBSatelliteLNBParameters as lnbParam, \
eDVBSatelliteDiseqcParameters as diseqcParam, \
eDVBSatellite... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.