code stringlengths 1 199k |
|---|
from debug_toolbar.panels.templates import TemplatesPanel as BaseTemplatesPanel
class TemplatesPanel(BaseTemplatesPanel):
def generate_stats(self, *args):
template = self.templates[0]['template']
if not hasattr(template, 'engine') and hasattr(template, 'backend'):
template.engine = templ... |
from django.shortcuts import render, get_object_or_404
from vehicles.context_processor import global_context_processor
from vehicles.models import Vehicle, VehicleMake, Category
from settings.models import SliderImage
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from dynamic_preferences.registrie... |
import sys
import zlib, base64
_g = ("Ah+LCAAAAAAABACT7+ZgAAEWhre3/LNvG0iwP1i/yPTlUbXVqdvzlJoi+a3Lj8v6RJl1JZacmaK7/Otuf07ZXEnrN/zZZ+cdV4iexrfrz59Tftsevr0tcO7wz0oLK678"
+ "PLvaHVX/Lff8K6otFRbb/W/369X9D7+oMAiXlZWJlbEzGIQaM4yCUTAKRsEoGPzgnzcjw4w9ejJ35HS6A8KTT0zfPp3dVXBWrHr2qoXeofNfZVm8eZ31+0g2a93585ut"
+ "w3JN9984E/el... |
__version__ = '0.8.0'
__author__ = 'Steven Loria'
__license__ = 'MIT'
from webargs.core import Arg, WebargsError, ValidationError, Missing
__all__ = ['Arg', 'WebargsError', 'ValidationError', 'Missing'] |
import numpy
import numpy.linalg
def training(inputs, minvar=0.1):
"""Trains a naive-bayes classifier using inputs
Returns means and variances of the classifiers
"""
return numpy.mean(inputs, axis=0), numpy.maximum(minvar, numpy.var(inputs, axis=0))
def gaussian(input, mu, sigma2):
"""Calculates gau... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home),
url(r'^interviewer/$', views.interviewer),
url(r'^candidate/$', views.candidate),
] |
import pytest
from ezdxf.entities.appid import AppID
@pytest.fixture
def appid():
return AppID.new(
"FFFF",
dxfattribs={
"name": "EZDXF",
},
)
def test_name(appid):
assert appid.dxf.name == "EZDXF" |
import os
from twilio.rest import Client
account = os.environ['TWILIO_ACCOUNT_SID']
token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account, token)
role = client.chat \
.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.roles("RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.fetch()
new_permissions = ['sendM... |
from flask import render_template, flash, redirect
from app import app
from .forms import Deck
@app.route('/submit', methods=('GET', 'POST'))
def submit():
form = Deck()
if form.validate_on_submit():
return redirect('/index')
return render_template('submit.html',
title='Create Card',
form=form)
@app.... |
"""
rio.blueprints.api_1
~~~~~~~~~~~~~~~~~~~~~
"""
from flask import Blueprint
bp = Blueprint('api_1', __name__) |
import math
from ..df import DocumentFrequencyVectorCreator
from . import InverseDocumentFrequencyVector
class InverseDocumentFrequencyVectorCreator(DocumentFrequencyVectorCreator):
"""Creates inverse-document-frequency vectors
Inherits from :class:`recommender.vector.abstractvector.VectorCreator`
:paramete... |
from scripts.db_api import accident
def usa_query(hour):
return '''
SELECT count(*), (select count(*) from accident
join vehicle on(acc_id = accident.id)
where country = 'USA'
and vehicle.speed > accident.speed_limit
and vehicle.speed > -1
and accident.speed_limit > 0
and date_part('hour', t... |
class TestDevice:
def __init__(self, cf):
self.type = cf.get('device_test_type', 'test')
self.host = ('test', 80)
self.mac = [1, 2, 3, 4, 5, 6]
def auth(self):
pass
# RM2/RM4
def check_temperature(self):
return 23.5
# RM4
def check_humidity(self):
... |
import os
import stat
import socket
import paramiko
from transfert.statresult import stat_result
from transfert.resources._resource import _Resource
from transfert.exceptions import TransfertFileExistsError, TransfertFileNotFoundError
class SftpResource(_Resource):
KNOW_HOSt_FILE = '~/.ssh/known_hosts'
GSS_AUTH... |
import unittest
import numpy as np
from collections import Counter
from diogenes.utils import remove_cols,cast_list_of_list_to_sa
import utils_for_tests
import unittest
import numpy as np
from numpy.random import rand
import diogenes.read
import diogenes.utils
from diogenes.modify import remove_cols_where
from diogenes... |
from .base import BaseType
class SavedActionApproval(BaseType):
_soap_tag = 'saved_action_approval'
def __init__(self):
BaseType.__init__(
self,
simple_properties={'id': int,
'name': str,
'approved_flag': int},
complex_p... |
import unittest
import os
from os.path import dirname
import sys
import json
from rtree import index
from . import ROOT
from geotweet.mapreduce.utils.lookup import project, SpatialLookup
testdata = os.path.join(dirname(os.path.abspath(__file__)), 'testdata')
def read(geojson):
return json.loads(open(os.path.join(te... |
import os
from PIL import Image
import glob
start_dir = "images/full_sprites/opaque/kanto/"
end_dir = "images/full_sprites/transparent/kanto/"
iconmap = os.listdir(start_dir)
print(len(iconmap))
for filename in iconmap:
image = Image.open(start_dir+filename)
image_width, image_height = image.size
print( "the imag... |
"""
Fields represent CronTrigger options which map to :class:`~datetime.datetime`
fields.
"""
from calendar import monthrange
from apscheduler.triggers.cron.expressions import (
AllExpression, RangeExpression, WeekdayPositionExpression, LastDayOfMonthExpression, WeekdayRangeExpression)
__all__ = ('MIN_VALUES', 'MAX... |
from django.utils.translation import ugettext_lazy as _
from reviewboard.admin.read_only import is_site_read_only_for
from reviewboard.reviews.actions import (BaseReviewRequestAction,
BaseReviewRequestMenuAction)
from reviewboard.reviews.features import general_comments_feature
... |
"""
Retrieves menu from Drupal site
"""
from aashestrap.models import Menu
from django.core.management.base import BaseCommand
import urllib2
from django.http import HttpResponse
from BeautifulSoup import BeautifulSoup
from django.core.exceptions import ObjectDoesNotExist
class Command(BaseCommand):
def handle(... |
from __future__ import unicode_literals
from django.apps import AppConfig
class FileuploadConfig(AppConfig):
name = 'fileupload' |
"""
Django settings for blog project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
BASE_DIR = ... |
import cPickle
import logging
import numpy
import os
import time
from collections import deque
from copy import deepcopy
from datetime import datetime
from pytz import timezone
from threading import Event, Thread
from coinbase.wallet.client import Client
from jarvis.utils.messaging.client import TwilioMessenger
from ja... |
def NUMBER(value):
return ("NUMBER", value)
def NAME(value):
return ("NAME", value)
def SYMBOL(value):
return ("SYMBOL", value)
def SEMICOLON():
return ("SEMICOLON", )
def OPENPAREN():
return ("OPENPAREN", )
def CLOSEPAREN():
return ("CLOSEPAREN", )
def OPENBRACKET():
return ("OPENBRACKET", ... |
"""
Talon.One API
The Talon.One API is used to manage applications and campaigns, as well as to integrate with your application. The operations in the _Integration API_ section are used to integrate with our platform, while the other operations are used to manage applications and campaigns. ### Where is the AP... |
import os
import re
from . import utils
PARTIAL = re.compile('(?P<tag>{{>\s*(?P<name>.+?)\s*}})')
PARTIAL_CUSTOM = re.compile('^(?P<whitespace>\s*)(?P<tag>{{>\s*(?P<name>.+?)\s*}}(?(1)\r?\n?))', re.M)
def build(template, partials=None):
template = '{}\n'.format(template)
for regex in (PARTIAL_CUSTOM, PARTIAL):
... |
import socket as sk
from kivy.logger import Logger
def getWebsite():
return "www.google.com"
def getIpPort():
sock_info=sk.getaddrinfo(getWebsite(),80,proto=sk.IPPROTO_TCP)
return sock_info[0][-1]
def checkInternet():
sock=sk.socket()
sock.settimeout(1)
try:
sock.connect(getIpPort())
... |
import os
import subprocess
import tempfile
from awscli.customizations.emr import constants
from awscli.customizations.emr import emrutils
from awscli.customizations.emr import sshutils
from awscli.customizations.emr.command import Command
KEY_PAIR_FILE_HELP_TEXT = '\nA value for the variable Key Pair File ' \
'can... |
from __future__ import absolute_import
from __future__ import unicode_literals
import io
import os.path
import sqlite3
import mock
import pytest
import six
from pre_commit.store import _get_default_directory
from pre_commit.store import Store
from pre_commit.util import cmd_output
from pre_commit.util import cwd
from p... |
import sys, logging
import numpy as np
from math import ceil
from gseapy.stats import multiple_testing_correction
from joblib import delayed, Parallel
def enrichment_score(gene_list, correl_vector, gene_set, weighted_score_type=1,
nperm=1000, seed=None, single=False, scale=False):
"""This is th... |
import os
import csv
from collections import (
defaultdict as dd,
OrderedDict as od
)
from math import log
import datetime
from flask import (
Flask,
render_template,
g,
request,
redirect,
url_for,
send_from_directory,
flash,
jsonify,
make_response,
Markup,
Respon... |
from datetime import timedelta
import logging
from django.utils.timezone import now
from django.core.management.base import BaseCommand
from TWLight.users.models import Editor
from TWLight.users.helpers.editor_data import (
editor_global_userinfo,
editor_valid,
editor_enough_edits,
editor_not_blocked,
... |
import os
import shutil
from jinja2 import Environment, FileSystemLoader
from webassets import Environment as AssetsEnvironment
from webassets.ext.jinja2 import AssetsExtension
from webassets.loaders import YAMLLoader
class TemplateBuilder(object):
def __init__(self, path, output,
static_path='stat... |
import string
from time import strftime
def append_new_end(word,user_end):
space_count = word.count('~') # count number of placeholders
if space_count > 0:
total_word = word[:-space_count] + user_end # supplied from raw input
else:
total_word = word
return total_word
def create_updated_array(text_complete,text_... |
__revision__ = "test/Platform.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
import TestSCons
test = TestSCons.TestSCons()
test.write('SConstruct', """
env = Environment()
Platform('cygwin')(env)
print "'%s'" % env['PROGSUFFIX']
assert env['SHELL'] == 'sh'
Platform('os2')(env)
print "'%s'" % env['PROGSUFF... |
"""Run Monte Carlo simulations."""
from joblib import Parallel, delayed
from frbpoppy import Survey, CosmicPopulation, SurveyPopulation, pprint
from datetime import datetime
from copy import deepcopy
from glob import glob
import frbpoppy.paths
import os
import numpy as np
import pandas as pd
from tqdm import tqdm
impor... |
try: from setuptools import setup
except: from distutils.core import setup
setup( long_description=open("README.rst").read(),
name="""tinypath""",
license="""MIT""",
author="""Karim Bahgat""",
author_email="""karim.bahgat.norway@gmail.com""",
py_modules=['tinypath'],
url="""http://github.com/karimbahgat/tinypath"... |
from south.db import db
from django.db import models
from askmeanything.models import *
class Migration:
def forwards(self, orm):
"Write your forwards migration here"
def backwards(self, orm):
"Write your backwards migration here"
models = {
'askmeanything.poll': {
'creat... |
import os
from shutil import copyfile
from photomanip.metadata import ImageExif, SetExifTool
from nose import tools
ORIGINAL_IMAGE_FILENAME = 'photomanip/tests/turd_ferguson.jpeg'
TEST_IMAGE_FILENAME = 'photomanip/tests/image_exif_test.jpg'
ORIGINAL_PHOTO_FILENAME = 'photomanip/tests/test_photo_0.jpg'
TEST_PHOTO_01_FIL... |
__author__ = 'jhala'
import types
import os.path, time
import json
import logging
import logging.config
logging.config.fileConfig('logging.conf')
logger = logging.getLogger(__name__)
import re
appInfo='appinfo.json'
''' Helper Functions '''
''' get the file as an array of arrays ( header + rows and columns) '''
def fi... |
from django.contrib.sites.models import Site
from django.utils._os import safe_join
from django.views.generic import TemplateView
from skin.conf import settings
from skin.template.loaders.util import get_site_skin
class TemplateSkinView(TemplateView):
"""
A view that extends Djangos base TemplateView to allow y... |
from direct.directnotify.DirectNotifyGlobal import *
from otp.ai.AIBaseGlobal import *
from toontown.building import DistributedBuildingAI
from toontown.building import GagshopBuildingAI
from toontown.building import HQBuildingAI
from toontown.building import KartShopBuildingAI
from toontown.building import PetshopBuil... |
__author__ = 'ivan.shynkarenka'
import argparse
from TTWebClient.TickTraderWebClient import TickTraderWebClient
def main():
parser = argparse.ArgumentParser(description='TickTrader Web API sample')
parser.add_argument('web_api_address', help='TickTrader Web API address')
args = parser.parse_args()
# Cre... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import spectator.core.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
("spectator_core", "0001_initial"),
]
operations = [
migrations.CreateMode... |
from gluon.storage import Storage
settings = Storage()
settings.logon_methods = 'web2pyandjanrain'
settings.verification = False
settings.approval = False |
import bottle
import settings
from controller import admin as admin_controller
from controller import email as email_controller
app = application = bottle.Bottle()
app.route(settings.BASEPATH, 'GET', admin_controller.index)
app.route(settings.BASEPATH + '/', 'GET', admin_controller.index)
app.route(
settings.BASEPA... |
import vk
import json
from sentiment_classifiers import SentimentClassifier, binary_dict, files
class VkFeatureProvider(object):
def __init__(self):
self._vk_api = vk.API(vk.Session())
self._vk_delay = 0.3
self._clf = SentimentClassifier(files['binary_goods'], binary_dict)
def _vk_grace(... |
"""Settings to be used for running tests."""
from settings import *
INSTALLED_APPS.append('integration_tests')
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
EMAIL_SUBJECT_PREFIX = '[test] '
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBacken... |
import sublime, sublime_plugin, re
class EmmetCssFromOneLineCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
line_region = view.line(view.sel()[0])
line_str = view.substr(line_region)
left_padding = re.findall(r'^(\s+)', line_str)[0]
# find commands ... |
try:
from ._models_py3 import Error
from ._models_py3 import Key
from ._models_py3 import KeyListResult
from ._models_py3 import KeyValue
from ._models_py3 import KeyValueListResult
from ._models_py3 import Label
from ._models_py3 import LabelListResult
except (SyntaxError, ImportError):
... |
"""
https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-16.html#%_thm_2.60
"""
from Chapter2.themes.lisp_list_structured_data import car, cdr, cons, lisp_list, nil, print_lisp_list
from Chapter2.themes.sequences_as_conventional_interfaces import accumulate
def element_of_set(x, set):
"""Tests if x is element of s... |
""" You've recently read "The Gold-Bug" by Edgar Allan Poe, and was so impressed by the cryptogram in it that
decided to try and decipher an encrypted text yourself. You asked your friend to encode a piece of text using
a substitution cipher, and now have an encryptedText that you'd like to decipher.
The encryption pro... |
def True(
foo
):
True(
foo
)
def False(
foo
):
False(
foo
)
def None(
foo
):
None(
foo
)
def nonlocal (
foo
):
nonlocal(
foo
) |
import tensorflow as tf
from tensorflow.contrib import slim as slim
from avb.ops import *
import math
def encoder(x, config, is_training=True):
df_dim = config['df_dim']
z_dim = config['z_dim']
a_dim = config['iaf_a_dim']
# Center x at 0
x = 2*x - 1
net = flatten_spatial(x)
net = slim.fully_... |
import sys
sys.path.append("./")
import pandas as pd
import gensim
from utility.mongodb import MongoDBManager
from utility.sentence import segment, sent2vec
class Doc2Vector(object):
"""
文本转向量
"""
def __init__(self):
"""
:param keep_val: 设定的阈值
"""
self.mongo_db = MongoDBM... |
from __future__ import unicode_literals
from future.builtins import int
from collections import defaultdict
from django.core.urlresolvers import reverse
from django.template.defaultfilters import linebreaksbr, urlize
from mezzanine import template
from mezzanine.conf import settings
from mezzanine.generic.forms import ... |
import _plotly_utils.basevalidators
class ComputedValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(self, plotly_name="computed", parent_name="layout", **kwargs):
super(ComputedValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
e... |
""" sysdiag
Pierre Haessig — September 2013
"""
from __future__ import division, print_function
def _create_name(name_list, base):
'''Returns a name (str) built on `base` that doesn't exist in `name_list`.
Useful for automatic creation of subsystems or wires
'''
base = str(base).strip()
if base == '... |
import _plotly_utils.basevalidators
class HoverlabelValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="hoverlabel", parent_name="sankey", **kwargs):
super(HoverlabelValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
import ConfigParser
import os
import sys
import utils
site_list_location = os.path.dirname(__file__) + '/sitelist.txt'
parser = ConfigParser.RawConfigParser()
parser.read(os.path.dirname(__file__) + '/config.cfg')
general = dict(parser.items('general'))
gmail_account = dict(parser.items('gmail_account'))
write_error = ... |
import traceback # for logging exceptions
import logging
logging.getLogger().setLevel(logging.INFO) #before doing anything else, set the desired log... |
from time import sleep
import unittest2 as unittest
from tweepy.api import API
from tweepy.auth import OAuthHandler
from tweepy.models import Status
from tweepy.streaming import Stream, StreamListener
from config import create_auth
from test_utils import mock_tweet
from mock import MagicMock, patch
class MockStreamList... |
import sys, math, os
import matplotlib.pyplot as plt
def main():
# Check that there's at least one argument
if len(sys.argv) < 2:
print("Usage python {} <file1> [<file2> ...]".format(sys.argv[0]))
return 1
# Automatically detect if decayed
if "decayed" in sys.argv[1]:
plotDecayed... |
T = int(raw_input())
while(not T == 0):
word = str(raw_input())
if len(word)>10:
print word[0]+str(len(word[1:len(word)-1]))+word[len(word)-1]
else:
print word
T-=1 |
BOT_NAME = 'aCloudGuru'
SPIDER_MODULES = ['aCloudGuru.spiders']
NEWSPIDER_MODULE = 'aCloudGuru.spiders'
ROBOTSTXT_OBEY = True |
import asyncio
import functools
import random
import time
from testing import Client
from testing import default_test_setup
from testing import gen_data
from testing import gen_points
from testing import gen_series
from testing import InsertError
from testing import PoolError
from testing import QueryError
from testing... |
"""
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis on Heroku
"""
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
from django.utils import six
from .common im... |
from .base import * # TODO: import the relevant names instead of importing everything.
import cuda_convnet
import corrmm |
"""
FILE: sample_recognize_business_cards.py
DESCRIPTION:
This sample demonstrates how to recognize fields on business cards.
See fields found on a business card here:
https://aka.ms/formrecognizer/businesscardfields
USAGE:
python sample_recognize_business_cards.py
Set the environment variables with... |
from time import sleep
import os
import shutil
import merfi
from merfi import logger
from merfi import util
from merfi.collector import RepoCollector
from merfi.backends import base
class RpmSign(base.BaseBackend):
help_menu = 'rpm-sign handler for signing files'
_help = """
Signs files with rpm-sign. Crawls a ... |
# -*- coding: utf-8 -*-
import arrow
import datetime
import ujson
import timeit
from flask.ext.login import login_required
from flask import (
Blueprint, render_template
)
from feedback.dashboard.vendorsurveys import (
get_rating_scale, get_surveys_by_role,
get_surveys_by_completion, get_surveys_by_purpose... |
import unittest
import requests
class TranslationTests(unittest.TestCase):
def setUp(self):
self.url = 'http://127.0.0.1/api/translate'
def test_given_words(self):
"""Should pass for the basic test cases provided"""
test_words = ['pig', 'banana', 'trash', 'happy', 'duck', 'glove',
... |
import datetime
__all__ = [
'info',
]
def info():
return {
'birthday': datetime.date(1992, 2, 10),
'class': 3,
'family_name_en': u'nakagawa',
'family_name_kana': u'なかがわ',
'first_name_en': u'haruka',
'first_name_kana': u'はるか',
'... |
<!DOCTYPE html>
<html lang="en" class="">
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# object: http://ogp.me/ns/object# article: http://ogp.me/ns/article# profile: http://ogp.me/ns/profile#">
<meta charset='utf-8'>
<link crossorigin="anonymous" href="https://assets-cdn.github.com/assets/framew... |
'''
modified by Chongxuan Li (chongxuanli1991@gmail.com)
'''
import sys
sys.path.append('..')
sys.path.append('../../data/')
import os, numpy as np
import scipy.io as sio
import time
import anglepy as ap
import anglepy.paramgraphics as paramgraphics
import anglepy.ndict as ndict
import theano
import theano.tensor as T
... |
import praw
import smtplib
import requests
import parsel
import re
import io
import json
import os
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from argparse import ArgumentParser
from premailer import Premailer
HEADERS = requests.utils.default_head... |
from __future__ import unicode_literals
from django.forms import ModelForm, TextInput
from django.contrib import admin
from blog.models import Post
class PostAdmin(admin.ModelAdmin):
list_display = ['id', 'title', 'created', 'status']
list_filter = ('status', )
admin.site.register(Post, PostAdmin) |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Test for BitBucket PR 126:
SConf doesn't work well with 'io' module on pre-3.0 Python. This is because
io.StringIO (used by SCons.SConf.Streamer) accepts only unicode strings.
Non-unicode input causes it to raise an exception.
"""
import TestSCons
test =... |
import os
import inspect
import vcr
def build_path(function):
return os.path.join(os.path.dirname(inspect.getfile(function)),
'cassettes',
function.__module__.split('.')[1],
function.__name__ + '.yml')
vcr = vcr.config.VCR(
func_path_generato... |
import os
class Config(object):
SPOTIPY_REDIRECT_URI = os.environ['SPOTIPY_REDIRECT_URI']
SPOTIPY_CLIENT_ID = os.environ['SPOTIPY_CLIENT_ID']
SPOTIPY_CLIENT_SECRET = os.environ['SPOTIPY_CLIENT_SECRET']
SPOTIFY_ACCESS_SCOPE = 'playlist-modify-public playlist-modify-private playlist-read-private user-libr... |
candidates = set([str(a * b) for a in range(100, 1000) for b in range(100, 1000)])
candidates = filter(lambda x: x == x[::-1], candidates)
print max([int(x) for x in candidates]) |
from distutils.core import setup
import py2exe
build_dir =
data_files = [('',['settings.ini',
'LICENSE',
'README.md']),
('sessions',[])]
options = {'py2exe': {
'dist_dir': build_dir}}
setup(
windows=['youtube_downloader.py'],
data_fil... |
import random
import pytest
from microbial_ai.regulation import Event, Action, Memory
@pytest.fixture
def random_action():
return Action(type='fixed', phi={'rxn1': (random.random(), '+')})
@pytest.fixture
def random_event(random_action):
return Event(state=random.randint(0, 100), action=random_action,
... |
from .utils import do, do_ex, trace
from .version import meta
from os.path import abspath, realpath
FILES_COMMAND = 'git ls-files'
DEFAULT_DESCRIBE = 'git describe --dirty --tags --long --match *.*'
def parse(root, describe_command=DEFAULT_DESCRIBE):
real_root, _, ret = do_ex('git rev-parse --show-toplevel', root)
... |
import logging
import utils
import options
_Warning = logging.Warning
_Info = logging.Info
_site_setup = []
_user_setup = {}
_tools_setup = {}
_tools_post_setup = {}
def ResetSetup( site_setup = _site_setup,
user_setup = _user_setup,
tools_setup = _tools_setup,
... |
import os
from src.core import prep
from sgprocessor import *
def ProcessSg(p, opts):
if opts.anno == True:
if 'BEDDB' not in os.environ:
p.error('$BEDDB Not Exist. See README')
str_path_sgfq = opts.sg
str_nm = os.path.basename(os.path.splitext(opts.sg)[0])
str_proj = 'aux'
str_p... |
import pandas as pd
import numpy as np
from dateutil.relativedelta import relativedelta
def get_first_visit_date(data_patient):
''' Determines the first visit for a given patient'''
#IDEA Could be parallelized in Dask
data_patient['first_visit_date'] = min(data_patient.visit_date)
return data_patient
de... |
import os
import sys
from Bio.Seq import Seq
def main(*args, **kwargs):
fpath = os.path.join(os.getcwd(), args[-2])
tmp = []
with open(fpath,'r') as f:
for line in f:
txt = line.strip()
tmp.append(txt)
S1 = set(tmp)
S2 = set([str(Seq(s).reverse_complement()) for s in ... |
from ballot.models import OFFICE, CANDIDATE, POLITICIAN, MEASURE, KIND_OF_BALLOT_ITEM_CHOICES
from django.db import models
from exception.models import handle_exception, handle_record_found_more_than_one_exception,\
handle_record_not_saved_exception
import wevote_functions.admin
from wevote_functions.functions impo... |
from models.anchor import *
if __name__=='__main__':
# TEMP: Wipe existing anchors
# THIS IS TEMPORARY:
anchors = {'Vaccination', 'Vaccinations', 'Vaccine', 'Vaccines', 'Inoculation', 'Immunization', 'Shot', 'Chickenpox', 'Disease', 'Diseases', 'Hepatitis A', 'Hepatitis B', 'infection', 'infections', 'measles', 'out... |
from bs4 import BeautifulSoup
import httplib, codecs, datetime
import cPickle as pickle
import time
def stan_tag(criteria, server):
tagged = []
file_count = 47
for ix, c in enumerate(criteria[2250000:]):
# initialize list of sentences
sents = []
try:
# send text to server... |
try:
from ._models_py3 import ARMBaseModel
from ._models_py3 import Address
from ._models_py3 import Alert
from ._models_py3 import AlertErrorDetails
from ._models_py3 import AlertList
from ._models_py3 import AsymmetricEncryptedSecret
from ._models_py3 import Authentication
from ._model... |
import os
import web
import rediswebpy
from web.contrib.template import render_jinja
import misc
db = web.database(dbn='mysql', db='geeksoho', user='geeksoho', passwd='geeksoho')
urls = (
'/', 'index',
'/test', 'test'
)
class index:
"""Home"""
def GET(self):
# return pjax('jobs.html'... |
from azure.cli.testsdk import ScenarioTest, record_only, ResourceGroupPreparer
class TestClusterScenarios(ScenarioTest):
@record_only()
@ResourceGroupPreparer(name_prefix='cli_test_monitor_log_analytics_cluster_c', parameter_name='rg1', key='rg1', location='centralus')
def test_monitor_log_analytics_cluster... |
import factory
from dominion.games.models import Game
class GameFactory(factory.django.DjangoModelFactory):
class Meta:
model = Game |
from django.core.management.base import BaseCommand
from aspc.courses.models import Schedule
from datetime import datetime, timedelta
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
from aspc.settings import EMAIL_HOST_USER
MIN_DAYS... |
"""
The utility module.
"""
import traceback
def extract_traceback(exception):
"""
Utility function for extracting the traceback from an exception.
:param exception: The exception to extract the traceback from.
:return: The extracted traceback.
"""
return ''.join(traceback.format_tb(exception.__... |
"""
@name: Modules/Computer/Nodes/nodes.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2014-2030 by D. Brian Kimmel
@license: MIT License
@note: Created on Mar 6, 2014
@summary: This module does everything for nodes.
Nodes are read in from the config Xml file.
Then node... |
"""
Created on Fri Oct 14 15:30:11 2016
@author: worm_rig
"""
import json
import os
import tables
from tierpsy.analysis.compress.compressVideo import compressVideo, initMasksGroups
from tierpsy.analysis.compress.selectVideoReader import selectVideoReader
from tierpsy.helper.misc import TimeCounter, print_flush
DFLT_SAV... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.