code stringlengths 1 199k |
|---|
"""Init and utils."""
from zope.i18nmessageid import MessageFactory
MessageFactory = MessageFactory('sng.sitecontent')
def initialize(context):
"""Initializer called when used as a Zope 2 product.""" |
"""
Problem 11
Data Structures : Trie, Bloom Filters
"""
import unittest
class UrlEncodingUsingTrie:
def __init__(self):
self._visited_paths = {}
@property
def visited(self):
return self._visited_paths
@visited.setter
def visited(self, link):
"""
:param link:
... |
import requests
import re
import urllib
import logging
logger = logging.getLogger('pycanvas.BaseCanvasAPI')
class BaseCanvasAPI(object):
def __init__(self, instance_address, access_token, **kwargs):
self.instance_address = instance_address
self.access_token = access_token
logger.debug('Creat... |
import numpy as np
import os
import weight
from fpa import post_process_operation
from fpa.FPA import Wing
def main(wing, velocity, temperature, aoaarray):
"""
csvfile, number of cell, design cruise speed, ambient temperature
:param velocity:
:param temperature:
:param aoaarray:
:return:
"""... |
'''
render.py
changelog
2013-12-01[00:32:46]:created
2013-12-14[23:52:33]:define TokenRender
2013-12-17[12:13:55]:move removeCssDepsDeclaration out of class
@info yinyong,osx-x64,UTF-8,192.168.1.101,py,/Users/yinyong/work/ursa2/src
@author yanni4night@gmail.com
@version 0.0.1
@since 0.0.1
'''
from conf import ... |
"""Python version compatibility code."""
import enum
import functools
import inspect
import os
import re
import sys
from contextlib import contextmanager
from inspect import Parameter
from inspect import signature
from typing import Any
from typing import Callable
from typing import Generic
from typing import Optional
... |
import numpy as np
import pandas as pd
import statsmodels
import statsmodels.api as sm
from statsmodels.tsa.stattools import coint
import sys
import matplotlib.pyplot as plt
class Market_Maker:
def __init__(self):
self._stocks = ["BOND", "GS", "MS", "WFC", "XLF", "VALBZ", "VALE"]
self._limits = {"BO... |
import os
import sys
from setuptools import find_packages
from distutils.core import setup
name = "spectate"
here = os.path.abspath(os.path.dirname(__file__))
pkg_root = os.path.join(here, name)
package = dict(
name=name,
license="MIT",
packages=find_packages(exclude=["tests*"]),
python_requires=">=3.6"... |
import pytest
import os
from csv import Sniffer
from natural_bm import callbacks
from natural_bm import optimizers
from natural_bm import training
from natural_bm.models import Model
from natural_bm.datasets import random
from natural_bm.utils_testing import nnet_for_testing
@pytest.mark.parametrize('sep', [',', '\t'],... |
import argparse
import srilm.vocab
import srilm.stats
import srilm.ngram
import srilm.discount
import srilm.maxent
gtmin = [1, 1, 1, 2, 2, 2, 2, 2, 2, 2]
gtmax = [5, 1, 7, 7, 7, 7, 7, 7, 7, 7]
def ngramLmWithGoodTuring(order, vocab, train, heldout, test):
tr = srilm.stats.Stats(vocab, order)
tr.count_file(train... |
"""FileBackend functional tests."""
import unittest
import os
import os.path
import shutil
HERE = os.path.dirname(__file__)
DATA_DIR = os.path.join(HERE, 'data')
TMP_DIR = os.path.join(HERE, 'tmp')
class FileBackendBugs(unittest.TestCase):
def setUp(self):
if not os.path.isdir(TMP_DIR):
os.mkdir... |
"""
Random supporting methods.
(c) May 2017 by Daniel Seita
"""
import numpy as np
import sys
import tensorflow as tf
def compute_ranks(x):
""" Returns ranks in [0, len(x))
Note: This is different from scipy.stats.rankdata, which returns
ranks in [1, len(x)].
Note: this is from OpenAI's code.
"""
... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20151024_1544'),
]
operations = [
migrations.AlterField(
model_name='user',
name='username',
field... |
import django
if django.VERSION > (2,):
from django.urls import reverse, include, reverse_lazy
from django.urls import re_path as url
else:
from django.core.urlresolvers import reverse, reverse_lazy
from django.conf.urls import url, include
__all__ = ['reverse', 'include', 'reverse_lazy', 'url'] |
from django import forms
class SignInForm(forms.Form):
email = forms.EmailField()
password = forms.CharField(min_length=6) |
from _external import *
java = HeaderChecker('java', 'jni.h', 'c') |
import _plotly_utils.basevalidators
class WidthValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="width", parent_name="surface.contours.y", **kwargs):
super(WidthValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
import ConfigParser
import datetime as dt
import numpy as np
from fisher import pvalue
import os
import elasticsearch as es
from es_query_generator import es_query_generator
from itertools import izip
import json
class DictParser(ConfigParser.ConfigParser):
def as_dict(self):
d = dict(self._sections)
... |
"""Edit a genome
"""
import os
import requests
from requests.auth import HTTPBasicAuth
import sys
import json
import argparse
if "FABRIC_API_PASSWORD" not in os.environ:
sys.exit("FABRIC_API_PASSWORD environment variable missing")
if "FABRIC_API_LOGIN" not in os.environ:
sys.exit("FABRIC_API_LOGIN environment v... |
"""Attempt #3 at organizing neuron models
- We specify types of neurons using subclasses of Neuron
- This includes things like LIF vs HH and also Float vs Fixed, Rate vs Spiking
- We build a NeuronPool object which actually has code for running neurons
- We keep a list of known Neuron types around so if we're asked for... |
import struct
def read_fmt(handle, fmt):
size = struct.calcsize(fmt)
read = handle.read(size)
if len(read) != size:
raise EOFError()
return struct.unpack(fmt, read)[0] |
from setuptools import setup
setup(
name='wildpath',
version='0.3.1',
description='easy data structure access utility',
long_description='see <https://github.com/gemerden/wildpath>',
author='Lars van Gemerden',
author_email='gemerden@gmail.com',
license='MIT License',
packages=['wildpath... |
import socket
host = ''
port = 7000
addr = (host, port)
serv_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serv_socket.bind(addr)
serv_socket.listen(10)
print 'aguardando conexao'
con, cliente = serv_socket.accept()
print 'conectado'
print "... |
from .key_value_pair import KeyValuePair
from .tag import Tag
from .frame import Frame
from .frames import Frames
from .classification import Classification
from .status import Status
from .email import Email
from .ipa import IPA
from .phone import Phone
from .address import Address
from .pii import PII
from .detected_... |
KOI8R_CharToOrderMap = (
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 254, 255, 255, # 00
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, # 10
253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, # 20
252, 252, 252, 252, 2... |
from __future__ import absolute_import, division, print_function, unicode_literals
import aspen
from psycopg2 import IntegrityError
from gratipay.billing.payday import Payday
class PaydayRunner(object):
"""The Gratipay application can start a weekly payday process.
"""
def __init__(self, app):
self.... |
from setuptools import setup
setup(name='kurdishmorph',
version='0.0.1',
description='Kurmanji Morphology Analyzer',
url='http://github.com/halilagin/kurjmorph',
author='Halil Agin',
author_email='halil.agin@gmail.com',
license='MIT',
packages=['kurdish','kurdish.kurmanji', 'ku... |
from django.conf.urls import url
from . import views
from .apps import NewBuildingsConfig
app_name = NewBuildingsConfig.name
urlpatterns = [
url(r'^$', views.ResidentalComplexList.as_view(),
name='residental-complex-list'),
# url(r'^(?P<pk>\d+)/$',
url(r'^(?P<slug>[-\w]+)/$',
views.Residenta... |
import io
import builtins
from unittest.mock import patch
from unittest.mock import MagicMock
from mt_shared import mt_io
def test_read_file_non_user_expand():
file_name = '/path/2/file_name.txt'
mock_content = io.StringIO('some text')
mock = MagicMock(return_value=mock_content)
with patch('builtins.ope... |
from unittest import TestCase, main
import numpy as np
import datetime
from bcp.ethoscan import (parse_ethoscan_line, parse_ethoscan_report,
align_ethoscan_data)
class TestEthoscan(TestCase):
'''Test Ethoscan parameters are correctly calculated.'''
def setUp(self):
self.ethosca... |
import os
MONGO_HOST = os.environ.get('MONGO_SERVICE_HOST')
MONGO_PORT = int(os.environ.get('MONGO_SERVICE_PORT'))
MONGO_DBNAME = 'reports'
XML = False
X_DOMAINS = "*"
X_HEADERS = "Content-Type, Accept, Authorization, X-Requested-With, " \
" Access-Control-Request-Headers, Access-Control-Allow-Origin, " \
" Acc... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jormungandr.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0003_auto_20161014_0109'),
]
operations = [
migrations.AddField(
model_name='event',
name='subtitle',
field... |
import sys
from cx_Freeze import setup, Executable
setup(
name = "Lockwatcher",
version = "0.1",
description = "Anti-tampering monitor",
executables = [Executable("lockwatcher-gui.py", base = "Win32GUI",icon='favicon.ico'),
Executable('serviceconfig.py', base='Win32Service',targetName... |
"""Test the invalidateblock RPC."""
from test_framework.test_framework import TrollcoinTestFramework
from test_framework.util import *
class InvalidateTest(TrollcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 3
def setup_network(s... |
from .base import TestCase
from mongu import Client, Model, ModelAttributeError
from pymongo import MongoClient
class ClientTests(TestCase):
def test_default(self):
self.assertEqual(Client().client, MongoClient())
def test_uri(self):
self.assertEqual(
Client('mongodb://localhost:2701... |
from django.core.management import call_command
from django.test.testcases import TestCase
from 臺灣言語服務.models import 訓練過渡格式
from 匯入.management.commands.教典詞條 import Command
from 臺灣言語工具.解析整理.拆文分析器 import 拆文分析器
class 教典詞條試驗(TestCase):
@classmethod
def setUpClass(cls):
call_command('教典詞條')
return su... |
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport im... |
from urllib.parse import urlencode
from django.urls import reverse
from frontend.utils.bnf_hierarchy import simplify_bnf_codes
from .build_search_query import build_query_obj
from .build_rules import build_rules
from .models import VTM, VMP, VMPP, AMP, AMPP
NUM_RESULTS_PER_OBJ_TYPE = 10
def search(q, obj_types, include... |
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('wishlist_app', '0017_auto_20151001_1318'),
]
operations = [
migrations.AlterField(
model_name='role',
name='creat... |
import json
import time
from gbdxtools import Interface
start_time = time.time()
catalog_ids = ['1030010034AFCE00',
'103001003696B200',
'105041001126A900',
'1050410011360600',
'1050410011360700']
print 'Order imagery from GBDX'
gbdx = Interface()
order_id = gb... |
from System.IO import *
from System.Drawing import *
from System.Runtime.Remoting import *
from System.Threading import *
from System.Windows.Forms import *
from System.Xml.Serialization import *
from System import *
from Analysis.EDM import *
from DAQ.Environment import *
from EDMConfig import *
def saveBlockConfig(pa... |
people = 20
cats = 30
dogs = 15
if people < cats:
print("Too many cats! The world is doomed!")
if people > cats:
print("Not many cats! The world is saved!")
if people < dogs:
print("The world is drooled on!")
if people > dogs:
print("The world is dry!")
dogs += 5
if people >= dogs:
print("People are... |
from .air import air
from .water import water
from .mercury import mercury |
from unittest import TestCase
from day6 import Santa
class TestSanta(TestCase):
def test_coordinates_from_single_digit(self):
santa = Santa()
actual = santa._coordinates_from('turn on 0,0 through 0,0')
expected = [0, 0, 0, 0]
self.assertEqual(expected, actual)
def test_coordinate... |
from __future__ import with_statement, absolute_import
import os
import sys
import re
import six
import pkg_resources
from six.moves.configparser import ConfigParser
from six.moves.urllib.parse import unquote
from .util import fix_call, lookup_object
__all__ = ['loadapp', 'loadserver', 'loadfilter', 'appconfig']
def im... |
import re
import requests
import lxml.html
def main():
'''
main process
'''
session = requests.Session()
response = session.get('https://gihyo.jp/dp')
urls = scrape_list_page(response)
for url in urls:
response = session.get(url)
ebook = scrape_detail_page(response)
p... |
import requests
__author__ = 'Rob Derksen <rob.derksen@hubsec.eu>'
__version__ = '0.1.1'
class PynoramioException(Exception):
""" PynoramioException: class used as a custom exception for Pynoramio related errors.
"""
pass
class Pynoramio:
def __init__(self):
self.base_url = 'http://www.panoramio... |
from django.db import models
import datetime
class ProductInfo(models.Model):
name = models.CharField(max_length=60, unique=True)
# Global Trade Item Number
gtin = models.CharField(max_length=60)
image_url = models.CharField(max_length=128)
# disk_size = models.PositiveIntegerField()
# Nutrient ... |
import logging
logging.getLogger ( "scapy.runtime" ).setLevel ( logging.CRITICAL )
from scapy.all import *
load_contrib ( 'ppi_cace' )
import sys, os, time, signal, subprocess
import argparse
sys.path.insert ( 0, '../../lib/' )
from Queries import *
parser = argparse.ArgumentParser ()
parser.add_argument ( '-f', '--for... |
class MysqlDumpCommandResult(object):
""" Represents a mysqldump command execution result """
status = -1
result_code = -1
has_error = False
error_cause = None
# MysqlDumpCommand object
command = None
def __init__(self):
status = -1
result_code = -1
has_error = Fa... |
import websocket
import json
import time
import threading
class Connection:
"""
A basic object that provides a simple interface of callbacks for sending and
receiving packets.
"""
def __init__(self, limit=0, site="euphoria.io"):
self.site = site
self.socket = None
self.room =... |
from __future__ import absolute_import
import logging
from datetime import timedelta
from dateutil.parser import parse
import requests
from django.contrib.auth import get_user_model
from .models import Run, RunkeeperToken
log = logging.getLogger(__name__)
RUNKEEPER_BASE_URL = 'https://api.runkeeper.com'
def rk_items_to... |
import requests
from bs4 import BeautifulSoup
import sys
import orgs
import parse
reload(sys)
sys.setdefaultencoding('utf8')
def determine_bounds():
ops = orgs.OPS()
try:
r = requests.get(ops.request_url)
except requests.exceptions.SSLError:
print "Invalid SSL cert:"
r = requests.get... |
import cv2
class VideoCamera(object):
def __init__(self):
print("---VIDEOCAMERA INITIALIZED")
self.video = cv2.VideoCapture(0)
success = False
while not success:
success, image = self.video.read()
if success:
ret, jpeg = cv2.imencode('.jpg', im... |
import iz
import op
from iterator import Iterator
INFINITY = float('inf')
class Delta(object):
def __init__(self, ops=[]):
# Assume we are given a well formed ops
if isinstance(ops, Delta):
self.ops = ops.ops
elif iz.array(ops):
self.ops = ops
elif iz.dictiona... |
import numpy as np
import pylab as pl
import glob
from scipy.optimize import curve_fit as cf
import time
def gauss(x,a,b,c):
return a*np.exp(-(x-b)**2 / (2*c**2))
def twoD_Gaussian((x, y), amplitude, xo, yo, sigma_x, sigma_y, theta, offset):
xo = float(xo)
yo = float(yo)
a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.... |
"""`cssmin` - A Python port of the YUI CSS compressor."""
"""
Home page: https://github.com/zacharyvoase/cssmin
License: BSD: https://github.com/zacharyvoase/cssmin/blob/master/LICENSE
Original author: Zachary Voase
Modified for inclusion into web2py by: Ross Peoples <ross.peoples@gmail.com>
"""
from StringIO import St... |
import os
from flask import Flask, request, redirect, url_for, send_file
from werkzeug import secure_filename
import src
UPLOAD_FOLDER = 'uploads/'
ALLOWED_EXTENSIONS = set(['xlsx'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
... |
"""Run the app."""
from app import app
app.run(debug=True) |
import csv
import sys
import os
searchdir = sys.argv[0]
readcsvf = sys.argv[1]
with open(readcsvf) as f:
reader = csv.DictReader(f)
for line in reader:
source = line[0]
dest = line[1]
os.rename(source, dest) |
import json
import signal
import sys
import logging
from dateutil import parser, tz
from datetime import datetime, timedelta
from collections import OrderedDict, defaultdict
log = logging.getLogger(__name__)
def read_http(res):
while True:
data = res.read(4*1024*1024)
if not data:
break
... |
from importlib import import_module
import os
import logging
PLUGIN_NAMESPACE = 'apis'
log = logging.getLogger('dash')
_loaded = []
def load_plugins(names):
plugins = list_available_plugins()
for name in names:
if name not in plugins:
log.warn("Plugin '{0}' not found in list of available plu... |
"""OracleDB Mappings."""
from asciipic.db.oracle import manager
from asciipic.db.oracle import factory
ORACLE_DB = manager.OracleDBManager()
for table in factory.TableFactory.get_items():
ORACLE_DB.register(table) |
def mosaic(img, pad=True):
"""
Create a 2-D mosaic of images from an n-D image. An attempt is made to
make the resulting 2-D image as square as possible.
Parameters
----------
img : ndarray
n-dimensional image be tiled into a mosaic. All but last two dims are
lumped.
Returns
... |
'''Trains a simple deep NN on the MNIST dataset using **Focal Loss**.
'''
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop
from losses import focal_loss
batch_size = 128
nu... |
import sys
import math
import kfasta
from array import array
try:
from PIL import Image
except ImportError:
print "You don't have PIL (the Python Imaging Library) installed."
print "Please check README.txt for instructions on how to install PIL."
sys.exit(-1)
class RollingHash:
def __init__(self, s)... |
'''
This code does the following:
1. Fixes the broken href tags for figures
'''
import os
from lxml import etree
path = '/home/heather/Desktop/books/physical-sciences-12/afrikaans/build/epubs/science12/OPS/xhtml/science12'
def fig_ref_fix(xml):
for a in xml.findall('.//a'): # find all the a tags
tempText =... |
import boto.sqs
import argparse
import urllib
import os
import sys
import signal
import time
import datetime
import socket
import fcntl
import struct
from boto.sqs.message import Message
from subprocess import call
import boto.s3.connection
from boto.s3.connection import S3Connection
from boto.s3.connection import Loca... |
"""
environment variable inventory source
If the environment variable is undefined, the variable is also undefined.
The group level environment variables are only supported, and the host level environment variables are not supported.
The environment variable name must be uppercase.
The environment variable "FOO" is ass... |
def patch_range(line, strip = True):
"""This function returns a list of parts that include ranges (i.e. [2:5]) if
they were present in the original line."""
pieces = line.split(':')
parts = []
tmp = ''
for part in pieces:
if part.count('[')>part.count(']') and not(tmp):
tmp =... |
""" Fixes wrong package names with pacman or yaourt.
For example the `llc` program is in package `llvm` so this:
yaourt -S llc
should be:
yaourt -S llvm
"""
from thefuck.utils import replace_command
from thefuck.specific.archlinux import get_pkgfile, archlinux_env
def match(command):
return (command.script_... |
from mfr.core import FileHandler, get_file_extension
from mfr_docx.render import render_html
__version__ = '0.1.0'
EXTENSIONS = [
'.docx',
]
class Handler(FileHandler):
# Renderers and exporters are callables
renderers = {
'html': render_html
}
def detect(self, fp):
return get_file_e... |
"""PyAudio example: Record a few seconds of audio and save to a WAVE file."""
import pyaudio
import wave
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
... |
import os
backend = os.environ.get("CRYPTO_BACKEND", "cryptography")
if backend == "cryptodome":
from Crypto.Cipher import AES
from Crypto.Hash import HMAC, SHA1, SHA256
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Util import Padding
AES_BLOCK_BYTES = AES.block_size
def aes_cbc_pkcs7_encr... |
import os
from flask import Flask, make_response, request, session, render_template, send_from_directory, redirect
from werkzeug import secure_filename
import json
TREE_BASE_FILENAME = 'flare.json'
DATA_DIR = 'data'
DATA_DIR_PATH = '../{}'.format(DATA_DIR)
TREE_FILENAME = '{}/{}'.format(DATA_DIR_PATH, TREE_BASE_FILENAM... |
import base64
from requests import HTTPError
from blobstash.base.client import Client
from blobstash.base.error import BlobStashError
from blobstash.base.iterator import BasePaginationIterator
class KVStoreError(BlobStashError):
"""Base error for the kvstore module."""
class KeyNotFoundError(KVStoreError):
"""E... |
import requests
from matroid import error
from matroid.src.helpers import api_call
@api_call(error.InvalidQueryError)
def create_video_summary(self, url=None, videoId=None, file=None):
"""Create an video summary with provided url or file"""
(endpoint, method) = self.endpoints['create_video_summary']
if not file a... |
import socket
import logging
import threading
import time
class SyslogServer(threading.Thread):
""" This is a test"""
def __init__(self):
threading.Thread.__init__(self,name="Syslog")
self.daemon = True
self.logfile = "syslog.txt"
self.server = None
self.ip = "0.0.0.0"
... |
"""
Services templatetags docstring
""" |
try:
import importlib.metadata as importlib_metadata
except ModuleNotFoundError:
# This is required for Python versions < 3.8
import importlib_metadata
try:
__version__ = importlib_metadata.version('django-cacheback')
except Exception:
__version__ = 'HEAD'
default_app_config = 'cacheback.apps.Cacheb... |
from directory_massager import cloakroom_file, get_top_level_agencies, cabinet_level_ids
import json
class Network:
# Base class for Cloakroom Networks
def __init__(self, name, numeric_id):
self.name = name
self.numeric_id = numeric_id
self.domains = []
self.locations = []
de... |
class QuickSort():
def __init__(self):
self.list = [5,1,4,2,3]
def partition(self, list, size):
if size < 2:
return
pivot = list[size-1]
L, U = 0, size-1
while L < U:
while list[L] < pivot:
L = L + 1
while list[U] > pivo... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Notification.message'
db.delete_column(u'riskgame_notification', 'message')
def backwards(self, orm):
# A... |
from pkg_resources import resource_filename
from pyramid.events import (
BeforeRender,
subscriber,
)
from pyramid.httpexceptions import (
HTTPMovedPermanently,
HTTPPreconditionFailed,
HTTPUnauthorized,
HTTPUnsupportedMediaType,
)
from pyramid.security import forget
from pyramid.settings import a... |
import json
import requests
from requests.exceptions import HTTPError, RequestException, Timeout
from werkzeug.urls import url_join
from indico.core.config import config
from indico.modules.cephalopod import cephalopod_settings, logger
from indico.modules.core.settings import core_settings
HEADERS = {'Content-Type': 'a... |
from __future__ import absolute_import
import os.path
import sys
try:
import ansible_mitogen.connection
except ImportError:
base_dir = os.path.dirname(__file__)
sys.path.insert(0, os.path.abspath(os.path.join(base_dir, '../../..')))
del base_dir
import ansible_mitogen.connection
class Connection(ansible... |
import sys
import unittest
sys.path.append('./code')
from transforms import Transform, RadialGaussianization
from models import GSM
from numpy import all, sqrt, sum, square
Transform.VERBOSITY = 0
class Tests(unittest.TestCase):
def test_inverse(self):
"""
Make sure inverse Gaussianization is inverse to Gaussianiz... |
from library.stigma.application import Button
class HomeNewgame(Button):
def __init__(self):
super(HomeNewgame, self).__init__()
self.text = 'New game'
self.params = None |
from app import manager
if __name__ == "__main__":
manager.run() |
"""
Unit tests for the Pythia PRF service implementation.
"""
from django.test import SimpleTestCase
import json
from settings import dp
from pyrelic import vpop, vprf, bls
from pyrelic.pbc import G1Element, G2Element
from crypto import *
w = "abcdefg0987654321"
t = "123456789poiuytrewq"
pw = "super secret pw"
class Vp... |
import tornado.escape
import tornado.web
import tornado.websocket
import motor
import logging
import ast
import bcrypt
from interface import *
from choices import *
from decorators import *
__all__ = [
"LoginHandler", "LogoutHandler",
"DeviceListHandler", "DeviceCreateHandler", "DeviceUpdateHandler",
"UserL... |
"""
A utility module to simplify tweepy usage from within the flask app
"""
import tweepy
from tweepy import Cursor
import app_settings as cfg
def sort_statuses(statuses):
length = len(statuses)
for cnt1 in range(length):
for cnt2 in range(length-1):
if statuses[cnt2].retweet_count < statuses[cnt2+1].retweet_cou... |
import unittest
import sys
import os
from report.eval_summary import *
import build_id
from testsupport import checkin
def get_sample_eval_summary():
bi = buildinfo.BuildInfo()
return EvalSummary(
'sadm.trunk.136.20',
'OFFICIAL',
'zufa',
EvalPhase.TEST,
None,
1314... |
try:
from . import generic as g
except BaseException:
import generic as g
class VHACDTest(g.unittest.TestCase):
def test_vhacd(self):
# exit if no VHACD
if not g.trimesh.interfaces.vhacd.exists and not g.all_dep:
g.log.warning(
'not testing convex decomposition (n... |
from .robot_model import RobotModel, create_robot
from .manipulators import * |
import yaml
import csv
import time
import setup
textfile_path, deffile_path = setup.get_arguments()
from functions import generate_tables
analyzing = "\nAnalyzing '{textfile}' using definitions from '{deffile}'".format(
textfile=textfile_path,
deffile=deffile_path
)
print analyzing
with open(textfile_path, "r")... |
import sys
import json
import hashlib
import base64
import datetime
import os
def dir_size(path):
total_size = os.path.getsize(path)
for item in os.listdir(path):
itempath = os.path.join(path, item)
if os.path.isfile(itempath):
total_size += os.path.getsize(itempath)
elif os.... |
from machine import SPI, Pin
SPI = machine.SPI(0) # GP14 (CLK) + GP16 (MOSI->DIN), User-LED jumper removed!
RST = machine.Pin('GP24')
CE = machine.Pin('GP12')
DC = machine.Pin('GP22')
LIGHT = machine.Pin('GP23')
import upcd8544
lcd = upcd8544.PCD8544(SPI, RST, CE, DC, LIGHT)
lcd.data([0xff])
lcd.data([... |
from utils.logger import Logger
import os, unittest
def foo():
logger = Logger().getLogger(__name__)
print 'Hello foo()'
logger.info('Hi, foo')
class TestLogger(unittest.TestCase):
def setUp(self):
self.logger = Logger().getLogger(__name__)
def test_log(self):
self.logger.debug("debu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.