content string |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Unit converter using pint.
"""
from pint import UnitRegistry
from logger import Logger
class UnitConverter():
def __init__(self, log_level="ERROR"):
logger = Logger(log_level)
self.log = logger.get_logger()
self.ureg = UnitRegistry()
... |
import dem
import os
from functools import reduce
#t = map(f,{1,2,3,4,5})
#print(t)
#print(type(t))
#print(t)
#print(f)
#print(dir(os))
#print(dir(dem))
#r = reduce(dem.cadd,(1,2,3,4))
#print(r)
#L = [('Bob', 75), ('Adam', 92),('Da',100), ('Bart', 66), ('Lisa', 88)]
#l = sorted(L,key=dem.s,reverse=True)
#print(l)
... |
"""@ package BaseObject
Classes for the BaseObjects types.
Each type of object from the level.egg file will be build from these.
"""
# System Imports
import logging as log
# Panda Engine Imports
from panda3d.core import PointLight, DirectionalLight, Spotlight, AmbientLight
from panda3d.core import VBase4, Perspectiv... |
import graphene
from django.db.models import Count, QuerySet
from ..core.types import SortInputObjectType
class ServiceAccountSortField(graphene.Enum):
NAME = "name"
CREATION_DATE = "created"
@property
def description(self):
# pylint: disable=no-member
if self in [
Servic... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# http://binux.me
# Created on 2015-04-30 21:47:08
try:
from urllib import parse as urlparse
except ImportError:
import urlparse
def connect_message_queue(name, url=None, maxsize=0, lazy_limit=True):
... |
from Components.VariableText import VariableText
from enigma import eLabel, eEPGCache
from Components.config import config
from Renderer import Renderer
from time import localtime
class OMNextEvent(Renderer, VariableText):
def __init__(self):
Renderer.__init__(self)
VariableText.__init__(self)
self.epgcache = e... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
"""
Code modified from:
https://github.com/r0wb0t/markdown-urlize
A more liberal autolinker
Inspired by Django's urlize function.
Positive examples:
>>> import markdown
>>> md = markdown.Markdown(extensions=['urli... |
__author__ = 'breddels'
from ctypes import *
import h5py
import sys
import numpy as np
import mmap
import vaex
import vaex.vaexfast
import timeit
import threading
filename = sys.argv[1]
h5file = h5py.File(filename, "r")
column = h5file[sys.argv[2]]
length = len(column)
assert column.dtype == np.float64
offset = colu... |
import json
import datetime
import requests
import logging
from redash.query_runner import *
from redash.utils import JSONEncoder
logger = logging.getLogger(__name__)
def _transform_result(response):
columns = ({'name': 'Time::x', 'type': TYPE_DATETIME},
{'name': 'value::y', 'type': TYPE_FLOAT},
... |
# -*- coding: utf-8 -*-
import 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 'Profile.drive_folder'
db.add_column(u'user_profile', 'drive_folder',
s... |
"""\
========================
Session Example
========================
A simple persistent request handler component.
Each time a URL that is handled by this component is requested, the page's
'hit counter' is incremented and shown to the user as text.
"""
from Axon.Component import component
from Axon.Ipc import prod... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
def simple_plot1():
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
def simple_plot2():
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
plt.axis([0, 6, 0... |
import functools
import traceback
from fife.extensions import pychan
import horizons.globals
from horizons.gui.style import STYLES
from horizons.gui.widgets.imagebutton import ImageButton
from horizons.messaging import GuiAction, GuiCancelAction, GuiHover
from horizons.util.python.callback import Callback
class Ren... |
from django.http import Http404
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from rest_framework import permissions
from rest_framework import status
from rest_framework.response import Response
from rest_framework import views
f... |
from spack import *
class RSurvey(RPackage):
"""Summary statistics, two-sample tests, rank tests, generalised linear
models, cumulative link models, Cox models, loglinear models, and general
maximum pseudolikelihood estimation for multistage stratified,
cluster-sampled, unequally weighted survey sampl... |
"""Volume v2 snapshot action implementations"""
import copy
import functools
import logging
from cliff import columns as cliff_columns
from osc_lib.cli import format_columns
from osc_lib.cli import parseractions
from osc_lib.command import command
from osc_lib import exceptions
from osc_lib import utils
from opensta... |
'''Module holding functions related to miscellaneous metrics, such as Halstead
metrics or the Maintainability Index.
'''
import ast
import collections
import math
from radon.raw import analyze
from radon.visitors import ComplexityVisitor, HalsteadVisitor
# Halstead metrics
HalsteadReport = collections.namedtuple(
... |
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.conf import settings
from . import views
urlpatterns = [
url(r'^page/edit/(?P<user_name>[^/]+)/(?P<page_name>.+)/$', views.edit_page, name='wiki_edit_page'),
url(r'^page/create/(?P<user_name>[^/]+)/$', views.creat... |
import sys
import glob
import scripts.skewtools as skewtools
# Read the input argument. We're expecting something with a wildcard,
# but a single file is okay too.
files = glob.glob(sys.argv[1])
files.sort()
# Gather the data from the files.
times = skewtools.gatherDataFromFiles(files,'Time')
skews = skewtools.gath... |
from chirp.drivers import icf
from chirp import chirp_common, util, directory
from chirp import bitwise
mem_format = """
struct memory {
bbcd freq[3];
bbcd offset[3];
u8 rtone;
u8 ctone;
};
struct flags {
u8 empty:1,
skip:1,
tmode:2,
duplex:2,
unknown2:2;
};
struct memory memory[100];
... |
# This code has been copied and modified from (https://github.com/DominicBreuker/self-driving-car-experiments#getting-data)
import os
import rosbag
import cv2
import numpy as np
from cv_bridge import CvBridge, CvBridgeError
data_dir = "../Dataset/"
rosbag_file = os.path.join(data_dir, "dataset.bag")
def get_image_di... |
import re
import sys
import dns.resolver
import collections
NSEEDS=512
MAX_SEEDS_PER_ASN=2
MIN_BLOCKS = 337600
# These are hosts that have been observed to be behaving strangely (e.g.
# aggressively connecting to every node).
with open("suspicious_hosts.txt", mode="r", encoding="utf-8") as f:
SUSPICIOUS_HOSTS =... |
import datetime
from abc import ABCMeta, abstractmethod
from . import Server
class Alarmable(object):
'''
Superclass for all objects implementing a OnTimeoutDo() method
to be used within the select() system call when this system call times out.
Efficient but not accurate implememtation valid for a few s... |
"""Tests covering Credentials utilities."""
import unittest
from django.conf import settings
from django.core.cache import cache
from django.test import TestCase
from nose.plugins.attrib import attr
import httpretty
from edx_oauth2_provider.tests.factories import ClientFactory
from provider.constants import CONFIDENTI... |
import json
import matplotlib
matplotlib.use('Agg')
import scipy.stats as ss
import matplotlib
matplotlib.rcParams['ps.useafm'] = True
matplotlib.rcParams['pdf.use14corefonts'] = True
import matplotlib.pyplot as plt
plt.style.use('classic')
from Utils import *
# def get_simulation_data(file_name, trunc_index=None):
... |
"""
Tests for Consoleauth Code.
"""
import mock
from mox3 import mox
from oslo_utils import timeutils
from jacket.compute.consoleauth import manager
from jacket import context
from jacket.compute import test
class ConsoleauthTestCase(test.NoDBTestCase):
"""Test Case for consoleauth."""
def setUp(self):
... |
import sys
import asyncio
import aiozmq
import zmq
@asyncio.coroutine
def go(zip_filter):
"""
Weather update client
Connects SUB socket to tcp://localhost:5556
Collects weather updates and finds avg temp in zipcode
"""
# create SUB socket
sub = yield from aiozmq.create_zmq_stream(zmq.SUB,... |
'''
Created on Sep 11, 2013
@author: Jose Antonio Sal y Rosas Celi
@contact: <EMAIL>
'''
from lib.html.requestAPI import requestAPI
from config import config
class AppInformation(object):
def __init__(self):
configuration = config()
APIParams = configuration.getContentFile()
sel... |
import re
import tarfile
from pants_test.backend.python.pants_requirement_integration_test_base import (
PantsRequirementIntegrationTestBase,
)
class SetupPyIntegrationTest(PantsRequirementIntegrationTestBase):
def assert_sdist(self, pants_run, key, files):
sdist_path = f"dist/{key}-0.0.1.tar.gz"
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Generate C++ code for the compiled-in checkpoints.
Script will connect to Gulden rpc server.
Generated code goes into chainparams.cpp
"""
from bitcoinrpc.authproxy import AuthServiceProxy
import sys
import string
import os
__copyright__ = 'Copyright (c) 2018 The... |
from __future__ import unicode_literals
import json
from tests import TestCase, with_settings, logged_in
from nose.tools import eq_
from catsnap import Client
from catsnap.table.image import Image
from catsnap.table.tag import Tag
from catsnap.table.image_tag import ImageTag
from catsnap.table.album import Album
from... |
"""Google Analytics Admin API sample application which creates a web data stream
for the Google Analytics 4 property.
See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/properties.webDataStreams/create
for more information.
"""
# [START analyticsadmin_properties_web_data_streams_create]... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Update encrypted deploy password in Travis config file
"""
from __future__ import print_function
import base64
import json
import os
from getpass import getpass
import yaml
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from cryptography.h... |
import logging
import os
import cairocffi as cairo
try:
from io import BytesIO
except ImportError:
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from StringIO import StringIO as BytesIO
from lib.hdlr.base import BaseHandler
class WoopseHandler(BaseHandler):
logger... |
import gi
gi.require_version('Gtk','3.0')
from gi.repository import Gtk
from gi.repository import Gdk
import logging
from gettext import gettext as _
from toolbar_utils import button_factory, radio_factory, label_factory, \
separator_factory
from utils import json_load, json_dump
from sugar3 import profile
from ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from pyagentx.updater import Updater
from pyagentx.agent import Agent
from pyagentx.sethandler import SetHandler, SetHandlerError
def setup_logging(debug=False):
if debug:
level = logging.DEBUG
else:
level = logging.INFO
logger ... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
from Cython.Build import cythonize
import numpy
import os
# hack to allow user to specify location of minc installation
import sys
# default location of minc library
# find location of minc-toolkit
MINCD... |
import psi4
from psi4.driver.p4const.physconst import psi_hartree2ev
psi4.set_output_file("output.dat", False)
benz = psi4.geometry("""
pubchem:benzene
""")
psi4.set_options({"REFERENCE" : "RHF",
"MAX_ENERGY_G_CONVERGENCE" : 8,
"BASIS" : "STO-... |
"""Tests for ceilometer/publisher/messaging.py
"""
import datetime
import uuid
import eventlet
import mock
from oslo_config import fixture as fixture_config
from oslo_context import context
from oslo_utils import netutils
import testscenarios.testcase
from ceilometer.event.storage import models as event
from ceilomet... |
import numpy as np
from fate_arch.computing import ComputingType
from fate_arch.session import computing_session as session
from federatedml.feature.hetero_feature_binning.hetero_binning_host import HeteroFeatureBinningHost
from federatedml.feature.instance import Instance
class TestHeteroFeatureBinning():
def _... |
"""Utilities for working with tf.lookup tables in Keras."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import os
import numpy as np
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tenso... |
import paddle.fluid.core as core
import paddle.fluid.proto.framework_pb2 as framework_pb2
def get_all_op_protos():
"""
Get all registered op proto from PaddlePaddle C++ end.
:return: A list of registered OpProto.
"""
protostrs = core.get_all_op_protos()
ret_values = []
for pbstr in protost... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import hashlib
import argparse
from os.path import join, getsize
semanas = [
'Semana 1: 15 a 24-12-2017',
'Semana 2: 25-12 a 31-12-2017',
'Semana 3: 01 a 07-1-2018',
'Semana 4: 08 a 14-1-2018',
'Semana 5: 15 a 21-1-2018',
'Semana 6: 22 a 28-1-2018',
'... |
import web
from karesansui.lib.rest import Rest, auth
from karesansui.lib.utils import read_file, json_dumps
from karesansui.lib.const import TEMPLATE_DIR, \
MAIL_TEMPLATE_COLLECTD_WARNING, \
MAIL_TEMPLATE_COLLECTD_FAILURE, \
MAIL_TEMPLATE_COLLECTD_OKAY, \
WATCH_PLUGINS, DEFAULT_LANGS
from karesansui.... |
from __future__ import unicode_literals
from indico.modules.events.logs.views import WPEventLogs
from indico.modules.events.logs.models.entries import EventLogEntry
from MaKaC.webinterface.rh.conferenceModif import RHConferenceModifBase
class RHEventLogs(RHConferenceModifBase):
"""Shows the modification/action l... |
import usb.core
import usb.util
import time
import numpy
import sys
##function that converts a number into a bit string of given length
def convlen(a,l):
b=bin(a)[2:]
padding=l-len(b)
b='0'*padding+b
return b
##function that converts a bit string into a given number of bytes
def bitstobytes(a):
... |
"""
bkr system-delete: Delete a Beaker system permanently
=====================================================
.. program:: bkr system-delete
Synopsis
--------
:program:`bkr system-delete` [*options*] <fqdn>
Description
-----------
Deletes a Beaker system permanently, but only if the system was never referenced
i... |
"""
Implement a simple rotations cypher
"""
map1 = "abcdefghijklmnopqrstuvwxyz"
map2 = "etaoinshrdlucmfwypvbgkjqxz"
class Cipher(object):
def __init__(self, map1, map2):
self.inmap = map1
self.outmap = map2
def code(self, string,frommap,tomap):
r = ''
for s in string:
... |
'''
Test module for image to time series conversion.
'''
import os
import glob
import tempfile
import numpy as np
import numpy.testing as nptest
from ecmwf_models.erainterim.reshuffle import main
from ecmwf_models import ERATs
import shutil
def test_ERAInterim_reshuffle_grb():
# test reshuffling era interim grib... |
"""Custom BigQuery Hooks."""
import http
import logging
from typing import Text
from airflow.contrib.hooks import bigquery_hook
from googleapiclient import errors
class BigQueryHook(bigquery_hook.BigQueryHook):
"""Custom BigQuery Hook."""
def delete_table(self, dataset_id: Text, table_id: Text) -> None:
""... |
from lxml import etree
from tempest.common import rest_client
from tempest.common import xml_utils
from tempest import config
CONF = config.CONF
class BaseVolumeAvailabilityZoneClientXML(rest_client.RestClient):
TYPE = "xml"
def __init__(self, auth_provider):
super(BaseVolumeAvailabilityZoneClientX... |
# coding: utf-8
import os.path
import re
from subprocess import check_output
import mpienv.mpich as mpich
import mpienv.util as util
class Mvapich(mpich.Mpich):
def __init__(self, *args):
super(Mvapich, self).__init__(*args)
self._type = 'MVAPICH'
mpi_h = mpich.find_mpi_h(self.mpiexec)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'Click>=6.0',
'dateparser>=0.5.1',
# TODO: put package requireme... |
from collections import OrderedDict
from typing import Dict, Type
from .base import CustomerClientServiceTransport
from .grpc import CustomerClientServiceGrpcTransport
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[CustomerClientServiceTransport]]
_transport_registry[... |
"""Example code to do square matrix multiplication on Android Phone."""
import tvm
import os
from tvm import rpc
from tvm.contrib import util, ndk
import numpy as np
# Set to be address of tvm proxy.
proxy_host = os.environ["TVM_ANDROID_RPC_PROXY_HOST"]
proxy_port = 9090
key = "android"
# Change target configuration.... |
import datetime
import inspect
import simplejson
import sys
from django.utils.timezone import utc
import core
# from core.models import Log
def execute_command(command):
if not (command.name or command.raw_command):
return "", ""
if not command.name:
command.name, data = interpret_command(c... |
# -*- coding: utf-8 -*-
"""
celery.concurrency.threads
~~~~~~~~~~~~~~~~~~~~~~~~~~
Pool implementation using threads.
"""
from __future__ import absolute_import
from celery.utils.compat import UserDict
from .base import apply_target, BasePool
class NullDict(UserDict):
def __setitem__(self, key, va... |
# -*- coding: utf-8 -*-
"""
Contains a custom QTableWidget for easier displaying of CheckerMessages
"""
from pyqode.core.api.utils import memoized
from pyqode.core.modes import CheckerMessage, CheckerMessages
from pyqode.qt import QtCore, QtWidgets, QtGui
COL_TYPE = 0
COL_FILE_NAME = 1
COL_LINE_NBR = 2
COL_MSG = 3
... |
"""Tests that onjects used in a with statement implement context manager protocol"""
# pylint: disable=too-few-public-methods, invalid-name, import-error, missing-docstring
# pylint: disable=no-init,wrong-import-position, useless-object-inheritance
# Tests no messages for objects that implement the protocol
class Mana... |
# -*- coding: utf-8 -*-
"""
sphinxcontrib.cf3domain
~~~~~~~~~~~~~~~~~~~~~~~~
The CFEngine 3 domain.
:copyright: Copyright 2015 by Jimmy Thrasibule
:license: BSD, see LICENSE file for details.
"""
import re
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx import ... |
import unittest
import logging
import datastore
from datastore.core import DictDatastore
from .. import collection
from ..model import Key
from ..model import Model
from ..collection import Collection
from ..object_datastore import ObjectDatastore
class TestCollection(unittest.TestCase):
def test_exists(self):
... |
###############################################################################
# actionAngle: a Python module to calculate actions, angles, and frequencies
#
# class: actionAngleIsochrone
#
# Calculate actions-angle coordinates for the Isochrone potential
#
# methods:
# __call__: r... |
import sys
import logging
import copy
from . import game_map
class Game:
"""
:ivar map: Current map representation
:ivar initial_map: The initial version of the map before game starts
"""
@staticmethod
def _send_string(s):
"""
Send data to the game. Call :function:`done_sendin... |
import abc
from telemetry.page import page as page_module
from telemetry.page import traffic_setting as traffic_setting_module
from telemetry import story
# A complete list of page tags to check. This prevents misspellings and provides
# documentation of scenarios for code readers. These tags can be used to filter
# ... |
import errno
import os
import threading
import traceback
import socket
import inspect
from six.moves import queue
Queue = queue.Queue
Empty = queue.Empty
import zmq
from .namebroker import NameBrokerClient
from ..log import setup, show_msg
from ..zmq_tools import zmq_socket, Context
from ..exceptions import PipeExc... |
from unittest import TestCase
from prospector2.message import Location
class LocationOrderTest(TestCase):
def test_path_order(self):
locs = [
Location('/tmp/path/module3.py', 'module3', 'somefunc', 15, 0),
Location('/tmp/path/module1.py', 'module1', 'somefunc', 10, 0),
... |
{
'name': 'Base Location Provinces Import',
'version': '0.1',
'category': 'Extra Tools',
'license': 'AGPL-3',
'summary': 'Import base_location entries (provinces) from Geonames',
'description': """
This module extends base_location_geonames_import in order to correctly import
Italian provinces
"... |
"""This is an example script for the py/pyext object's threading functionality.
For threading support pyext exposes several function and variables
- _detach([0/1]): by enabling thread detaching, threads will run in their own threads
- _priority(prio+-): you can raise or lower the priority of the current thread
- _stop... |
import os
import unittest
import datetime
import time
from scam import detect, pipe
class ContourMatcherTestCase(unittest.TestCase):
def load_snapshot(self, name, context):
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(dir_path, 'resources', name), 'rb') as fh:
... |
# -*- coding: utf-8 -*-
import re
import CTK
URL_R1 = '/r1'
URL_R2 = '/r2'
URL_R3 = '/r3'
GOTO_JS = "$('#%s').trigger({'type': 'refresh_goto', 'goto': '%s'});"
class R1:
ID = "r1-id"
def __call__ (self):
box = CTK.Box({'id': self.ID})
for n in range(10):
item = CTK.Box (conten... |
{
'name' : 'l10n_co_doctor',
'version' : '1.0',
'summary': 'Location change for "Doctor" module in Colombia',
'description': """
Location change for "Doctor" module in Colombia
=================================================================
""",
'category' : '',
'author' : 'TIX SAS',
'web... |
# -*- coding: utf-8 -*-
"""
Copyright [2009-2020] EMBL-European Bioinformatics Institute
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... |
import commands
import logging
import sys
from libs import config_libs
from libs import utils_libs
from libs import verify_libs
def main():
# Run the Testcase:
test = test_gbp_ri_func_2()
test.run()
class test_gbp_ri_func_2(object):
# Initialize logging
logging.basicConfig(
format='%(... |
from datetime import timedelta, datetime, time
from itertools import product
from psycopg2._range import DateTimeTZRange, NumericRange
from apps.common import models as common_models
from apps.common.models import Property, Process
from apps.processing.o2.models import ANY_OCCURRENCE, OCCURRENCE_CHOICES, UNIQUES_CHOI... |
import functools as ft
import logging
import superdesk
from flask import current_app as app
from eve.utils import config, ParsedRequest
from copy import deepcopy
from apps.packages import PackageService
from superdesk.celery_task_utils import get_lock_id
from superdesk.utc import utcnow
from .archive import SOURCE as A... |
"""Tests for the toolchain sub-system"""
import sys
import os
from string import printable
from copy import deepcopy
from mock import MagicMock, patch
from hypothesis import given, settings
from hypothesis.strategies import text, lists, fixed_dictionaries, booleans
ROOT = os.path.abspath(os.path.join(os.path.dirname(_... |
import re
from clint.textui.colored import black, white
class RegexValidator(object):
regex = ''
message = 'Enter a valid value.'
def __init__(self, regex=None, message=None):
if regex is not None:
self.regex = regex
if message is not None:
self.message = message
... |
from mft.entries import entry
import Tkinter
import tkFileDialog
class App(Tkinter.Frame):
def __init__(self, master=None):
Tkinter.Frame.__init__(self, master)
self._create_menubar()
self.pack(fill=Tkinter.BOTH, expand=1)
self.center_window()
def _create_menubar(self):
self.menubar = Tkinter.Menu()
se... |
import logging
from autotest.client.shared import error
from virttest import virsh, libvirt_vm
from virttest.libvirt_xml import network_xml
def run_virsh_net_start(test, params, env):
"""
Test command: virsh net-start.
"""
# Gather test parameters
uri = libvirt_vm.normalize_connect_uri(params.get(... |
'''
Blob detection in astronomical images using various options in scikit-image module
Copyright (c) 2015, Laura Eckman
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, inclu... |
from numpy.testing import *
import numpy as np
from lulu.connected_region import ConnectedRegion
import lulu.connected_region_handler as crh
import lulu.int_array as iarr
class TestConnectedRegion:
c = ConnectedRegion(shape=(5,5),
value=1, start_row=1,
rowptr=[0,4,6... |
import sys
import re
import time, hashlib
import urllib.request
import json
def r1(r, text):
m = re.search(r, text)
if m:
return m.group(1)
def dl_json(url):
print('D: GET ' + url)
r = urllib.request.urlopen(url)
return json.load(r)
_BID_TO_FORMAT = {
19 : {
'index': 7,
... |
"""
Utilities for local system calls, everything here is cross-platform.
become_daemon was originally taken from Django:
https://github.com/django/django/commit/5836a5771f2aefca83349b111f4191d6485af1d5#diff-f7d80be2ccf77f4f009d08dcac4b7736
We might want to refactor this into:
system/__init__.py
system/posix.py
syste... |
import re
from .constants import SHA_COINS, SCRYPT_COINS, COIN_SYMBOL_SET, COIN_SYMBOL_MAPPINGS, FIRST4_MKEY_CS_MAPPINGS_UPPER, UNIT_CHOICES, UNIT_MAPPINGS
from .crypto import script_to_address
from bitcoin import safe_from_hex, deserialize
from collections import OrderedDict
from hashlib import sha256
HEX_CHARS_RE... |
from __future__ import absolute_import, division, print_function
from glob import glob
import os
try:
from skimage.io import imread as sk_imread
except (AttributeError, ImportError):
pass
from .core import Array
from ..base import tokenize
def add_leading_dimension(x):
return x[None, ...]
def imread(... |
from totalimpactwebapp import db
from util import cached_property
from util import commit
from util import dict_from_dir
import logging
logger = logging.getLogger("ti.refresh_status")
def save_profile_refresh_status(profile, status_string):
profile.refresh_status = status_string
db.session.add(profile)
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
import csv
from collections import defaultdict
import StringIO
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from jinja_template import JinjaTemplating
from google.appengine.ext import db
from google.appengine.api import memcache
from models.pegasus_model import B... |
import cv2
import numpy as np
FLANN_INDEX_LSH = 6
def test_orbmatch(ref_img, query_img, num_kp=None, min_match=10):
'''
Tests the ORB matcher by finding an homography and counting the
percentage of inliers in said homography.
Parameters
----------
ref_img: ndarray
Reference image, mu... |
#!/usr/bin/env python
"""
This script shows how to download docx transcripts and transform them to plain text files.
Results will be stored in /examples/transcripts/
To run this script, make sure the settings.ini file at the root of the project is properly filled.
"""
import os
import pprint
from rev.client import Re... |
from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to u... |
"""
Simulation of spheres at hexagonal lattice.
"""
import bornagain as ba
from bornagain import deg, angstrom, nm
import matplotlib
from matplotlib import pyplot as plt
def get_sample(radius=5*nm, lattice_constant=10*nm):
"""
Returns a sample with spheres forming a hexagonal lattice.
"""
m_air = ba.... |
from __future__ import absolute_import
import tweepy
from celery.utils.log import get_task_logger
from bookie.bcelery.celery import celery
import transaction
try:
from whoosh.store import LockError
except ImportError:
from whoosh.index import LockError
from whoosh.writing import IndexingError
from bookie.l... |
from flask import url_for
from kqueen_ui.api import KQueenResponse
import pytest
@pytest.mark.parametrize('view,values', [
('ui.index', {}),
('ui.logout', {}),
('ui.organization_manage', {}),
('ui.user_invite', {}),
('ui.user_delete', {'user_id': 1}),
('ui.user_change_password', {}),
('ui... |
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.tests.common import TransactionCase, users, warmup
from odoo.tests import tagged
from odoo.tools import mute_logger
class TestMassMailPerformanceBase(TransactionCase):
def setUp(self):
super(TestMassMailPerformanceBase, self).setUp()
... |
from datetime import date, datetime
from decimal import Decimal
import unittest
from uuid import UUID
from cassandra.cqlengine.models import Model
from cassandra.cqlengine.usertype import UserType
from cassandra.cqlengine import columns
from cassandra.cqlengine.management import sync_table, sync_type, create_keyspace_... |
"""
Commandline argument parsing for our test runner.
"""
import collections
import getopt
import stem.util.conf
import stem.util.log
from test.util import Target
LOG_TYPE_ERROR = """\
'%s' isn't a logging runlevel, use one of the following instead:
TRACE, DEBUG, INFO, NOTICE, WARN, ERROR
"""
CONFIG = stem.util.... |
"""
Contains BACE data loading utilities.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import sys
import os
import deepchem
import tempfile
import deepchem as dc
from deepchem.molnet.load_function.bace_features import bace_user_specified_features
d... |
from cyvcf2 import VCF as cyvcf2
from collections import OrderedDict, deque
from itertools import islice
import re
from vcfkit.utils import message
from copy import copy
import os
import numpy as np
from reference import resolve_reference_genome
np.set_printoptions(threshold=np.nan)
class vcf(cyvcf2):
def __init_... |
#!/usr/bin/python
import setup
setup.pre_install()
import subprocess
from charmhelpers.core import hookenv
from charmhelpers import fetch
from charmhelpers.fetch import archiveurl
from path import path
def install():
install_packages()
hookenv.log('Installing go')
download_go()
hookenv.log('Adding ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.