repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
effigies/mne-python | mne/io/write.py | Python | bsd-3-clause | 14,593 | 0.001576 | # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Matti Hamalainen <msh@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)
from ..externals.six import string_types, b
import time
import numpy as np
from scipy import linalg
import os.path as op
import re
import uuid
from .constants impor... | ession level 9, which is barely smaller but much
# slower. 2 offers a good compromise.
fid = gzip_open(fname, "wb", compresslevel=2)
else:
logger.debug('Writing using normal I/O')
fid = open(fname, "wb")
else:
logger.debug('Writing using %s I/O' % type... | he compulsory items
write_id(fid, FIFF.FIFF_FILE_ID, id_)
write_int(fid, FIFF.FIFF_DIR_POINTER, -1)
write_int(fid, FIFF.FIFF_FREE_LIST, -1)
return fid
def end_file(fid):
"""Writes the closing tags to a fif file and closes the file"""
data_size = 0
fid.write(np.array(FIFF.FIFF_NOP, dtype='>... |
hamedhsn/incubator-airflow | airflow/jobs.py | Python | apache-2.0 | 90,563 | 0.001391 | # -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | rocessing since the last heartbeat, it
will sleep 50 seconds to complete the 60 seconds and keep a steady
heart rate. If you go over 60 seconds before calling it, it won't
sleep at all.
'''
session = settings.Session()
job = session.query(BaseJob).filter_by(id=self.id).on... | b)
session.commit()
session.close()
if job.state == State.SHUTDOWN:
self.kill()
# Figure out how long to sleep for
sleep_for = 0
if job.latest_heartbeat:
sleep_for = max(
0,
self.heartrate - (datetime.now() - job.l... |
Kankroc/pdf2image | pdf2image/__init__.py | Python | mit | 106 | 0.009434 | """
__ | init__ of the pdf2image module
"""
from .pdf2image import convert_from_bytes, con | vert_from_path |
Bismarrck/tensorflow | tensorflow/python/keras/layers/simplernn_test.py | Python | apache-2.0 | 7,269 | 0.002339 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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 applic | able law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================... |
Thortoise/Super-Snake | Blender/animation_nodes-master/nodes/spline/splines_from_edges.py | Python | gpl-3.0 | 752 | 0.006649 | import bpy
from ... base_types.node import AnimationNode
from ... data_structures.splines.poly_spline import PolySpline
class SplinesFromEdgesNode(bpy.types.Node, AnimationNode):
bl_idname = "an_SplinesFromEdgesNode"
bl_label = "Splines from Edges"
def create(self):
self.newInput("Vector List", "V... | , "splines")
def execute(self, vertices, edgeIndices):
splines = []
for index1, index2 in edgeIndices:
spline = PolySpline.fro | mLocations([vertices[index1], vertices[index2]])
splines.append(spline)
return splines
|
malkavi/lutris | lutris/util/runtime.py | Python | gpl-3.0 | 1,774 | 0 | import os
from lutris.util import http
from lutris.util import extract
from lutris import settings
LOCAL_VERSION_PATH = os.path.join(settings.RUNTIME_DIR, "VERSION")
def parse_version(version_content):
try:
version = int(version_content)
except ValueError:
version = 0
return version
def... | ngs.RUNTIME_URL + runtime32_file, runtime32_path,
overwrite=True)
runtime64_path = os.path.j | oin(settings.RUNTIME_DIR, runtime64_file)
http.download_asset(settings.RUNTIME_URL + runtime64_file, runtime64_path,
overwrite=True)
extract.extract_archive(runtime32_path, settings.RUNTIME_DIR,
merge_single=False)
extract.extract_archive(runtime64_path, s... |
wehkamp/ansible | lib/ansible/plugins/action/fetch.py | Python | gpl-3.0 | 7,278 | 0.003572 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... | urn dict(failed=True, md5sum=new_md5, msg="checksum mismatch", file=source, dest=dest, remote_md5sum=None, checksum=new_checksum, remote_checksum=remote_checksum)
return dict(changed=True, md5sum=new_md5, dest=dest, remote_md5sum=None, checksum=new_checksum, r | emote_checksum=remote_checksum)
else:
# For backwards compatibility. We'll return None on FIPS enabled
# systems
try:
local_md5 = md5(dest)
except ValueError:
local_md5 = None
return dict(changed=False, md5sum=local_md... |
bbirand/python-driver | benchmarks/callback_full_pipeline.py | Python | apache-2.0 | 1,906 | 0.000525 | # Cop | yright 2013-2015 DataStax, Inc.
#
# 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.apa | che.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limi... |
AlexeyKruglov/Skeinforge-fabmetheus | skeinforge_application/skeinforge_plugins/analyze_plugins/statistic.py | Python | agpl-3.0 | 17,518 | 0.031225 | """
This page is in the table of contents.
Statistic is an extremely valuable analyze plugin to print and/or save the statistics of the generated gcode.
The statistic manual page is at:
http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Statistic
==Operation==
The default 'Activate Statistic' checkbox is on. Wh... | index.php/Skeinforge_Statistic')
self.activateStatistic = settings.BooleanSetting().getFromValue('Activate Statistic', self, True )
settings.LabelSeparator().getFromRepository(self)
settings.LabelDisplay().getFromName('- Cost -', self )
self.machineTime = settings.FloatSpin().getFromValue( 0.0, 'Machine Time ($... | ().getFromValue( 0.0, 'Material ($/kg):', self, 40.0, 20.0 )
settings.LabelSeparator().getFromRepository(self)
self.density = settings.FloatSpin().getFromValue( 500.0, 'Density (kg/m3):', self, 2000.0, 930.0 )
self.fileNameInput = settings.FileNameInput().getFromFileName( [ ('Gcode text files', '*.gcode') ], 'Ope... |
jason-neal/companion_simulations | tests/utilities/test_spectrum_utils.py | Python | mit | 1,224 | 0.000817 | import os
import numpy as np
import pytest
from spectrum_overload import Spectrum
from mingle.utilities.spectrum_utils import load_spectrum, select_observation
@pytest.mark.parametrize("fname", ["HD30501-1-mixavg-tellcorr_1.fits", "HD30501-1-mixavg-h2otellcorr_1.fits"])
def test_load_spectrum(fname):
fname = os... | tion("HD30501", "1", chip)
@pytest.mark.xfail()
de | f test_spectrum_plotter(spectra, label=None, show=False):
"""Plot a Spectrum object."""
assert False
@pytest.mark.xfail()
def test_plot_spectra(obs, model):
"""Plot two spectra."""
assert False
|
zuosc/PythonCode | OOP/subclass.py | Python | mit | 378 | 0.002717 | # !/usr/bin/env python3
# _*_ coding:utf8 _*_
# Power by zuosc 2016-10-23
'su | bclass demo 继承和多态'
class Animal(object):
def run(self):
print('Animal is running......')
class Dog(Animal):
def run(self):
print('Dog is running.....')
def eat(self):
print('dog | is eating......')
class Cat(Animal):
pass
dog = Dog()
dog.run() |
yohell/msaview | msaview_plugin_disopred/__init__.py | Python | mit | 4,493 | 0.004229 | """MSAView - Disopred support.
Copyright (c) 2011 Joel Hedlund.
Contact: Joel Hedlund <yohell@ifm.liu.se>
MSAView is a modular, configurable and extensible package for analysing and
visualising multiple sequence alignments and sequence features.
This package provides support for parsing dispored result files (mus... | ntial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES O... | HER DEALINGS IN
THE SOFTWARE.
"""
__version__ = "0.9.0"
import os
from msaview import action
from msaview.options import Option
from msaview.features import (SequenceFeature,
make_regions,
map_region_to_msa)
class DisopredPrediction(object):
def __in... |
Panos512/invenio | modules/bibclassify/lib/bibclassify_daemon.py | Python | gpl-2.0 | 15,602 | 0.006858 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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 2 of the
## Licens... | cords belonging to
the given collection."""
rec_onts = []
# User specified record IDs.
if recids:
rec_onts.append({
'ontology': taxonomy,
'collection': None,
'recIDs': recids,
})
return rec_onts
# User specified collections.
if collec... | rec_onts.append({
'ontology': taxonomy,
'collection': collection,
'recIDs': records
})
return rec_onts
# Use rules found in collection_clsMETHOD.
result = run_sql("SELECT clsMETHOD.name, clsMETHOD.last_updated, "
... |
grigouze/gandi.cli | gandi/cli/tests/fixtures/_operation.py | Python | gpl-3.0 | 5,786 | 0 | try:
# python3
from xmlrpc.client import DateTime
except ImportError:
# python2
from xmlrpclib import DateTime
type_list = list
def list(options):
ret = [{'date_created': DateTime('20150915T18:29:16'),
'date_start': None,
'date_updated': DateTime('20150915T18:29:17'),
... | 'product_type': 'corporate',
'quantity': ''},
'la | st_error': None,
'params': {'amount': 50.0,
'auth_id': 99999999,
'param_type': 'prepaid_add_money',
'prepaid_id': 100000,
'remote_addr': '127.0.0.1',
'tracker_id': 'ab0e5e67-6ca7-4afc-8311-f200... |
smarr/RTruffleSOM | src/som/interpreter/ast/nodes/specialized/to_do_node.py | Python | mit | 3,664 | 0.003821 | from rpython.rlib import jit
from ..expression_node import ExpressionNode
from .....vmobjects.block_ast import AstBlock
from .....vmobjects.double import Double
from .....vmobjects.integer import Integer
from .....vmobjects.method_ast import AstMethod
class AbstractToDoNode(ExpressionNode):
_immutable_fields_ ... | hod | = body_block.get_method()
i = rcvr.get_embedded_integer()
top = limit.get_embedded_integer()
while i <= top:
int_driver.jit_merge_point(block_method = block_method)
block_method.invoke(body_block, [self._universe.new_integer(i)])
i += 1
@staticmethod
... |
syscoin/syscoin | test/functional/mempool_resurrect.py | Python | mit | 2,589 | 0.001931 | #!/usr/bin/env python3
# Copyright (c) 2014-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test resurrection of mined transactions when the blockchain is re-organized."""
from test_framework.bl... | # Spend block 1/2/3's coinbase transactions
# Mine a block
# Create three more transactions, spen | ding the spends
# Mine another block
# ... make sure all the transactions are confirmed
# Invalidate both blocks
# ... make sure all the transactions are put back in the mempool
# Mine a new block
# ... make sure all the transactions are confirmed again
blocks = [... |
joke2k/faker | faker/utils/datasets.py | Python | mit | 535 | 0 | import operator
from collections import Counter
from functools import reduce
from typing import Dict, Tuple
def add_dicts(*args: Tuple[Dict, ...]) -> Dict:
"""
Adds two or more dicts together. Common keys will have their values added.
| For example::
>>> t1 = {'a':1, 'b':2}
>>> t2 = {'b':1, 'c':3}
>>> t3 = {'d':4}
>>> add_dicts(t1, t2, t3)
{'a': 1, 'c': 3, 'b': 3, | 'd': 4}
"""
counters = [Counter(arg) for arg in args]
return dict(reduce(operator.add, counters))
|
davidam/python-examples | nlp/ethnicolr/ethnicolr-example.py | Python | gpl-3.0 | 339 | 0 | #!/usr/bi | n/python
# -*- coding: utf-8 -*-
import pan | das as pd
from ethnicolr import census_ln, pred_census_ln
names = [{'name': 'smith'},
{'name': 'zhang'},
{'name': 'jackson'}]
df = pd.DataFrame(names)
print(df)
print(census_ln(df, 'name'))
print(census_ln(df, 'name', 2010))
print(pred_census_ln(df, 'name'))
|
Kromey/akwriters | api/utils.py | Python | mit | 1,500 | 0.001333 | import json
from django.http import HttpResponse
from django.utils.cache import add_never_cache_headers
class ApiResponse(HttpResponse):
"""JSON-encoded API response
I've arbitrarily decided that the API uses JSON responses. To ease the
encoding process and to ensure that the correct Content-Type is se... | .
The decorated method is expected to return a Python object that can be
encoded into JSON; it will then be magically transformed into one that
returns properly-encoded JSON."""
def wrapper(*args, **kwargs):
data = {
"meta": {
| "status": "OK",
},
"response": {}
}
try:
data["response"] = method(*args, **kwargs)
except Exception as e:
data["meta"]["status"] = "ERR"
data["meta"]["error"] = str(e)
response = ApiResponse(dat... |
oscarmcm/django-places | places/widgets.py | Python | mit | 1,789 | 0 | # -*- coding: utf-8 -*-
from django.forms import widgets
from django.template.loader import render_to_string
from django.utils.translation import gettext_lazy as _
from .conf import settings
class PlacesWidget(widgets.MultiWidget):
template_name = 'places/widgets/places.html'
def __init__(self, attrs=None)... | braries=places'.format(
settings.MAPS_API_KEY
),
'places/places.js',
)
| css = {'all': ('places/places.css',)}
|
joshrule/LOTlib | LOTlib/Inference/GrammarInference/SimpleGrammarHypothesis.py | Python | gpl-3.0 | 3,106 | 0.009981 | import numpy as np
from copy import deepcopy
from scipy.misc import logsumexp
from scipy.stats import binom
from LOTlib.Miscellaneous import sample1, self_update
from LOTlib.Hypotheses.Stochastics import *
class SimpleGrammarHypothesis(Hypothesis):
"""
A simple example of grammar inference that *only* fits gra... | s)
L = numpy.array(L)
self_update(self,locals())
self.N_groups = len(GroupLength)
self.nts = Counts.keys() # all nonterminals
self.nrules = { nt: Counts[nt].shape[1] for nt in self.nts} # number of rules for each nonterminal
self.N_hyps = Counts[self.nts[0]].s | hape[0]
if value is None:
value = { nt: GibbsDirchlet(alpha=np.ones(self.nrules[nt]), proposal_scale=1000.) for nt in self.nts }
Hypothesis.__init__(self, value=value) # sets the value
@attrmem('likelihood')
def compute_likelihood(self, data, **kwargs):
# The likelihood of... |
luanrafael/pygame-site | FlaskApp/src/views/__init__.py | Python | mit | 189 | 0 | ''''
This module is intended to contain the blueprints o | f the project
if you want more information about blue | prints you can checkout this link:
http://flask.pocoo.org/docs/blueprints/
'''
|
eevee/sanpera | doc/conf.py | Python | isc | 7,742 | 0.007492 | # -*- coding: utf-8 -*-
#
# sanpera documentation build configuration file, created by
# sphinx-quickstart2 on Sat May 12 21:24:07 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | tter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Defau | lt is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which... |
cjbe/artiqDrivers | artiqDrivers/frontend/rohdeSynth_controller.py | Python | gpl-3.0 | 1,342 | 0.00149 | #!/usr/bin/env python3.5
import argparse
import sys
from artiqDrivers.devices.rohdeSynth.driver import RohdeSynth
from sipyco.pc_rpc import simple_server_loop
from sipyco.common_args import simple_network_args, init_logger_from_args
from oxart.tools import add_common_args
def get_argparser():
parser = argparse.... | help="Put the driver in simulation mode, even if "
"--ipaddress is used.")
simple_network_args(parser, 4004)
add_common_args( | parser)
return parser
def main():
args = get_argparser().parse_args()
init_logger_from_args(args)
if not args.simulation and args.ipaddr is None:
print("You need to specify either --simulation or -i/--ipaddr "
"argument. Use --help for more information.")
sys.exit(1)
... |
googleapis/python-service-management | samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_sync.py | Python | apache-2.0 | 1,564 | 0.000639 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | matically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-service-management
# [START servicemanagement_v1_generated_ServiceManager_CreateService_... | e.cloud import servicemanagement_v1
def sample_create_service():
# Create a client
client = servicemanagement_v1.ServiceManagerClient()
# Initialize request argument(s)
request = servicemanagement_v1.CreateServiceRequest(
)
# Make the request
operation = client.create_service(request=req... |
Parsl/parsl | parsl/tests/test_monitoring/test_db_locks.py | Python | apache-2.0 | 2,848 | 0 | import logging
import os
import parsl
import pytest
import time
logger = logging.getLogger(__name__)
@parsl.python_app
def this_app():
return 5
@pytest.mark.local
def test_row_counts():
from parsl.tests.configs.htex_local_alternate import fresh_config
import sqlalchemy
if os.path.exists("runinfo/mo... | a SELECT in it.
# The lock will be held until the end of the transaction.
# (see bottom of https://sqlite.org/lockingv3.html)
logger.info("Getting a read lock on the monitoring database")
| with engine.begin() as readlock_connection:
readlock_connection.execute("BEGIN TRANSACTION")
result = readlock_connection.execute("SELECT COUNT(*) FROM workflow")
(c, ) = result.first()
assert c == 1
# now readlock_connection should have a read lock that will
# stay lo... |
bird-house/flyingpigeon | flyingpigeon/nc_statistic.py | Python | apache-2.0 | 10,385 | 0.002215 | from flyingpigeon.nc_utils import get_values, get_coordinates, get_index_lat, get_variable
from os.path import basename, join
from datetime import datetime as dt
from shutil import copyfile
from netCDF4 import Dataset
import numpy as np
import logging
LOGGER = logging.getLogger("PYWPS")
def fieldmean(resource):
... | LOGGER.debug(data.shape)
if len(data.shape) == 3:
# TODO if data.shape == 2 , 4 ...
lats, lons = get_coordinates(resource, unrotate=False)
lats = array(lats)
if len(lats.shape) == 2:
lats = lats[:, 0]
else:
LOGGER.debug('Latitudes not reduced to 1D... | ole coordinates)
# lats, lons = get_coordinates(resource, unrotate=False)
# if len(lats.shape) == 2:
# lats, lons = get_coordinates(resource)
lat_index = get_index_lat(resource)
LOGGER.debug('lats dimension %s ' % len(lats.shape))
LOGGER.debug('lats index %s' % lat_i... |
statik/grr | lib/aff4_objects/reports.py | Python | apache-2.0 | 8,500 | 0.007529 | #!/usr/bin/env python
"""Module containing a set of reports for management of GRR."""
import csv
import datetime
import StringIO
import time
import logging
from grr.lib import config_lib
from grr.lib import email_alerts
from grr.lib import export_utils
from grr.lib import rdfvalue
from grr.lib import registry
from g... | ClientReportIterator, self).__init__(**kwargs)
self.report_attrs = report_attrs
self.extended_report_attrs = extended_report_attrs
def IterFunction(self, client, out_queue, unused_token):
"""Extract report attributes."""
result = {}
for attr in self.report_attrs:
# Do some special formattin... | GRR client":
c_info = client.Get(attr)
if not c_info:
self.broken_subjects.append(client.client_id)
result[attr.name] = None
continue
result[attr.name] = "%s %s" % (c_info.client_name,
str(c_info.client_version))
else:
... |
ThatSnail/impede | impede-app/server/py/wire.py | Python | mit | 2,414 | 0.000414 |
""" A component that designates a wire. """
from graph import Node, Edge
from constraint import Constraint
class Wire(object):
""" Wire component """
def __init__(self, graph, node_a=None, node_b=None, edge_i=None):
""" Initializes a wire with two nodes. Current goes from
A to B. If nodes /... | if not node_a:
node_a = Node(graph)
if not node_b:
node_b = Node(graph)
if not edge_i:
edge_i = Edge(graph, node_a, node_b)
self._node_a = node_a
self._node_b = node_b
self._edge_i = edge_i
def node_a(self):
""" Returns node A.... | Returns node B.
Returns:
Node object
"""
return self._node_b
def edge_i(self):
""" Returns the edge that stores current from A to B.
Returns:
Edge object
"""
return self._edge_i
def substitutions(self):
""" Return a dict... |
jpardobl/monscale | monscale/management/commands/trap_worker.py | Python | bsd-3-clause | 654 | 0.009174 | import l | ogging, redis, time
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from monscale.rules import evaluate_traps
class Command(BaseCommand):
args = ''
help = 'Retrieve queued actions and execute them.'
def handle(self, *args, **options):
# logging.bas... | gging.debug("[trap_worker] going to sleep for %ss" % settings.ACTION_WORKER_SLEEP_SECS)
time.sleep(settings.ACTION_WORKER_SLEEP_SECS)
|
JoeJasinski/WindyTransit | mobiletrans/mtimport/management/commands/mt_import_zipcodes.py | Python | mit | 714 | 0.007003 | import os
from django.core.management.b | ase import BaseCommand, CommandError
from django.conf import settings
from mobiletrans.mtimport.importers import importer_zipcode as importer
class Command(BaseCommand):
args = '<zipcodes.kml>'
help = 'Import Routes'
def handle(self, input_file_path="", **options):
if not input_file_path:
... | importer.Zipcode.data_import(input_file_path)
print input_file_path
self.stdout.write('Import completed with status: %s\n' % input_record.get_status_display())
|
HydrelioxGitHub/home-assistant | homeassistant/components/vacuum/demo.py | Python | apache-2.0 | 10,494 | 0 | """
Demo platform for the vacuum component.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/demo/
"""
import logging
from homeassistant.components.vacuum import (
ATTR_CLEANED_AREA, SUPPORT_BATTERY, SUPPORT_CLEAN_SPOT,
SUPPORT_FAN_SPEED, SUPPORT_LOC... | MO_VACUUM_STATE),
])
class DemoVacuum(VacuumDevice):
"""Representation of a demo vacuum."""
def __init__(self, name, supported_features):
"""Initialize the vacuum."""
self._name = name
self | ._supported_features = supported_features
self._state = False
self._status = 'Charging'
self._fan_speed = FAN_SPEEDS[1]
self._cleaned_area = 0
self._battery_level = 100
@property
def name(self):
"""Return the name of the vacuum."""
return self._name
... |
rahulunair/nova | nova/tests/functional/api_sample_tests/test_shelve.py | Python | apache-2.0 | 2,812 | 0 | # Copyright 2012 Nebula, Inc.
# Copyright 2013 IBM Corp.
#
# 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... | st_server_action(self, uuid, template, action):
response = self._do_post('servers/%s/action' % uuid,
template, {'a | ction': action})
self.assertEqual(202, response.status_code)
self.assertEqual("", response.text)
def test_shelve(self):
uuid = self._post_server()
self._test_server_action(uuid, 'os-shelve', 'shelve')
def test_shelve_offload(self):
uuid = self._post_server()
sel... |
arangodb/arangodb | 3rdParty/jemalloc/v5.2.1/scripts/gen_travis.py | Python | apache-2.0 | 8,683 | 0.001497 | #!/usr/bin/env python3
from itertools import combinations, chain
from enum import Enum, auto
LINUX = 'linux'
OSX = 'osx'
WINDOWS = 'windows'
AMD64 = 'amd64'
ARM64 = 'arm64'
PPC64LE = 'ppc64le'
TRAVIS_TEMPLATE = """\
# This config file is generated by ./scripts/gen_travis.py.
# Do not edit by hand.
# We use 'min... | tion',
'-Wno-ignored-attributes'
]
if os == OSX:
extra_cflags += [
'-Wno-deprecated-declarations',
]
return extra_cflags
# Formats a job from a combination of flags
def format_job(os, arch, combination):
compilers = [x.value for x in combination if x.type ==... | [x.value for x in combination if x.type == Option.Type.COMPILER_FLAG]
configure_flags = [x.value for x in combination if x.type == Option.Type.CONFIGURE_FLAG]
malloc_conf = [x.value for x in combination if x.type == Option.Type.MALLOC_CONF]
features = [x.value for x in combination if x.type == Option.Type.F... |
piskvorky/pattern | pattern/__init__.py | Python | bsd-3-clause | 2,453 | 0.004892 | #### PATTERN ########################################################################## | #############
# Author: Tom De Smedt <tom@organisms.be>
# License: BSD License, see LICENSE.txt
# | Copyright (c) 2010 University of Antwerp, Belgium
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, thi... |
mikn/autobot | setup.py | Python | mit | 648 | 0 | from setuptools import setup, find_packages
with open('requirements.txt') as reqs:
inst_reqs = reqs.read().split('\n')
setup(
name='autobot',
version='0.1.0',
packages=find_packages(),
author='M | ikael Knutsson',
author_email='mikael.knutsson@gmail.com',
description='A bot framework made according to actual software principles',
long_descript | ion=open('README.md').read(),
classifiers=['License :: OSI Approved :: BSD License'],
install_requires=inst_reqs,
entry_points={
'console_scripts': ['autobot = autobot.main:main',
'autobot_init = autobot.init:main']
}
)
|
resmo/cloudstack | test/integration/plugins/nuagevsp/test_nuage_vpc_internal_lb.py | Python | apache-2.0 | 123,514 | 0 | # 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 u... | "" Component tests for VPC Internal Load Balancer functionality with
Nuage VSP SDN plugin
"""
# Import Local Modules
from nuageTestCase import nuageTestCase
from marvin.lib.base import (Account,
ApplicationLoadBalancer,
Network,
Rout... |
# Import System Modules
from nose.plugins.attrib import attr
import copy
import time
class TestNuageInternalLb(nuageTestCase):
"""Test VPC Internal LB functionality with Nuage VSP SDN plugin
"""
@classmethod
def setUpClass(cls):
super(TestNuageInternalLb, cls).setUpClass()
return
... |
rkojedzinszky/thermo-center | heatcontrol/migrations/0016_heatcontrol_profile_end_null.py | Python | bsd-3-clause | 473 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-12-27 09:40
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('heatcontrol', '0015_heatcontrol_prof | ile_add_holes'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='end',
field=models.TimeField(blank=True, nul | l=True),
),
]
|
benjyw/pants | src/python/pants/testutil/pants_integration_test.py | Python | apache-2.0 | 11,626 | 0.002752 | # Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import glob
import os
import subprocess
import sys
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Any, Itera... | lf.workdir)
return PantsResult(
command=self.command,
exit_code=self.process.returncode,
stdout=stdout.decode(),
stderr=stderr.decode(),
workdir=self.workdir,
pid=self.process.pid,
)
def run_pants_with_workdir_without_waiting(
... | rmetic: bool = True,
use_pantsd: bool = True,
config: Mapping | None = None,
extra_env: Mapping[str, str] | None = None,
print_stacktrace: bool = True,
**kwargs: Any,
) -> PantsJoinHandle:
args = [
"--no-pantsrc",
f"--pants-workdir={workdir}",
f"--print-stacktrace={print_... |
guncoin/guncoin | test/functional/feature_nulldummy.py | Python | mit | 6,442 | 0.00652 | #!/usr/bin/env python3
# Copyright (c) 2016-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test NULLDUMMY softfork.
Connect to a single node.
Generate 2 blocks (save the coinbases for later).
G... | on")
test2tx = create_transaction(self.nodes[0], txid2, self.ms_address, amount=47)
trueDummy(test2tx)
| assert_raises_rpc_error(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, bytes_to_hex_str(test2tx.serialize_with_witness()), True)
self.log.info("Test 3: Non-NULLDUMMY base transactions should be accepted in a block before activation [431]")
self.block_submit(self.nodes[0], [test2tx], False, Tr... |
neosergio/hackatonqr | vote/models.py | Python | gpl-2.0 | 312 | 0.019231 | #-*- coding:utf-8 -*-
from django.db import models
# Create your models here.
class Candidate(models.Model):
name = models.CharField(max_length=250, verbose_name="Nombre de candid | ato")
votes = models.IntegerField(verbose_name="Cantidad de votos")
def __unicode__(self):
return | self.name + str(self.votes)
|
justyns/home-assistant | tests/components/test_weblink.py | Python | mit | 1,040 | 0 | """The tests for the weblink component."""
import unittest
from homeassistant.components import weblink
from tests.common import get_test_home_assistant
class TestComponentWeblink(unittest.TestCase) | :
"""Test the Weblink component."""
def setUp(self):
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self):
"""Stop everything tha | t was started."""
self.hass.stop()
def test_entities_get_created(self):
"""Test if new entity is created."""
self.assertTrue(weblink.setup(self.hass, {
weblink.DOMAIN: {
'entities': [
{
weblink.ATTR_NAME: 'My router',
... |
zhu327/forum | forum/admin.py | Python | mit | 1,293 | 0.001547 | # coding=utf-8
from django.contrib import admin
from forum.models import ForumUser, Plane, Node, Topic, Reply, Favorite, Notification, Transaction, Vote
class ForumUserAdmin(admin.ModelAdmin):
list_display = ('username', 'email', 'is_active', 'is_staff', 'date_joined')
search_fields = ('username', 'email', '... | search_fields = ('name',)
list_filter = ('created',)
class TopicAdmin(admin.ModelAdmin):
list_display = ('title', 'created')
search_fields = ('title', 'content')
list_filter = ('created',)
class ReplyAdmin(admin.ModelAdmin):
list_display = ('content', 'created')
search_fields = ('content'... | ster(Plane, PlaneAdmin)
admin.site.register(Node, NodeAdmin)
admin.site.register(Topic, TopicAdmin)
admin.site.register(Reply, ReplyAdmin)
admin.site.register(Favorite)
admin.site.register(Notification)
admin.site.register(Transaction)
admin.site.register(Vote)
|
wanghongjuan/meta-iotqa-1 | lib/oeqa/runtime/sensor/test_accel_bma222e.py | Python | mit | 2,499 | 0.008003 | """
@file test_accel_bma222e.py
"""
##
# @addtogroup soletta sensor
# @brief This is sensor test based on soletta app
# @brief test sensor bma222e on Galileo/MinnowMax
##
import os
import time
from oeqa.utils.helper import shell_cmd
from oeqa.oetest import oeRuntimeTest
from oeqa.runtime.sensor.EnvirSetup import Envir... | s/bus/i2c/devices; \
echo 0x19 >i2c-1/delete_device")
elif "Galileo" in output or "SDS" in output:
(status, output) = self.target.run(
"cd /sys/bus/i2c/devices; \
echo 0x19 >i2c-0/delete_device")
def test_Accel_... | ata!')
(status, output) = self.target.run(
"chmod 777 /opt/apps/test_accel_bma222e.fbp")
(status, output) = self.target.run(
"cd /opt/apps; ./test_accel_bma222e.fbp >re.log")
error = output
#check whether data collected
(status, o... |
benjyw/pants | src/python/pants/base/exiter_integration_test.py | Python | apache-2.0 | 1,213 | 0.003303 | # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE). |
import os
from pants.testutil.pants_integration_test import ensure_daemon, run_pants, setup_tmpdir
dir_layout = {
# This file is expected to fail to "compile" when run via `./pants run` due to a SyntaxError.
# Because the error itself contains unicode, it can exercise that error handling codepaths
# are... | if __name__ == '__main__':\n import sys¡",
os.path.join(
"exiter_integration_test_harness", "BUILD"
): "python_library()\npex_binary(name='bin', entry_point='main.py')",
}
@ensure_daemon
def test_unicode_containing_exception(use_pantsd: bool) -> None:
with setup_tmpdir(dir_layout) as tmpdir:
... |
lukesummer/vnpy | vn.trader/ctaAlgo/strategyAtrRsi.py | Python | mit | 9,927 | 0.004494 | # encoding: UTF-8
"""
一个ATR-RSI指标结合的交易策略,适合用在股指的1分钟和5分钟线上。
注意事项:
1. 作者不对交易盈利做任何保证,策略代码仅供参考
2. 本策略需要用到talib,没有安装的用户请先参考www.vnpy.org上的教程安装
3. 将IF0000_1min.csv用ctaHistoryData.py导入MongoDB后,直接运行本文件即可回测策略
"""
from ctaBase import *
from ctaTemplate import CtaTemplate
import talib
import numpy as np
###################... | ray = np.zeros(bufferSize) # K线最低价的数组
closeArray = np.zeros(bufferSize) # K线收盘价的数组
atrCount = 0 # 目前已经缓存了的ATR的计数
atrArray = np.z | eros(bufferSize) # ATR指标的数组
atrValue = 0 # 最新的ATR指标数值
atrMa = 0 # ATR移动平均的数值
rsiValue = 0 # RSI指标的数值
rsiBuy = 0 # RSI买开阈值
rsiSell = 0 # RSI卖开阈值
intraTradeHigh = 0 ... |
sumitb/cse537 | multiagent/multiAgents.py | Python | gpl-2.0 | 7,379 | 0.006234 | # multiAgents.py
# --------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to
# http://inst.ee... | :
"""
Your m | inimax agent (question 2)
"""
def getAction(self, gameState):
"""
Returns the minimax action from the current gameState using self.depth
and self.evaluationFunction.
Here are some method calls that might be useful when implementing minimax.
gameState.getLegalAc... |
0-wiz-0/psutil | psutil/tests/test_linux.py | Python | bsd-3-clause | 27,328 | 0.00022 | #!/usr/bin/env python
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Linux specific tests."""
import contextlib
import errno
import io
import os
import pprint
import re
import shutil
import socket
... | tlib.clo | sing(s):
return socket.inet_ntoa(
fcntl.ioctl(s.fileno(),
SIOCGIFADDR,
struct.pack('256s', ifname))[20:24])
def get_mac_address(ifname):
import fcntl
ifname = ifname[:15]
if PY3:
ifname = bytes(ifname, 'ascii')
s = socket.sock... |
tensorflow/tensorflow | tensorflow/python/tpu/tpu_embedding_v2_utils_test.py | Python | apache-2.0 | 4,791 | 0.004174 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | =======================
"""Tests for TPU Embeddings mid level API utils on TPU."""
from absl.testing import parameterized
from tensorflow.core.protobuf.tpu import tpu_embedding_configuration_pb2
from tensorflow.python.compat import v2_compat
from tensorflo | w.python.platform import test
from tensorflow.python.tpu import tpu_embedding_v2_utils
class TPUEmbeddingOptimizerTest(parameterized.TestCase, test.TestCase):
@parameterized.parameters(tpu_embedding_v2_utils.Adagrad,
tpu_embedding_v2_utils.Adam,
tpu_embedding... |
bmi-forum/bmi-pyre | pythia-0.8/packages/pulse/tests/signon.py | Python | gpl-2.0 | 867 | 0.00692 | #!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Michael A.G. Aivazis
# | California Institute of Technology
# (C) 1998-2005 All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
if __name__ == "__main__":
import pulse
from pulse import pulse as pulsemodule
print "copyright inf... | print
print "module information:"
print " file:", pulsemodule.__file__
print " doc:", pulsemodule.__doc__
print " contents:", dir(pulsemodule)
# version
__id__ = "$Id: signon.py,v 1.1.1.1 2005/03/08 16:13:57 aivazis Exp $"
# End of file
|
urrego093/proyecto_mv | applications/welcome/models/db.py | Python | gpl-3.0 | 4,097 | 0.01196 | # -*- coding: utf-8 -*-
#########################################################################
## This scaffolding model makes your app work on Google App Engine too
## File is released under public domain and you can use without limitations
#########################################################################
... | eger autoincrement' field
## Consult manual for more options, validators, etc.
##
## More API examples for controllers:
##
## >>> db.mytable.insert(myfield='value')
## >>> rows=db(db.mytable.myfield=='value').select(db.myta | ble.ALL)
## >>> for row in rows: print row.id, row.myfield
#########################################################################
## after defining tables, uncomment below to enable auditing
# auth.enable_record_versioning(db)
|
sirikata/scene-generator | scene.py | Python | bsd-2-clause | 4,096 | 0.00708 | import numpy
import cache
import open3dhub
def sirikata_bounds(boundsInfo):
minpt, maxpt = boundsInfo['bounds']
minpt, maxpt = numpy.copy(minpt), numpy.copy(maxpt)
center = boundsInfo['center']
center_distance = boundsInfo['center_farthest_distance']
# center the bounding box
minpt -... | self._metadata, self._mesh = open3dhub.path_to_mesh(self.path, cache=True)
def _get_mesh(self):
self._load_mesh()
return self._mesh
mesh = property(_get_mesh)
def _get_metadata(self):
if self._metadata is N | one:
self._metadata = cache.get_metadata(self.path)
return self._metadata
metadata = property(_get_metadata)
def _get_bounds_info(self):
if self._boundsInfo is None:
self._boundsInfo = cache.get_bounds(self.path)
return self._boundsInfo
boundsInfo =... |
ivanovmi/google-cli-tools | setup.py | Python | gpl-2.0 | 218 | 0 | #!/usr/bin/env python
# -- coding: utf-8 --
__author__ = 'michael'
import setuptools
try:
import multiprocessing # noqa
except ImportError:
pass
setuptools.setup(
setup_requires=['pbr'],
pbr=True) | ||
Akagi201/akcode | python/numpy/numpy_create.py | Python | gpl-2.0 | 3,554 | 0.012158 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
## NumPy提供了很多专门用于创建数组的函数
"""
arange()类似于内置函数range(),通过指定开始值、终值和步长创建表示等差数列的一维数组,注意所得到的结果数组不包含终值。
例如下面的程序创建开始值为0、终值为1、步长为0.1的等差数组,注意终值1不在数组中:
"""
import numpy as np
print np.arange(0, 1, 0.1)
"""
linspace()通过指定开始值、终值和元素个数创建表示等差数列的一维数组,可以通过endpoint参数指定是否包含终值,... | s()则将数组元素初始化为0,ones()将数组元素初始化为1。
下面创建一个长度为4、元素类型为浮点数的一维数组,并且元素全部初始化为0:
"""
print np.zeros(4, np.float)
print np.ones(4, np.float)
"""
使用frombuffer()、fromstring()、fromfile()等函数可以从字节序列或者文件创建数组
"""
s = "abcdefg | h"
"""
Python的字符串实际上是一个字节序列,每个字符占一个字节,因此如果从字符串s创建一个8bit的整数数组,
所得到的数组正好就是字符串中每个字符的ASCII编码
"""
print np.fromstring(s, dtype = np.int8)
"""
如果从字符串s创建16bit的整数数组,那么两个相邻的字节就表示一个整数,把字节98和字节97当作一个16位的整数,
它的值就是98*256+97 = 25185。可以看出16bit的整数是以低位字节在前(little-endian)的方式保存在内存中的
"""
print np.fromstring(s, dtype = np.int... |
Stanford-Online/edx-submissions | submissions/migrations/0002_auto_20151119_0913.py | Python | agpl-3.0 | 948 | 0.00211 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import submissions.models
class Migration(migrations.Migration):
dependencies = [
('submissions', '0001_initial'),
]
operations = [
migrations.CreateModel(
| name='ScoreAnnotation',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('annotation_type', models.CharField(max_length=255, db_index=True)),
('creator', submissions.models.AnonymizedUserIDFiel... | ('reason', models.TextField()),
('score', models.ForeignKey(to='submissions.Score')),
],
),
migrations.AlterField(
model_name='studentitem',
name='student_id',
field=submissions.models.AnonymizedUserIDField(),
),
]
|
chrisdrackett/django-support | support/functions.py | Python | bsd-3-clause | 187 | 0.016043 | from django.utils.importlib import i | mport_module
def function_from_string(string):
modu | le, func = string.rsplit(".", 1)
m = import_module(module)
return getattr(m, func) |
dwighthubbard/micropython-cloudmanager | cloudmanager/utility.py | Python | mit | 538 | 0.001859 | """
Basic utility functions
"""
import redislite
from .server import RDB | _FILE
def header(message, width=80):
header_message = '## ' + message | + ' '
end_chars = width - (len(message) + 4)
header_message += '#'*end_chars
print(header_message)
def connect_to_redis():
return redislite.Redis(dbfilename=RDB_FILE)
host = read_rc_config()["settings"].get('redis_server', '127.0.0.1')
port = read_rc_config()["settings"].get('redis_port', '18... |
cloudbase/heat2arm | heat2arm/parser/tests/hot/test_template.py | Python | apache-2.0 | 2,462 | 0 | # Copyright 2015 Cloudbase Solutions Srl
# All Rights Reserved.
#
# 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 r... | r parsing of Heat Templates.
"""
_field_names = HEAT_TEMPLATE_FIELDS
_function_application_test_data = COMPLETE_TEST_TEMPLATE
_re | source_parsing_test_data = COMPLETE_TEST_TEMPLATE
_template_parsing_test_data = [
TemplateParsingTestInput(
"test empty template",
"",
TemplateDataException
),
TemplateParsingTestInput(
"test invalid JSON",
"some : [random] _ ness ... |
nealzhang/util | FastBloomFilter.py | Python | lgpl-3.0 | 2,828 | 0.02157 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from FastBitSet import FastBitSet
import math
import mmh3
class FastBloomFilter(object):
mask32 = 0xffffffff
mask64 = 0xffffffffffffffff
mask128 = 0xffffffffffffffffffffffffffffffff
seeds = [2, 3, 5, 7, 11,
13, 17, 19, 23, 29, ... | 443, 449, 457, 461, 463,
467, 479, 487, 491, 499,
503, 509, 521, 523, 541,
547, 557, 563, 569, 571,
577, 587, 593, 599, 601,
607, 613, 617, 619, 631,
641, 643, 647, 653, 659,
661, 673, 677, 683, 691]
... | f.n = int(math.ceil(n))
self.fpr = fpr
self.m = int(math.ceil(m))
self.k = int(k)
self.bsUnitSize = 64
self.bsCap = int(math.ceil(self.m / 64))
self.bitSet = FastBitSet(self.bsCap, self.bsUnitSize)
self.bitSetLength = self.bitSet.length
d... |
jungla/ICOM-fluidity-toolbox | Detectors/offline_advection/plot_Tracer_spec.py | Python | gpl-2.0 | 3,374 | 0.035566 | import os, sys
import myfun
import numpy as np
import matplotlib as mpl
mpl.use('ps')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy import interpolate
import lagrangian_st | ats
import scipy.fftpack
## READ archive (too many points... somehow)
# args: name, dayi, dayf, days
#label = 'm_25_2_512'
label = 'm_25_1_particles'
dayi = 0 #10*24*2
dayf = 1 #10*24*4
days = 1
#label = sys.argv[1]
#basename = sys.argv[2]
#dayi = int(sys.argv[3])
#da | yf = int(sys.argv[4])
#days = int(sys.argv[5])
path = '../Tracer_CG/'
try: os.stat('./plot/'+label)
except OSError: os.mkdir('./plot/'+label)
# dimensions archives
# ML exp
Xlist = np.linspace(0,2000,161)
Ylist = np.linspace(0,2000,161)
Zlist = np.linspace(0,-50,51)
dl = [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1... |
boegel/easybuild-easyblocks | easybuild/easyblocks/p/psi.py | Python | gpl-2.0 | 11,600 | 0.003534 | ##
# Copyright 2013-2021 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | objdir)
except OSError as err:
raise EasyBuildError("Failed to prepare for configuration of PSI build: %s", err)
env.setvar('F77FLAGS', os.getenv('F90FLAGS'))
# In order to create new plugins with PSI, it needs to know the location of the source
# and the obj dir after inst... | configure script.
self.psi_srcdir = os.path.basename(self.cfg['start_dir'].rstrip(os.sep))
self.install_psi_objdir = os.path.join(self.installdir, 'obj')
self.install_psi_srcdir = os.path.join(self.installdir, self.psi_srcdir)
env.setvar('PSI_OBJ_INSTALL_DIR', self.install_psi_objdir)
... |
tshirtman/ultimate-smash-friends | usf/screens/network_game_conf_screen.py | Python | gpl-3.0 | 6,713 | 0.006108 | ################################################################################
# copyright 2010 Lucas Baudin <xapantu@gmail.com> #
# #
# This file is part of Ultimate Smash Friends. ... | #get the index of the player
player_number = self.player_spinner.index(action)
self.players[player_number] = action.get_index()
#change the portrait
self.portraits[player_number].setImage(
join(
self.game_data['character... | for player in self.players:
if player != 0:
i += 1
if i > 1:
return {'goto': 'level'}
if action.text == _('Back'):
return {'goto': 'back'}
|
CARocha/addac_fadcanic | lugar/admin.py | Python | gpl-3.0 | 567 | 0.021164 | from django.contrib import admin
from lugar.models import Departamento, Municipio, Microcuenca, Comunidad
class ComunidadAdmin(admin.ModelAdmin):
list_display = ['nombre', 'municipio']
class DepartamentoAdmin(admin.ModelAdmin):
pass
class MicrocuencaAdmin | (admin.ModelAdmin):
pass
class MunicipioAdmin(admin.ModelAdmin):
list_display = ['nombre', 'departamento']
admin.site.register(Departamento,DepartamentoAdmin )
admin.site.register(Municipio, MunicipioAdmin)
admin.site.register(Microcuenca,MicrocuencaAdmin)
admin.site.register(Comunidad, Co | munidadAdmin)
|
makinacorpus/mapnik2 | scons/scons-local-1.2.0/SCons/Tool/packaging/targz.py | Python | lgpl-2.1 | 1,677 | 0.002385 | """SCons.Tool.Packaging.targz
The targz SRC packager.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
#
# 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 Sof... | revision__ = "src/engine/SCons/Tool/packaging/targz.py 3842 2008/12/20 22:59:52 scons"
from SCons.Tool.packaging import stripinstallbuilder, putintopackageroot
de | f package(env, target, source, PACKAGEROOT, **kw):
bld = env['BUILDERS']['Tar']
bld.set_suffix('.tar.gz')
target, source = stripinstallbuilder(target, source, env)
target, source = putintopackageroot(target, source, env, PACKAGEROOT)
return bld(env, target, source, TARFLAGS='-zc')
|
googleapis/python-talent | samples/generated_samples/jobs_v4_generated_company_service_delete_company_sync.py | Python | apache-2.0 | 1,376 | 0.000727 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | e_DeleteCompany_sync]
from google.cloud import talent_v4
def sample_delete_company():
# Create a client
client = talent_v4.CompanyServiceClient()
# Initialize request argument(s)
request = talent_v4.DeleteCompanyRequest(
name="name_value | ",
)
# Make the request
client.delete_company(request=request)
# [END jobs_v4_generated_CompanyService_DeleteCompany_sync]
|
bwhite/hadoopy | doc/conf.py | Python | gpl-3.0 | 6,505 | 0.006303 | # -*- coding: utf-8 -*-
#
# Hadoopy documentation build configuration file, created by
# sphinx-quickstart on Sat Jan 15 20:41:41 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All... | cument tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Hadoopy.tex', u'Hadoopy Documentation',
u'Brandyn White', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the ... | #latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
|
DarthMaulware/EquationGroupLeaks | Leak #1 - Equation Group Cyber Weapons Auction - Invitation/EQGRP-Free-File/Firewall/EXPLOITS/EPBA/EPICBANANA/versions/asa711.py | Python | unlicense | 2,590 | 0.002317 | from params import *
from util import *
from asa711_loader import *
def payload(params):
block_enc = []
while len(block_enc) == 0:
mask_byte = ord(rand_byte()) # one byte, used as an int
#print "trying to mask data with 0x%02x" % mask_byte
block_enc = prepare_blocks(params, mask_byte... | enc[11]) + LINEFEED
payload += ctrl_v_escape(block_enc[12]) + LINEFEED
payload += ctrl_v_escape(block_enc[13]) + LINEFEED
payload += ctrl_v_escape(block_enc[14]) + LINEFEED
return(p | ayload)
|
fvioz/hil-sample | main.py | Python | apache-2.0 | 572 | 0.006993 | # -*- coding: utf-8 -*-
from hil import Core
from context import AppContext
from apps.vibration.main import Vibration
from apps.voice.main import Voice
from apps.react.mai | n import React
from apps.sound.main import Sound
from apps.dialog.main import Dialog
class Main:
def __init__(self):
super(Main, self).__init__()
self.components = [Vibration, Voice, React, Sound, Dialog]
self.context = AppContext
def run(self):
self.core = Core( | self.components, self.context)
self.core.start()
if __name__ == "__main__":
main = Main()
main.run()
|
LyndonChin/CatyHIS | CatyHIS/settings.py | Python | mit | 2,157 | 0.000464 | """
Django settings for CatyHIS project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djan | goproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECU... | he secret key used in production secret!
SECRET_KEY = 'jh40i$ueqp$s7+@e71)s-&c*ek8vgt9atzdz7un6=r9(9^*5+-'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.con... |
hoodie/libavg | src/samples/abort_gestures.py | Python | lgpl-2.1 | 3,317 | 0.006331 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from libavg import avg, gesture, app
import gestures
RESOLUTION = avg.Point2 | D(800, 600)
nodeList = []
nodesEnabled = True
def abortAll():
for node in nodeList:
node.recognizer.abort()
def switchNodesEnabled():
global nodesEnabled
nodesEnabled = not nodesEnabled
for node in nodeList:
node.recognizer.enable(nodesEnabled)
class TapButton(gestures.TextRect):
... | r=self._onPossible, detectedHandler=self._onDetected,
failHandler=self._onFail)
def _onPossible(self):
self.rect.fillcolor = "FFFFFF"
def _onDetected(self):
self.rect.fillcolor = "000000"
self.rect.color = "00FF00"
def _onFail(self):
self.rect.fillcolor... |
leppa/home-assistant | homeassistant/components/neato/camera.py | Python | apache-2.0 | 3,990 | 0.000752 | """Support for loading picture from Neato."""
from datetime import timedelta
import logging
from pybotvac.exceptions import NeatoRobotException
from homeassistant.components.camera import Camera
from .const import (
NEATO_DOMAIN,
NEATO_LOGIN,
NEATO_MAP_DATA,
NEATO_ROBOTS,
SCAN_INTERVAL_MINUTES,
)... | obot, mapdata):
"""Initialize Neato cleaning map."""
super().__init__ | ()
self.robot = robot
self.neato = neato
self._mapdata = mapdata
self._available = self.neato.logged_in if self.neato is not None else False
self._robot_name = f"{self.robot.name} Cleaning Map"
self._robot_serial = self.robot.serial
self._generated_at = None
... |
bdmod/extreme-subversion | BinarySourcce/subversion-1.6.17/tools/bdb/whatis-rep.py | Python | gpl-2.0 | 1,674 | 0.018519 | #!/usr/bin/env python
#
# Print a description (including data, path, and revision) of the
# specified node reps in a Subversion filesystem. Walks as much of
# the reps table as necessary to locate the data (e.g. does a table
# scan).
# Standard modules
import sys, os, re, codecs
# Local support modules
import skel, ... | gname)
sys.stderr.flush()
sys.exit(1)
print("%s running on repository '%s'" % (prog | name, dbhome))
print("")
rep_ids = dict.fromkeys(rep_ids)
ctx = svnfs.Ctx(dbhome)
try:
cur = ctx.nodes_db.cursor()
try:
rec = cur.first()
while rec:
if rec[0] != 'next-key':
nid, cid, tid = rec[0].split(".")
nd = skel.Node(rec[1])
if nd.datarep in rep_id... |
NaN-tic/nereid | nereid/sessions.py | Python | gpl-3.0 | 3,596 | 0.000556 | #This file is part of Tryton & Nereid. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
from datetime import datetime # noqa
from flask.sessions import SessionInterface, SessionMixin
from werkzeug.contrib.sessions import Session as SessionBase, SessionStor... | session is unavailable | because no secret '
'key was set. Set the secret_key on the '
'application to something unique and secret.')
__setitem__ = __delitem__ = clear = pop = popitem = \
update = setdefault = _fail
del _fail
class MemcachedSessionStore(SessionStore):
... |
ntucker/django-user-accounts | account/auth_backends.py | Python | mit | 2,826 | 0.004954 | from __future__ import unicode_literals
import re
from django.db.models import Q
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from account.models import EmailAddress
from account.utils import get_user_lookup_kwargs
email_re = re.compile(
r"(^[-!#$%&'*+/=... | user = User.objects.get(**lookup_kwargs)
except (User.DoesNotExist, KeyError):
return None
else:
try:
if user.check_password(credentials["password"]):
return user
except KeyError:
return None
class EmailAuthe... | mail_address = qs.get(email__iexact=credentials["username"])
except (EmailAddress.DoesNotExist, KeyError):
return None
else:
user = email_address.user
try:
if user.check_password(credentials["password"]):
return user
exc... |
sander76/home-assistant | homeassistant/components/light/__init__.py | Python | apache-2.0 | 36,404 | 0.001209 | """Provides functionality to interact with lights."""
from __future__ import annotations
from collections.abc import Iterable
import csv
import dataclasses
from datetime import timedelta
import logging
import os
from typing import cast, final
import voluptuous as vol
from homeassistant.config_entries import ConfigEn... | l.Coerce(int), vol.Range(min=0, max=255)),
ATTR_FLASH: VALID_FLASH,
ATTR_EFFECT: cv.string,
}
LIGHT_TURN_OFF_SCHEMA = {ATTR_TRANSITION: VALID_TR | ANSITION, ATTR_FLASH: VALID_FLASH}
_LOGGER = logging.getLogger(__name__)
@bind_hass
def is_on(hass: HomeAssistant, entity_id: str) -> bool:
"""Return if the lights are on based on the statemachine."""
return hass.states.is_state(entity_id, STATE_ON)
def preprocess_turn_on_alternatives(hass, params):
"... |
mihaip/NewsBlur | apps/rss_feeds/icon_importer.py | Python | mit | 13,810 | 0.001593 | import urllib2
import lxml.html
import numpy
import scipy
import scipy.misc
import scipy.cluster
import urlparse
import struct
import operator
import gzip
import datetime
import requests
import httplib
from PIL import BmpImagePlugin, PngImagePlugin, Image
from socket import error as SocketError
from boto.s3.key import ... | dex]
# Seek to the bitmap data
image_file.seek(directory[7])
prefix = image_file.read(16)
image_file.seek(-16, 1)
if PngImagePlugin._accept(prefix):
# Windows Vista icon with PNG inside
try:
image = PngImagePlugin.PngImageFile(image_file... | pt IOError:
return
else:
# Load XOR bitmap
try:
image = BmpImagePlugin.DibImageFile(image_file)
except IOError:
return
if image.mode == 'RGBA':
# Windows XP 32-bit color depth icon without AND bitmap
... |
motobyus/moto | module_django/jstest/manage.py | Python | mit | 804 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os | .environ.setdefault("DJANGO_SETTINGS_MODULE", "jstest.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
... | ns on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environ... |
mlwbarlow/scripts-as-required | python/TypeSubjectFromRIFCS.py | Python | gpl-2.0 | 1,871 | 0.005879 | # TypeSubjectFromRIFCS.py takes input xml in RIFCS format and outputs subjectType and subjectText to .csv file per line as:
# subjectType|subjectText
#
#
#Usage: TypeSubjectFromRIFCS.py [options] arg1
#
#Options:
# -h, --help show this help message and exit
# --input_xml=INPUT_XML
# ... | it(-1)
print("Opened file %s for %s" % (fileName, mode)) |
return file
usage = "usage: %prog [options] arg1"
parser = OptionParser(usage=usage)
parser.add_option("--input_xml", action="store", dest="input_xml", help="e.g ExampleRIFCS.xml - xml in RIFCS format")
(options, args) = parser.parse_args()
# Validate options
if not options.input_xml:
parser.error("Requires... |
wandb/client | wandb/integration/sacred/__init__.py | Python | mit | 5,783 | 0.002959 | import warnings
import numpy
from sacred.dependencies import get_digest
from sacred.observers import RunObserver
import wandb
class WandbObserver(RunObserver):
"""Logs sacred experiment data to W&B.
Arguments:
Accepts all the arguments accepted by wandb.init()
name — A display name for this ... | an exception if config values are overwritten. (default: False)
Examples:
Create sacred experiment::
from wandb.sacred import WandbObserver
ex.observers.append(WandbObserver(project='sacred_test',
name='test1'))
@ex.config
def... | _run):
iris = datasets.load_iris()
per = permutation(iris.target.size)
iris.data = iris.data[per]
iris.target = iris.target[per]
clf = svm.SVC(C, 'rbf', gamma=gamma)
clf.fit(iris.data[:90],
iris.target[:90])
return c... |
Zentyal/samba | selftest/run.py | Python | gpl-3.0 | 4,316 | 0.001622 | #!/usr/bin/python -u
# Bootstrap Samba and run a number of tests against it.
# Copyright (C) 2012 Jelmer Vernooij <jelmer@samba.org>
# This program 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 versi... | Name of the testsuite
:param cmd: Command to run
:param subunit_ops: Subunit ops to use for reporting results
:param env: Environment the test is run in
:param outf: File-like object to write standard out to (defaults to sys.stdout)
:return: Exit code or None if the test failed to run completely
... | :
exitcode = subprocess.call(cmd, shell=True, stdout=outf)
except Exception, e:
subunit_ops.time(now())
subunit_ops.progress(None, subunit.PROGRESS_POP)
subunit_ops.end_testsuite(name, "error", "Unable to run %r: %s" % (cmd, e))
return None
subunit_ops.time(now())
su... |
open-forcefield-group/openforcefield | openff/toolkit/tests/test_chemicalenvironment.py | Python | mit | 7,356 | 0.001631 | import pytest
from openff.toolkit.typing.chemistry import *
from openff.toolkit.utils.toolkits import OPENEYE_AVAILABLE
# TODO: Evaluate which tests in this file should be moved to test_toolkits
toolkits = []
if OPENEYE_AVAILABLE:
from openff.toolkit.utils.toolkits import OpenEyeToolkitWrapper, RDKitToolkitWrappe... | oolkit, smirks, expected_valence, expected_chemenv_class
):
"""
Test creating environments with SMIRKS
"""
env = expected_chemenv_class(smirks=smirks, toolkit_regis | try=toolkit)
actual_type = env.get_type()
assert (
actual_type == expected_valence
), f"SMIRKS ({smirks}) classified as {actual_type} instead of {expected_valence} using {toolkit} toolkit"
@pytest.mark.parametrize(
("smirks", "wrong_envs"),
[
(
... |
google-research/robodesk | robodesk/robodesk_example.py | Python | apache-2.0 | 642 | 0 | """
Copyright 2021 Google L | LC
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 t | he License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governi... |
RoboArmadillo/JSIM | motor.py | Python | gpl-2.0 | 1,123 | 0.015138 | import os,sys
import serial
import time
from websocket import create_connection
ws = create_connection("ws://echo.websocket.org/")
class Motor(object):
def __init__(self, which_motor, speed = 0):
global ser
self._speed = speed
if which_motor == 0:
self.motor_side = "left"
... | ==1:
self.motor_side = "right"
@property
def speed(self):
return self._speed
@speed.setter
def speed(self, value):
self._speed = value
ws.send("1257, " + str(self.motor_side) +", "+ str(self._speed))
elif self._spee... | |
tidus747/Tutoriales_juegos_Python | Nociones PyGame/hola_mundo.py | Python | gpl-3.0 | 592 | 0.020305 | # -*- coding: utf-8 -*-
import pygame
pygame.init()
window = pygame.display.s | et_mode( (500, 400) )
while True:
pygame.draw.rect(window, (255, 0, 0), (100, 100, 100, 50), 2)
pygame.draw.ellipse(window, (255, 0, 0), (100, 100, 100, 50))
pygame.draw.rect(window, (0, 255, 0), (100, 150, 80, 40), 2)
pygame.draw | .ellipse(window, (0, 255, 0), (100, 150, 80, 40))
pygame.draw.rect(window, (0, 0, 255), (100, 190, 60, 30), 2)
pygame.draw.ellipse(window, (0, 0, 255), (100, 190, 60, 30))
#Círculo
pygame.draw.ellipse(window, (0, 0, 255), (100, 250, 40, 40))
pygame.display.update()
|
maartenq/ansible | lib/ansible/modules/net_tools/cloudflare_dns.py | Python | gpl-3.0 | 33,473 | 0.003256 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2016 Michael Gruener <michael.gruener@chaosmoon.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_versio... | tion: Service weight. Required for C(type=SRV)
default: "1"
zone:
description:
- The name of the Zone to work with (e.g. "example.com"). The Zone must already exist.
required: true
aliases: ["domain"]
'''
EXAMPLES = '''
# create a test.my.com A record to point to 127.0.0.1
- cloudflare_dns:
... | eate a my.com CNAME record to example.com
- cloudflare_dns:
zone: my.com
type: CNAME
value: example.com
state: present
account_email: test@example.com
account_api_token: dummyapitoken
# change it's ttl
- cloudflare_dns:
zone: my.com
type: CNAME
value: example.com
ttl: 600
st... |
theworldbright/mainsite | aspc/blog/migrations/0001_initial.py | Python | mit | 736 | 0.001359 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(verbose... | options={
'orderin | g': ['posted'],
},
bases=(models.Model,),
),
]
|
PythonProgramming/Python-3-basics-series | 28. multi line print.py | Python | mit | 549 | 0.007286 | '''
So now I just briefly want to cover multi line p | rint outs.
I remember making beautiful print outs as sort of guis, but I would do
print and then print out the line, then another print... and so on,
but you can actually do multi line prints with just 1 print. So let's see:
'''
print(
'''
This
is
a
test
'''
)
print(
'''
So it works like a multi-line
comment, ... | |
| BOX |
| |
| |
==============
'''
)
|
ultra-lstm/RNA-GAN | Refinement/predict.py | Python | mit | 7,897 | 0.008358 | import numpy as np
import pandas as pd
import tensorflow as tf
import scipy.misc
from keras.utils import plot_model
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model, Sequential
from keras.layers import Input, Dropout, Activation, LSTM, Conv2D, Conv2DTranspose, Dense, TimeDistribu... | = makeMask(gta, cta)
m2 = makeMask(gtb, ctb)
m3 = makeMask(gtc, ctc)
gt = np.concatenate((m1, m2, m3), axis=4)
return data, gt, np.concatenate((cta, ctb, ctc), | axis=4)
def combine(e, g, p1, q1):
p, m = np.split(e, 2, axis=4)
return np.sign(g + np.sign(p-p1) - np.sign(m-q1))
def merge(yo, error, p, q):
ae, be, ce = np.split(error, 3, axis=4)
ag, bg, cg = np.split(yo, 3, axis=4)
a = combine(ae, ag, p, q)
b = combine(be, bg, p, q)
c = ... |
fedspendingtransparency/data-act-broker-backend | dataactcore/migrations/versions/967fbc28a6ef_merge_ada3c1420257_and_bab396e50b1f.py | Python | cc0-1.0 | 581 | 0.006885 | """merge ad | a3c1420257 and bab396e50b1f
Revision ID: 967fbc28a6ef
Revises: ada3c1420257, bab396e50b1f
Create Date: 2017-08-07 11:48:14.479939
"""
# revision identifiers, used by Alembic.
revision = '967fbc28a6ef'
down_revision = ('ada3c1420257', 'bab396e50b1f')
branch_labels = None
depends_on = None
from alembic import op
impo... | bals()["downgrade_%s" % engine_name]()
def upgrade_data_broker():
pass
def downgrade_data_broker():
pass
|
bert9bert/statsmodels | statsmodels/regression/quantile_regression.py | Python | bsd-3-clause | 15,397 | 0.002663 | #!/usr/bin/env python
'''
Quantile regression model
Model parameters are estimated using iterated reweighted least squares. The
asymptotic covariance matrix estimated using kernel density estimation.
Author: Vincent Arel-Bundock
License: BSD-3
Created: 2013-03-19
The original IRLS function was written for Matlab by... | s.tools.sm_exceptions import (ConvergenceWarning,
IterationLimitWarning)
class QuantReg(RegressionModel):
'''Quantile Regression
Estimate a quantile regression model using iterative reweighted least
squares.
Parameters
----------
endog : array or d... | Absolute Deviation (LAD) estimator is a special case where
quantile is set to 0.5 (q argument of the fit method).
The asymptotic covariance matrix is estimated following the procedure in
Greene (2008, p.407-408), using either the logistic or gaussian kernels
(kernel argument of the fit method).
R... |
fridex/fabric8-analytics-worker | tests/workers/test_licensecheck.py | Python | gpl-3.0 | 2,348 | 0.001278 | # -*- coding: utf-8 -*-
import pytest
import os
import jsonschema
from flexmock import flexmock
from f8a_worker.workers import LicenseCheckTask
from f8a_worker.schemas import load_worker_schema, pop_schema_ref
from f8a_worker.object_cache import EPVCache
# TODO: drop the try/except after switching to Python 3
try:
... | directory"
args = dict.fromkeys(('ecosystem', 'name', 'version'), 'some-value')
flexm | ock(EPVCache).should_receive('get_sources').and_return(data)
task = LicenseCheckTask.create_test_instance(task_name='source_licenses')
with pytest.raises(Exception):
results = task.execute(arguments=args)
@pytest.mark.skipif(not os.path.isfile('/opt/scancode-toolkit/scancode'),
... |
anthkris/oppia | core/controllers/base.py | Python | apache-2.0 | 20,845 | 0.000096 | # Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | raised.
"""
def test_registered_as_editor(self, **kwargs):
"""Check that the user has registered as an editor."""
if (not self.user_id
or self.username in config_domain.BANNED_USERNAMES.value
or not user_services.has_fully_registered(self.user_id)):
r... | )
return handler(self, **kwargs)
return test_registered_as_editor
def _clear_login_cookies(response_headers):
# AppEngine sets the ACSID cookie for http:// and the SACSID cookie
# for https:// . We just unset both below.
cookie = Cookie.SimpleCookie()
for cookie_name in ['ACSID', 'SACSID... |
vdmann/cse-360-image-hosting-website | django-varnish-master/varnishapp/urls.py | Python | mit | 180 | 0.005556 | from django. | conf.urls.defaults import *
from django.conf import settings
from manager import VarnishManager
urlpatterns = patterns('varnishapp.views',
(r'', 'management'),
| )
|
fontanon/deldichoalhecho | test.py | Python | gpl-3.0 | 221 | 0 | #!/usr/bin/env python
from django.core.management import call_command
impor | t os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_site.settings")
call_command('test', 'promises_instances', 'ddah | _web', verbosity=1)
|
gunan/tensorflow | tensorflow/python/eager/tape.py | Python | apache-2.0 | 7,733 | 0.007242 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | nput_tensors,
backward_function)
def record_operation_forwardprop_only(op_type, output_tensors | , input_tensors,
backward_function,
forwardprop_output_indices):
"""Records the operation on all forward accumulators in the stack.
Args:
op_type: a string for the operation type, used in the backprop code
output_tensors: a list of... |
Jc2k/libcloud | libcloud/storage/drivers/local.py | Python | apache-2.0 | 18,796 | 0.00016 | # 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 ... | ner instances.
@rtype: C{generator} of L{Contain | er}
"""
for container_name in os.listdir(self.base_path):
full_path = os.path.join(self.base_path, container_name)
if not os.path.isdir(full_path):
continue
yield self._make_container(container_name)
def _get_objects(self, container):
"""... |
ramusus/django-vkontakte-groups-statistic | setup.py | Python | bsd-3-clause | 1,127 | 0.000887 | from setuptools import setup, find_packages
setup(
name='django-vkontakte-groups-statistic',
version=__import__('vkontakte_groups_statistic').__version__,
description='Django implementation for vkontakte API Groups Statistic',
long_description=open('README.md').read(),
author='ramusus',
author_... | Django needs
install_requires=[
'django-vkontakte-api>=0.4.2',
'django-vkontakte-groups>=0.3.5',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers', |
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
CybOXProject/python-cybox | cybox/objects/win_volume_object.py | Python | bsd-3-clause | 1,947 | 0.001027 | # Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import entities, fields
import cybox.bindings.win_volume_object as win_volume_binding
from cybox.objects.volume_object import Volume
from cybox.common import BaseProperty, String
class WindowsDrive(Ba... | _binding = win_volume_binding
_binding_class = win_volume_binding.WindowsDriveType
_namespace = "http://cybox.mitre.org/objects#WinVolumeObject | -2"
TYPE_DRIVE_UNKNOWN = "DRIVE_UNKNOWN"
TYPE_DRIVE_NO_ROOT_DIR = "DRIVE_NO_ROOT_DIR"
TYPE_DRIVE_REMOVABLE = "DRIVE_REMOVABLE"
TYPE_DRIVE_FIXED = "DRIVE_FIXED"
TYPE_DRIVE_REMOTE = "DRIVE_REMOTE"
TYPE_DRIVE_CDROM = "DRIVE_CDROM"
TYPE_DRIVE_RAMDISK = "DRIVE_RAMDISK"
class WindowsVolumeAttri... |
ledatelescope/bifrost | test/test_serialize.py | Python | bsd-3-clause | 9,648 | 0.001658 |
# Copyright (c) 2016-2020, The Bifrost Authors. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditi... | e_inc=1)
self.run_test_serialize_with_name_no_ringlets(gulp_nframe_inc=3)
def test_serialize_with_time_tag_no_ringlets(self):
with bf.Pipeline() as pipeline:
data = read_sigproc([self.fil_file], self.gulp_nframe)
# Custom view sets sequence name to '', which causes SerializeB... | ta, self.temp_path)
with TemporaryDirectory(self.temp_path):
pipeline.run()
basepath = os.path.join(self.temp_path,
'%020i' % self.time_tag)
hdrpath = basepath + '.bf.json'
datpath = basepath + '.bf.' + '... |
weegreenblobbie/nsound | src/examples/stretcher.py | Python | gpl-2.0 | 1,481 | 0.00135 | ###############################################################################
#
# $Id: stretcher.py 585 2010-12-15 05:21:28Z weegreenblobbie $
#
###############################################################################
from Nsound import *
# Read in the wavefile.
a1 = AudioStream("Temperature_in.wav")
# Gra... | rogress(True)
print("Pitch Shifting Up")
# Create new output AudioStream.
out = AudioStream(sr, 2)
# Pitch shift the input AudioStream.
out << stretch.pitchShift(a1, bend)
out >> "Temperature_Pitch_Shifted_Up.wav"
print("Time Shifting Faster")
# Time shift input AudioStream
out = AudioStream(sr,2)
out << stretch.t... | ature_Time_Shifted_Faster.wav"
bend = Buffer()
bend << 1.0 - 0.25 * sin.drawFatGaussian(duration, 0.15)
print("Pitch Shifting Down")
out = AudioStream(sr, 2)
out << stretch.pitchShift(a1, bend)
out >> "Temperature_Pitch_Shifted_Down.wav"
print("Time Shifting Slower")
bend = Buffer()
bend << 1.0 + 0.75 * sin.drawFa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.