content string |
|---|
#!/usr/bin/python2
# -*- coding: utf-8 -*-
##intento import cElementTree que es código nativo
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import csv
import os
import glob
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
"""
Creado 1 de Diciembre 2015
@... |
import logging as log
import sys
import getopt
import os
import subprocess
import shutil
def RunCMake(workspace, target, platform):
# run CMake
print "\n==================================================\n"
returncode = 0
if platform == "windows":
print "Running: vcvarsall.bat x86_amd64 && " +... |
import os
import re
import sys
import shutil
import subprocess
import platform
import argparse
import stat
import UpdateVersion
if len(sys.argv) < 2 or sys.argv[1] in ('-h','--help'):
print "usage: " + sys.argv[0] + " <x86|x64|Arm|android> [UpdateVersion]"
sys.exit(1)
plat = sys.argv[1]
origDir = os.getc... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0013_update_golive_expire_help_text'),
]
operations = [
migrations.AlterField(
model_name='groupp... |
import logging
from openerp import _, api, exceptions, models, SUPERUSER_ID
from openerp.tools.safe_eval import safe_eval
from psycopg2 import OperationalError
_logger = logging.getLogger(__name__)
class Cron(models.Model):
_name = _inherit = "ir.cron"
@api.one
def run_manually(self):
"""Run a j... |
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
__title__ = 'id-pools-vsn-ranges'
__version__ = '0.0.1'
__copyright__ = '(C) Copyright (2012-2016)... |
import re
import rose.macro
class DuplicateChecker(rose.macro.MacroBase):
"""Returns settings whose duplicate status does not match their name."""
WARNING_DUPL_SECT_NO_NUM = ('incorrect "duplicate=true" metadata')
WARNING_NUM_SECT_NO_DUPL = ('{0} requires "duplicate=true" metadata')
def validate(s... |
"""
This is the default template for our main set of AWS servers.
"""
# We intentionally define lots of variables that aren't used, and
# want to import all variables from base settings files
# pylint: disable=W0401, W0614
import json
from .common import *
from logsettings import get_logger_config
import os
from p... |
import unittest
from email import _encoded_words as _ew
from email import errors
from test.test_email import TestEmailBase
class TestDecodeQ(TestEmailBase):
def _test(self, source, ex_result, ex_defects=[]):
result, defects = _ew.decode_q(source)
self.assertEqual(result, ex_result)
self.a... |
import os
from sys import exc_info
from .Maildir import MaildirFolder
from offlineimap import OfflineImapError
import offlineimap.accounts
from offlineimap import imaputil
class GmailMaildirFolder(MaildirFolder):
"""Folder implementation to support adding labels to messages in a Maildir.
"""
def __init__(s... |
import json
import os
import posixpath
import shutil
import subprocess
import sys
import tempfile
import unittest
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
TOOLS_DIR = os.path.dirname(SCRIPT_DIR)
DATA_DIR = os.path.join(TOOLS_DIR, 'lib', 'tests', 'data')
BUILD_TOOLS_DIR = os.path.join(os.path.dirname(TOO... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
from ansible.module_utils.nxos import load_config, run_commands
from ansible.module_utils.nxos import nxos_argument_spec, check_args
from ansible.module_utils.basic import AnsibleModule
de... |
'''
=================================================================================================
R Cipher Suite
Includes all variants of the R cipher
=================================================================================================
Developed by: ProgramRandom, a division of RandomCorporations
A Pa... |
from pyspark.mllib.fpm import FPGrowth
# $example off$
from pyspark import SparkContext
if __name__ == "__main__":
sc = SparkContext(appName="FPGrowth")
# $example on$
data = sc.textFile("data/mllib/sample_fpgrowth.txt")
transactions = data.map(lambda line: line.strip().split(' '))
model = FPGrowt... |
"""
Slack OAuth2 backend, docs at:
http://psa.matiasaguirre.net/docs/backends/slack.html
https://api.slack.com/docs/oauth
"""
import re
from social.backends.oauth import BaseOAuth2
class SlackOAuth2(BaseOAuth2):
"""Slack OAuth authentication backend"""
name = 'slack'
AUTHORIZATION_URL = 'https://... |
import wx
from gnuradio import gr
import panel
default_gui_size = (200, 100)
class top_block_gui(gr.top_block):
"""gr top block with wx gui app and grid sizer."""
def __init__(self, title='', size=default_gui_size):
"""
Initialize the gr top block.
Create the wx gui elements.
@param title the main window t... |
from functools import partial
import traceback
from vdsm import supervdsm
import hooking
import ovs_utils
log = partial(ovs_utils.log, tag='ovs_after_network_setup_fail: ')
def main():
setup_nets_config = hooking.read_json()
in_rollback = setup_nets_config['request']['options'].get('_inRollback')
if... |
"""Simple API for XML (SAX) implementation for Python.
This module provides an implementation of the SAX 2 interface;
information about the Java version of the interface can be found at
http://www.megginson.com/SAX/. The Python version of the interface is
documented at <...>.
This package contains the following modu... |
'''SSL with SNI_-support for Python 2. Follow these instructions if you would
like to verify SSL certificates in Python 2. Note, the default libraries do
*not* do certificate checking; you need to do additional work to validate
certificates yourself.
This needs the following packages installed:
* pyOpenSSL (tested wi... |
import six
import chainer
from chainer.backends import cuda
from chainer.functions.activation import lstm
from chainer.functions.array import concat
from chainer.functions.array import split_axis
from chainer import initializers
from chainer import link
from chainer.links.connection import linear
from chainer import u... |
from __future__ import unicode_literals
import time
import hmac
import hashlib
import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
ExtractorError,
float_or_none,
int_or_none,
sanitized_Request,
urlencode_postdata,
xpath_text,
)
class AtresPlayerI... |
import urllib
import urlparse
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from .utils import json_response
from ..models import Author, Module, Release
## Helper methods
def error_response(errors, **kwargs):
"""
Returns an error response for v3 Forge API.
""... |
"""Helper functions to make working with the PISM/PETSc option system more pythonic."""
import PISM
def _to_tuple(option, use_default):
"""Convert a PISM Option object into a tuple of (value, flag). Return
(None, False) if use_default is False and the option was not set.
"""
if option.is_set() or use... |
from lib.actions import OpsGenieBaseAction
class ListUsersAction(OpsGenieBaseAction):
def run(self):
"""
List users in OpsGenie.
Returns:
- dict: Data from OpsGenie.
"""
payload = {"apiKey": self.api_key}
data = self._req("GET",
"... |
from . import config
from . import assertions, schema
from .util import adict
from .. import util
from .engines import drop_all_tables
from .entities import BasicEntity, ComparableEntity
import sys
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta
# whether or not we use ... |
"""
Matrix Solver
Parses a calibration table and solves the equations for the alpha constants
used in the Hardy's Multi-Quadric method of calibration.
"""
import os, sys, string
from math import sqrt
from xml.dom import *
from xml.dom.minidom import *
import Numeric, LinearAlgebra
# Define useful functions
def length(... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: aci_contract_subject
short_description: Manage initial Contr... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import hamming, triang, blackmanharris
import sys, os, functools, time
from scipy.fftpack import fft, ifft, fftshift
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../software/models/'))
import dftModel as DFT
import ... |
"""
Forms and validation code for user user_registration.
"""
from django.contrib.auth.models import User
from django import forms
from django.utils.translation import ugettext_lazy as _
# I put this on all required fields, because it's easier to pick up
# on them with CSS or JavaScript if they have a ... |
"""ASN.1 specification for X509 extensions."""
from ct.crypto.asn1 import named_value
from ct.crypto.asn1 import oid
from ct.crypto.asn1 import tag
from ct.crypto.asn1 import types
from ct.crypto.asn1 import x509_common
from ct.crypto.asn1 import x509_name
# Standard extensions from RFC 5280.
class BasicConstraints(... |
from django.conf import settings
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
DEFAULT_PAGE = getattr(settings, 'REST_API_DEFAULT_PAGE', 1)
DEFAULT_PAGE_SIZE = getattr(settings, 'REST_API_DEFAULT_PAGE_SIZE', 10)
DEFAULT_PAGE_QUERY_PARAM = getattr(settings, 'RES... |
# -*- coding: utf-8 -*-
"""
AR-specific Form helpers.
"""
from __future__ import absolute_import
from django.contrib.localflavor.ar.ar_provinces import PROVINCE_CHOICES
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import RegexField, CharField, Selec... |
from __future__ import unicode_literals
import sys
from django.conf import settings
from django.template import Library, Node, TemplateSyntaxError, Variable
from django.template.base import TOKEN_TEXT, TOKEN_VAR, render_value_in_context
from django.template.defaulttags import token_kwargs
from django.utils import six... |
import unittest
import time
from django.test import TestCase
from django.test.utils import override_settings
from django.conf import settings
from django.core import management
from django.utils.six import StringIO
from wagtail.tests.utils import WagtailTestUtils
from wagtail.tests.search import models
from wagtail.w... |
"""
Utilities for django models.
"""
import unicodedata
import re
from eventtracking import tracker
from django.conf import settings
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
from django_countries.fields import Country
# The setting name used for events when "sett... |
"""
A refactored implementation of Boids from a deliberately bad implementation of
[Boids](http://dl.acm.org/citation.cfm?doid=37401.37406): an exercise for class.
"""
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
class Boids(object):
def __init__(self,
... |
import observer
import os.path
import sys
import os.path
_call_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
def get_installation_path():
try:
if sys.frozen:
path = _call_dir
else:
raise AttributeError()
except AttributeError:
path = os.path.abspath(observ... |
from protocols.forms import forms
from core.utils import VOLUME_UNITS, CONCENTRATION_UNITS, TIME_UNITS
class ResuspendForm(forms.VerbForm):
name = "Resuspend"
slug = "resuspend"
# has_component = True
has_manual = True
layers = ['item_to_act', 'reagent', 'settify']
item_to_act = forms.CharFie... |
"""
Mostly equivalent to the views from django.contrib.auth.views, but
implemented as class-based views.
"""
from __future__ import unicode_literals
import warnings
from django.conf import settings
from django.contrib.auth import get_user_model, REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import login_requ... |
# -*- coding: utf-8 -*-
"""
Tests that quoting specifications are properly handled
during parsing for all of the parsers defined in parsers.py
"""
import csv
import pandas.util.testing as tm
from pandas import DataFrame
from pandas.compat import PY3, StringIO, u
class QuotingTests(object):
def test_bad_quote_... |
"""Unittests for test.script_helper. Who tests the test helper?"""
import subprocess
import sys
from test import script_helper
import unittest
from unittest import mock
class TestScriptHelper(unittest.TestCase):
def test_assert_python_expect_success(self):
t = script_helper._assert_python(True, '-c', 'i... |
"""Univariate features selection."""
# Authors: V. Michel, B. Thirion, G. Varoquaux, A. Gramfort, E. Duchesnay.
# L. Buitinck, A. Joly
# License: BSD 3 clause
import numpy as np
import warnings
from scipy import special, stats
from scipy.sparse import issparse
from ..base import BaseEstimator
from ..prepr... |
import os
import threading
import unittest
import concurrent
def _ForkTestHelper(arg1, arg2, pickle_me_not, test_instance, parent_pid):
_ = pickle_me_not # Suppress lint warning.
test_instance.assertNotEquals(os.getpid(), parent_pid)
return arg1 + arg2
class Unpicklable(object):
"""Ensures that pickle() i... |
from unittest import TestCase
from mock import patch, MagicMock, call
import probe.controllers.ftpctrl as module
from irma.common.base.exceptions import IrmaFtpError
class TestFtpctrl(TestCase):
@patch("probe.controllers.ftpctrl.os.path.isdir")
@patch('probe.controllers.ftpctrl.config.IrmaSFTPv2')
def te... |
import threading
import Queue
import time
from core.task import Task
def _populate_list_with_file(file_name):
""" Open a file, read its content and strips it. Returns a list with the content
additionally it filter and clean some splinters
"""
with open(file_name, 'r') as f:
tmp_list = f.r... |
from common_fixtures import * # NOQA
from gdapi import ApiError
@pytest.fixture(scope='module')
def user_client(context):
return context.user_client
def _user_preference(client, name=None):
if name is None:
name = random_str()
preference = client.wait_success(client.create_user_preference(
... |
from __future__ import absolute_import, division, print_function
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "packaging"
__summary__ = "Core utilities for Python packages"
__uri__ = "https://github.com/pypa/packagin... |
"""Read the time series and output a csv"""
import argparse
import h5py
import csv
import sys
import numpy as np
parser = argparse.ArgumentParser(
__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
"file",
nargs=1,
help="hdf5 file"
)
if __name__ == '__main__':
... |
from . import base
from .decorators import command_custom
from tuned import consts
import tuned.logs
import errno
import perf
import re
log = tuned.logs.get()
class IrqbalancePlugin(base.Plugin):
"""
Plugin for irqbalance settings management.
"""
def __init__(self, *args, **kwargs):
super(IrqbalancePlugin, sel... |
import sys
def setdlopenflags():
oldflags = sys.getdlopenflags()
try:
from DLFCN import RTLD_GLOBAL, RTLD_LAZY
except ImportError:
RTLD_GLOBAL = -1
RTLD_LAZY = -1
import os
osname = os.uname()[0]
if osname == 'Linux' or osname == 'SunOS' or osname == 'FreeBSD... |
from __future__ import absolute_import
from datetime import timedelta
from django.core.urlresolvers import reverse
from django.utils import timezone
from mock import patch
from sentry.models import (
EventMapping, Group, GroupBookmark, GroupSeen, GroupStatus
)
from sentry.testutils import APITestCase
from sentry.... |
#!/usr/bin/env python
'''
menu handling widgets for wx
Andrew Tridgell
November 2013
'''
import wx
from MAVProxy.modules.lib import mp_util
class MPMenuGeneric(object):
'''a MP menu separator'''
def __init__(self):
pass
def find_selected(self, event):
return None
def _append(self, m... |
from pandac.PandaModules import Point3
from direct.distributed.ClockDelta import globalClockDelta
from direct.fsm import ClassicFSM, State
from direct.task import Task
from toontown.minigame import DistributedMinigameAI
from toontown.minigame import MinigameGlobals
from toontown.minigame import IceGameGlobals
from toon... |
from math import cos, sin
from vector2d import Vector2
def rotate(v, theta):
cos_theta = cos(theta)
sin_theta = sin(theta)
return rotate_fast(v, cos_theta, sin_theta)
def rotate_fast(v, cos_theta, sin_theta):
x = cos_theta * v.x - sin_theta * v.y
y = sin_theta * v.x + cos_theta * v.y
retur... |
import os
import sys
from flask import Flask
from flask.ext.httpauth import HTTPBasicAuth
PROJECT_DIR, PROJECT_MODULE_NAME = os.path.split(
os.path.dirname(os.path.realpath(__file__))
)
FLASK_JSONRPC_PROJECT_DIR = os.path.join(PROJECT_DIR, os.pardir)
if os.path.exists(FLASK_JSONRPC_PROJECT_DIR) \
and no... |
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'd F Y' # 25 Ottobre 2006
TIME_FORMAT = 'H:i' # 14:30
DATETIME_FORMAT = 'l d F Y H:i' # Mercoledì 25 Ottobre 2006 14:30
YEAR_MONTH_F... |
from openerp.osv import fields, osv
class account_general_journal(osv.osv_memory):
_inherit = "account.common.journal.report"
_name = 'account.general.journal'
_description = 'Account General Journal'
_columns = {
'journal_ids': fields.many2many('account.journal', 'account_general_journal_jou... |
from time import time
from unittest import TestCase
import mock
from apache.thermos.monitoring.monitor import TaskMonitor
from apache.thermos.monitoring.process import ProcessSample
from apache.thermos.monitoring.resource import (
ResourceHistory,
ResourceMonitorBase,
TaskResourceMonitor
)
from gen.apach... |
'''
Created on May 8, 2011
@author: sander
'''
import os.path
import shutil
import sys
'''
nose.tools has to be imported into the Eclipse project, eg, from
/usr/local/lib/python2.6/dist-packages/nose-1.0.0-py2.6.egg/nose/tools.py
'''
from tools import with_setup, raises, nottest
import lab_o_matic.compiler
paths ... |
"""By using execfile(this_file, dict(__file__=this_file)) you will
activate this virtualenv environment.
This can be used when you must use an existing Python interpreter, not
the virtualenv bin/python
"""
try:
__file__
except NameError:
raise AssertionError(
"You must run this like execfile('path/to/... |
####################################################
#
# This file records all the constant variables used
# in tsdb module
#
####################################################
OPMAP = {
'<': 0,
'>': 1,
'==': 2,
'!=': 3,
'<=': 4,
'>=': 5
}
FILES_DIR = 'persistent_files'
MAX_CARD = 8
INDEX... |
from openerp import models, fields, api
class ProcurementOrder(models.Model):
_inherit = 'procurement.order'
mrp_operation = fields.Many2one(
'mrp.production.workcenter.line', 'MRP Operation')
@api.multi
def make_po(self):
purchase_line_obj = self.env['purchase.order.line']
r... |
from clang.cindex import TokenKind
from nose.tools import eq_
from nose.tools import ok_
from nose.tools import raises
def test_constructor():
"""Ensure TokenKind constructor works as expected."""
t = TokenKind(5, 'foo')
eq_(t.value, 5)
eq_(t.name, 'foo')
@raises(ValueError)
def test_bad_register():... |
import fsui
from launcher.i18n import gettext
from launcher.setup.setupwelcomepage import SetupWelcomePage
from launcher.ui.skin import LauncherTheme
from launcher.ui.widgets import PrevButton, NextButton, CloseButton
class SetupWizardDialog(fsui.Window):
@classmethod
def open(cls, parent=None):
retur... |
import os
from tab import tab_class
from icon_lib import icon_get
#qt
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtWidgets import QWidget,QVBoxLayout,QToolBar,QSizePolicy,QAction,QTabWidget,QDialog
from PyQt5.QtGui import QPainter,QIcon
#python modules
import webbrowser
from help import help_window
from win_lin... |
"""Tests for volume name_id."""
from oslo.config import cfg
from cinder import context
from cinder import db
from cinder import test
from cinder.tests import utils as testutils
CONF = cfg.CONF
class NameIDsTestCase(test.TestCase):
"""Test cases for naming volumes with name_id."""
def setUp(self):
... |
import account
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The code base had inconsistent usage of tabs/spaces for indenting in Lua.
files. Spaces were more prominent - and I prefer them over tabs. So I wrote
this small script to fix leading tabs in Lua files to spaces.
It also saves files in unix file endings ("\r\n") and s... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import jsonfield.fields
import badges.models
from django.conf import settings
import django.utils.timezone
from model_utils import fields
import xmodule_django.models
class Migration(migrations.Migration):
d... |
from base64 import b64encode
import traceback
import sickbeard
from sickbeard import logger
from sickbeard.clients.generic import GenericClient
from lib.rtorrent import RTorrent
from lib.rtorrent.err import MethodError
class rTorrentAPI(GenericClient):
def __init__(self, host=None, username=None, password=None):... |
import perf
def main():
cpus = perf.cpu_map()
threads = perf.thread_map()
evsel = perf.evsel(task = 1, comm = 1, mmap = 0,
wakeup_events = 1, watermark = 1,
sample_id_all = 1,
sample_type = perf.SAMPLE_PERIOD | perf.SAMPLE_TID | perf.SAMPLE_CPU | perf.SAMPLE_TID)
evsel.open(cpus = cpus, threads =... |
"""Unit tests for the shared functions and classes for tfdbg CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import namedtuple
from tensorflow.python.debug.cli import cli_shared
from tensorflow.python.debug.cli import debugger_cli_c... |
import os
import shutil
import tempfile
import uuid
import zipfile
from oslo_config import cfg
import yaml
from rally.common import fileutils
from rally.common import utils as common_utils
from rally.plugins.openstack import scenario
from rally.task import atomic
from rally.task import utils
CONF = cfg.CONF
MURANO_... |
"""
Error reporting should be safe from encoding/decoding errors.
However, implicit conversions of strings and exceptions like
>>> u'%s world: %s' % ('H\xe4llo', Exception(u'H\xe4llo')
fail in some Python versions:
* In Python <= 2.6, ``unicode(<exception instance>)`` uses
`__str__` and fails with non-ASCII chars ... |
from m5.params import *
from m5.proxy import *
from m5.SimObject import SimObject
from BasicLink import BasicIntLink, BasicExtLink
class SimpleExtLink(BasicExtLink):
type = 'SimpleExtLink'
class SimpleIntLink(BasicIntLink):
type = 'SimpleIntLink' |
from django.template.defaultfilters import linebreaks_filter
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import setup
class LinebreaksTests(SimpleTestCase):
"""
The contents in "linebreaks" are escaped according to the current
autoescape setting.
... |
# This file will generate random test data and write it to a database.
import os
import sys
import string
import django
import random
# Fake Factory
from faker import Faker
fake = Faker()
# Connect to the Django Database
sys.path.insert(1,'/home/spearphisher/spearphisher')
script_path = os.path.dirname(__file__)
sys... |
import os
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import importutils
from cinder import context
from cinder.db.sqlalchemy import api
from cinder import exception
from cinder.i18n import _, _LI
from cinder.image import image_utils
from cinder.volume import driver
from cinder.vol... |
"""
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"); you may not use this ... |
from keystoneclient.v2_0 import client as ksclient
from ironicclient.common import utils
from ironicclient import exc
from ironicclient.openstack.common import gettextutils
gettextutils.install('ironicclient')
def _get_ksclient(**kwargs):
"""Get an endpoint and auth token from Keystone.
:param kwargs: keyw... |
import itertools
import collections
import random
import string
import miasm2.expression.expression as m2_expr
def parity(a):
tmp = (a) & 0xFFL
cpt = 1
while tmp != 0:
cpt ^= tmp & 1
tmp >>= 1
return cpt
def merge_sliceto_slice(args):
sources = {}
non_slice = {}
sources_... |
from gnuradio import gr, gr_unittest
class test_nlog10(gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test_001(self):
src_data = (-10, 0, 10, 100, 1000, 10000, 100000)
expected_result = (-180, -180, 10, 20, 30, 4... |
import re
import sys
# Reason last stmt is continued (or C_NONE if it's not).
(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE,
C_STRING_NEXT_LINES, C_BRACKET) = range(5)
if 0: # for throwaway debugging output
def dump(*stuff):
sys.__stdout__.write(" ".join(map(str, stuff)) + "\n")
# Find what looks like the... |
from .. import exc as sa_exc
from ..util import ScopedRegistry, ThreadLocalRegistry, warn
from . import class_mapper, exc as orm_exc
from .session import Session
__all__ = ['scoped_session']
class scoped_session(object):
"""Provides scoped management of :class:`.Session` objects.
See :ref:`unitofwork_conte... |
"""Index.py
This module provides a way to create indexes to text files.
Classes:
Index Dictionary-like class used to store index information.
_ShelveIndex An Index class based on the shelve module.
_InMemoryIndex An in-memory Index class.
"""
import os
import array
import shelve
try:
import cPickle a... |
from __future__ import unicode_literals
from calendar import timegm
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.http import Http404, HttpResponse
from django.template import Templat... |
try:
# for Python 2
from Tkinter import *
except ImportError:
# for Python 3
from tkinter import *
import time
import Solving_algorithm
# Converts a set of coordinates into indexes in the cube
# returns square index horizontally and vertically (x,y)
def CoordinatesToIndex(coordinates):
t = (coordi... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class GetPriceEstimates(Choreography):
def __init__(self, temboo_session):
"""
Crea... |
"""Support for Copy Number Variations (CNVs) with GATK4
https://software.broadinstitute.org/gatk/documentation/article?id=11682
https://gatkforums.broadinstitute.org/dsde/discussion/11683/
"""
import glob
import os
import shutil
import numpy as np
import toolz as tz
from bcbio import broad, utils
from bcbio.distribu... |
from bson import ObjectId
import superdesk
import urllib3
import urllib
import xml.etree.ElementTree as etree
import pytz
from pytz import NonExistentTimeError, AmbiguousTimeError
from superdesk import config
from superdesk.io.iptc import subject_codes
from datetime import datetime
import time
from superdesk.metadata.... |
from __future__ import absolute_import
from __future__ import print_function
from typing import Any
from argparse import ArgumentParser
from django.core.management.base import BaseCommand
from confirmation.models import Confirmation
from zerver.models import UserProfile, PreregistrationUser, \
get_user_profile_by... |
#! /usr/bin/env python
"""Test script for the anydbm module
based on testdumbdbm.py
"""
import os
import unittest
import glob
from test import test_support
_fname = test_support.TESTFN
# Silence Py3k warning
anydbm = test_support.import_module('anydbm', deprecated=True)
def _delete_files():
# we don't know t... |
import os
from autotest_lib.client.bin import test, utils
class linus_stress(test.test):
version = 1
def setup(self):
os.mkdir(self.srcdir)
os.chdir(self.bindir)
utils.system('cp linus_stress.c src/')
os.chdir(self.srcdir)
utils.system(utils.get_cc() + ' linus_stress.c... |
"""
===========================
Plotting feature importance
===========================
A simple example showing how to compute and display
feature importances, it is also compared with the
feature importances obtained using random forests.
Feature importance is a measure of the effect of the features
on the outputs.... |
"""
Vector3 is a three dimensional vector class.
Below are examples of Vector3 use.
>>> from vector3 import Vector3
>>> origin = Vector3()
>>> origin
0.0, 0.0, 0.0
>>> pythagoras = Vector3( 3, 4, 0 )
>>> pythagoras
3.0, 4.0, 0.0
>>> pythagoras.magnitude()
5.0
>>> pythagoras.magnitudeSquared()
25
>>> triplePythagoras ... |
from flask import jsonify
class NotUniqueException(Exception):
pass
class ExistedException(Exception):
pass
class DoesNotExistsException(Exception):
pass
class HttpException(Exception):
pass
except_dict = {
'LoginFailed': {
'code': 403,
'message': "Login Failed"
},
'Ne... |
from __future__ import print_function, unicode_literals
from os import path, getcwd, listdir
import subprocess
import sys
from mach.decorators import (
CommandArgument,
CommandProvider,
Command,
)
from servo.command_base import CommandBase, cd
@CommandProvider
class MachCommands(CommandBase):
@Comm... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import binascii
import io
import os
from binascii import hexlify
import pytest
from ansible.compat.tests import unittest
from ansible import errors
from ansible.module_utils import six
from ansible.module_utils._text import to_b... |
# Tai Sakuma <<EMAIL>>
import pandas as pd
from .ToTupleListWithDatasetColumn import ToTupleListWithDatasetColumn
##__________________________________________________________________||
class ToDataFrameWithDatasetColumn:
def __init__(self, summaryColumnNames,
datasetColumnName = 'component'
... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
simtime = 80e-12
size_y = 1400e-6
c = 3e8
maxfreq = 2e12
## Import common moduli
import numpy as np
from scipy.constants import c, hbar, pi
import matplotlib, sys, os, time
import matplotlib.pyplot as plt
## Start figure + subplot (interactive)
fig = plt.figure(figsize=(1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.