code stringlengths 1 199k |
|---|
import copy
import datetime
import json
import os
from typing import Dict, List, Optional
import jinja2
import jsonschema
import yaml
from ray_release.anyscale_util import find_cloud_by_name
from ray_release.exception import ReleaseTestConfigError
from ray_release.logger import logger
from ray_release.util import deep_... |
"""
Create generic LPU and simple pulse input signal.
"""
from itertools import product
import sys
import numpy as np
import h5py
import networkx as nx
def create_lpu_graph(lpu_name, N_sensory, N_local, N_proj):
"""
Create a generic LPU graph.
Creates a graph containing the neuron and synapse parameters for... |
from pyramid.interfaces import IRequest
from openprocurement.api.interfaces import IContentConfigurator
from openprocurement.tender.belowthreshold.models import Tender, IBelowThresholdTender
from openprocurement.tender.belowthreshold.adapters import TenderBelowThersholdConfigurator
def includeme(config):
config.add... |
"""
* Copyright (C) Caleb Marshall and others... - All Rights Reserved
* Written by Caleb Marshall <anythingtechpro@gmail.com>, May 27th, 2017
* Licensing information can found in 'LICENSE', which is part of this source code package.
"""
import struct
class Endianness(object):
"""
A enum that stores network ... |
from element import BasePageElement
from locators import PageFooterLocators
from selenium.webdriver.common.action_chains import ActionChains
class BasePage(object):
def __init__(self, driver):
self.driver = driver
class FooterPage(BasePage):
def is_copyright_matches(self):
return "Lauren Nicole ... |
from google.cloud import datacatalog_v1
def sample_update_tag():
# Create a client
client = datacatalog_v1.DataCatalogClient()
# Initialize request argument(s)
tag = datacatalog_v1.Tag()
tag.column = "column_value"
tag.template = "template_value"
request = datacatalog_v1.UpdateTagRequest(
... |
import re
import os, sys
import json
import csv
import shutil
import ctypes
import logging
import datetime
import fileinput
import subprocess
import xml.etree.ElementTree as etree
DEFAULT_HELPER_PATH = "helper"
class Logger(object):
def __init__(self):
"""Init method
"""
self.terminal = sys.... |
"""Exposes the TRT conversion for Windows platform."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import platform
from tensorflow.python.util.tf_export import tf_export
if platform.system() != "Windows":
raise RuntimeError(
"This module is expect... |
from abc import ABC, abstractmethod
from .utils import FileUtils, LoggingUtils
import os
import subprocess
class Build(ABC):
def __init__(self, configuration):
super().__init__()
self.configuration = configuration
@abstractmethod
def before_build(self):
raise NotImplementedError()
... |
NWID=1
NR_NODES=20
Controllers=[{"ip":'10.0.1.28', "port":6633}]
"""
Start up a Simple topology
"""
from mininet.net import Mininet
from mininet.node import Controller, RemoteController
from mininet.log import setLogLevel, info, error, warn, debug
from mininet.cli import CLI
from mininet.topo import Topo
from mininet.u... |
CLASS_REGISTRATION_CONFLICT = "The actor %s has already been registered as " \
"a singleton actor."
INSTANCE_REGISTRATION_CONFLICT = "The actor %s has already been registered " \
"as a non singleton actor."
INVALID_ACTOR_CLASS = "The class %s is not a subcl... |
from __future__ import absolute_import
import json
import logging
from multiprocessing.dummy import Pool
from pip._vendor import six
from pip._vendor.requests.adapters import DEFAULT_POOLSIZE
from pip._internal.cli import cmdoptions
from pip._internal.cli.req_command import IndexGroupCommand
from pip._internal.exceptio... |
"""
Copyright 2017-present Airbnb, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwa... |
"""Script to extract a catalog of Windows Registry keys and values."""
import argparse
import logging
import sys
from dfwinreg import creg as dfwinreg_creg
from dfwinreg import regf as dfwinreg_regf
from dfwinreg import registry as dfwinreg_registry
from winregrc import catalog
from winregrc import output_writers
class... |
import sqlite3
import logging
from time import sleep
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
import sweetSecurityDB
dbPath="/opt/sweetsecurity/client/SweetSecurity.db"
def convertMAC(mac):
newMac="%s%s:%s%s:%s%s:%s%s:%s%s:%s%s" % (mac[0],mac[1],mac[2],mac[3],mac[4],mac[5],mac... |
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template5", checking_point=8, path_list=[
[TestAction.create_vm, 'vm1', ],
[TestAction.create_volume, 'volume1', 'flag=scsi'],
[TestAction.attach_volume, 'vm1', 'volume1'],
... |
import logging
from fiblary.client import Client
logging.basicConfig(
format='%(asctime)-15s %(levelname)s: %(module)s:%(funcName)s'
':%(lineno)d: %(message)s',
level=logging.CRITICAL)
def main():
hc2 = Client(
'v3',
'http://192.168.1.230/api/',
'admin',
'admin'
)
... |
from nets import vgg
import tensorflow as tf
from preprocessing import vgg_preprocessing
from ..utils.upsampling import bilinear_upsample_weights
slim = tf.contrib.slim
from preprocessing.vgg_preprocessing import _R_MEAN, _G_MEAN, _B_MEAN
def extract_vgg_16_mapping_without_fc8(vgg_16_variables_mapping):
"""Removes ... |
import factory
from zeus import models
from zeus.utils import timezone
from .base import ModelFactory
from .types import GUIDFactory
class UserFactory(ModelFactory):
id = GUIDFactory()
email = factory.Faker("email")
date_created = factory.LazyAttribute(lambda o: timezone.now())
date_active = factory.Laz... |
"""Unit tests for result_form_functional_tests.py
Systems:
- indicators.views.ResultCreate
- bad indicator id 404
- get with good ids gives form
- initial form data is correct
- correct disaggregation values
- form valid returns appropriate response
- form invalid ret... |
import urllib
from keystone.tests import test_v3
from keystone.common import config as common_cfg
from keystone.contrib.two_factor_auth import controllers
from keystone.contrib.two_factor_auth import core
from keystone.openstack.common import log
from keystone import exception
import pyotp
import json
LOG = log.getLogg... |
import threading
from mock import patch
from uuid import uuid4
from changes_lxc_wrapper.cli.wrapper import WrapperCommand
def generate_jobstep_data():
# this must generic a *valid* dataset that should result in a full
# run
return {
'status': {'id': 'queued'},
'data': {},
'expectedSn... |
def add(a, b):
return a + b
def fprintf(fmt, *args):
"""args is tuple"""
print fmt % args
print "{0:s}".format("ljinshuan")
fprintf("%s,%d,%s", "xxx", 1, "gerg")
def fprintf(fmt, **args):
"""args is map"""
print args
fprintf("{name} ,{age}", name="ljinshuan", age=10)
event_handers = {}
def eventhand... |
import unittest
from profitbricks.client import ProfitBricksService, Datacenter, Volume
from profitbricks.errors import PBError, PBNotAuthorizedError, PBNotFoundError, PBValidationError
from helpers import configuration
from helpers.resources import resource
class TestErrors(unittest.TestCase):
@classmethod
def... |
"""Auto-generated file, do not edit by hand. NZ metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_NZ = PhoneMetadata(id='NZ', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='[14]\\d{2,3}', possible_length=(3, 4)),
... |
"""Test mongo using the synchronizer, i.e. as it would be used by an
user
"""
import os
import sys
import time
from bson import SON
from gridfs import GridFS
sys.path[0:0] = [""]
from mongo_connector.doc_managers.mongo_doc_manager import DocManager
from mongo_connector.connector import Connector
from mongo_connecto... |
def test_image_export_reference(exporters, state, bpy_image_default, gltf_image_default):
state['settings']['images_data_storage'] = 'REFERENCE'
gltf_image_default['uri'] = '../filepath.png'
output = exporters.ImageExporter.export(state, bpy_image_default)
assert output == gltf_image_default
def test_im... |
"""
Common design parameters for minimum order design methods
@author: Christian Muenker
"""
from __future__ import print_function, division, unicode_literals
class min_order_common(object):
def __init__(self):
self.name = {'common':'Common filter params'}
# message for min. filter order response ty... |
import re
from django import forms
from django.core.urlresolvers import reverse
from django.contrib.formtools.wizard import FormWizard
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.utils.translation import ugettext_lazy as _
from google.appengine.ext.db import ... |
"""
local_qiskit_simulator command to snapshot the quantum state.
"""
from qiskit import CompositeGate
from qiskit import Gate
from qiskit import QuantumCircuit
from qiskit._instructionset import InstructionSet
from qiskit._quantumregister import QuantumRegister
from qiskit.qasm import _node as node
class SnapshotGate(... |
import datetime
from optparse import make_option
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from six import print_
import bigbro
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--store',
dest='stor... |
'''
Created on May 6, 2014
@author: cmills
The idea here is to provide client-side functions to interact with the TASR
repo. We use the requests package here. We provide both stand-alone functions
and a class with methods. The class is easier if you are using non-default
values for the host or port.
'''
import reque... |
from app import app
from flask import render_template
@app.route('/')
def index():
return render_template('index.html')
@app.route('/story/')
def story():
return render_template('story.html')
@app.route('/bio/')
def bio():
return render_template('bio.html')
@app.route('/contact/')
def contact():
return render_templ... |
"""Library functions for ContextRCNN."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
import tf_slim as slim
_NEGATIVE_PADDING_VALUE = -100000
def filter_weight_value(weights, values, valid_mask):
"""Filters weights and ... |
"""Tests for trax.shapes."""
from absl.testing import absltest
import numpy as np
from trax import shapes
from trax.shapes import ShapeDtype
class ShapesTest(absltest.TestCase):
def test_constructor_and_read_properties(self):
sd = ShapeDtype((2, 3), np.int32)
self.assertEqual(sd.shape, (2, 3))
self.assert... |
"""Auto-generated file, do not edit by hand. IS metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_IS = PhoneMetadata(id='IS', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='1\\d{2,5}', possible_length=(3, 4, 6)),
... |
import os
import six
import string
import sys
import time
sys.path.insert(0, os.path.abspath('./extensions'))
extensions = [
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
]
numfig = True
numfig_secnum_depth = (2)
templates_path = ['_templates']
source_suffix = '.rst'
source_encoding = 'utf-8-sig'
master_doc = 'index'
... |
from pygments.lexer import RegexLexer, include, bygroups
import pygments.token as t
class SnortLexer(RegexLexer):
name = 'Snort'
aliases = ['snort', 'hog']
filenames = ['*.rules']
tokens = {
'root': [
(r'#.*$', t.Comment),
(r'(\$\w+)', t.Name.Variable),
(r'\b(... |
"""
Utilities for parseing SExtractor files.
H. Ferguson - revised 4/23/03 to promote ints to floats if a value
with a decimal point appears somewhere in the column originally thought
to be integers
version::
v2.1 - fails gracefully when the catalog has no sources
v3.0 - added gettypes to return column types
... |
import sys
import compile
import os
import subprocess
import context
def run_test (cmd, *args):
cmd = PJ ('tests', cmd)
p = subprocess.Popen ([cmd] + list(args), stdout=subprocess.PIPE)
out = p.stdout.read()
return out
def test_t17():
lines = run_test ('t17').split ('\n')
# we can't say anything... |
"""
Basic framework for acquiring a roach measurement that includes both sweep(s) and stream(s).
Acquire
-Initialize equipment.
-Initialize roach: preload frequencies, if necessary.
-Create state dictionary containing state from all equipment, including temperatures, if possible.
-Run a coarse sweep, if necessary: crea... |
import os
from flask import Flask, request, render_template
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.debug = True
app.threaded = True
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:////tmp/test.db')
db = SQLAlchemy(app)
class Email(db.Model):
id = db.Colu... |
from __future__ import print_function
import locale
import numpy as np
import numba
from pynndescent.utils import (
tau_rand_int,
make_heap,
new_build_candidates,
deheap_sort,
checked_flagged_heap_push,
apply_graph_updates_high_memory,
apply_graph_updates_low_memory,
)
from pynndescent.spars... |
import sys
import osxdaemons
COL_RED = "\033[91m"
COL_GRN = "\033[92m"
COL_END = "\033[0m"
load_actions = ["up", "on", "load", "start"]
unload_actions = ["down", "off", "unload", "stop"]
ACTIONS = {act:"load" for act in load_actions}
ACTIONS.update({act:"unload" for act in unload_actions})
def usage():
sname = str(sy... |
from peyotl.api import OTI
from peyotl.test.support.pathmap import get_test_ot_service_domains
from peyotl.utility import get_logger
import unittest
import os
_LOG = get_logger(__name__)
@unittest.skipIf('RUN_WEB_SERVICE_TESTS' not in os.environ,
'RUN_WEB_SERVICE_TESTS is not in your environment, so tes... |
from setuptools import setup, find_packages
import sys, os
setup(name='nanoweb',
version="1.0",
description="The nano web framework",
long_description="""\
The nano framework provides some glue for Webob and Routes.""",
classifiers=[],
keywords='WSGI',
author='Eric Moritz',
aut... |
"""nrvr.util.ipaddress - Utilities regarding IP addresses
Class provided by this module is IPAddress.
Works in Linux and Windows.
Idea and first implementation - Leo Baschy <srguiwiz12 AT nrvr DOT com>
Contributor - Nora Baschy
Public repository - https://github.com/srguiwiz/nrvr-commander
Copyright (c) Nirvana Researc... |
from ..errors import ErrorFolderNotFound, ErrorInvalidOperation, ErrorNoPublicFolderReplicaAvailable
from ..util import MNS, create_element
from .common import EWSAccountService, folder_ids_element, parse_folder_elem, shape_element
class GetFolder(EWSAccountService):
"""MSDN: https://docs.microsoft.com/en-us/exchan... |
"""Base settings shared by all environments.
This is a reusable basic settings file.
"""
from django.conf.global_settings import *
import os
import sys
import re
TIME_ZONE = 'GB'
USE_TZ = True
USE_I18N = True
USE_L10N = True
LANGUAGE_CODE = 'en-GB'
LANGUAGES = (
('en-GB', 'British English'),
)
SITE_ID = 1
LOGIN_URL... |
"""
Application for testing syncing algorithm
(c) 2013-2014 by Mega Limited, Wellsford, New Zealand
This file is part of the MEGA SDK - Client Access Engine.
Applications using the MEGA API must present a valid application key
and comply with the the rules set forth in the Terms of Service.
The MEGA SDK is distri... |
from __future__ import print_function, absolute_import
import weakref
class PDroneCreator(object):
def __init__(self, mainwindow, clipboard, title="drones"):
self._mainwindow = mainwindow
self._clipboard = clipboard
self._subwin = mainwindow.newSubWindow(title)
from . import PTree
... |
import os
from setuptools import setup
def read(fname):
with open(os.path.join(os.path.dirname(__file__), fname)) as f:
return f.read()
setup(name='django-darkknight',
version='0.9.0',
license="BSD",
description="He's a silent guardian, a watchful protector",
long_description=read('R... |
"""Dictionary-based password generator.
Usage: pass.py [options]
Options:
-h --help Show this help text
-d --dictionary=<path> Specify a non-default dictionary
-n --length=N Specify number of words to use [default: 4]
-v --verbose Print entropy estimate
--complex ... |
import os
PATH = os.path.dirname(os.path.abspath(__file__)) |
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'hyperlink15.xlsx'
te... |
"""
ROC Analysis Widget
-------------------
"""
import operator
from functools import reduce, wraps
from collections import namedtuple, deque
import numpy
import sklearn.metrics as skl_metrics
from PyQt4 import QtGui
from PyQt4.QtGui import QColor, QPen, QBrush
from PyQt4.QtCore import Qt
import pyqtgraph as pg
import ... |
'''
Created on 21.04.2015
@author: marscher
'''
from __future__ import absolute_import
"""Miscellaneous classes/functions/etc."""
import os
import struct
import ctypes
if os.name != 'nt':
import fcntl
import termios
else:
import ctypes.wintypes
DEFAULT_TERMINAL_WIDTH = None
class _WindowsCSBI(object):
"... |
import functools
import itertools
import contextlib
import weakref
import logging
l = logging.getLogger("angr.sim_state")
import claripy
import ana
from archinfo import arch_from_id
from .misc.ux import deprecated
def arch_overrideable(f):
@functools.wraps(f)
def wrapped_f(self, *args, **kwargs):
if has... |
import calendar
from django.template import Library
from molo.core.templatetags.core_tags import load_sections
from molo.profiles.models import UserProfilesSettings
from nurseconnect.utils import get_survey_results_for_user
register = Library()
@register.filter('fieldtype')
def fieldtype(field):
return field.field.... |
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="cubehelix",
version="0.1.0",
author="James Davenport",
# author_email="",
description="Cubehelix colormaps for matplotlib",
long_description=read('README.md... |
import unittest
from petsc4py import PETSc
class TestVersion(unittest.TestCase):
def testGetVersion(self):
version = PETSc.Sys.getVersion()
self.assertTrue(version > (0, 0, 0))
v, patch = PETSc.Sys.getVersion(patch=True)
self.assertTrue(version == v)
self.assertTrue(patch >= ... |
'''test_filter2d
Test the filter2d() example from the PyCon'12 slide deck.
'''
import numpy
from numba import *
from numba.decorators import jit
import sys
import unittest
def filter2d(image, filt):
M, N = image.shape
Mf, Nf = filt.shape
Mf2 = Mf // 2
Nf2 = Nf // 2
result = numpy.zeros_like(image)
... |
import zmq
if __name__ == '__main__':
ctx = zmq.Context()
sinker = ctx.socket(zmq.PULL)
sinker.bind('tcp://*:6666')
print 'sender server init success ...'
msg = sinker.recv()
print '\t%s' % msg
while True:
try:
msg = sinker.recv()
print msg
except KeyboardInterrupt:
break
sinke... |
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from tastypie.resources import NamespacedModelResource, fields, ALL, ALL_WITH_RELATIONS
from django.contrib.auth.models import User #BUG: Import the correct user object from settings.py
from .models import Incident... |
from gensim.models import word2vec
from gensim import models
import jieba
import codecs
import io
from collections import Counter
import operator
import numpy
f = codecs.open("target_article.txt",'r','utf8')
content = f.readlines()
article = []
jieba.set_dictionary('jieba_dict/dict.txt.big')
model = models.Word2Vec.loa... |
"""
cookiecutter.main
-----------------
Main entry point for the `cookiecutter` command.
The code in this module is also a good example of how to use Cookiecutter as a
library rather than a script.
"""
from __future__ import unicode_literals
import logging
import os
from datetime import datetime
from . import __version... |
from decouple import config
from mongrey.web.settings import Test as BaseTest
class Test(BaseTest):
DB_SETTINGS = {
'host': config('MONGREY_DB', 'sqlite:///../mongrey_test.db'),
} |
r"""Experimental multi-sample make_examples for DeepVariant.
This is a prototype for experimentation with multiple samples in DeepVariant, a
proof of concept enabled by a refactoring to join together DeepVariant and
DeepTrio, generalizing the functionality of make_examples to work with multiple
samples.
The output of t... |
from django.test import TestCase
from django.conf import settings
from django.contrib.sites.models import Site
from django.db.models.query import QuerySet
from preferences import preferences
from music.models import TrackContributor, Credit, Track, Album, CreditOption
from music.utils import wikipedia, lastfm
class Scr... |
from django.conf import settings
def mask_toggle(number_to_mask_or_unmask):
return int(number_to_mask_or_unmask) ^ settings.MASKING_KEY |
"""SIP Flask Master Device package."""
import logging
__subsystem__ = 'TangoControl'
__service_name__ = 'FlaskMaster'
__version_info__ = (1, 3, 0)
__version__ = '.'.join(map(str, __version_info__))
__service_id__ = ':'.join(map(str, (__subsystem__,
__service_name__,
... |
"""Read migrated cache file."""
import argparse
import logging
import sys
import rss2irc
def main():
"""Try to read given cache file."""
args = parse_args()
logger = logging.getLogger('read-migrated-cache')
cache = rss2irc.read_cache(logger, args.cache)
assert isinstance(cache, rss2irc.CachedData)
... |
import json
from telemetry import timeline_model
def Import(data):
trace = json.loads(data) # pylint: disable=W0612
model = timeline_model.TimelineModel()
# TODO(nduca): Actually import things.
return model |
import h5py
import sys
import os.path as op
from fos import *
import numpy as np
a=np.loadtxt(op.join(op.dirname(__file__), "data", "rat-basal-forebrain.swc") )
pos = a[:,2:5].astype( np.float32 )
radius = a[:,5].astype( np.float32 ) * 4
parents = a[1:,6] - 1
parents = parents.astype(np.uint32).T
connectivity = np.vsta... |
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Integration'] , ['MovingAverage'] , ['Seasonal_WeekOfYear'] , ['AR'] ); |
"""Fichier contenant le module secondaire diligence."""
from abstraits.module import *
from primaires.format.fonctions import format_nb
from secondaires.diligence import commandes
from secondaires.diligence.diligence import DiligenceMaudite
from secondaires.diligence import editeurs
class Module(BaseModule):
"""Mod... |
import os
import sys
import commands
import shutil
import urllib2
SCRIPT_PATH = os.path.realpath(__file__)
ConstPath = os.path.dirname(SCRIPT_PATH)
def setUp():
global device, XwalkPath, crosswalkVersion, PackTools, ARCH, cachedir
#device = "E6OKCY411012"
device = os.environ.get('DEVICE_ID')
cachedir = ... |
from ooni.utils import log
from twisted.python import usage
from twisted.internet import defer
from ooni.templates import dnst
class UsageOptions(usage.Options):
optParameters = [
['target', 't', None, 'Specify a single hostname to query.'],
['expected', 'e', None, 'Speficy... |
"""`Factory of Factories` pattern."""
from dependency_injector import containers, providers
class SqlAlchemyDatabaseService:
def __init__(self, session, base_class):
self.session = session
self.base_class = base_class
class TokensService:
def __init__(self, id_generator, database):
self.... |
from django.test import TestCase
class CollectionTests(TestCase):
pass |
"""
.. module:: burpui.api.misc
:platform: Unix
:synopsis: Burp-UI misc api module.
.. moduleauthor:: Ziirish <hi+burpui@ziirish.me>
"""
from . import api, cache_key, force_refresh
from ..engines.server import BUIServer # noqa
from .custom import fields, Resource
from .client import ClientLabels
from ..filter ... |
"""
Network Plugin
Network usage and connections
"""
import os, netifaces, psutil, time
from pkm import utils, SHAREDIR
from pkm.decorators import never_raise, threaded_method
from pkm.plugin import BasePlugin, BaseConfig
from pkm.filters import register_filter
NAME = 'Network'
DEFAULT_IGNORES = 'lxc tun'
class Plugin(... |
from parameter import *
from parse_digit import *
from os import system
cmd = "make -C tools >/dev/null 2>/dev/null;mkdir log model 2>/dev/null"
system(cmd)
methodlist = ['random-forest','gbdt']
data = ['MQ2007','MQ2008','MSLR','YAHOO_SET1','YAHOO_SET2','MQ2007-list','MQ2008-list']
print "\\begin{tabular}{l"+"|rrr"*le... |
"""
Prepare Sparse Matrix for Sparse Affinity Propagation Clustering (SAP)
"""
import numpy as np
import pandas as pd
import sparseAP_cy # cython for calculation
def copySym(rowBased_row_array,rowBased_col_array,rowBased_data_array,singleRowInds):
"""
For single col items or single row items, copy sym minimal v... |
import cPickle
import numpy as np
import sys
from collections import OrderedDict
def format_chars(chars_sent_ls):
max_leng = max([len(l) for l in chars_sent_ls])
to_pads = [max_leng - len(l) for l in chars_sent_ls]
for i, to_pad in enumerate(to_pads):
if to_pad % 2 == 0:
chars_sent_ls[i]... |
from ..module import get_introspection_module
from ..overrides import override
import warnings
GElektra = get_introspection_module('GElektra')
def __func_alias(klass, old, new):
func = getattr(klass, old)
setattr(klass, new, func)
def __func_rename(klass, old, new):
__func_alias(klass, old, new)
delattr(klass, old)... |
"""Test initalization and other aspects of Angle and subclasses"""
import threading
import warnings
import numpy as np
import pytest
from numpy.testing import assert_allclose, assert_array_equal
import astropy.units as u
from astropy.coordinates.angles import Longitude, Latitude, Angle
from astropy.coordinates.errors i... |
import os
PACKAGE_NAME = 'pyflux'
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration(PACKAGE_NAME, parent_package, top_path)
config.add_subpackage('__check_build')
config.add_subpackage('arma')
config.add_subpackage('ensemb... |
import uuid
from couchdbkit import ResourceConflict
from couchdbkit.exceptions import ResourceNotFound
from django.test import TestCase
from toggle.shortcuts import update_toggle_cache, namespaced_item, clear_toggle_cache
from .models import generate_toggle_id, Toggle
from .shortcuts import toggle_enabled, set_toggle
c... |
import os
import unittest
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../lib'))
from testlib import random_string
from systestlib import DutSystemTest
class TestApiSystem(DutSystemTest):
def test_get(self):
for dut in self.duts:
dut.config('default hostname')
... |
from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from django.core.urlresolvers import RegexURLResolver
from django.http import Http404
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.url_routing import RouteResult
_creation_counter = 0
def route(pattern, nam... |
from decimal import Decimal
from django.http import HttpResponse, HttpRequest
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.core.urlresolvers import reverse
from django.test import TestCase, Client
from ....cart.app import cart_app
from ....cart.models import CART_SESS... |
import logging
import warnings
from flypwd.config import config
with warnings.catch_warnings():
warnings.simplefilter("ignore")
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
log = logging.getLogger(__name__)
def check_key(keyfile):
"""
checks the RSA key file
raises Value... |
import os
import shutil
import unittest
import copy
from nvpy.nvpy import Config
from nvpy.notes_db import NotesDB
notes = {
'1': {
'modifydate': 1111111222,
'tags': [],
'createdate': 1111111111,
'syncdate': 0,
'content': 'active note 1',
'savedate': 0,
},
'2'... |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 12, transform = "None", sigma = 0.0, exog_count = 100, ar_order = 12); |
import tests.periodicities.period_test as per
per.buildModel((120 , 'S' , 25)); |
from nose.plugins.skip import SkipTest
from oyster.conf import settings
from oyster.core import Kernel
from oyster.storage.gridfs import GridFSStorage
from oyster.storage.dummy import DummyStorage
def _simple_storage_test(StorageCls):
kernel = Kernel(mongo_db='oyster_test')
kernel.doc_classes['default'] = {}
... |
from flexbe_core import EventState, Logger
import rospy
from flexbe_core.proxy import ProxyPublisher
from geometry_msgs.msg import Twist
"""Created on June. 21, 2017
@author: Alireza Hosseini
"""
class PublishTwistState(EventState):
"""
Publishes a velocity command from userdata.
-- topic string Topic to which ... |
"""
Runs GenomeMapper on single-end or paired-end data.
"""
import optparse, os, sys, tempfile
def stop_err( msg ):
sys.stderr.write( "%s\n" % msg )
sys.exit()
def __main__():
#Parse Command Line
parser = optparse.OptionParser()
parser.add_option('', '--threads', dest='threads', help='The number of ... |
r"""Browse raw data.
This uses :func:`mne.io.read_raw` so it supports the same formats
(without keyword arguments).
Examples
--------
.. code-block:: console
$ mne browse_raw sample_audvis_raw.fif \
--proj sample_audvis_ecg-proj.fif \
--eve sample_audvis_raw-eve.fif
"""
imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.