code stringlengths 1 199k |
|---|
"""The BZIP2 format analyzer helper implementation."""
from dfvfs.analyzer import analyzer
from dfvfs.analyzer import analyzer_helper
from dfvfs.analyzer import specification
from dfvfs.lib import definitions
class BZIP2AnalyzerHelper(analyzer_helper.AnalyzerHelper):
"""Class that implements the BZIP2 analyzer helper... |
import select
import serial
import socket
WRITE_CHUNK_SIZE = 4096
READ_CHUNK_SIZE = 4096
class RemoteSerialClient(object):
"""
Represents a remote client reading serial data over a socket. This class
handles buffering data and writing data to the client over its socket.
"""
def __init__(self, socket... |
from oslo_serialization import jsonutils as json
from six.moves.urllib import parse as urllib
from tempest.lib.api_schema.response.compute.v2_1 import \
security_groups as schema
from tempest.lib.common import rest_client
from tempest.lib import exceptions as lib_exc
class SecurityGroupsClient(rest_client.RestClien... |
"""
Ring Master Daemon for ring orchestration
"""
import os
import sys
import optparse
import subprocess
import cPickle as pickle
from os.path import exists
from time import time, sleep, gmtime
from tempfile import mkstemp
from datetime import datetime
from os import stat, unlink, rename, close, fdopen, chmod
from swif... |
from java.lang import System
from org.sleuthkit.autopsy.casemodule import Case
from org.sleuthkit.autopsy.report import GeneralReportModuleAdapter
class SampleGeneralReportModule(GeneralReportModuleAdapter):
# TODO: Rename this. Will be shown to users when making a report
def getName(self):
return "Sam... |
class Handler(object):
def __init__(self, configuration):
self.configuration = configuration
def cleanup(self):
pass
def clients(self):
return {} |
"""Data generation script for Maze environment.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
from absl import flags
from .env import environment
import h5py
import numpy as np
FLAGS = flags.FLAGS
flags.DEFINE_string('savepath', '/t... |
"""This module contains the general information for ChassisPowerBudget ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class ChassisPowerBudgetConsts:
ADMIN_ACTION_RESET_POWER_PROFILE_DEFAULT = "reset-power-profile-default"
... |
"""
Fitmarket
Mali broj ljudi - donori - dijele dnevna mjerenja svoje težine. Iz dnevne težine jednog donora određujemo vrijednosti dviju dionica: - dionica X ima vrijednost koja odgovara težini donora na taj dan. - inverzna dionica ~X ima vrijednost (150 kg - X). Primjetimo da: - kako X raste, ~X pada. - X... |
from neutron_lib.api.definitions import servicetype
from neutron_lib.tests.unit.api.definitions import base
class ServiceTypeDefinitionTestCase(base.DefinitionBaseTestCase):
extension_module = servicetype
extension_resources = (servicetype.COLLECTION_NAME,)
extension_attributes = ('default', servicetype.SER... |
def test_create_supply_agreement(app, json_agreements):
agreement = json_agreements
app.session.ensure_login(email=app.target["userEmail"], password=app.target["userPassword"])
app.agreement.create(agreement) |
from __future__ import unicode_literals
import collections
from datetime import datetime
from django.conf import settings
from django.db import models
import reversion
from base.model_utils import TimeStampedModel
def default_moderate_state():
return ModerateState.pending()
class CmsError(Exception):
def __init... |
import logging
import os
from jobslave.generators import bootable_image, constants
from jobslave.util import logCall
from conary.lib import util
from jobslave import buildtypes
log = logging.getLogger(__name__)
class Tarball(bootable_image.BootableImage):
fileType = buildtypes.typeNames[buildtypes.TARBALL]
def ... |
"""Code to test the db module."""
import logging
import unittest
import core.config
import core.db as db
class TestDBprivate(unittest.TestCase):
"""Test the private methods of the DB class."""
def setUp(self):
"""Set up common test harness for this class."""
self.config = core.config.Config()
... |
"""Constants for export/import.
See: https://goo.gl/OIDCqz for these constants and directory structure.
"""
VERSION_FORMAT_SPECIFIER = "%08d"
ASSETS_DIRECTORY = "assets"
EXPORT_BASE_NAME = "export"
EXPORT_SUFFIX_NAME = "meta"
META_GRAPH_DEF_FILENAME = EXPORT_BASE_NAME + "." + EXPORT_SUFFIX_NAME
VARIABLES_FILENAME = EXP... |
import settings
from flask import Flask
from atompark import SmsManager
from flask.ext.script import Manager
app = Flask(__name__)
manager = Manager(app)
@manager.option('-n', '--name', dest='name', default=None)
@manager.option('-d', '--description', dest='description', default="")
def add_address_book(name, descripti... |
from datetime import datetime
from sqlalchemy import (
Column,
Index,
Integer,
Text,
String,
DateTime
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = sc... |
from dsl_parser import functions
from mock import MagicMock
from dsl_parser import exceptions
from dsl_parser.tasks import prepare_deployment_plan
from dsl_parser.tests.abstract_test_parser import AbstractTestParser
class TestGetSecret(AbstractTestParser):
secrets_yaml = """
data_types:
agent_config_type:
... |
from api.utils.run_utils import run_model_job
from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch import receiver
import django_rq
from rq.job import Job
class ModelRun(models.Model):
INITIALIZED = "initialized"
STARTED = "started"
FAILED = "failed"
FINISHED... |
"""Base Estimator class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import os
import tempfile
import numpy as np
import six
from tensorflow.core.framework import summary_pb2
from tensorflow.core.protobuf import config_pb2
from tensorflow.p... |
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
from jinja2 import Environment
from jinja2 import FileSystemLoader
from hybridLogger import hybridLogger
from exception import *
import os
import yaml
class createJuniperConfig(hybridLogger):
def __init__(self, *... |
import pytest
from anchore_engine.analyzers.syft.handlers.java import save_entry
class TestJava:
@pytest.mark.parametrize(
"param",
[
pytest.param(
{
"findings": {},
"engine_entry": {
"name": "test",
... |
from __future__ import absolute_import
import logging
from django.conf import settings
from horizon.utils.memoized import memoized # noqa
from openstack_dashboard.api import base
from openstack_dashboard.api.neutron import NeutronAPIDictWrapper
from a10_openstack.neutron_ext.api import client as neutron_client
LOG = l... |
"""Test quantization on keras application models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import tempfile
from absl.testing import parameterized
import numpy as np
import tensorflow as tf
from tensorflow.python.keras import keras_par... |
from datetime import datetime, timedelta
from json import dumps, loads
from random import randint
from itertools import groupby
from sqlite3 import IntegrityError
from hashlib import sha1
from fcsite import models
from fcsite.models import schedules as scheds
from fcsite.models import stats
from fcsite.utils import san... |
from __future__ import unicode_literals
from datetime import datetime
from django.db import models
from django.contrib.auth.models import AbstractUser
class UserProfile(AbstractUser):
nickname = models.CharField(max_length=50, verbose_name=u"昵称", default="")
birthday = models.DateField(verbose_name=u"生日", null=... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0010_auto_20170715_1819'),
]
operations = [
migrations.RemoveField(
model_name='chat',
name='user',
),
mi... |
from datetime import datetime
from flask import Flask, redirect, render_template, request
from google.cloud import datastore
try:
from urllib import urlencode
except Exception:
from urllib.parse import urlencode
app = Flask(__name__)
client = datastore.Client()
@app.route('/', methods=['GET'])
def display_guest... |
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template5", checking_point=1, faild_point=100000, path_list=[
[TestAction.create_mini_vm, 'vm1', 'cluster=cluster2'],
[TestAction.change_vm_ha, 'vm1'],
[TestAction.create_mini... |
"""UniFi POE control platform tests."""
from collections import deque
from unittest.mock import Mock
import pytest
from tests.common import mock_coro
import aiounifi
from aiounifi.clients import Clients, ClientsAll
from aiounifi.devices import Devices
from homeassistant import config_entries
from homeassistant.componen... |
"""
Identifier Class for ip-reverse-dns
"""
import dns
import ipaddress
import re
import sre_constants
from ...iso8601 import *
from ...psjson import *
from ...pstime import *
from ...stringmatcher import *
data_validator = {
"type": "object",
"properties": {
"match": { "$ref": "#/pScheduler/StringMatch... |
import os
import yaml
from twisted.trial.unittest import SkipTest
from flocker.node.agents.test.test_blockdevice import (
make_iblockdeviceapi_tests)
from openvstorage_flocker_plugin.openvstorage_blockdevice import (
OpenvStorageBlockDeviceAPI)
def read_config():
config_file = os.getenv('VPOOL_FLOCKER_CONFI... |
"""
Created on Sat Mar 25 20:42:44 2017
@author: Yefee
"""
from .share_constant import *
sday = SHR_CONST_SDAY
omega = SHR_CONST_OMEGA
rearth = SHR_CONST_REARTH
g = SHR_CONST_G
stebol = SHR_CONST_STEBOL
boltz = SHR_CONST_BOLTZ
avogad = SHR_CONST_AVOGAD
rgas = SHR_CONST_RGAS
mwdair = SHR_CONST_MWDAIR
mwwv = SHR_CONST_MW... |
import os
from pants.backend.native.targets.external_native_library import ExternalNativeLibrary
from pants.backend.native.tasks.conan_fetch import ConanFetch
from pants.backend.native.tasks.conan_prep import ConanPrep
from pants.testutil.task_test_base import TaskTestBase
class ConanFetchTest(TaskTestBase):
@class... |
"""
Tests For Capacity Weigher.
"""
import mock
from oslo_config import cfg
from cinder import context
from cinder.openstack.common.scheduler.weights import HostWeightHandler
from cinder.scheduler.weights.capacity import CapacityWeigher
from cinder import test
from cinder.tests.scheduler import fakes
from cinder.volume... |
import comtypes
import ctypes
from comtypes import client
from ctypes import wintypes
VDS_QUERY_SOFTWARE_PROVIDERS = 1
VDS_DET_FREE = 1
CLSID_VdsLoader = '{9C38ED61-D565-4728-AEEE-C80952F0ECDE}'
msvcrt = ctypes.cdll.msvcrt
msvcrt.memcmp.restype = ctypes.c_int
msvcrt.memcmp.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ... |
""" Cisco_IOS_XR_ipv6_acl_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR ipv6\-acl package operational data.
This module contains definitions
for the following management objects\:
ipv6\-acl\-and\-prefix\-list\: Root class of IPv6 Oper schema tree
Copyright (c) 2013\-2016 by Cisco System... |
import Image
import cv2
import numpy as np
def set_global():
global test_label_file_a
global w_resize
global h_resize
global crop_x1
global crop_x2
global crop_y1
global crop_y2
global LABELS
global LABEL_names
global LABEL_short
global Misclassified
global CorrectClassif... |
from .profile_edit import * |
from connector import channel
from google3.cloud.graphite.mmv2.services.google.composer import environment_pb2
from google3.cloud.graphite.mmv2.services.google.composer import environment_pb2_grpc
from typing import List
class Environment(object):
def __init__(
self,
name: str = None,
config... |
import rstem
from rstem.button import Button
from rstem.gpio import Output
from rstem.sound import Note
from random import randrange
import time
buttons = [Button(27), Button(23), Button(24), Button(22)]
lights = [Output(4), Output(18), Output(14), Output(15)]
notes = [Note('A'), Note('B'), Note('C'), Note('D')]
you_fa... |
"""This application demonstrates how to construct a Signed URL for objects in
Google Cloud Storage.
For more information, see the README.md under /storage and the documentation
at https://cloud.google.com/storage/docs/access-control/signing-urls-manually.
"""
import argparse
import binascii
import collections
import... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
from omr_utils import *
from OmrExceptions import *
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
def get_x_splits(start, end):
# assert end > start
delta = (end - start) / 10
return [start + in... |
import contextlib
import mock
from oslo.config import cfg
import testtools
from neutron.plugins.mlnx.agent import eswitch_neutron_agent
from neutron.plugins.mlnx.agent import utils
from neutron.plugins.mlnx.common import exceptions
from neutron.tests import base
class TestEswichManager(base.BaseTestCase):
def setUp... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import unittest
from pants.base.validation import assert_list
class ParseValidation(unittest.TestCase):
def test_valid_inputs(self):
list_result0 = assert_list(["... |
def mult(m,n):
def loop(m,n):
if n > 1:
if(n%2==0):
return loop(m*2,n//2)
else:
return m+ loop(m*2,n//2)
else: # n == 1
return m
if n > 0:
return loop(m,n)
else:
return 0 |
"""Runs a command, saving stdout, stderr, and the return code in files.
Simplifies executing long-running commands on a remote host.
The status file (as specified by --status) is exclusively locked until the
child process running the user-specified command exits.
This command will fail if the status file cannot be succ... |
import os
import subprocess
from string import find
def run_command(command):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return out,err
def schema():
"""
This returns
"""
return { 'title': 'apt schema',
'type': 'string... |
"""
Produce a Reduced Representation genome from fasta file genome . The sequence is cut into fragments according to the given restriction enzyme recognition sequence : This sequence is always cleaved just after the 5prime first base towards 3prime and just before the last base on the complementary strand
ex for Msp1:
... |
"""
All methods must return media_ids that can be
passed into e.g. like() or comment() functions.
"""
import random
from tqdm import tqdm
from . import delay
def get_media_owner(self, media_id):
self.mediaInfo(media_id)
try:
return str(self.LastJson["items"][0]["user"]["pk"])
except:
... |
import unittest
from dummy import dummy
class DummyTestCase(unittest.TestCase):
def setUp(self):
self.tobcri = dummy.Dummy()
def test_true(self):
self.assertEqual('Hello World!', str(self.tobcri))
if __name__ == '__main__':
unittest.main() |
"""Implementation of the AWS Config Service APIs."""
import json
import re
import time
import random
import string
from datetime import datetime
from moto.config.exceptions import (
InvalidResourceTypeException,
InvalidDeliveryFrequency,
InvalidConfigurationRecorderNameException,
NameTooLongException,
... |
"""Tests for slim.pnasnet."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from nets.nasnet import pnasnet
slim = tf.contrib.slim
class PNASNetTest(tf.test.TestCase):
def testBuildLogitsLargeModel(self):
batch_size = 5
hei... |
from unittest import TestCase
from dino.environ import GNEnvironment, ConfigDict, ConfigKeys
from dino.cache.redis import CacheRedis
from dino.config import RedisKeys
from datetime import datetime, timedelta
import time
__author__ = 'Oscar Eriksson <oscar.eriks@gmail.com>'
class CacheRedisTest(TestCase):
class Fake... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crowdcop_web', '0019_auto_20160412_1627'),
]
operations = [
migrations.AlterField(
model_name='tip',
name='details',
... |
import asyncio
import asyncio.streams
import http.server
import socket
import traceback
import warnings
from collections import deque
from contextlib import suppress
from html import escape as html_escape
from . import helpers, http
from .helpers import CeilTimeout, create_future, ensure_future
from .http import (HttpP... |
ARR = [int(x) for x in input().split()]
BEG, END = [int(x) for x in input().split()]
K = int(input())
def range_k_smallest(arr, beg, end, k):
return k_smallest(arr[beg-1:end], k-1)
def part(arr, low, high):
if low >= high:
return low
pivot = arr[high]
i = low
for j in range(low, high+1):
... |
"""This example creates a content category with the given name and description.
Tags: contentcategory.saveContentCategory
"""
__author__ = 'Joseph DiLallo'
import uuid
from googleads import dfa
def main(client):
# Initialize appropriate service.
content_category_service = client.GetService(
'contentcategory',... |
'''
Service support for Solaris 10 and 11, should work with other systems
that use SMF also. (e.g. SmartOS)
'''
from __future__ import absolute_import
__func_alias__ = {
'reload_': 'reload'
}
__virtualname__ = 'service'
def __virtual__():
'''
Only work on systems which default to SMF
'''
if 'Solaris... |
import sys, argparse, gzip, re, random, collections, inspect, os
from multiprocessing import Pool, cpu_count
from seqtools.statistics import average, median
def main(args):
inf = sys.stdin
if args.input != '-':
if re.search('\.gz$',args.input):
inf = gzip.open(args.input)
else:
inf = open(args.i... |
"""Utils for metrics used in eval."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
from tensor2tensor.layers import common_layers
from tensor2tensor.utils import bleu_hook
from tensor2tensor.utils import rouge
import tensorflow as tf
class M... |
import wx
from cairis.core.armid import *
import WidgetFactory
from cairis.core.Borg import Borg
__author__ = 'Shamal Faily'
class RoleCostDialog(wx.Dialog):
def __init__(self,parent):
wx.Dialog.__init__(self,parent,ROLECOST_ID,'Add Role Cost',style=wx.DEFAULT_DIALOG_STYLE|wx.MAXIMIZE_BOX|wx.THICK_FRAME|wx.RESIZE... |
from __future__ import print_function
import sys
import itertools
import time
if __name__ == "__main__":
request = int(sys.argv[1])
# if the request is less than 0, sleep forever
if request < 0:
cycles = itertools.count()
else:
cycles = range(request)
for cycle in cycles:
pri... |
LOGIN = """
{
"path": "/logincheck",
"method": "POST",
"body": {
"username": "$username",
"secretkey": "$secretkey"
}
}
"""
RELOGIN = """login?redir=%2fapi%2fv2"""
LOGOUT = """
{
"path": "/logout",
"method": "POST"
}
"""
ADD_VLAN_INTERFACE = """
{
"path": "/api/v2/cmdb/system... |
from boto.ec2 import connect_to_region
from sys import path
from os import environ
path.append('%s/programs/lib' % environ['HOME'])
from AwsConfigMFA import AwsConfigMFA
class InstanceByTag():
"""
Do things with instances defined by AWS tags.
"""
def __init__(self, profile, region='us-east-1', tag=None,... |
import os
import csv
import re
import sys
import msvcrt
int_total10g = 0
int_total1g = 0
def connect(str_hostname,str_username,str_password):
# Declaring global variables to count total ports
global int_total10g
global int_total1g
# Resetting local variables that count avaliable ports for this host
int_port10g = 0... |
from litex.build.generic_platform import Pins, Subsignal, IOStandard, Misc
from litex.build.xilinx import XilinxPlatform
from litex.build.openocd import OpenOCD
_io = [
# Clk / Rst
("clk50", 0, Pins("N11"), IOStandard("LVCMOS33")),
# The core board does not have a USB serial on it,
# so you will have to... |
cars = 100
space_in_a_car = 4
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars available."
print "There are only", drivers, "drivers available."
print "... |
"""Some sample datasets"""
from __future__ import division
import os
import numpy as np
from scipy import ndimage
from sklearn.utils import check_random_state
import collections
def get_megaman_image(factor=1):
"""Return an RGBA representation of the megaman icon"""
imfile = os.path.join(os.path.dirname(__file_... |
"""
Default settings for the ``mezzanine.forms`` app. Each of these can be
overridden in your project's settings module, just like regular
Django settings. The ``editable`` argument for each controls whether
the setting is editable via Django's admin.
Thought should be given to how a setting is actually used before
mak... |
import re
from uuid import uuid4
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
from streamlink.plugin import Plugin
from streamlink.plugin.api import http
from streamlink.stream import RTMPStream, HDSStream
from streamlink.compat import urlparse, unquote
ITV_PLA... |
from . import json_checker
def validate_json_checker(x):
"""
Property: Policy.SecurityServicePolicyData
"""
return json_checker(x) |
from distutils.core import setup
DESCRIPTION = "General tools for Astronomical Time Series in Python"
LONG_DESCRIPTION = """
nufftpy: Non-Uniform FFT in Python
==================================
This is a pure python implementation of the NUFFT.
For more information, visit http://github.com/jakevdp/nufftpy
"""
NAME = "... |
"""aio -- asynchronous IO"""
from __future__ import absolute_import
import socket, ssl, select, errno, logging, fcntl
from tornado.ioloop import IOLoop
__all__ = (
'TCPServer', 'TCPClient', 'SocketError', 'would_block', 'in_progress',
'starttls', 'is_ssl',
'loop', 'start'
)
class TCPServer(object):
"""A... |
"""Calculate the band structure of graphene with Rashba spin-orbit coupling"""
import pybinding as pb
import numpy as np
import matplotlib.pyplot as plt
from math import pi, sqrt
def monolayer_graphene_soc():
"""Return the lattice specification for monolayer graphene with Rashba SOC,
see http://doi.org/10.11... |
from django.conf import settings
from django.test import TestCase
from unittest import SkipTest, skipIf
from django.db import connection
from django.contrib.gis.geos import MultiLineString, LineString, Point
from django.utils import translation
from geotrek.core.models import Path, Topology
from geotrek.core.factories ... |
from migen import *
from litex.soc.interconnect.csr import *
class XADC(Module, AutoCSR):
def __init__(self):
# Temperature(°C) = adc_value*503.975/4096 - 273.15
self._temperature = CSRStatus(12)
# Voltage(V) = adc_value*)/4096*3
self._vccint = CSRStatus(12)
self._vccaux = ... |
from __future__ import absolute_import, print_function
import io
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
def read(*names, **kwargs):
return io.open... |
from __future__ import print_function
from enum import Enum, IntEnum
class Color(Enum):
red = 1
green = 2
blue = 3
class Shake(Enum):
vanilla = 7
chocolate = 4
cookies = 9
# Same as Color.blue
mint = 3
class Planet(Enum):
MERCURY = (3.303e+23, 2.4397e6)
VENUS = (4.869e+24, 6.05... |
from numpy import *
from numpy import f2py # not part of import *
from scitools.StringFunction import StringFunction
import time, sys, os
sys.path.insert(0, os.path.join(os.environ['scripting'],
'src','py','examples'))
from Grid2D import Grid2D
try:
import ext_gridloop
except Import... |
from setuptools import setup
setup(name='speakeasy',
version='1.0',
description='A Communications Platform for Paranoid People',
author='Zhehao Mao',
author_email='zhehao.mao@gmail.com',
url='http://speakeasy-zhehao.rhcloud.com/',
install_requires=['Flask', 'Flask-PyMongo', 'pycrypto... |
import capstone as _capstone
try:
import unicorn as _unicorn
except ImportError:
_unicorn = None
from .arch import Arch
class ArchMIPS32(Arch):
def __init__(self, endness="Iend_LE"):
super(ArchMIPS32, self).__init__(endness)
if endness == 'Iend_BE':
self.function_prologs = {
... |
from __future__ import print_function
from __future__ import unicode_literals
import datetime
import inspect
import os
import wrapt
from tombstones.log import LogEntry
from tombstones.log import save_log_entry
def line_number_for_tombstone(lines, line_number):
for line in lines:
if line.strip() == "@tombsto... |
from os import path
from setuptools import setup
CLASSIFIERS = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Pro... |
from fabric.api import task, env
from fabric.colors import green, red
from fabric_colors.environment import set_target_env
@task
@set_target_env
def distro():
"""
Usage: `fab -R all distro`. Determine the distro of given target host(s).
"""
if env.get('distro'):
print(green("Host distro is {0}."... |
import numpy as np
import pickle
import bson
import util.associate as ass
import core.benchmark_comparison
class RPEBenchmarkComparison(core.benchmark_comparison.BenchmarkComparison):
"""
Comparison of two Relative Pose Error benchmark results.
Basically just the difference in translational error.
"""
... |
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from widgets import HoneypotWidget
class HoneypotField(forms.BooleanField):
def __init__(self, *args, **kwargs):
super(HoneypotField, self).__init__(
widget = Hon... |
def accelerator_ipaddresstype(type):
"""
Property: Accelerator.IpAddressType
"""
valid_types = ["IPV4"]
if type not in valid_types:
raise ValueError(
'IpAddressType must be one of: "%s"' % (", ".join(valid_types))
)
return type
def endpointgroup_healthcheckprotocol(pr... |
import numpy as np
import sys
from jug import TaskGenerator
from os.path import expanduser
HOME = expanduser("~")
if "storage" in HOME:
HOME = "/storage/home/geffroy"
sys.path.append(HOME + "/Code/PG/Source")
from phase_fluctuations import DWaveModel
from MCMC import MCMCDriver
N_RUNS = 32
TARGET_SNAPSHOTS = 32
TEM... |
import os
from .ProactiveScript import *
class ProactiveForkEnv(ProactiveScript):
"""
Represents a generic proactive fork env script
script_language (ProactiveScriptLanguage)
implementation (string)
java_home (string)
"""
def __init__(self, script_language):
super(ProactiveForkEnv, s... |
from copy import deepcopy
import numpy as np
class DBN(object):
def __init__(self, number_visible_units=1, number_hidden_units=1, layers=1, network=None):
"""Creates an architecture for a deep belief network.
Keyword arguments:
number_visible_units -- An integer denoting the number of visibl... |
import Orange
from orangecontrib.recommendation.tests.coverage import TestRankingModels
from orangecontrib.recommendation import CLiMFLearner
from orangecontrib.recommendation.optimizers import *
import unittest
__dataset__ = 'binary_data.tab'
__dataset2__ = 'binary_data_dis.tab'
__optimizers__ = [SGD(), Momentum(momen... |
import hoggorm as ho
import hoggormplot as hop
import pandas as pd
import numpy as np
X_df = pd.read_csv('cheese_fluorescence.txt', index_col=0, sep='\t')
X_df
Y_df = pd.read_csv('cheese_sensory.txt', index_col=0, sep='\t')
Y_df
X = X_df.values
Y = Y_df.values
X_varNames = list(X_df.columns)
Y_varNames = list(Y_df.colu... |
"""
@file shuffle_lines.py
@brief shuffle lines in a file
@author ChenglongChen
"""
import sys
import csv
import random
import numpy as np
from string import atoi
def main():
# collect argvs
seed = atoi(sys.argv[1])
file_in = sys.argv[2]
file_out = sys.argv[3]
# read
with open(file_in) as in_:
... |
import config
import shutil
import jinja2
import markdown2 as markdown
import os.path
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name, TextLexer
import re
import yaml
POST_HEADER_SEP_RE = re.compile('^---$', re.MULTILINE)
DATE_FORMAT = '%Y-%m-%d... |
import peachpy.x86_64.uarch as uarch
import peachpy.x86_64.isa as isa
from peachpy.x86_64.function import Function
from peachpy.function import Argument
from peachpy.c.types import ptr
import peachpy.c.types as ctypes
from common.YepStatus import YepStatus
from kernels.sum_reduction import sum_Haswell, sum_squared_Hasw... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'EventTag.group_id'
db.add_column(
'sentry_eventtag',
'group_... |
"""
NWBIO
=====
IO class for reading data from a Neurodata Without Borders (NWB) dataset
Documentation : https://www.nwb.org/
Depends on: h5py, nwb, dateutil
Supported: Read, Write
Python API - https://pynwb.readthedocs.io
Sample datasets from CRCNS - https://crcns.org/NWB
Sample datasets from Allen Institute
- http:/... |
import StringIO
from collections import OrderedDict
import csv
from django.http.response import HttpResponse
from tastypie.api import Api
from tastypie.resources import ModelResource
from tastypie.serializers import Serializer
from tastypie.utils.mime import build_content_type
from cvservices.models import Unit
from rd... |
from flexbe_core import EventState, Logger
from moveit_commander import MoveGroupCommander
from tf.transformations import quaternion_from_euler
from geometry_msgs.msg import Pose, Point, Quaternion, PointStamped
import math
import rospy
import tf
class GenGripperPose(EventState):
'''
Apply a transformation to a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.