content stringlengths 4 20k |
|---|
from __future__ import print_function, with_statement, absolute_import
from glob import glob
import os.path
import platform
MAX_FILES_TO_CACHE = 1000
class PathUnNormcase(object):
"""Ensures path names of files are returned as they exist on the fs."""
def __init__(self):
self._dict = {}
se... |
#!/usr/bin/env python
"""
BER simulation for QPSK signals, compare to theoretical values.
Change the N_BITS value to simulate more bits per Eb/N0 value,
thus allowing to check for lower BER values.
Lower values will work faster, higher values will use a lot of RAM.
Also, this app isn't highly optimized--the flow graph... |
from uuid import uuid4
from social.utils import slugify, module_member
USER_FIELDS = ['username', 'email']
def get_username(strategy, details, user=None, *args, **kwargs):
if 'username' not in strategy.setting('USER_FIELDS', USER_FIELDS):
return
storage = strategy.storage
if not user:
... |
from oslo.config import cfg
from cinder import exception
from cinder.image import glance
from cinder.image import image_utils
from cinder.openstack.common import log as logging
from cinder.volume import driver
from cinder.volume.drivers.xenapi import lib as xenapi_lib
LOG = logging.getLogger(__name__)
xenapi_opts = ... |
import re
from decimal import Decimal
from inchi_converter import convert_inchi_to_formula
from adducts import positive_mode_adducts, negative_mode_adducts
import molmass
class Formula_Base(object):
H_ADDUCT = 1.0073
def __init__(self, formula=None):
self.__formula = formula
@property
def formula(self):... |
"""Common utility for testing third party oauth2 features."""
import json
import httpretty
from provider.constants import PUBLIC
from provider.oauth2.models import Client
from social.apps.django_app.default.models import UserSocialAuth
from social.backends.facebook import FacebookOAuth2
from student.tests.factories im... |
"""i18n template search and interpolation."""
__all__ = [
'TemplateNotFoundError',
'find',
'make',
'search',
]
import os
import sys
import errno
from itertools import product
from mailman.config import config
from mailman.core.constants import system_preferences
from mailman.core.errors import M... |
from spack import *
class Zeromq(AutotoolsPackage):
""" The ZMQ networking/concurrency library and core API """
homepage = "http://zguide.zeromq.org/"
url = "http://download.zeromq.org/zeromq-4.1.2.tar.gz"
version('develop', branch='master',
git='https://github.com/zeromq/libzmq.git'... |
from django.contrib import auth
from django.core import validators
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.db.models.manager import EmptyManager
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import smart_str
from django.uti... |
import psycopg2
from sqlalchemy import create_engine
import json
import pandas as pd
import subprocess, os
import re
import argparse
from argparse import ArgumentParser
argparse_desc = ('PostgreSQL uploader for CSV files\n'
'usage: python psql_uploader.py [options] -i filename '
'... |
import unittest
from test.tools.mock_descriptors import make_field
from google.protobuf import descriptor_pb2
from google.api import field_behavior_pb2
from google.api import resource_pb2
class FieldTest(unittest.TestCase):
def test_basic_properties(self):
field = make_field("Foo")
self.assertEqua... |
import util
import os
import time
import base64
import re
import const
import json
def login(username, password, endpoint):
login_body = const.LOGIN_BODY.format(
username = username,
password = password
)
res = util.httpRequest("POST", endpoint, login_body, const.SOAP_HEADER)
server_ur... |
"""
Twitter Objects representation. Data is normalized to python types.
"""
import sys
from parsers import parsedate, unescape
#########################################################
# Basic Objects
#########################################################
class TwitterObject(object):
"""
Common base object... |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import csv
from logger import to_unicode
def csv2list(s):
assert isinstance(s, unicode)
for l in csv.reader([s.encode('utf-8')]):
v = [x.decode('utf-8').strip(' \t') for x in l]
return v
def csvquote(s):
do_quote = False
if s.find('"') >... |
import functools
import logging
import os
from lintreview.review import IssueComment
from lintreview.tools import Tool, run_command, process_checkstyle
from lintreview.utils import in_path, npm_exists
log = logging.getLogger(__name__)
class Eslint(Tool):
name = 'eslint'
def check_dependencies(self):
... |
from edxmako.shortcuts import render_to_string
from pipeline.conf import settings
from pipeline.packager import Packager
from pipeline.utils import guess_type
from static_replace import try_staticfiles_lookup
from django.conf import settings as django_settings
from django.contrib.staticfiles.storage import staticfile... |
import pprint
import collections
import binaryninja as bn
from binja_var_recovery.util import *
from binja_var_recovery.il_analysis import *
FUNCTION_OBJECTS = collections.defaultdict()
VARIABLE_ALIAS_SET = collections.defaultdict(set)
SSAVariableSet = collections.defaultdict(set)
class ILVisitor(object):
""" Cla... |
""" This method implements the spi interface to the
powersupply Korad ka3005p.
Powersupply = Korad()
Powersupply.Output = True
"""
import serial
import time
import sys
python_version = sys.version_info[0]
# constants for the status
ConstantCurrent = 0
CosntantVoltage = 1
ON = 1
OFF = 0
class Korad(object):
... |
#!/usr/bin/env python
"""
@file transportationTestProblems.py
@author Michael Behrisch
@date 2015-02-24
@version $Id: transportationTestProblems.py 22608 2017-01-17 06:28:54Z behrisch $
Create a network and trips for inputs found at http://www.bgu.ac.il/~bargera/tntp/.
SUMO, Simulation of Urban MObility; see h... |
from ..args import arg
from ..command import command
from ..result import Result
from ..util import abs_path, StreamOptions
from .local import local
@command
def sync(
source,
destination,
host,
user=None,
sudo=False,
run_as=None,
options=("-rltvz", "--no-perms", "--no-group"),
exclude... |
import copy
import fixtures
import mox
from nova import context
from nova import test
import nova.tests.image.fake
from nova.tests import utils
from nova.tests.virt.vmwareapi import stubs
from nova.virt import fake
from nova.virt.vmwareapi import driver
from nova.virt.vmwareapi import fake as vmwareapi_fake
from nova.... |
from odoo.tests import common
@common.at_install(False)
@common.post_install(True)
class base_action_rule_test(common.TransactionCase):
def setUp(self):
super(base_action_rule_test, self).setUp()
self.user_admin = self.env.ref('base.user_root')
self.user_demo = self.env.ref('base.user_dem... |
import hashlib
import hmac
import httplib2
from neutronclient.v2_0 import client
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging
import six
import six.moves.urllib.parse as urlparse
import webob
from neutron.agent.linux import utils as agent_utils
from neutron.agent.metadata impo... |
import logging
import time
import threading
from Config import config
if config.debug: # Only load pyfilesytem if using debug mode
try:
from fs.osfs import OSFS
pyfilesystem = OSFS("src")
pyfilesystem_plugins = OSFS("plugins")
logging.debug("Pyfilesystem detected, source code auto... |
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
from django.utils import unittest
from admin_sso import settings
from admin_sso.auth import DjangoSSOAuthBackend
from admin_sso.models import Ass... |
import adm
from wh import xlt, YesNo
from _dns import BindConnection
class Server(adm.ServerNode):
shortname=xlt("BIND Server")
typename=xlt("BIND Server")
def __init__(self, settings):
adm.ServerNode.__init__(self, settings)
self.zones=adm.config.Read(self.name, [], self, "Zones")
self.revzones=... |
import testtools as unittest
import basicdb
from basicdb import utils
class UtilsTests(unittest.TestCase):
def _create_request(self, params):
class Request(object):
def __init__(self, params):
self._params = params
return Request(params)
def test_extract_numbered_... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
TestOTBAlgorithms.py
---------------------
Copyright : (C) 2013 by CS Systemes d'information
Email : otb at c-s dot fr
Contributors : Oscar Picas
***************... |
#!/usr/bin/env python
"""
main.py -- Udacity conference server-side Python App Engine
HTTP controller handlers for memcache & task queue access
$Id$
created by wesc on 2014 may 24
"""
__author__ = '<EMAIL> (Wesley Chun)'
import webapp2
from google.appengine.api import app_identity
from google.appengine.api im... |
#/usr/bin/env python
# Script which goes with hpp-rbprm-corba package.
# The script launches a skeleton-robot and a groundcrouch environment.
# It defines init and final configs, and solve them with RBPRM.
# Range Of Motions are spheres linked to the 4 end-effectors
#blender/urdf_to_blender.py -p rbprmBuilder/ -i /loc... |
#!/usr/bin/env python
"""
=================================================
Draw a Quantile-Quantile Plot and Confidence Band
=================================================
This is an example of drawing a quantile-quantile plot with a confidence level
(CL) band.
"""
print __doc__
import ROOT
from rootpy.interactive... |
'''
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License");... |
class classPathHacker:
##########################################################
# from http://forum.java.sun.com/thread.jspa?threadID=300557
#
# Jython class
# Purpose: Allow runtime additions of new Class/jars either from
# local files or URL
######################################################
imp... |
from __future__ import absolute_import
from datetime import datetime
import argparse as _argparse
import os
def is_dir(string):
"""
Type check for a valid directory for ArgumentParser.
"""
if not os.path.isdir(string):
msg = '{0} is not a directory'.format(string)
raise _argparse.Argu... |
import socket
import os
import sys
import threading
import warnings
from main.constants import SESSION_TOKEN_LEN
from main.settings import BASE_DIR
from network.models import ConnectedGateway, ConnectedDevice
IPC_COMMAND_PATH = BASE_DIR + "/manager-ipc"
class ManagerException(Exception):
"""Exception thrown by man... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_security
----------------------------------
Tests for the security operations.
"""
import copy
import unittest
from magpie.security import mask_credentials
from tests import runner, utils
@runner.MAGPIE_TEST_LOCAL
@runner.MAGPIE_TEST_SECURITY
class TestSecurit... |
from pages.ui_component import UIComponent
class Label(UIComponent):
def get_for_attribute(self):
return self.locate().get_attribute("for") |
from ._discodb import _DiscoDB, DiscoDBConstructor, DiscoDBError, DiscoDBIter, DiscoDBView
from .query import Q
from .tools import kvgroup
def discodb_unpickle(string):
return DiscoDB.loads(string)
class DiscoDBInquiry(object):
def __init__(self, iterfunc):
self.iterfunc = iterfunc
def __iter__(s... |
from deploy_board.webapp.helpers.rodimus_client import RodimusClient
rodimus_client = RodimusClient()
def create_security_zone(request, security_zone_info):
return rodimus_client.post("/security_zones", request.teletraan_user_id.token, data=security_zone_info)
def get_all(request, index, size):
params = [(... |
"""CPU module for Auburndale"""
import bits
from cpu_gen import mwait_hint_to_cstate
from cpu_nhm import register_tests, generate_mwait_menu
name = 'Auburndale'
def is_cpu():
return bits.cpuid(bits.bsp_apicid(),1).eax & ~0xf == 0x106f0
def init():
pass |
'''
Generic message-based protocol used by Starwels and P2Pool for P2P communication
'''
import hashlib
import struct
from twisted.internet import protocol
from twisted.python import log
import p2pool
from p2pool.util import datachunker, variable
class TooLong(Exception):
pass
class Protocol(protocol.Protocol)... |
import json
import pytest
from datadog_checks.base import ConfigurationError
from datadog_checks.ns1 import Ns1Check
def test_empty_instance(aggregator, instance_empty):
with pytest.raises(ConfigurationError):
_ = Ns1Check('ns1', {}, [instance_empty])
def test_config(aggregator, instance):
check =... |
import webbrowser
import wx
from timelinelib.wxgui.dialogs.feedback.controller import FeedbackDialogController
from timelinelib.wxgui.framework import Dialog
class FeedbackDialog(Dialog):
"""
<BoxSizerVertical>
<StaticText name="info" border="LEFT|TOP|RIGHT" />
<FlexGridSizer columns="2" gr... |
"""The glimpse network produces features out of glimpses.
From the original RAM paper:
The glimpse network fg(x, l) had two fully connected layers.
Let Linear(x) de- note a linear transformation of the vector x,
i.e. Linear(x) = Wx+b for some weight matrixW and bias vector b,
and letRect(x) = max(x, 0) be the rectifie... |
# 6.00x Problem Set 4A Template
#
# The 6.00 Word Game
# Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens>
# Modified by: Sarina Canelake <sarina>
#
import random
import string
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': ... |
from openerp.osv import osv, fields
class res_partner(osv.Model):
_inherit = 'res.partner'
_order = "parent_left"
_parent_order = "ref"
_parent_store = True
_columns = {
'parent_right': fields.integer('Parent Right', select=1),
'parent_left': fields.integer('Parent Left', select=... |
import os
import random
import string
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
TEST_APP_URL = os.getenv('TEST_APP_URL')
TEST_CLIENT_URL = os.getenv('TEST_CLIENT_URL')
E2E_ARGS = os.getenv('E2E_ARGS')
TEST_URL = TEST_CLIENT_URL if E2E_ARGS... |
"""
This module contains fixups for using nose under different versions of Python.
"""
import sys
import os
import types
import inspect
import nose.util
__all__ = ['make_instancemethod', 'cmp_to_key', 'sort_list', 'ClassType',
'TypeType', 'UNICODE_STRINGS', 'unbound_method', 'ismethod',
'bytes_']... |
""" Simulations a random assignment of tasks to workers. """
import math
import numpy
import random
import Queue
from util import Job, TaskDistributions
MEDIAN_TASK_DURATION = 100
NETWORK_DELAY = 0.5
TASKS_PER_JOB = 100
SLOTS_PER_WORKER = 4
TOTAL_WORKERS = 10000
def get_percentile(N, percent, key=lambda x:x):
if... |
from StarFile import StarBlock,StarFile,StarList,StarDict
# An alternative specification for the Cif Parser, based on Yapps2
# by Amit Patel (http://theory.stanford.edu/~amitp/Yapps)
#
# helper code: we define our match tokens
lastval = ''
def monitor(location,value):
global lastval
#print 'At %s: %s' % (locati... |
from optparse import OptionParser
from troubleshooting.framework.version.version import VERSION
import sys,os
class BaseCommand(object):
"""
this is command
"""
def __init__(self):
super(BaseCommand,self).__init__()
self.opt = None
self.successor = None
def handle(self,*args... |
import os
import socket
import os
from flask import Flask, request
#https://docs.aws.amazon.com/xray-sdk-for-python/latest/reference/basic.html
# #Lets try to use AWS X-ray for metrics / logging if available to us
try:
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all
from... |
from django.test import TestCase
from poradnia.letters.factories import LetterFactory
from poradnia.letters.models import Letter
from poradnia.records.models import Record
from poradnia.users.factories import UserFactory
class QuerySetTestCase(TestCase):
def _test_letter_for_user(self, staff, status, res):
... |
import os
from sahara import conductor as c
from sahara import context
from sahara import exceptions as e
from sahara.i18n import _
import sahara.plugins.general.utils as plugin_utils
from sahara.plugins.mapr.services.spark import spark
from sahara.service.edp import job_utils
from sahara.service.edp.spark import engi... |
{
"name": "Product Customer code on sale",
"version": "1.0",
"author": "Agile Business Group",
"website": "http://www.agilebg.com",
"category": "Sales Management",
"depends": [
'base',
'product',
'sale',
'product_customer_code'
],
"description": """
Ba... |
"""
Declaration of CourseOverview model
"""
import json
from django.db import models, transaction
from django.db.models.fields import BooleanField, DateTimeField, DecimalField, TextField, FloatField, IntegerField
from django.db.utils import IntegrityError
from django.utils.translation import ugettext
from lms.djangoap... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division, print_function
from collections import namedtuple
from dateutil.parser import parse as parse_date
import requests
from lxml import etree
__all__ = ['get_current_tournaments', 'get_status', 'WEBSITE_URL', 'TOURNAMENTS_XML_URL'... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from twisted.protocols.basic import NetstringReceiver
from twisted.internet.protocol import Factory
from twisted.internet import reactor
import zmq
import socket
import threading
from obci.control.common.message import OBCIMessageTool, send_msg, recv_msg, PollingObject
from ... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Blockstack
~~~~~
copyright: (c) 2014-2015 by Halfmoon Labs, Inc.
copyright: (c) 2016 by Blockstack.org
This file is part of Blockstack
Blockstack is free software: you can redistribute it and/or modify
it under the terms of the GNU General... |
#! /usr/bin/env python
import os
import select
import sys
import termios
import threading
import tty
import numpy as np
import rospy
from am_driver.msg import BatteryStatus, Mode, SensorStatus
from geometry_msgs.msg import Twist
from std_msgs.msg import UInt16
def mowerStateToString(x):
return {
SensorStatus.M... |
import pytest
import torch
from torch.autograd import grad
import pyro
import pyro.distributions as dist
from pyro import poutine
from pyro.infer.reparam import HaarReparam
from tests.common import assert_close
# Test helper to extract central moments from samples.
def get_moments(x):
n = x.size(0)
x = x.res... |
"""Support for Flo Water Monitor binary sensors."""
from __future__ import annotations
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_PROBLEM,
BinarySensorEntity,
)
from .const import DOMAIN as FLO_DOMAIN
from .device import FloDeviceDataUpdateCoordinator
from .entity import FloEntity
asy... |
import io
from codecs import encode as codecs_encode
import os
import string
from base64 import b64decode
from base64 import b64encode
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.ha... |
from __future__ import absolute_import, unicode_literals
import pytest
import logging
import os
from IPython.display import display
from psd_tools.constants import Tag
from psd_tools.psd.base import IntegerElement
from psd_tools.psd.tagged_blocks import (
TaggedBlocks,
TaggedBlock,
Annotation,
Annotati... |
#!/usr/bin/env python2
import argparse
import sys
def main():
desc = 'Crash simulator script, useful for testing the bisection tool.\
bisection-tool.py --cmd "./pydir/bisection-test.py -c 2x3" \
--end 1000 --timeout 60'
argparser = argparse.ArgumentParser(description=desc)
argparser.add_argum... |
import logging
from .NodeTest import NodeTest
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class NCNameNodeTest(NodeTest):
def __init__(self, name):
super().__init__()
self.name = name
def evaluate(self, context_node, context_position, context_size, variables):
... |
import os
from oslo_config import cfg
import tenacity
from gnocchi import carbonara
from gnocchi.common import s3
from gnocchi import storage
from gnocchi import utils
boto3 = s3.boto3
botocore = s3.botocore
OPTS = [
cfg.StrOpt('s3_endpoint_url',
help='S3 endpoint URL'),
cfg.StrOpt('s3_region... |
def remove_letters(letters, word):
for ch in word:
del letters[letters.index(ch)]
t = int(raw_input())
for case in xrange(1,t+1):
numbers = []
letters = [x for x in raw_input()]
#ZERO
while 'Z' in letters:
numbers.append(0)
remove_letters(letters, 'ZERO')
#TWO
while... |
"""Copyright 2009 Chris Davis
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, software
dist... |
# -*- coding: utf-8 -*-
from haystack.backends.elasticsearch_backend import (ElasticsearchSearchBackend,
ElasticsearchSearchEngine)
class KuromojiElasticsearchBackend(ElasticsearchSearchBackend):
DEFAULT_ANALYZER = 'kuromoji_analyzer'
# This can be removed after Haystack 2.1.1 hits.
RESERVED_CHARACTE... |
'''
Calculate AR@N and AUC;
Modefied from ActivityNet Gitub repository](https://github.com/activitynet/ActivityNet.git)
'''
import sys
sys.path.append('../../Evaluation')
from eval_proposal import ANETproposal
import numpy as np
import argparse
parser = argparse.ArgumentParser("Eval AR vs AN of proposal")
parser.add... |
import inspect
import logging as std_logging
import os
import random
from oslo.config import cfg
from tacker.common import config
from tacker.common import rpc_compat
from tacker import context
from tacker.openstack.common import excutils
from tacker.openstack.common import importutils
from tacker.openstack.common im... |
import os
import sys
import json
from textwrap import dedent
from polls.models import Question, Choice
from django.test import Client, TestCase
from django.test.utils import override_settings
import pyexcel as pe
import pyexcel.ext.xls # noqa
import pyexcel.ext.xlsx # noqa
import pyexcel.ext.ods3 # noqa
PY2 = sys.ve... |
import matplotlib.pyplot as plt
import numpy as np
import scattering
import scipy.constants as consts
import quantities as pq
def plot_csec(scatterer, d, var, name):
lam = scatterer.wavelength.rescale('cm')
plt.plot(d, var,
label='%.1f %s' % (lam, lam.dimensionality))
plt.xlabel('Diameter (%s)'... |
'''
Examples from the documentation.
'''
from logging import getLogger
from unittest import TestCase
from traceback import format_exception_only, format_exc
from lepl._test.base import assert_str
class Example(TestCase):
def examples(self, examples):
'''
Run each example and check expected a... |
import pytest
from hypothesis import given, assume
from hypothesis.strategies import fixed_dictionaries, integers, characters, composite, \
dictionaries, booleans, floats, lists
from datatyping.datatyping import validate
def test_empty():
assert validate({}, {}) is None
@given(dct=fixed_dictionaries({'a': ... |
try:
from ._models_py3 import DatadogAgreementProperties
from ._models_py3 import DatadogAgreementResource
from ._models_py3 import DatadogAgreementResourceListResponse
from ._models_py3 import DatadogApiKey
from ._models_py3 import DatadogApiKeyListResponse
from ._models_py3 import DatadogHost
... |
import csv
import sys
import argparse
import re
from rdflib import Graph, URIRef, RDF, RDFS, OWL, Literal
from io import StringIO
from namespaces import namespaces, ICDCG, WHO, SCTCG
from ConverterGateway import SCTConverterGateway
from ontology_defs import cg_ontology
# maptype values. post_coordinated means tha... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 13 12:21:40 2015
take user documents and create a word2vec doc out of it
@author: frickjm
"""
from random import shuffle
import numpy as np
def getRandom(user,words,numLines,numWords,outfile):
for x in range(numLines):
shuffle(words)
new = ' '.... |
import re
import json
import datetime
from cstock.base_engine import Engine
from cstock.model import Stock, ParserException
class SinaEngine(Engine):
"""
Sina Engine transform stock id & parse data
"""
DEFAULT_BASE_URL = "http://hq.sinajs.cn/list=%s"
def __init__(self, base_url=None):
... |
from utils.views import JsonView
from utils.models import *
from utils.tcpclient import tcp_request
from django.http import HttpResponseServerError
class ChatMessagesView(JsonView):
def react(self, data):
if 'last_id' in data:
result = ChatMessage.objects.filter(id__gt=data['last_id'])
... |
"""
Doubly-linked list class.
"""
class DLL(object):
"""An indexed, doubly-linked list
>>> l = DLL()
>>> l
[]
>>> l.push(1)
>>> l.push(2)
>>> l
[2, 1]
"""
def __init__(self):
"""
>>> l = DLL()
"""
self._first = None
self._last = None
... |
""" The implementation of local host communication"""
import os
import time
import socket
import re
from shutil import copyfile
from testkitlite.util.log import LOGGER
from testkitlite.util.autoexec import shell_command, shell_command_ext
HOST_NS = "127.0.0.1"
os.environ['no_proxy'] = HOST_NS
os.environ['TEST_PLATF... |
"""
Avoid using default `language` field for text indexes
as it would throw an error when saving document with
unsupported language.
So instead we should define indexes with custom language
field (via `language_override`) and only set it when it's supported.
"""
_TEXT_MONGO_LANGUAGE = "_mongo_language"
# https://doc... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("services", "0010_auto_20170406_0110"),
]
operations = [
migrations.CreateModel(
name="AccessibilitySentence",
... |
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from exam import fixture
from sentry.testutils import TestCase
class HomeTest(TestCase):
@fixture
def path(self):
return reverse('sentry')
def test_redirects_to_login(self):
resp = self.client.get(self.p... |
#!/usr/bin/env python3
# James Livulpi
# 10/24/2013
# Outputs day number
# SELF EVALUATION
# PROGRAM PRESENTATION
# The header comment at the top contains
# * Your name:Yes
# * Date:Yes
# * Short specification of the program:Yes
# The comments have correct spelling, grammar and punctuat... |
# cython: infer_types=True, language_level=3, py2_import=True
#
# Cython Scanner
#
from __future__ import absolute_import
import cython
cython.declare(make_lexicon=object, lexicon=object,
print_function=object, error=object, warning=object,
os=object, platform=object)
import os
import... |
"""Composer Extension
Downloads, installs and runs Composer.
"""
import os
import os.path
import sys
import logging
import re
import json
import StringIO
from build_pack_utils import utils
from build_pack_utils import stream_output
from compile_helpers import warn_invalid_php_version
from extension_helpers import Exte... |
from msrest.serialization import Model
class ExpressRouteCircuitPeeringConfig(Model):
"""Specifies the peering configuration.
:param advertised_public_prefixes: The reference of
AdvertisedPublicPrefixes.
:type advertised_public_prefixes: list[str]
:param advertised_communities: The communities o... |
"""
The histfactory module provides functions to easily create
one or two dimensional histograms, estimating the necessary
binning and fill them.
"""
import dashi.histogram as histogram
import dashi.histfuncs as histfuncs
import numpy as n
def hist1d(sample, bins, weights=None, label=None, title=None):
... |
"""Implements commands for running and interacting with Fuchsia on QEMU."""
import boot_data
import common
import emu_target
import hashlib
import logging
import os
import platform
import qemu_image
import shutil
import subprocess
import sys
import tempfile
from common import GetHostArchFromPlatform, GetEmuRootForPla... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os.path
import sys
import TestSCons
test = TestSCons.TestSCons()
test.subdir('repository', ['repository', 'src'],
'work1', ['work1', 'src'],
'work2', ['work2', 'src'])
opts = "-Y " + test.workpath('repository')
#
test.writ... |
from __future__ import division
import os
import sys
from copy import deepcopy
from collections import Counter
from nltk.tag import CRFTagger
THIS_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.append(THIS_DIR + "/../..")
from deep_disfluency.feature_extraction.feature_utils import\
load_data_from_dis... |
import numpy as np
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
# print(iris.feature_names)
# print(iris.target_names)
# print(iris.data[100])
# print(iris.target[100])
# for i in range(len(iris.target)):
# print("Example %d: label %s, features %s" % (i, iris.target[i], iris.da... |
#!/usr/bin/env python
import rospy
import math
import tf
import numpy as np
import time
from tf import TransformListener
from geometry_msgs.msg import PoseStamped
class Circle():
def __init__(self, goals):
rospy.init_node('circle', anonymous=True)
self.worldFrame = rospy.get_param("~worldFrame", "... |
'''@file lstm_reconstructor.py
contains the LstmReconstructor class'''
import tensorflow as tf
from nabu.neuralnetworks.classifiers.asr.reconstructors import reconstructor
from nabu.neuralnetworks.classifiers import layer
class LstmFeatureReconstructor(reconstructor.Reconstructor):
'''
A reconstructor that re... |
import io
import traceback
from pyramid.events import NewRequest
from zope.interface import Interface
class IExceptionHandler(Interface):
"""handling exception"""
def handle(request):
pass
class ExceptionHandler(object):
def handle(self, request):
return {
"code": "500 Intern... |
import MySQLdb
def results_db_fetch(cursor,query):
"""used to fetch data from database
and return a dictionary containing the required values
"""
cursor.execute(query)
data=cursor.fetchone()
fetch={
'tps':data[1],
'min_req_lat_ms':data[2],
'max_req_lat_ms':... |
# # @Time : 2016/11/17 14:52
# # @Author : lixintong
from ifeng_video_common import switch_tab
from keywords import get_var, keyword, call
login_et_account_id = "com.ifeng.newvideo:id/login_et_account"
login_et_pwd_id = "com.ifeng.newvideo:id/login_et_pwd"
login_btn_id = "com.ifeng.newvideo:id/tv_login_btn"
login... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.