code stringlengths 1 199k |
|---|
import json
from collections import Counter, OrderedDict
import os
class JsonPipeline(object):
def __init__(self, data_dir, id):
self.data_dir = data_dir
self.id = id
def _create_node(self, item):
id = item.post_author_id
node = {}
node['group'] = 1
node['name'] = item.post_author
self.... |
'''/queue/push, 任务队列入口
'''
import os
import time
import tornado.web
import tornado.escape
import assembly
from util import options
from util import g_logger
from util import CommonUtil
from util import decorator as util_decorator
from base import BaseHandler
from domain.object.error import ErrorCode as ECODE
from domai... |
from testscenarios import load_tests_apply_scenarios as load_tests # noqa
import testtools
from oslo.config import cfg
from designate.openstack.common import log as logging
from designate import quota
from designate import tests
from designate import exceptions
LOG = logging.getLogger(__name__)
class QuotaTestCase(tes... |
"""Commands for sketches."""
import click
@click.group('sketch')
def sketch_group():
"""Manage sketch."""
@sketch_group.command('list')
@click.pass_context
def list_sketches(ctx):
"""List all sketches.
Args:
ctx: Click CLI context object.
"""
api_client = ctx.obj.api
for sketch in api_cl... |
from gluon import current
current.db = db
current.auth = auth |
"""Contains a factory function for accessing models.
You can either use the provided `get_model` function, or directly access the
`models_map` variable containing a dictionary from a model name to its class.
"""
from __future__ import absolute_import, division, print_function
import inspect
import tensorflow as tf
from... |
import httpretty
import json
from click.testing import CliRunner
from vl.cli.cloud_provider import list_cloud_providers
@httpretty.activate
def test_cloud_provider_list_one():
name = 'aws'
output = {'name': '%s' % name, 'defaults': {'region': 'us-east-1', 'instance_type': 't1.micro'}}
httpretty.register_uri... |
import unittest
from webob import multidict
from webob.compat import text_
class BaseDictTests(object):
def setUp(self):
self._list = [('a', text_('\xe9')), ('a', 'e'), ('a', 'f'), ('b', '1')]
self.data = multidict.MultiDict(self._list)
self.d = self._get_instance()
def _get_instance(sel... |
import scrapy
class CraigslistItem(scrapy.Item):
"""Item object to store name, link, date"""
title = scrapy.Field()
url = scrapy.Field()
date = scrapy.Field()
class CraigslistSpider(scrapy.Spider):
"""
Tickets spider for NYC
"""
name = "cl-spider"
allowed_domains = "craigslist.org"
... |
"""Formatters for well known objects that don't show up nicely by default."""
import six
try:
from protorpc import messages # pylint: disable=g-import-not-at-top
except ImportError:
messages = None
try:
from google.appengine.ext import ndb # pylint: disable=g-import-not-at-top
except ImportError:
ndb = None
d... |
import fnmatch
import os
import sys
import pytest
from ibis.compat import Path
collect_ignore = ['setup.py']
if sys.version_info.major == 2:
this_directory = os.path.dirname(__file__)
bigquery_udf = os.path.join(this_directory, 'ibis', 'bigquery', 'udf')
for root, _, filenames in os.walk(bigquery_udf):
... |
def join_left(self,
right,
left_on,
right_on=None,
use_broadcast_right=False):
"""
join_left performs left join(Left outer) operation on one or two frames, creating a new frame.
Parameters
---------
:param right: (Frame) Another frame to join w... |
"""This is the script executed by workers of the quality control pipline."""
import argparse
import datetime
from os.path import basename
from pprint import pprint
import re
import subprocess
from google.cloud import bigquery
from google.cloud import datastore
class Pattern(object):
"""Defines a pattern for regular e... |
import os
import os.path
import tempfile
import shutil
import json
from nose.tools import eq_
from nose.tools import with_setup
from build_pack_utils import utils
from common.integration import ErrorHelper
from common.components import BuildPackAssertHelper
from common.components import HttpdAssertHelper
from common.co... |
import logging
import os
from addons.base.apps import BaseAddonAppConfig
from addons.gitlab.api import GitLabClient, ref_to_params
from addons.gitlab.exceptions import NotFoundError, GitLabError
from addons.gitlab.utils import get_refs, check_permissions
from website.util import rubeus
logger = logging.getLogger(__name... |
"""
Define common commands available for all the scripts
"""
import subprocess
import os
import sys
DRIVER_REPO = "/home/driver/repo/"
def is_enabled(value):
return value.lower() in (
"y", "yes", "t", "true", "1", "on"
)
def run(args, env=None, cwd=None, check=True):
subprocess.run(
args, un... |
from tempest.api.volume import base
from tempest.common.utils import data_utils as utils
from tempest import test
class VolumesActionsTest(base.BaseVolumeV1AdminTest):
_interface = "json"
@classmethod
@test.safe_setup
def setUpClass(cls):
super(VolumesActionsTest, cls).setUpClass()
cls.c... |
from websocket import create_connection
run_id = '192bed11-ed86-413a-a2fb-e2c2f648ffd4'
ws = create_connection('ws://localhost:30001/runs/' + run_id + '/nodes/node1/1/p1')
print "Receiving..."
while True:
result = ws.recv()
print "Received '%s'" % result
result = ws.recv()
print "Received '%s'" % result
ws.cl... |
from pyspark import SparkConf, SparkContext
from pyspark.sql import HiveContext
from decimal import Decimal
from datetime import datetime, date
from pyspark.sql import StructType, StructField, ByteType, ShortType, IntegerType, LongType, FloatType, DoubleType, DecimalType, StringType, BooleanType, TimestampType, DateTyp... |
"""
Glance Scrub Service
"""
import os
import sys
import eventlet
eventlet.hubs.get_hub()
if os.name == 'nt':
# eventlet monkey patching the os module causes subprocess.Popen to fail
# on Windows when using pipes due to missing non-blocking IO support.
eventlet.patcher.monkey_patch(os=False)
else:
event... |
"""
Script which verifies that /addEvents API endpoint returns correct response headers in different
scenarios.
"""
from __future__ import absolute_import
from __future__ import print_function
if False: # NOSONAR
from typing import List
import json
import requests
from scalyr_agent import compat
EXPECTED_HEADER_NA... |
from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
import re
import os
import codecs
here = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
# intentionally *not* adding an encoding option to open
return codecs.open(os.path.join(here, *parts), 'r').read()... |
"""
Views for managing images.
"""
from django.conf import settings
from django.forms import ValidationError # noqa
from django.forms.widgets import HiddenInput # noqa
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from ope... |
import Live
from APCSessionComponent import APCSessionComponent
from _Framework.ButtonElement import ButtonElement
from ConfigurableButtonElement import ConfigurableButtonElement #added
class PedaledSessionComponent(APCSessionComponent):
' Special SessionComponent with a button (pedal) to fire the selected clip slo... |
from __future__ import print_function, division, absolute_import
from .logging import get_logger
from .value_object import ValueObject
from .variant_helpers import (
interbase_range_affected_by_variant_on_transcript,
variant_matches_reference_sequence
)
logger = get_logger(__name__)
class ReferenceSequenceKey(V... |
import typing as t
from elastic_transport import ObjectApiResponse
from ._base import NamespacedClient
from .utils import SKIP_IN_PATH, _quote, _rewrite_parameters
class MigrationClient(NamespacedClient):
@_rewrite_parameters()
def deprecations(
self,
*,
index: t.Optional[str] = None,
... |
import traceback
import json
class PayloadSchemaParser:
def parse(self, envelope, standardsMapping):
document = self.base_document(envelope)
try:
self._parse(document, envelope, standardsMapping)
except Exception as ex:
print "Failed to parse"
traceback.pr... |
from .information_coeff import FactorIC
from .factor_quantile import FactorQuantile
from .simple_rank import FactorSimpleRank
from .top_minus_bottom import TopMinusBottom
__all__ = ['FactorIC',
'FactorQuantile',
'FactorSimpleRank',
'TopMinusBottom'] |
"""Useful constants."""
DEFAULT_DNN = "model_search/model_search/configs/dnn_config.pbtxt"
DEFAULT_CNN = "model_search/model_search/configs/cnn_config.pbtxt"
DEFAULT_RNN_ALL = (
"model_search/model_search/configs/rnn_all_config.pbtxt")
DEFAULT_RNN_LAST = (
"model_search/model_search/configs/rnn_last_config.pbtx... |
"""
Description:
This program implements a simple Twitter bot that tweets information about bills in Congress
that are (in)directly related to cyber issues. This bot uses a MySQL database backend to
keep track of bills, both posted and unposted (i.e., tweeted and yet to be tweeted, respectively).
For th... |
"""Produces two plots. One compares aggregators and their analyses. The other
illustrates sources of privacy loss for Confident-GNMax.
A script in support of the paper "Scalable Private Learning with PATE" by
Nicolas Papernot, Shuang Song, Ilya Mironov, Ananth Raghunathan, Kunal Talwar,
Ulfar Erlingsson (https://arxiv.... |
"""Terms of Services page."""
__author__ = 'ichikawa@google.com (Hiroshi Ichikawa)'
from django.utils.translation import ugettext as _
import logging
import traceback
import urllib2
import urlparse
import lxml.etree
import utils
class Handler(utils.BaseHandler):
repo_required = False
def get(self):
arti... |
from sqlalchemy import Column, Integer, String, Text, Numeric, ForeignKey
from sqlalchemy.orm import relationship, backref
from CoreCatalog.database import Base
class Items(Base):
__tablename__ = 'items'
upc = Column(String(13), primary_key=True)
short_description = Column(String(35))
long_description =... |
"""Uniform sampling method.
Samples in batches.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from sampling_methods.sampling_def import SamplingMethod
class UniformSampling(SamplingMethod):
def __init__(self, X, y, seed):
self.X... |
import logging
from osc_lib.i18n import _
from tripleoclient import command
from tripleoclient import constants
from tripleoclient import utils
class ReportExecute(command.Command):
"""Run sosreport on selected servers."""
log = logging.getLogger(__name__ + ".ReportExecute")
def get_parser(self, prog_name):... |
"""Module with input pipeline functions specific for pjit."""
import collections
import itertools
from typing import Any, Iterator, Optional
import jax
from jax.experimental import maps
from jax.experimental import pjit
Mesh = maps.Mesh
PyTree = Any
def prefetch_to_device(
iterator: Iterator[PyTree],
axis_resou... |
"""
This is the Noodles executable worker module. This is usually run by the
scheduler to dispatch jobs remotely, using
.. code-block:: bash
> python3 -m noodles.pilot_job <args>...
Recieve worker commands as JSON objects through stdin and send out results to
stdout.
.. code-block:: bash
> python3 -m no... |
"""The System Bridge integration."""
from __future__ import annotations
import asyncio
import logging
import shlex
import async_timeout
from systembridge import Bridge
from systembridge.client import BridgeClient
from systembridge.exceptions import BridgeAuthenticationException
from systembridge.objects.command.respons... |
from __future__ import unicode_literals
from ... import ProResource
class RegisteredAddress(ProResource):
attribute_names = [
# 'id',
# string The registered ID of the company
'last_update',
# dateTime Date of last update
'company',
# string Company registration numbe... |
import sys
import os
import unittest
import random
import decimal
TEST_HOST = os.environ.get('CQL_TEST_HOST', 'localhost')
TEST_PORT = int(os.environ.get('CQL_TEST_PORT', 9170))
TEST_CQL_VERSION = '3.0.0-beta1'
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import cql
MIN_THRIFT_FOR_CQL_3_0_0_FINAL = (1... |
from setuptools import setup, find_packages
setup(
name="pyhazard",
version="0.0.1",
description="Python client for Hazard.",
author="Jonathan Lange",
author_email="jml@mumak.net",
install_requires=[
'pyrsistent',
'requests',
],
zip_safe=False,
packages=find_packages(... |
"""
db.py - wrapper class to provide all database interaction functions
"""
import MySQLdb as mdb
import sys
import obf_global_vars
__author__ = obf_global_vars.AUTHORS
__copyright__ = obf_global_vars.COPYRIGHT
__credits__ = obf_global_vars.CREDITS
__license__ = obf_global_vars.LICENSE
__version__ = ... |
import os
from setuptools import setup
try:
from pypandoc import convert
README = convert('README.md', 'rst')
except ImportError:
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
print("warning: pypandoc module not found, could not convert Markdown to RST")
with open(os.path.jo... |
from otp.ai.AIBaseGlobal import *
from direct.task.Task import Task
from direct.distributed.ClockDelta import *
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.distributed import DistributedObjectAI
from direct.fsm import State
class DistributedDoorAI(DistributedO... |
"""Functions to query billing info using the Google API."""
from apiclient.discovery import build
import credentials_utils
import log_utils
_LOG = log_utils.GetLogger('messagerecall.billing_info')
class BillingInfo(object):
"""Class to retrieve billing info.
Uses http_utils to add error handling and retry using bac... |
from .mobilenet_v3_paddle import mobilenet_v3_large, mobilenet_v3_small |
import math
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
def oligoTm(seqobj):
"""Computes the melting temp based on the NN model.
(Originated from Kun Zhang)
"""
if isinstance(seqobj,SeqRecord):
seq = seqobj.seq.tostring().upper()
elif isinstance(seqobj,Seq):
seq = seq... |
"""
Cloudbreak API
Cloudbreak is a powerful left surf that breaks over a coral reef, a mile off southwest the island of Tavarua, Fiji. Cloudbreak is a cloud agnostic Hadoop as a Service API. Abstracts the provisioning and ease management and monitoring of on-demand clusters. SequenceIQ's Cloudbreak is a RESTful... |
import ddt
import mock
from rally.plugins.openstack.scenarios.keystone import utils
from tests.unit import fakes
from tests.unit import test
UTILS = "rally.plugins.openstack.scenarios.keystone.utils."
@ddt.ddt
class KeystoneScenarioTestCase(test.ScenarioTestCase):
@mock.patch("uuid.uuid4", return_value="pwd")
d... |
"""FAUCET event notification."""
import json
import os
import socket
import time
from contextlib import contextmanager
import eventlet
eventlet.monkey_patch()
from ryu.lib import hub # pylint: disable=wrong-import-position
from ryu.lib.hub import StreamServer # pylint: disable=wrong-import-position
class NonBlockLock:
... |
import pymongo
from config import DB_CONFIG, DEFAULT_SCORE
from db.ISqlHelper import ISqlHelper
class MongoHelper(ISqlHelper):
def __init__(self):
self.client = pymongo.MongoClient(DB_CONFIG['DB_CONNECT_STRING'], connect=False)
def init_db(self):
self.db = self.client.proxy
self.proxys =... |
"""Tests for the netify.app module."""
from unittest import main
from unittest import skip
from unittest.mock import Mock
from unittest.mock import patch
import netify
import netify.app as app
import netify.config as config
from .base import NetifyTest
from .base import BasicTest
class TestNetifyCore(NetifyTest):
"... |
from __future__ import unicode_literals
from pyte import DiffScreen, mo
def test_mark_whole_screen():
# .. this is straightforward -- make sure we have a dirty attribute
# and whole screen is marked as dirty on initialization, reset,
# resize etc.
screen = DiffScreen(80, 24)
# a) init.
assert ha... |
from datetime import timedelta
from oslo_utils import timeutils
import six
from senlin.common import exception
from senlin.db.sqlalchemy import api as db_api
from senlin.engine import cluster_policy as cpm
from senlin.tests.unit.common import base
from senlin.tests.unit.common import utils
class TestClusterPolicy(base.... |
class Tank():
def init(self, color):
self.color = color
def update(self):
pass
def shoot(self):
pass |
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
import kan
import sphinx_bootstrap_theme
from kan import (
__author__,
__version__,
__release__,
__title__,
)
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.cov... |
import logging
def flattenProperties(items):
if len(items) <1:
return {}
item = items[0]
if type(item) is dict:
if item.has_key("type"):
props ={"type":item.get("type",["-"])[0].split("-")[1:][0]}
properties = item.get("properties",{})
for prop in propert... |
"""The broadlink component."""
import asyncio
from base64 import b64decode, b64encode
from binascii import unhexlify
from datetime import timedelta
import logging
import re
import socket
import voluptuous as vol
from homeassistant.const import CONF_HOST
import homeassistant.helpers.config_validation as cv
from homeassi... |
from turtle import *
from math import *
from time import *
from random import *
def numbers():
hourdistance = 10 #create the hour hand
hourhand = ((0,0),(-20,40),(0,50),(20,40))
hourhandshape = Shape("compound")
hourhandshape.addcomponent(hourhand, "red")
t_hr = Turtle()
... |
import argparse
import os
from west import log
from west.configuration import config
from zcmake import DEFAULT_CMAKE_GENERATOR, run_cmake, run_build, CMakeCache
from build_helpers import is_zephyr_build, find_build_dir, \
BUILD_DIR_DESCRIPTION
from zephyr_ext_common import Forceable
_ARG_SEPARATOR = '--'
BUILD_USA... |
import logging
import os
import sys
import threading
from logging.handlers import RotatingFileHandler
from typing import Callable
import ray
from ray._private.utils import binary_to_hex
_default_handler = None
def setup_logger(logging_level, logging_format):
"""Setup default logging for ray."""
logger = logging... |
import unittest
import canonizer, string
class CanonizeTest(unittest.TestCase):
def testCanonize(self):
text = ''
result = canonizer.canonize(text)
self.assertEqual('', result);
text = 'ab cd. dd f;fae'
result = canonizer.canonize(text)
self.assertEqual('ab cd dd ffae... |
import pytest
from tests.model.ddl import create_table
@pytest.fixture(scope='session')
def table():
return create_table('test')
@pytest.fixture(scope='session')
def table2():
return create_table('test2')
@pytest.fixture(scope='session')
def table3():
return create_table('test3') |
from __future__ import print_function
from __future__ import unicode_literals
import os
import sys
import time
import json
import shutil
import tarfile
import zipfile
import logging
import platform
import argparse
import tempfile
import subprocess
import pkg_resources
from io import StringIO
from threading import Threa... |
import pymongo
import bottle
import cgi
import re
import dictionaryDAO
from flask import json
from bottle import route, request
from bson import json_util
from bson.json_util import dumps
from bottle import static_file
__author__ = 'Sagar Gugwad'
input = "abcatoleaksave"
words = ['cat', 'leak', 'to', 'save']
inputList... |
from rasa.core import run
CREDENTIALS_FILE = "examples/moodbot/credentials.yml"
def test_create_http_input_channels():
channels = run.create_http_input_channels(None, CREDENTIALS_FILE)
assert len(channels) == 7
# ensure correct order
assert {c.name() for c in channels} == {"twilio", "slack",
... |
from __future__ import unicode_literals
from Tkinter import *
from tkFileDialog import *
from nltk.tree import *
import nltk
from nltk.tag import tnt
from nltk.corpus import indian
import tkFont
import re
import sys
import string
reload(sys)
sys.setdefaultencoding('utf-8')
g2=open("depth_22.txt","w")
g=open("depth_21.t... |
"""Setup tool for artman."""
import io
import os
import re
import setuptools
cur_dir = os.path.realpath(os.path.dirname(__file__))
current_version = None
with io.open(os.path.join(cur_dir, 'Dockerfile')) as dockerfile:
for line in dockerfile:
match = re.match(r'^ENV ARTMAN_VERSION (\S+)$', line)
if ... |
import netaddr
def check_subnet_ip(cidr, ip_address):
"""Validate that the IP address is on the subnet."""
ip = netaddr.IPAddress(ip_address)
net = netaddr.IPNetwork(cidr)
# Check that the IP is valid on subnet. This cannot be the
# network or the broadcast address (which exists only in IPv4)
re... |
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kubern... |
import copy
import inspect
from typing import Any, Callable, Dict
import ibis.expr.rules as rlz
from ibis import util
EMPTY = inspect.Parameter.empty # marker for missing argument
class Validator(Callable):
pass
class ValidatorFunction(Validator):
__slots__ = ('fn',)
def __init__(self, fn):
self.fn... |
from sovrin_common import test
test.run() |
"""
KubeVirt API
This is KubeVirt API an add-on for Kubernetes.
OpenAPI spec version: 1.0.0
Contact: kubevirt-dev@googlegroups.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class V1FilesystemVirtiofs(object):
... |
import nltk
from nltk.corpus import brown
brown_tagged_sents = brown.tagged_sents(categories='news')
brown_sents = brown.sents(categories='news')
default_tagger = nltk.DefaultTagger('NN')
print(default_tagger.tag(brown_sents[2007]))
r = default_tagger.evaluate(brown_tagged_sents)
print(r)
unigram_tagger = nltk.UnigramT... |
for ch in GetAllSelCh(False):
nm = GetChName(ch).lower()
if nm=="b" or nm=="blue":
v = GetChVal(ch) - 5
if (v>255): v=255
SetChVal(ch, v)
elif nm=="g" or nm=="green" or nm=="r" or nm=="red":
v = GetChVal(ch) + 5
if (v>255): v=255
SetChVal(ch, v) |
"""
Generate a file of X Mb with text, where X is fetched from the
command line.
"""
def generate(Mb, filename='tmp.dat'):
line = 'here is some line with a number %09d and no useful text\n'
line_len = len(line) - 4 + 9 # length of each line
nlines = int(Mb*1000000/line_len) # no of lines to generate Mb me... |
from setuptools import setup, find_packages
import sys
_locals = {}
with open("invoke/_version.py") as fp:
exec(fp.read(), None, _locals)
version = _locals["__version__"]
exclude = ["*.yaml3" if sys.version_info[0] == 2 else "*.yaml2"]
text = open("README.rst").read()
long_description = """
To find out what's new i... |
ISO_3166 = {
'BD': u'Bangladesh',
'BE': u'Belgium',
'BF': u'Burkina Faso',
'BG': u'Bulgaria',
'BA': u'Bosnia and Herzegovina',
'BB': u'Barbados',
'WF': u'Wallis and Futuna',
'BL': u'Saint Barthélemy',
'BM': u'Bermuda',
'BN': u'Brunei Darussalam',
'BO': u'Bolivia',
'BH': u... |
import collections
from .trie import Trie
class Vocab(object):
def __init__(self):
self.words = Trie()
self.suffixes = collections.defaultdict(set)
self.stems = dict()
def update(self, words):
for w in words:
self.words.add(w)
for w in self.words.words():
... |
from ..excel_comparison_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.set_filename('chart_column10.xlsx')
def test_create_file(se... |
import collections
import datetime
import fractions
import warnings
import numpy as np
import numpy.testing as npt
def assert_dtypes_equal(a, b):
# Check that two dtypes are equal, but ignorning itemsize for dtypes
# whose shape is 0.
assert isinstance(a, np.dtype)
assert a.shape == b.shape
if b.nam... |
from distutils.core import setup
from answers import __version__
requirements = []
with open('./requirements.txt') as requirements_txt:
for line in requirements_txt:
prerequisite = line.split('#')[0].strip()
if prerequisite:
requirements += [prerequisite]
setup(
name='djaodjin-answer... |
'''
Provides a pluggable login manager that uses Kerberos for authentication
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import socket
from flask import _request_ctx_stack as stack
from flask import abort
from flask import request
import kerberos
log = logging.getLogger(_... |
class Base(object):
def __init__(self, client, fileName, path):
self._client = client
self._fileName = fileName
self._path = path
def __getitem__(self, args):
return self._client.call('getitem', fileName=self._fileName, path=self._path, args=args)
def __setitem__(self, args, ... |
"""
"""
from .addMembersToGroups import edir_add_members_to_groups
from ...core.exceptions import LDAPInvalidDnError
from ... import SEQUENCE_TYPES, BASE, DEREF_NEVER
from ...utils.dn import safe_dn
def _check_members_have_memberships(connection,
members_dn,
... |
import numpy as np
from numpy.testing import assert_allclose
import random
import math
from menpo.image import Image, MaskedImage
from menpo.feature import hog, lbp, es, igo
import menpo.io as mio
def test_imagewindowiterator_hog_padding():
n_cases = 5
image_width = np.random.randint(50, 250, [n_cases, 1])
... |
import platform
import csv
import time
from emokit.emotiv import Emotiv
import gevent
class EmotrixRecoder(object):
#El metodo init define algunos parametros por defecto, para almacenar las lecturas del EMOTIV
def __init__(self):
self.sequence = ['happy', 'neutral', 'sad', 'happy', 'neutral', 'sad', 'ha... |
import requests
imagedltimeout=3
def mkpath(outpath):
import os
pos_slash=[pos for pos,c in enumerate(outpath) if c=="/"]
for pos in pos_slash:
try:
os.mkdir(outpath[:pos])
except:
pass
def dlimage(url,verbose=False):
import numpy as np
import shutil
impor... |
from scalmulop import ScalMulV1
from doubleop import DoubleOp
from doublecop import DoubleCOp
from doublec import DoubleC
from doublecgpu import DoubleCGpu
from theano.gof import local_optimizer
from theano.tensor.opt import register_specialize
from theano.gpuarray.opt import (register_opt, op_lifter,
... |
import glob
import os
def fixLigconeRAs(files):
'''
Fixes the problem that some lightcones
had negative RAs. The fix is extemely crude
one only adds 360 to the RA value.
:param files: a list of files to be fixed
:type files: list
'''
for filename in files:
removeFile = True
... |
import radist
def check_result(result, n):
assert len(result) == n
for xnode, status in result:
assert status == 0
r = radist.get_r()
print "---- TEST r_exec ----"
assert r.index.common.r_exec('echo %(name)s; ls %(dir)s') == 0
node = r.get_node('index/001', 'index/002', 'index/003', 'index/common')
prin... |
""" This file defines and validates Flask-User forms. Forms are based on the WTForms module.
:copyright: (c) 2013 by Ling Thio
:author: Ling Thio (ling.thio@gmail.com)
:license: Simplified BSD License, see LICENSE.txt for more details."""
import string
from flask import current_app
from flask_login import c... |
import os
import logging
import sys
import nose
import angr
l = logging.getLogger("angr.tests")
test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests')
insn_texts = {
'i386': b"add eax, 15",
'x86_64': b"add rax, 15",
'ppc': b"addi %r1, %r1, 15",
'armel'... |
import suggestive.widget as widget
import suggestive.mstat as mstat
import suggestive.util as util
import suggestive.analytics as analytics
import suggestive.signals as signals
from suggestive.buffer import Buffer
from suggestive.action import lastfm_love_track
from suggestive.mvc.base import View, Model, Controller, T... |
from __future__ import absolute_import, division, print_function
from sys import getsizeof, stderr
from itertools import chain
from collections import deque
import resource
try:
from reprlib import repr
except ImportError:
pass
last_memory_usage = 0
def memory_usage(unit='mb'):
"""Returns the memory usage o... |
"""
@package mi.dataset.driver.parad_j.cspp.driver
@file marine-integrations/mi/dataset/driver/parad_j/cspp/driver.py
@author Joe Padula
@brief Driver for the parad_j_cspp
Release notes:
initial release
"""
__author__ = 'Joe Padula'
__license__ = 'Apache 2.0'
from mi.core.common import BaseEnum
from mi.core.log import ... |
"""
User settings/preference dialog
===============================
"""
import sys
import logging
from .. import config
from ..utils.settings import SettingChangedEvent
from ..utils.propertybindings import (
AbstractBoundProperty, PropertyBinding, BindingManager
)
from AnyQt.QtWidgets import (
QWidget, QMainWin... |
"""Database models for `lino_xl.lib.statbel.countries`.
.. autosummary::
Country
Place
my_details
"""
from __future__ import unicode_literals
from lino.api import rt, _
from lino_xl.lib.countries.models import *
class Country(Country):
"""Adds two fields :attr:`inscode` and :attr:`actual_country`.
.... |
import pytest
from lektor.utils import build_url
from lektor.utils import is_path_child_of
from lektor.utils import join_path
from lektor.utils import magic_split_ext
from lektor.utils import make_relative_url
from lektor.utils import parse_path
from lektor.utils import slugify
def test_join_path():
assert join_pat... |
import numpy as np
import restrictedBoltzmannMachine as rbm
from batchtrainer import *
from activationfunctions import *
from common import *
from debug import *
from trainingoptions import *
import theano
from theano import tensor as T
from theano.tensor.shared_randomstreams import RandomStreams
theanoFloat = theano.c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.