content stringlengths 4 20k |
|---|
import unittest
import time
from mongoctl.tests.test_base import MongoctlTestBase, append_user_arg
########################################################################################################################
# Servers
SERVERS = [
{
"_id": "cmdln_arbiter_test_server",
"address": "localh... |
from numba import jit
import unittest
import numpy as np
import copy
from numba.tests.support import MemoryLeakMixin
try:
xrange
except NameError:
xrange = range
@jit
def inc(a):
for i in xrange(len(a)):
a[i] += 1
return a
@jit
def inc1(a):
a[0] += 1
return a[0]
@jit
def inc2(a):
... |
import os
import re
from jflow.seqio import xopen
from jflow.seqio import FormatError
from jflow.seqio import UnknownFileType
def boolify(s):
return {'True': True, 'False': False}[s]
def autocast(s):
for fn in (boolify, int, float):
try:
return fn(s)
except:
pass
... |
import unittest
import mock
import logging
import esgfpid.rabbit.asynchronous.thread_shutter
from esgfpid.rabbit.asynchronous.exceptions import OperationNotAllowed
LOGGER = logging.getLogger(__name__)
LOGGER.addHandler(logging.NullHandler())
# Test resources:
import resources.TESTVALUES as TESTHELPERS
class ThreadSh... |
# -*- coding:utf-8 -*-
import struct
from Tribler.Core.Modules.restapi.util import convert_search_torrent_to_json, convert_db_channel_to_json, \
relevance_score_remote_torrent, get_parameter, can_edit_channel, fix_unicode_array, fix_unicode_dict
from Tribler.Core.Session import Session
from Tribler.Test.Core.base_... |
"""
Do a diff between two idf files.
Prints the diff in csv or html file format.
You can redirect the output to a file and open the file using as a spreadsheet or by using a browser
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import u... |
#!/usr/bin/env python
# coadd_ubercheck.py:
# --------------------------------
# usage: ./coadd_ubercheck.py cluster filter
#
# contributions welcome, should be of the form,
# of a function that only needs cluster and filter
# and looks up the rest. The main just runs the checks.
#
# No output unless there is some... |
import gtk
import gobject
import pygame
import pygame.event
class _MockEvent(object):
def __init__(self, keyval):
self.keyval = keyval
class Translator(object):
key_trans = {
'Alt_L': pygame.K_LALT,
'Alt_R': pygame.K_RALT,
'Control_L': pygame.K_LCTRL,
'Control_R': pygam... |
import six
import json
import re
from jsonpath_rw import parse
from st2common import log as logging
import st2common.operators as criteria_operators
from st2common.constants.rules import TRIGGER_PAYLOAD_PREFIX, RULE_TYPE_BACKSTOP, MATCH_CRITERIA
from st2common.constants.keyvalue import SYSTEM_SCOPES
from st2common.ser... |
import unittest
import pyspatialite.dbapi2 as sqlite
def func_returntext():
return "foo"
def func_returnunicode():
return u"bar"
def func_returnint():
return 42
def func_returnfloat():
return 3.14
def func_returnnull():
return None
def func_returnblob():
return buffer("blob")
def func_raiseexce... |
# -*- coding: utf-8 -*-
from denorm.helpers import find_fks,find_m2ms
from django.db import models
from django.db.models.fields import related
from denorm.models import DirtyInstance
from django.contrib.contenttypes.models import ContentType
from denorm.db import triggers
class DenormDependency(object):
"""
B... |
#!/usr/bin/env python
# * source-status-linker.py
# ** Imports
import datetime
import cgi
import re
import string
from collections import defaultdict, namedtuple
from sortedcontainers import SortedSet
# ** Classes
class User(object):
def __init__(self, name=None, id=None):
self.name = cgi.escape(name) i... |
from msgpackrpc import error
class Future(object):
"""
This class is used as the result of asynchronous call.
By using join(), the caller is able to wait for the completion.
"""
def __init__(self, loop, timeout, callback=None):
self._loop = loop
self._error = None
self._re... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
A script to generate documentation in docs/ directory
@author Wu Yuntao
@version 0.2.0
'''
import re
import sys
from os import path, walk, system, makedirs
ROOT_PATH = path.abspath(path.dirname(__file__))
COFFEE_PATH = path.join(ROOT_PATH, '../src/coffee')
D... |
"""MessageBird platform for notify component."""
import logging
import voluptuous as vol
from homeassistant.const import CONF_API_KEY, CONF_SENDER
import homeassistant.helpers.config_validation as cv
from homeassistant.components.notify import (
ATTR_TARGET,
PLATFORM_SCHEMA,
BaseNotificationService,
)
_... |
#Required for making unique id's and keeping track of nodes
import uuid
import numpy as np
import graphviz as gv
class vpnode():
def __init__(self):
self.parent = None
self.leftChild = None
self.rightChild = None
#Using preorder in a similar way as the lab
#returns a list and not a... |
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.table`.
"""
auto_colname = _config.ConfigItem(
'col{0}',
'The template that determines the name of a column if it cannot be '
'determined. Uses new-style (forma... |
import unittest
from datetime import timedelta
import django
import six
if six.PY3: # pragma: no cover
from importlib import reload
from mock import MagicMock, patch
from .. import fields
class DurationFieldToPythonTest(unittest.TestCase):
def setUp(self):
"""Create a mock of the DurationField cla... |
import os
import concurrent
import queue
import threading
import asyncio
import sqlite3
from .logging import Logger
def sql(func):
"""wrapper for sql methods"""
def wrapper(self, *args, **kwargs):
assert threading.currentThread() != self.sql_thread
f = asyncio.Future()
self.db_request... |
#!python
"""Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools... |
# Choregraphe bezier export in Python.
from naoqi import ALProxy
names = list()
times = list()
keys = list()
names.append("LShoulderPitch")
times.append([ 1.53846, 3.07692])
keys.append([ [ 1.56300, [ 3, -0.51282, 0.00000], [ 3, 0.51282, 0.00000]], [ 1.39626, [ 3, -0.51282, 0.00000], [ 3, 0.00000, 0.00000]]])
names.a... |
from lxml import etree
from route53 import xml_parsers, xml_generators
from route53.exceptions import Route53Error
from route53.transport import RequestsTransport
#from route53.util import prettyprint_xml
from route53.xml_parsers.common_change_info import parse_change_info
class Route53Connection(object):
"""
... |
import pandas as pd
from datetime import datetime
from datetime import timedelta
import json
import getopt
import sys
import pickle
import warnings
import os
def main(argv):
warnings.filterwarnings('ignore', category=DeprecationWarning)
input_file = ''
model_file = ''
output_folder = ''
output_post... |
from django.dispatch.saferef import *
from django.utils import unittest
class Test1(object):
def x(self):
pass
def test2(obj):
pass
class Test2(object):
def __call__(self, obj):
pass
class Tester(unittest.TestCase):
def setUp(self):
ts = []
ss = []
for x in x... |
#!/usr/bin/env python
import errno
import os
import platform
import sys
BASE_URL = os.getenv('LIBCHROMIUMCONTENT_MIRROR') or \
'https://s3.amazonaws.com/github-janky-artifacts/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '1a4c5e51a670633ff3ecd4448ad01ba21b440542'
PLATFORM = {
'cygwin': 'win32',
'darwin':... |
import json
from sqlalchemy import (
Column, Integer, String, Text, Boolean,
)
from superset import utils
from superset.models.helpers import AuditMixinNullable, ImportMixin
class BaseDatasource(AuditMixinNullable, ImportMixin):
"""A common interface to objects that are queryable (tables and datasources)"""... |
"""
A slightly customized subclass of qpopplerview.View.
This is used throughout Frescobaldi, to obey color settings etc.
"""
from PyQt5.QtCore import QSettings
import app
import textformats
import qpopplerview
# global setup of background color
def _setbackground():
colors = textformats.formatData('editor')... |
#!/usr/bin/env python
import sys
import os
from re import compile
from setuptools import setup, find_packages
if sys.argv[1] in ('submit', 'publish'):
os.system('python setup.py sdist upload')
sys.exit()
sysv = sys.version[:3]
requires = ['github3.py>=0.3']
pkg_data = {'': ['LICENSE', 'AUTHORS.rst']}
entry... |
import webracer
import nose.plugins.attrib
from . import utils
from .apps import kitchen_sink_app
utils.app_runner_setup(__name__, kitchen_sink_app.app, 8057)
@nose.plugins.attrib.attr('client')
@webracer.config(host='localhost', port=8057)
class CookieTest(webracer.WebTestCase):
def test_cookie(self):
se... |
#!/usr/bin/python
# carbonita.py
# a lightweight library for carbon metric delivery
# Email: <EMAIL>
import logging
import pickle
import socket
import struct
class Carbon(object):
"""
Carbon class.
"""
_plaintext_default_port = 2003
_pickle_default_port = 2004
def __init__(self, host, port... |
"""
Likelihood function to evaluate with PyMultiNest for parameter estimation
"""
import pymultinest as pmn
import numpy as np
import pandas as pd
import sys
from scipy.integrate import quad
#load the data from a file in the snfile/ directory within euclid sims
sim_data = pd.read_csv('/Users/lapguest/workspaces/eu... |
from fabric.api import env
from fabric.api import run
from fabric.api import settings
from novaclient.v1_1 import client as nova_client
from cloudferrylib.base import network
from cloudferrylib.os.compute import nova_compute
from cloudferrylib.utils.utils import forward_agent
class NovaNetwork(network.Network):
... |
import muffin
import pytest
from muffin_cache import CacheHandler, cache_view
@pytest.fixture(scope='session')
def app(loop):
return muffin.Application(
'cache', loop=loop,
PLUGINS=(
'muffin_redis',
'muffin_cache',
),
REDIS_FAKE=True,
)
def test_plug... |
# Module for the BNL image processing project
# Developed at the NSLS-II, Brookhaven National Laboratory
# Developed by Gabriel Iltis, Sept. 2014
"""
This module contains test functions for the file-IO functions
for reading and writing data sets using the netCDF file format.
The files read and written using this funct... |
from konlpy.tag import Twitter as KoNLPyTwitter
from customKonlpy.ckonlpy.custom_tag import SimpleTemplateTagger
from customKonlpy.ckonlpy.custom_tag import SimpleSelector
from customKonlpy.ckonlpy.data.tagset import twitter as tagset
from customKonlpy.ckonlpy.dictionary import CustomizedDictionary
from customKonlpy.ck... |
import glob
import os
import sys
import ah_bootstrap
from setuptools import setup
#A dirty hack to get around some early import/configurations ambiguities
if sys.version_info[0] >= 3:
import builtins
else:
import __builtin__ as builtins
builtins._ASTROPY_SETUP_ = True
from astropy_helpers.setup_helpers impor... |
from django.contrib import admin
from metadata.admin_base import TextMetadataInline
from metadata.admin_base import ImageMetadataInline
from lass_lerouge.models import Role
from lass_lerouge.models import RoleTextMetadata
from lass_lerouge.models import RoleImageMetadata
from lass_lerouge.models import GroupRootRole
... |
import HT16K33
# Digit value to bitmask mapping:
DIGIT_VALUES = {
' ': 0x00,
'-': 0x40,
'0': 0x3F,
'1': 0x06,
'2': 0x5B,
'3': 0x4F,
'4': 0x66,
'5': 0x6D,
'6': 0x7D,
'7': 0x07,
'8': 0x7F,
'9': 0x6F,
'A': 0x77,
'B': 0x7C,
'C': 0x39,
'D': 0x5E,
'E': 0x79,
'F': 0x71,
#G
'H': 0x76,
'I': 0x30,
'J': 0x... |
import sys
import re
import os
import subprocess
import collections
import json
import binascii
import base64
from capstone import *
from capstone.x86_const import *
from capstone.arm_const import *
ARCH = CS_ARCH_ARM
#MODE = CS_MODE_64
if ARCH == CS_ARCH_X86:
md = Cs(CS_ARCH_X86,MODE)
elif ARCH == CS_ARCH_ARM:
... |
import numpy as np
import labrad.units as units
import mem_commands as Mem
def _us(time):
"""
Convert time to microseconds. Return an integer without any
units attached.
Input:
time: time.
Output:
time: time in microseconds without any units attached.
"""
if isinstan... |
# -*- coding: utf-8 -*-
'''
Test Toolbox
-------
Test the toolbox module with nosetests
'''
import pandas as pd
import numpy as np
import scipy.stats as spystats
import nose.tools as nt
from scipy.special import gamma
from pandas.util.testing import assert_almost_equal
from climatic import toolbox
class TestTo... |
from mistral.actions import std_actions as std
from mistral.services import action_manager as a_m
from mistral.tests.unit import base
class ActionManagerTest(base.DbTestCase):
def test_register_standard_actions(self):
action_list = a_m.get_registered_actions()
self._assert_single_item(action_lis... |
import logging, numpy
from pycbc.types import Array, zeros, real_same_precision_as, TimeSeries
from pycbc.filter import overlap_cplx, matched_filter_core
from pycbc.waveform import FilterBank
from math import sqrt
def segment_snrs(filters, stilde, psd, low_frequency_cutoff):
""" This functions calculates the snr o... |
from api_lib import APITest
import xml.etree.ElementTree as ET
class GraphAPITest(APITest):
"""
GET /graph.:ext
"""
def check(self):
resp = self.get("/api/graph.png")
self.check_equal(resp.headers["Content-Type"], "image/png")
self.check_equal(resp.content[:4], '\x89PNG')
... |
#!/usr/bin/python
import json
import logging
import sys
from datetime import datetime
import csv
if __name__ == '__main__':
_loggingLevel = logging.DEBUG ## How much trace
logger = logging.getLogger(__name__)
logging.basicConfig(level=_loggingLevel)
a = {}
altmetricFile = sys.argv[1]
with op... |
from django import forms
class EditProfileForm(forms.Form):
first_name = forms.CharField()
last_name = forms.CharField()
date_of_birth = forms.DateField()
gender = forms.CharField()
receive_updates = forms.BooleanField(required=False) |
# !/usr/bin/python
# coding=utf-8
#
# @Author: LiXiaoYu
# @Time: 2013-10-17
# @Info: Server Library.
import os, sys
from optparse import OptionParser
from configparser import ConfigParser
class ParseConfig():
#配置对象
__config = ""
#配置文件
__config_file = "Config.ini"
#初始化文件
def __init__(self... |
from django.utils.translation import gettext_lazy as _
from wagtail.core import hooks
class LogActionRegistry:
"""
A central store for log actions.
The expected format for registered log actions: Namespaced action, Action label, Action message (or callable)
"""
def __init__(self):
# Has t... |
from restbasetest import *
from common.rest.networking_helper import NetworkingHelper
from common.rest.compute_helper import InstanceHelper
class TestNetworkingRequests(RESTBaseTest):
@classmethod
def setup_class(cls):
super(TestNetworkingRequests, cls).setup_class()
cls.net_helper = Network... |
import codecs
from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.encoding import force_unicode
from nose.tools import assert_false
from nose.tools import assert_is_none
from nose.tools import assert_not_equals
from nose.tools import assert_raises
from nose.tools impor... |
from .X15Chain import X15Chain
class HTMLcoin(X15Chain, PpcPosChain):
def __init__(chain, **kwargs):
chain.name = 'HTMLcoin'
chain.code3 = 'HTML'
chain.address_version = '\x28'
chain.magic = '\xa8\xa3\xa1\xa4'
chain.decimals = 8
X15Chain.__init__(chain, **kwargs)
def ha... |
import io
import json
import os
import shutil
import tempfile
import six
from . import api_test
from ..base import requires_api_version
class BuildTest(api_test.BaseTestCase):
def test_build_streaming(self):
script = io.BytesIO('\n'.join([
'FROM busybox',
'MAINTAINER docker-py',
... |
from .config import Configuration
from .phases import CompileC
from .phases import CompileCxx
from .phases import Assemble
from .phases import BuildAction
from .phases import MergeSwiftModule
from .target import OSType
from .path import Path
import os
class Product(BuildAction):
name = None
product_name = Non... |
#encoding=utf-8
import sys
import telnetlib
import time
import logging
import datetime
port = sys.argv[1]
delay_on = int(sys.argv[2])
delay_off = int(sys.argv[3])
# 配置选项
Host = '192.168.2.108'
username = 'apc'
password = 'apc'
finish = '>'
commands = ["whoami"]
# log
# logging
formatter="%(asctime)s %(le... |
#!/usr/bin/env python
import time
import json
import random
import praw
from peewee import *
from peewee import OperationalError
from peewee import DoesNotExist
import pypandoc
from prawoauth2 import PrawOAuth2Mini
from goodreadsapi import get_book_details_by_id, get_goodreads_ids
from settings import (app_key, app_... |
"""
define a QAbstractItemModel for a an Ordered Dict of an OrderedDict of DataQuickFrames, and also a
TreeView of the Items
"""
from PyQt5 import QtCore, QtWidgets
from .indexabledict import IndexableDict
from ..structures import DataQuickFrame
from . import dataframeview
class DQStructureTree(IndexableDict):
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
import curses
import sys
import fpformat
from StringIO import StringIO
from math import sqrt, fsum
import drone_game
import glob
def tests(size, screen, knowledge=False, reduxed=False):
results = []
counter = 1
test_size = size - 1
j = 1
prepare_window(screen)
screen.addstr(2, 2, "Eseguo i tes... |
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
import unittest
import json
from basetest import ResourceTestCase
from api import app, db
from api.models.groups import Company, Group
from api.models.users import User
#TODO put these generators in utils
def user_gen():
yield {"username":"Bill", "emai... |
# -*- coding: utf-8 -*-
from datetime import date, timedelta
import urllib.parse
from urllib.parse import quote
from django.conf import settings
from django.urls import reverse
from TWLight.tests import AuthorizationBaseTestCase
from TWLight.resources.tests import EditorCraftRoom
from TWLight.users.models import Auth... |
import sys
from copy import copy as copy_list
def read_sentence_col_fmt(sentences_col_fmt):
sentence = []
for line in sentences_col_fmt:
line = line.strip().split()
if not line:
break
sentence.append((line[1], line[2]))
if sentence:
return sentence
else:
... |
"""Sitemaps for Objectapp"""
from django.contrib.sitemaps import Sitemap
from django.core.urlresolvers import reverse
from tagging.models import TaggedItem
from objectapp.models import Gbobject
from objectapp.models import Author
from objectapp.models import Objecttype
from objectapp.managers import tags_published
... |
import unittest
from unittest.mock import MagicMock, patch
from airflow.exceptions import AirflowException
from airflow.models import Connection
from airflow.models.dag import DAG
from airflow.providers.apache.livy.hooks.livy import BatchState, LivyHook
from airflow.providers.apache.livy.operators.livy import LivyOper... |
import os
import PyInstaller
def hook(mod):
# Replace mod by fake 'site' module.
pyi_dir = os.path.abspath(os.path.dirname(PyInstaller.__file__))
fake_file = os.path.join(pyi_dir, 'fake', 'fake-site.py')
new_code_object = PyInstaller.utils.misc.get_code_object(fake_file)
mod = PyInstaller.depend.... |
import optparse
import py_utils
import re
import sys
import threading
import zlib
from devil.android import device_utils
from devil.android.sdk import version_codes
from py_trace_event import trace_time as trace_time_module
from systrace import trace_result
from systrace import tracing_agents
from systrace import util... |
# encoding: utf-8
"""GeoJSON support for Marrow Mongo."""
from __future__ import unicode_literals
from collections import MutableSequence
from numbers import Number as NumberABC
from . import Document, Field
from .field import Alias, Array, Number, String
class GeoJSON(Document):
__type_store__ = 'type'
kind ... |
"""
Provides functionality for extracting information from the faculty's info
dictionary.
The structure of this dictionary is as follows:
{
"class_name":{
"open": true,
"assignments":{
"assignment_name":{
"name":"assignment_name",
"published":true,
"reports_repo":{
"hash":"202585432b8ff21ff4f9... |
import logging
from virttest import libvirt_xml
from virttest import utils_libvirtd
from virttest import utils_misc
from autotest.client.shared import error
def run(test, params, env):
"""
Test capabilities with host numa node topology
"""
libvirtd = utils_libvirtd.Libvirtd()
libvirtd.start()
... |
from msrest.serialization import Model
class LabVirtualMachineCreationParameter(Model):
"""Properties for creating a virtual machine.
:param bulk_creation_parameters: The number of virtual machine instances
to create.
:type bulk_creation_parameters:
~azure.mgmt.devtestlabs.models.BulkCreationPa... |
"""
The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases
by 3330, is unusual in two ways: (i) each of the three terms are prime, and,
(ii) each of the 4-digit numbers are permutations of one another.
There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes,
exhibiting t... |
from __future__ import division, print_function, unicode_literals, \
absolute_import
"""
This script demonstrates the usage of the module interface.py
Also, demonstrates how to fetch data from the materialsproject
database using their API
Note: Before using the script, make sure that you do have a valid
api ke... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import flask
import logging as log
import repast
class Filter(repast.BaseFilter):
def __init__(self):
if 'headernorm' not in repast.app.CONFIG:
raise repast.ConfigurationError(
'headernorm plugin is unconfigured')
def make_bad... |
from flask import Flask, request, render_template
from db import Photo, Tag, PhotoTag
from peewee import fn, JOIN
from download_pic import remove_photo
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile('application.cfg', silent=True)
@app.route('/')
def index():
cnt = fn.Count(PhotoTa... |
from cloudify_agent import app
from cloudify_agent.tests.utils import env
from cloudify_agent.tests import BaseTest
class TestApp(BaseTest):
def test_broker_url_from_env(self):
with env('CELERY_BROKER_URL', 'test-url'):
reload(app)
self.assertEqual(app.broker_url, 'test-url')
... |
import time
import os
import sys
from shutil import copyfile
# Allow accesing files relative to this file
location = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(location, '../../'))
from ocr.viz import print_progress_bar
# Words with these characters are removed
# you have to extend the al... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
qualifier.py
@author Cassandra Henderson
<EMAIL>
* qualifier * -> mpi_prep -> mpi_run -> mpi_read -> jackknifer
Program Use Instructions:
Instructions are found in qualifier.ini, as well as space for user input.
Program Description:
Prepares the random a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import subprocess
import random
import cPickle as pickle
from collections import defaultdict
HOST = "localhost"
PORT = 8001
URL = "http://%s:%d"%(HOST,PORT)
RSYNC_INTERVAL = 5*60 + random.randint(-30,30)
PATH = "/root/Cipsi/"
PATH... |
"""
Setup file for egg builds
@copyright: 2010-2012
@author: Joseph Tallieu <<EMAIL>>
@author: Vijay Halaharvi <<EMAIL>>
@organization: Dell Inc. - PG Validation
@license: GNU LGLP v2.1
"""
# This file is part of WSManAPI.
#
# WSManAPI is free software: you can redistribute it and/or modify
# it under the ter... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from types import NoneType
import datetime
from django.db import models
import uuid
__author__ = 'Alberto Paro'
__all__ = ["get_values"]
#--- taken from http://djangosnippets.org/snippets/2278/
def get_values(instance, go_into={}, exclude=(), extra=(),... |
#!/usr/bin/env python
"""Tests for functions in utils."""
__author__ = "Jens Reeder"
__copyright__ = "Copyright 2011, The QIIME Project"
# remember to add yourself if you make changes
__credits__ = ["Jens Reeder", "Rob Knight"]
__license__ = "GPL"
__version__ = "1.8.0-dev"
__maintainer__ = "Jens Reeder"
__email__ = "<... |
"""This routine controls which localizable files and entries are
reported and l10n-merged.
It's common to all of mobile, mobile/android and mobile/xul, so
those three versions need to stay in sync.
"""
def test(mod, path, entity = None):
import re
# ignore anything but mobile, which is our local repo checkout name... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
from translitua import (
translit, ALL_RUSSIAN, ALL_UKRAINIAN, UkrainianKMU, RussianInternationalPassport)
from django.core.management.base import BaseCommand
from django.db.utils import IntegrityError
from core.models import Person, Ua2Ru... |
import numpy as np
from scipy.linalg import eigh
from scipy.misc import imresize
def ind2sub(array_shape, ind):
# Gives repeated indices, replicates matlabs ind2sub
rows = (ind.astype("int32") // array_shape[1])
cols = (ind.astype("int32") % array_shape[1])
return (rows, cols)
def graphcut(im, n_spl... |
from .field import Field
class Reference(Field):
def __init__(self, selection, string, **kw):
super().__init__(string=string, **kw)
self.selection = selection
def get_col_type(self):
return "varchar(64)"
def get_meta(self, context={}):
vals = super().get_meta(context=con... |
# <EMAIL>
#
# This is a simple little module I wrote to make life easier. I didn't
# see anything quite like it in the library, though I may have overlooked
# something. I wrote this when I was trying to read some heavily nested
# tuples with fairly non-descriptive content. This is modeled very muc... |
import enum
import pendulum
from typing import Dict, List, NamedTuple, Any
from ..context import Context
import pykube.objects
@enum.unique
class SnapshotStatus(enum.Enum):
PENDING = 'snapshot.pending'
COMPLETE = 'snapshot.complete'
# It's up to a backend to decide how a disk should be identified.
# However... |
import pytest
from houston.ardu.command_factory import create_command, read_commands_yml
from houston.command import Command
def test_create_command():
c_dict = {}
with pytest.raises(TypeError):
assert create_command(c_dict)
c_dict['name'] = 'TEST_COMMAND'
with pytest.raises(TypeError):
... |
# -*- coding: utf-8 -*-
import codecs
import os
import time
from cwr.parser.decoder.file import default_file_decoder
from cwr.parser.encoder.cwrjson import JSONEncoder
"""
Visual test for transforming file into a JSON.
This is used to generate a JSON for other tests.
The full JSON will be stored into a file.
"""
_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from django.contrib import admin
from django.core import urlresolvers
from django.utils.html import format_html
from .models import (
Member, NewMember, CheckinCount, MemberYearBook, MemberYearBo... |
"""
Python wrapper for the Worldpay Within SDK.
Includes a launcher for the RPC Agent, type wrappers, service wrapper,
interface for callbacks' event listeners and a method to create thrift client.
Example apps on:
https://github.com/WPTechInnovation/worldpay-within-sdk/tree/feature/python-wrapper/wrappers/python... |
from django.test import TestCase
from ..models import AwareModel, NaiveModel
from boardinghouse.templatetags.boardinghouse import schema_name, is_schema_aware, is_shared_model
from boardinghouse.models import Schema
class TestTemplateTags(TestCase):
def test_is_schema_aware_filter(self):
self.assertTrue(i... |
from __future__ import unicode_literals
from uuid import uuid4, UUID
from sqlalchemy.dialects.postgresql import JSONB, UUID as pg_UUID
from indico.core.db import db
from indico.core.db.sqlalchemy import UTCDateTime
from indico.util.date_time import now_utc
from indico.util.string import return_ascii, format_repr
c... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import tornado.web
from modules.db import db
import string
import constants
import baseHandler
class PostHandler(baseHandler.RequestHandler):
@tornado.web.authenticated
def get(self, id):
query = 'select id, title, content, type, member_id, category_id, create... |
# -*- coding: utf-8 -*-
from nose.tools import assert_equals, assert_not_equals
from nose.tools import assert_raises, assert_in, assert_not_in
from nettool.ace import Ace
from nettool.layer.network_layer import NetworkLayer
from nettool.layer.transport_layer import TransportLayer
from nettool.layer.transport_layer_bu... |
import pytest
import numpy as np
from FIAT import QuadratureElement, make_quadrature, ufc_simplex
@pytest.fixture(params=[1, 2, 3])
def cell(request):
return ufc_simplex(request.param)
@pytest.fixture
def quadrature(cell):
return make_quadrature(cell, 2)
@pytest.fixture
def element(cell, quadrature):
... |
import re
import sys
from .._compat import integer_types, long
from ..helpers.classes import Reference
from .base import SQLAdapter
from . import adapters, with_connection_or_raise
@adapters.register_for('oracle')
class Oracle(SQLAdapter):
dbengine = 'oracle'
drivers = ('cx_Oracle',)
cmd_fix = re.compile(... |
# DOLEV - YAO symmetric + asymmmetric
filenamemaude = "./maudespec/dolev_yao_full.maude"
rewritesystem = [['equat(dec(enc(X,K),K), X)', ['X', 'K']],
['equat(adec(aenc(X,pub(K)),prv(K)), X)', ['X', 'K']],
['equat(proj1(pair(X,Y)), X)', ['X', 'Y']],
['equat(proj2(pair(... |
import unittest
import numpy as np
import scipy as sp
#import scipy.linalg as la
###
### train the fisher linear discriminant using the training data X
### with the class labels Y
###
def trainLDA(X, Y, reg="AUTO"):
'''
method trainLDA(X, Y) obtains the fisher discriminant for multiple class dataset.
Ex... |
from os import getenv
from os.path import join, split
from xdg import BaseDirectory
# Data locations
SHARE_DIR = join(split(__file__)[0])
ALT_USER_DIR = join(getenv('HOME'), '.comics')
USER_DIR = join(BaseDirectory.xdg_config_home, 'awn', 'applets',
'comics')
SYS_FEEDS_DIR = join(SHARE_DIR, 'feeds')... |
# -*- coding: utf-8 -*-
import fixtures
from TSBVMIP import instructions
from TSBVMIP import value_containers
from TSBVMIP.code_parser import parse_string
from TSBVMIP.method import Method
from TSBVMIP.analysis import controlflow
from TSBVMIP.analysis.controlflow import BasicBlock
def test_flow_instructions():
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.