content stringlengths 4 20k |
|---|
from setuptools import setup, find_packages
import os
def expand_package_data(src_dirs, strip=""):
ret = []
for src_dir in src_dirs:
for path, dnames, fnames in os.walk(src_dir):
for fname in fnames:
ret.append(os.path.join(path, fname).replace(strip, ""))
return ret
os.chdir(os.path.dirname(o... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
import django_extensions.db.fields
class Migration(migrations.Migration):
dependencies = [
('branches', '0011_auto_20151225_0337'),
]
operations = [
migr... |
# -*- coding: utf-8 -*-
"""
Tests for course access
"""
import ddt
import itertools
import mock
from django.conf import settings
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from django.test.client import RequestFactory
from opaque_keys.edx.locations import SlashSeparate... |
import abc
import six
from neutron.api import extensions
from neutron.api.v2 import attributes as attr
from neutron.api.v2 import resource_helper
from neutron.common import exceptions as nexception
from neutron.plugins.common import constants
from neutron.services import service_base
class VPNServiceNotFound(nexcep... |
import h5py
import numpy as np
import dclab
from dclab import new_dataset
from dclab.features.bright import get_bright
from helper_methods import calltracker, retrieve_data
def test_af_brightness():
path = retrieve_data("rtdc_data_hdf5_image_bg.zip")
with h5py.File(path, "r+") as h5:
real_avg = h5["... |
def intersect(blank, tool):
from Intersection import Intersection
return Intersection(blank, tool)
def subtract(blank, tool):
from Difference import Difference
return Difference(blank, tool)
def unite(blank, tool):
from Union import Union
return Union(blank, tool)
# body transformations
d... |
from django.contrib.auth import authenticate
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _
from django import forms
class ConfirmedEmailAuthenticationForm(AuthenticationForm):
"""Your average form, but with an additional tweak to the clean method
... |
import os
from setuptools import setup, find_packages
from setuptools.command.install import install as _install
from fish_bundles import __version__
class install(_install):
def run(self):
_install.run(self)
os.system('fb init')
try:
os.system('fb install --boring')
ex... |
from get_edf import file_name
import os.path, sys
from numpy import float32, average, array,asfarray,mean,where
from time import time,sleep
def read_image(f,input_info,flat_field,wtotmask,tot_darks,indices,static_corrected,totsaxs='none'):
tread=time()
tdrop=0
detector=input_info['detector'].lower()
t... |
"""
@author: Fabio Erculiani <<EMAIL>>
@contact: <EMAIL>
@copyright: Fabio Erculiani
@license: GPL-2
B{Entropy Updates Notification Applet (Magneto) configuration module}
"""
import os
import entropy.dump
ICON_PATH = os.getenv("MAGNETO_ICON_PATH", "/usr/share/magneto/icons")
DATA_DIR = os.getenv... |
import codecs
import html.entities
import re
import sys
from PyQt4.QtCore import (QMutex, QThread, Qt, SIGNAL)
class Walker(QThread):
COMMON_WORDS_THRESHOLD = 250
MIN_WORD_LEN = 3
MAX_WORD_LEN = 25
INVALID_FIRST_OR_LAST = frozenset("0123456789_")
STRIPHTML_RE = re.compile(r"<[^>]*?>", re.IGNORECA... |
'''Test cases for overriding inherited protected virtual methods'''
import unittest
from PySide2.QtCore import QTimerEvent
from PySide2.QtWidgets import QApplication, QSpinBox
from helper import UsesQApplication
class MySpinButton(QSpinBox):
'''Simple example class of overriding QObject.timerEvent'''
def _... |
import escapade.backend.mapquest
import escapade.backend.shelve
from escapade.core.roadmap import Roadmap
class MapItemStore:
def __init__(self):
self.backend = escapade.backend.mapquest.MapItemBackend()
def item(self):
raise(NotImplementedError)
def search(self, query_string):
r... |
"""
Code to delay the import of a moldule, and give a nice error message if
the module is not installed. for dealing with dependencies.
"""
##############################################################################
# imports
##############################################################################
from __futu... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'PSL_Apps/templates/icon.ui'
#
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _f... |
from Monument import Monument, Dataset
import importer_utils as utils
import importer as importer
class DkBygningDa(Monument):
def set_adm_location(self):
if self.has_non_empty_attribute("kommune"):
if utils.count_wikilinks(self.kommune) == 1:
adm_location = utils.q_from_first... |
# vim: fileencoding=utf-8 et ts=4 sts=4 sw=4 tw=0
"""
Green version of the RPC client
Authors:
* Brian Granger
* Alexander Glyzov
* Axel Voitier
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2012-2014. Brian Granger, Min Ragan-Kelley, Alexander Glyzov,
# Axel V... |
"""Cookiecutter_manager tests """
import os
import shutil
from django.test import TestCase
from django.core.management import call_command
from .models import CookieCutterTemplate
from .helpers.helper_cookiecutter import clone_cookiecutter_template, \
clone_cookiecutter_template_with_dict
class CookieCutterTe... |
__all__ = []
# The following pattern is used below for importing sub-modules:
#
# 1. "from foo import *". This imports all the names from foo.__all__ into
# this module. But, this does not put those names into the __all__ of
# this module. This enables "from sympy.physics.quantum import State" to
# work.
# 2... |
from tempest.lib.services.compute import floating_ip_pools_client
from tempest.tests.lib import fake_auth_provider
from tempest.tests.lib.services import base
class TestFloatingIPPoolsClient(base.BaseServiceTest):
FAKE_FLOATING_IP_POOLS = {
"floating_ip_pools":
[
{"name": u'\u3042'},
... |
import sys, pwd, getopt, re, os
from subprocess import getstatusoutput
EXCLUDE_LOGINS=["/sbin/nologin", "/bin/false"]
def getStartingUID():
starting_uid = 99999
rc=getstatusoutput("grep -h '^UID_MIN' /etc/login.defs")
if rc[0] == 0:
uid_min = re.sub("^UID_MIN[^0-9]*", "", rc[1])
#stip any comment from the end... |
from django.core.urlresolvers import reverse
from django.template.defaultfilters import title # noqa
from django.utils.translation import ugettext_lazy as _
from horizon import tables
from horizon.utils import filters
from openstack_dashboard import api
STATUS_CHOICES = (
("BUILDING", None),
("COMPLETED", ... |
# -*- coding: utf-8 -*-
"""
mul.recipe.appengine.lib
"""
import logging
import os
import os.path
import pkg_resources
import setuptools.archive_util
import shutil
import tempfile
import zc.recipe.egg.egg
import zipfile
# pylint: disable=too-many-branches
# pylint: disable=too-many-instance-attributes
# pylint: di... |
#!/usr/env python
import redis
class NondirectionalEdge(object):
def __init__(self, a, b, weight):
self.a = a
self.b = b
self.weight = weight
def __eq__(self, other):
# TODO(bluecmd): we don't consider different weights here
return (self.a == other.a and self.b == other.b) or (
self.a ... |
import sys
__all__ = ['install', 'NullFinder', 'PyPy_repr', 'Protocol']
try:
from typing import Protocol
except ImportError: # pragma: no cover
"""
pytest-mypy complains here because:
error: Incompatible import of "Protocol" (imported name has type
"typing_extensions._SpecialForm", local name h... |
from flask.ext.login import current_user
from core.database.models import ResourceData, Permission, ResourceLayout
from core.manager import BaseManager, ExecutionContext
from core.resources.permissions import ResourcePermissionsManager
from core.util import get_context_for_scope, IncorrectPermissionsException
import js... |
import matplotlib.pyplot as plt
x_values = [1, 2, 3, 4, 5]
y_values = [1, 4, 9, 16, 25]
plt.scatter(x_values, y_values, s=50, color='r')
# 设置图表标题并给坐标轴加上标签
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# 设置刻度标记的大小
plt.tick_params(axis='both', whi... |
#!/usr/bin/env python3
"""
@author: Roy Nielsen
"""
#--- Native python libraries
import os
import sys
from optparse import OptionParser, SUPPRESS_HELP
sys.path.append("..")
#--- non-native python libraries in this source tree
from lib.loggers import CyLogger
from lib.loggers import LogPriority as lp
#####
# Load OS ... |
from __future__ import unicode_literals
import json
try:
import urllib.parse as urllib
except ImportError:
import urllib
from django.core.urlresolvers import reverse
from django.contrib.auth import get_user_model
from django.test import TestCase, RequestFactory
from django.views.generic import View
from oau... |
"""
Created on Nov 10, 2011
@author: Bilel Msekni
@contact: <EMAIL>
@author: Houssem Medhioub
@contact: <EMAIL>
@organization: Institut Mines-Telecom - Telecom SudParis
@license: Apache License, Version 2.0
"""
#import pyocni.backend.backend as backend
from pyocni.backends.backend import backend_interface
import pyoc... |
"""
This script tests the scf module.
"""
import os
import numpy as np
import pytest
from frankenstein.be import BE
@pytest.mark.parametrize(
"geom, basis, fsites, frank, incore, nibath, solver, jac, B0, bad_con, "
"good_con, e_ps_ref",
[
# Frankenstein BE, FCI solver
("geom/h10.zmat", "st... |
import requests
from urllib import urlencode
class Resource(object):
"""
A REST Resource
"""
name = 'resource'
def __init__(self, base_uri, auth):
self.base_uri = base_uri
self.auth = auth
def request(self, method, uri, data={}):
data = dict(data.ite... |
def findRectangle_O_N_N(histogram, left, right):
if left >= right: return 0
minHeight = histogram[left]
pivot = left
i = left+1
while i < right:
if histogram[i] < minHeight:
minHeight = histogram[i]
pivot = i
i += 1
return max( minHeight * (right-left),
... |
import requests
import urllib
import datetime
from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from multiexplorer.models import PushHistory, Memo
class Command(BaseCommand):
help = 'Perform pushing of memos from another memo serve... |
# pylint: skip-file
'''
Production Configuration
'''
from .common import * # noqa
MIDDLEWARE = [
# Make sure djangosecure.middleware.SecurityMiddleware is listed first
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
] + MIDDLEWARE
# No fallback values for th... |
from degas.analysis_setup import calc_stellar_mass
from astropy.table import Table
from astropy.io import fits
import os
multiDir = os.path.join(os.environ['ANALYSISDIR'],'ancillary_data','multiwavelength')
iracDir = os.path.join(multiDir,'data','irac1','convolved_with_astropy')
MtoLDir = os.path.join(multiDir,'data'... |
#! /usr/bin/env python
# concatenates all DNA sequences from a single strain
# into one long genome with NNNNNNNNNNNNNNNNN between
# sequences
#
# uses taxonomy file to determine strain ID of each fasta
# sequence
#
# requires fasta in order by strain
#
# usage (NNNNNNNNN is what to separate strains with):
# *.py input... |
#!/usr/bin/python
import scipy
import numpy
import pickle
from numpy import *
from scipy import ndimage
from scipy import interpolate
from numpy import loadtxt
import os
import numpy as np
from numpy import *
import matplotlib
from pylab import rcParams
from pylab import *
from matplotlib import pyplot
from ma... |
from __future__ import absolute_import, division, print_function, unicode_literals
import re
import requests
from pants.subsystem.subsystem import Subsystem
from pants.util.memo import memoized_method
from pants.contrib.go.subsystems.imported_repo import ImportedRepo
class GoImportMetaTagReader(Subsystem):
"""Im... |
import re
from urllib import parse
import requests
from lxml import html
from requests import HTTPError
from cloudbot import hook
from cloudbot.util import formatting
api_url = "http://encyclopediadramatica.se/api.php"
ed_url = "http://encyclopediadramatica.se/"
@hook.command()
def drama(text, reply):
"""<phra... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import httplib
import re
from lib.core.common import readInput
from lib.core.data import kb
from lib.core.data import logger
from lib.core.exception import SqlmapSyntaxExcept... |
import unittest
import mock
from lxml import etree
import os
from redi import redi
file_dir = os.path.dirname(os.path.realpath(__file__))
goal_dir = os.path.join(file_dir, "../")
proj_root = os.path.abspath(goal_dir)+'/'
DEFAULT_DATA_DIRECTORY = os.getcwd()
class TestUpdateEventName_KeepAllEvents(unittest.TestCase):... |
from __future__ import division, print_function, unicode_literals
from pysped.xml_sped import *
from pysped.nfe.leiaute import ESQUEMA_ATUAL_VERSAO_3 as ESQUEMA_ATUAL
from pysped.nfe.leiaute import consrecinfe_200
import os
from nfe_300 import NFe
DIRNAME = os.path.dirname(__file__)
class ConsReciNFe(consrecinfe_2... |
#!/usr/bin/env python
"""
A pure python ping implementation using raw socket.
Note that ICMP messages can only be sent from processes running as root.
Derived from ping.c distributed in Linux's netkit. That code is
copyright (c) 1989 by The Regents of the University of California.
That code is ... |
import threading
import select
import time
import types
import socket
from DIRAC import gConfig, gMonitor, gLogger, S_OK, S_ERROR
from DIRAC.Core.DISET.private.TransportPool import getGlobalTransportPool
from DIRAC.Core.Utilities.ThreadPool import getGlobalThreadPool
from DIRAC.Core.Utilities.ReturnValues import isRet... |
from builtins import str
from builtins import object
from multiprocessing import Process, Queue
from flask import Flask,request, send_from_directory, jsonify
from flask_cors import cross_origin
import os, traceback
import time
from werkzeug.utils import secure_filename
from werkzeug.datastructures import CombinedMulti... |
__author__ = "Ian Goodfellow"
"""
Exceptions related to datasets
"""
class EnvironmentVariableError(Exception):
""" An exception raised when a required environment variable is not defined """
def __init__(self, *args):
super(EnvironmentVariableError,self).__init__(*args)
class NoDataPathError(Environ... |
from knack.help_files import helps # pylint: disable=unused-import
# pylint: disable=line-too-long, too-many-lines
helps['config'] = """
type: group
short-summary: Manage Azure CLI configuration.
long-summary: Available since Azure CLI 2.10.0.
"""
helps['config set'] = """
type: command
short-summary: Set a configur... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases() # NOQA
import chainer
from chainerrl.agents import dqn
class DoubleDQN(dqn.DQN):
"""Double ... |
from codecs import open # To use a consistent encoding
from os import path
from setuptools import setup
HERE = path.dirname(path.abspath(__file__))
# Get version info
ABOUT = {}
with open(path.join(HERE, 'datadog_checks', 'gnatsd_streaming', '__about__.py')) as f:
exec(f.read(), ABOUT)
# Get the long descripti... |
import hashlib
import time
from Tribler.Core.Utilities.encoding import encode
from Tribler.community.market.core.message import TraderId, MessageNumber, MessageId, Message
from Tribler.community.market.core.order import OrderId, OrderNumber, Order
from Tribler.community.market.core.price import Price
from Tribler.comm... |
from tests import BaseTestCase, authenticated_user
from redash import redis_connection
from redash.models import User, db
from redash.utils import dt_from_timestamp
from redash.models.users import (
sync_last_active_at,
update_user_active_at,
LAST_ACTIVE_KEY,
)
class TestUserUpdateGroupAssignments(BaseTe... |
"""
CartoDB Spatial Analysis Python Library
See:
https://github.com/CartoDB/crankshaft
"""
from setuptools import setup, find_packages
setup(
name='crankshaft',
version='0.0.0',
description='CartoDB Spatial Analysis Python Library',
url='https://github.com/CartoDB/crankshaft',
author='Data Ser... |
"""
Sender
------
Sender is easy
``````````````
.. code:: python
from sender import Mail
mail = Mail()
mail.send_message("Hello", fromaddr="<EMAIL>",
to="<EMAIL>", body="Hello world!")
Install
```````
.. code:: bash
$ pip install sender
Links
`````
* `documentation <h... |
import datetime as dt
import lxml.html
import urllib
import re
from billy.scrape.bills import BillScraper, Bill
from billy.scrape.utils import url_xpath
subjects = None
bill_subjects = None
MAXQUERY=250 # What a silly low number. This is just putting more load on the
# server, not even helping with that. Shees... |
from satosa.internal_data import InternalResponse, AuthenticationInformation
from satosa.micro_services.attribute_generation import AddSyntheticAttributes
from satosa.exception import SATOSAAuthenticationError
from satosa.context import Context
class TestAddSyntheticAttributes:
def create_syn_service(self, synthet... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
SagaGroupNameDecorator.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
****************... |
"""
Read a cophenetic matrix
"""
import os
import sys
import argparse
import gzip
def pairwise_distances(matrixfile):
"""
Read the matrix file and return a hash of all distances
:param treefile: The cophenetic matrix file to read
:return: a dict of each entry and its distances
"""
global verb... |
# -*- coding: utf-8 -*-
"""Common docstring snippets for plot.
"""
BASE_PLOT_DOCSTRING = \
"""Plot the signal at the current coordinates.
For multidimensional datasets an optional figure,
the "navigator", with a cursor to navigate that data is
raised. In any case it is possible to navigat... |
"""Config flow for Smappee."""
import logging
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_HOST, CONF_IP_ADDRESS
from homeassistant.helpers import config_entry_oauth2_flow
from . import api
from .const import (
CONF_HOSTNAME,
CONF_SERIALNUMBER,
DO... |
import snappy
from skadi import *
from skadi import index
from skadi.io import protobuf
from skadi.protoc import demo_pb2 as pb_d
IMPL_BY_KIND = {
pb_d.DEM_Stop: pb_d.CDemoStop,
pb_d.DEM_FileHeader: pb_d.CDemoFileHeader,
pb_d.DEM_FileInfo: pb_d.CDemoFileInfo,
pb_d.DEM_SendT... |
"""Provides a set of functions nad clases for different purpose."""
import logging
from logging.handlers import WatchedFileHandler
import socket
import codecs
import time
import re
import os
import yaml
def delegate(attribute_name, method_names):
"""Pass the call to the attribute called attribute_name for every ... |
import time
class Timer(object):
"""A simple timer."""
def __init__(self):
self.total_time = 0.
self.calls = 0
self.start_time = 0.
self.diff = 0.
self.average_time = 0.
self.skip_times = 0
def tic(self):
# using time.time instead of time.clock becau... |
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.9.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# ... |
from sys import stdout
import time
def asctime(t=None):
"""
Converts the 8-tuple which contains:
(year, month, mday, hour, minute, second, weekday, yearday)
into a string in the form:
'Sun Sep 16 01:03:52 1973\n'
"""
t = list(t or time.lcaltime())
month_name = [
"Jan", "Feb", ... |
'''
`Frida <http://www.frida.re>`_ based controllers for server fuzzing.
'''
from __future__ import absolute_import
import frida
from kitty.controllers.base import BaseController
class FridaLaunchServerController(BaseController):
'''
This controller uses frida to launch an application.
You can pass JS scr... |
import json
import os
import shutil
import tarfile
import time
import traceback
import zipfile
from datetime import datetime
from threading import RLock
import re
from couchpotato.api import addApiView
from couchpotato.core.event import addEvent, fireEvent, fireEventAsync
from couchpotato.core.helpers.encoding import ... |
import numpy as np
def mov_av(t,x,l,type_av="t"):
""" mov_av returns the moving average of a time series.
If type_av="n":
For each data point, it makes the average on l points, i.e. enter in the average: the (l-1)/2 data points before, the (l-1)/2 data points after, and the current data point. l must then be o... |
import hashlib
import os
import logging
import tempfile
from pathlib import Path
from unittest.mock import patch
import numpy as np
import pytest
import hyperspy.api as hs
from hyperspy.signals import Signal1D
FULLFILENAME = Path(__file__).resolve().parent.joinpath("test_io_overwriting.hspy")
class TestIOOverwrit... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1', 'statu... |
from __future__ import unicode_literals, print_function, division
__author__ = 'dongliu'
# read and parse pcap file
# see http://wiki.wireshark.org/Development/LibpcapFileFormat
import sys
import struct
class PcapFile(object):
def __init__(self, infile, head):
self.infile = infile
self.byteorder... |
from pyramid.config import Configurator
import blue_yellow_app.controllers.home_controller as home
import blue_yellow_app.controllers.albums_controller as albums
import blue_yellow_app.controllers.account_controller as account
def main(_, **settings):
config = Configurator(settings=settings)
init_includes(co... |
import atexit
import os
import shutil
import tempfile
# Put gen_py cache in temp directory.
supportdir = tempfile.mkdtemp()
# gen_py has to be put into directory 'gen_py'.
genpydir = os.path.join(supportdir, 'gen_py')
# Create 'gen_py' directory. This directory does not need
# to contain '__init__.py' file.
try:
... |
#!/usr/bin/python
import commondns
import hashlib
dnssec_status = {
"GETDNS_DNSSEC_SECURE" : 400,
"GETDNS_DNSSEC_BOGUS" : 401,
"GETDNS_DNSSEC_INDETERMINATE" : 402,
"GETDNS_DNSSEC_INSECURE" : 403,
"GETDNS_DNSSEC_NOT_PERFORMED" : 404
}
def buildOtrFingerprintHostname(jid):
"""
Build the hos... |
import copy
from db.versions.v0_9_4.domain import DBVistrail, DBAction, DBTag, DBModule, \
DBConnection, DBPortSpec, DBFunction, DBParameter, DBLocation, DBAdd, \
DBChange, DBDelete, DBAnnotation, DBPort, DBGroup, \
DBWorkflow, DBLog, DBAbstraction
def translateVistrail(_vistrail):
def update_workflow(... |
from slicc.ast.AST import *
# actual ASTs
from slicc.ast.ActionDeclAST import *
from slicc.ast.AssignStatementAST import *
from slicc.ast.CheckAllocateStatementAST import *
from slicc.ast.DeclAST import *
from slicc.ast.DeclListAST import *
from slicc.ast.EnqueueStatementAST import *
from slicc.ast.EnumDeclAST import ... |
import version
import commands
import json
class cached(version.version_info):
def __init__(self, base):
with open(".vcsversion", "r") as versioninfo:
_versions = json.load(versioninfo)
self.revno = _versions['revno']
self.revision_id = _versions['revision_id']
self.r... |
import os
import sipconfig
import PyQt4.pyqtconfig as pyqtconfig
import sys
import getopt
import glob
opt_static=0
opt_debug=0
opt_generate_code=1
class FreezerModuleMakefile(pyqtconfig.QtCoreModuleMakefile):
"""The Makefile class for modules that %Import QtXml.
"""
def __init__(self, *args, **kw):
... |
import numpy
import six
import chainer
from chainer import backend
from chainer import utils
import chainerx
def assert_allclose(x, y, atol=1e-5, rtol=1e-4, verbose=True):
"""Asserts if some corresponding element of x and y differs too much.
This function can handle both CPU and GPU arrays simultaneously.
... |
import boto3
import mxnet as mx
import os
import numpy as np
import logging
from mxnet import gluon
from mxnet.gluon import nn
import re
from mxnet.test_utils import assert_almost_equal
def cmp(x, y): # Python 3
return (x > y) - (x < y)
# Set fixed random seeds.
mx.random.seed(7)
np.random.seed(7)
logging.basic... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('candidates', '0034_add_can_edit_settings_group'),
]
operations = [
migrations.AlterField(
model_name='sitesettin... |
from setuptools import setup
version = "1.4.38"
setup(name='MAVProxy',
version=version,
zip_safe=True,
description='MAVProxy MAVLink ground station',
long_description='''A MAVLink protocol proxy and ground station. MAVProxy
is oriented towards command line operation, and is suitable for embedd... |
"""
Test for allantools (https://github.com/aewallin/allantools)
Stable32 was used to calculate the deviations we compare against.
The 5071A_phase.txt is a dataset collected with a time-interval-counter
between 1 pulse-per-second outputs from a 5071A Cs clock against a H-maser
first datapoint 13911... |
"""
Test unit for the miscutil/mailutils module.
"""
import os
import sys
from base64 import encodestring
from flask import current_app
from invenio_ext.email import send_email
from invenio_testing import InvenioTestCase
from mock import patch
import pkg_resources
from six import StringIO, iteritems
def _rem... |
from KicadModTree import * # NOQA
def add_bump(m, anchor_pos, bump_length, bump_width, direction, layer, width, offset=(0, 0)):
if direction == 'up':
delta_x = bump_length
delta_y = -bump_width
start_x = anchor_pos[0]
start_y = anchor_pos[1] - offset[1]
elif direction == 'down... |
import warnings
from django.conf.urls.defaults import *
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from tastypie.exceptions import NotRegistered, BadRequest
from tastypie.serializers import Serializer
from tastypie.utils impo... |
from array import array
import matplotlib.pyplot as plt
def main():
avg = 0
samples = 0
values = []
# Get alpha
alpha = int(input("IIR alpha (0..255): "))
# Check alpha bounds
if (alpha > 255):
print ('Setting alpha to 255')
alpha = 255
if (alpha < 0):
print ('... |
import re
from ..URLBase import URLBase
from ..common import NotifyType
from ..common import NOTIFY_TYPES
from ..common import NotifyFormat
from ..common import NOTIFY_FORMATS
from ..common import OverflowMode
from ..common import OVERFLOW_MODES
from ..AppriseLocale import gettext_lazy as _
from ..AppriseAttachment im... |
from selenium.webdriver import DesiredCapabilities, Firefox
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from splinter.driver.webdriver import (
BaseWebDriver, WebDriverElement as WebDriverElement)
from splinter.driver.webdriver.cookie_manager import CookieManager
from selenium.webdriver.co... |
# script to convert the newly generated Relative Humidity
def convert_to_hur( tas_arr, vap_arr ):
esa_arr = 6.112 * np.exp( 17.62 * tas_arr/ (243.12 + tas_arr) )
# esa_arr = 6.112 * np.exp( 22.46 * tas_arr / (272.62 + tas_arr) )
return vap_arr/esa_arr * 100
def convert_to_vap( tas_arr, hur_arr ):
''' create relati... |
from mantid.api import PythonAlgorithm, AlgorithmFactory, IMDHistoWorkspaceProperty, PropertyMode, WorkspaceProperty, Progress
from mantid.kernel import (Direction, EnabledWhenProperty, PropertyCriterion, Property, StringListValidator, FloatArrayBoundedValidator,
FloatArrayProperty, FloatBoun... |
import os
import urlparse
class url_process():
"""
所有关于url处理的函数
"""
#所有资源链接的文件后缀名
sorce_list = ['3GP', '7Z', 'AAC',' ACE', 'AIF', 'ARJ', 'ASF', 'AVI', 'BIN', 'BZ2', 'EXE', 'GZ', 'GZIP', 'IMG', 'ISO', 'LZH', 'M4A', 'M4V', 'MKV', 'MOV', 'MP3', 'MP4', 'MPA', 'MPE', 'MPEG', 'MPG', 'MSI', 'MSU', 'O... |
import os
import unittest
import itertools
import six
import IECore
import Gaffer
import GafferTest
import GafferDispatch
import GafferDispatchTest
class TaskNodeTest( GafferTest.TestCase ) :
def testTypeNamePrefixes( self ) :
self.assertTypeNamesArePrefixed( GafferDispatch )
def testDefaultNames( self ) :
... |
# -*- coding: utf-8 -*-
"""
This file is part of zoteromarkdown.
zoteromarkdown is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
zoteromark... |
"""
WSGI config for heap_todo project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`... |
"""Autograph compiles Python code into equivalent TensorFlow code.
Equivalent here means that they have the same effect when executed.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# TODO(mdan): Bring only the relevant symbols to the top level.
from ... |
"""MCMC-Gibbs for SPGP.
Author:
Ilias Bilionis
Date:
3/11/2013
"""
__all__ = ['SPGPMCMCGibbs']
import numpy as np
import math
#import matplotlib.pylab as plt
class SPGPMCMCGibbs(object):
"""MCMC-Gibbs for SPGP."""
# The target distribution
_target = None
# The proposal
_proposal = ... |
from osv import osv
from osv import fields
class hr_employee(osv.osv):
_name = 'hr.employee'
_inherit = 'hr.employee'
_columns = {# Calendario del empleado
'hr_employee_calendar_ids':fields.one2many('hr.employee.calendar','employee_id','Calendars'),
}
hr_employ... |
import sys
if len(sys.argv) != 2:
print "Syntax: sympler_viewer.py <input-filename>"
sys.exit(1)
print "Loading os, gtk, gtk.glade, gobject and glob."
import os
import gtk
import gtk.glade
import gobject
import glob
print "Loading vtk. This may take a while."
import vtk
from vtk.util.colors import *
from... |
class RAW(object):
"""
RAW GCodes for Marlin/FABtotum version.
GCode list take from:
http://forum.fabtotum.cc/showthread.php?1364-Supported-Gcodes
"""
def __init__(self, output):
self.output = output
def COMMENT(self, comment):
self.output.write('; ' + comment)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.