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 |
|---|---|---|---|---|---|---|---|---|
JeffpanUK/NuPyTools | multiprocessTutorial.py | Python | mit | 1,085 | 0.029493 | # Written by Vamei
import os
import multiprocessing
import time
#==================
# input worker
def inputQ(queue, info):
# info = str(os.getpid()) + '(put):' + str(time.time())
queue.put(info)
# output worker
def outputQ(queue,lock):
info = queue.get()
print(info)
# lock.acquire()
# print (s... | process = multiprocessing.Process(target=inputQ,args=(queue,i))
process.start()
record1.append(process)
# output processes
for i in range(10):
process = multiprocessing.Process(target=outputQ,args=(queue,lock))
process.start()
record2.append(process)
for p in record1:
p.join... | e, close the queue
for p in record2:
p.join() |
spennihana/h2o-3 | h2o-py/tests/testdir_apis/Data_Manipulation/pyunit_h2oH2OFrame_ascharacter.py | Python | apache-2.0 | 734 | 0.013624 | from __future__ import print_function
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.utils.typechecks import assert_is_type
from h2o.frame import H2OFrame
def h2o_H2OFrame_ascharacter():
"""
Python API test: h2o.frame.H2OFrame.ascharacter()
Copied from pyunit_... | racter()
assert_is_type(newFrame, H2OFrame)
assert newFrame.isstring()[0], "h2o.H2OFrame.ascharacter() command is not working."
if __name__ == "__main__":
pyuni | t_utils.standalone_test(h2o_H2OFrame_ascharacter())
else:
h2o_H2OFrame_ascharacter()
|
rpedigoni/trackr | trackr/carriers/fake.py | Python | mit | 572 | 0 | from datetime import datetime
from .base import BaseCarrier
class FakeCarrier(BaseCarrier):
id = 'fake'
name = | 'Fake Carrier'
def _track_single(self, object_id):
package = self.create_package(
object_id=object_id,
service_name='Default',
)
for i in range(1, 5):
package.add_tracking_info(
date=datetime.now(),
location='City {}'.form... | status='In transit {}'.format(i),
description='Wow',
)
return package
|
OaklandPeters/pyinterfaces | pyinterfaces/valueabc/__init__.py | Python | mit | 498 | 0 | """
Provides ValueMeta metaclass - which allows its descendants to override
__instancecheck__ and __subcl | asscheck__ to be used as | *classmethods*
"""
from __future__ import absolute_import
__all__ = [
'ValueMeta',
'ValueABC',
'InterfaceType',
'ExistingDirectory',
'ExistingFile'
]
from .existing_directory import ExistingDirectory
from .existing_file import ExistingFile
from .interface_type import InterfaceType
from .valueabc ... |
jungla/ICOM-fluidity-toolbox | 2D/RST/extract_Scalar_temp.py | Python | gpl-2.0 | 3,216 | 0.03949 | try: paraview.simple
except: from paraview.simple import *
import numpy as np
from mpi4py import MPI
import os
import csv
from scipy import interpolate
import gc
import sys
gc.enable()
comm = MPI.COMM_WORLD
label = 'm_25_3b'
labelo = 'm_25_3b'
basename = 'mli'
## READ archive (too many points... somehow)
# args: n... | == 0:
Tr = np.zeros((len(Ylist),len(Xlist),len(Zlist)))
for n in range(nl+ll):
layer = n+rank*nl
print 'layer:', rank, layer
sliceFilter.SliceType.Origin = [0,0,-1*Zlist[layer]]
DataSliceFile = paraview.servermanager.Fetch(sliceFilter)
points = DataSliceFile.GetPoints()
numPoints = DataSliceFile.GetNumb... | Points()
#
data=np.zeros((numPoints))
coords=np.zeros((numPoints,3))
#
for x in xrange(numPoints):
data[x] = DataSliceFile.GetPointData().GetArray(field).GetValue(x)
coords[x] = points.GetPoint(x)
Tr[:,:,layer] = interpolate.griddata((coords[:,0],coords[:,1]),data,(X,Y),method='linear')
# print ra... |
herove/dotfiles | sublime/Packages/Package Control/package_control/providers/release_selector.py | Python | mit | 2,521 | 0.003173 | import re
import sublime
from ..versions import version_exclude_prerelease
def filter_releases(package, settings, releases):
"""
Returns all releases in the list of releases that are compatible with
the current platform and version of Sublime Text
:param package:
The name of the package
... | tput.append(release)
return output
|
def is_compatible_version(version_range):
min_version = float("-inf")
max_version = float("inf")
if version_range == '*':
return True
gt_match = re.match('>(\d+)$', version_range)
ge_match = re.match('>=(\d+)$', version_range)
lt_match = re.match('<(\d+)$', version_range)
le_match... |
oaubert/TwitterFontana | backend/src/app.py | Python | mit | 7,176 | 0.007664 | import flask
import json
import bson
import os
from flask import request, redirect
import sys
from fontana import twitter
import pymongo
DEFAULT_PORT = 2014
DB = 'fontana'
connection = pymongo.Connection("localhost", 27017)
db = connection[DB]
latest_headers = {}
MODERATED_SIZE = 40
class MongoEncoder(json.JSONE... | JSONEncoder.default(obj, **kwargs)
app = flask.Flask('fontana')
def twitter_authorisation_begin():
"""
Step 1 and 2 of the Twitter oAuth flow.
"""
callback = absolute_url('twitter_signin')
if 'next' in flask.request.args:
callback = '%s?next=%s' % (callback, flask.request.args['next | '])
try:
token = twitter.request_token(app.config, callback)
flask.session['twitter_oauth_token'] = token['oauth_token']
flask.session['twitter_oauth_token_secret'] = token['oauth_token_secret']
return flask.redirect(twitter.authenticate_url(token, callback))
except twitter.Twitt... |
jesonyang001/qarepo | askbot/context.py | Python | gpl-3.0 | 5,245 | 0.004385 | """Askbot template context processor that makes some parameters
from the django settings, all parameters from the askbot livesettings
and the application available for the templates
"""
import sys
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils import simplejson
import a... | ntext = {
'base_url': site_url(''),
'empty_search_state': SearchState.get_empty(),
'min_search_word_length': min_search_word_length,
'current_language_code': current_language,
'settings': my_settings,
'moderation_items': api.get_info_on_moderation_items(request.user),
... | }
if askbot_settings.GROUPS_ENABLED:
#calculate context needed to list all the groups
def _get_group_url(group):
"""calculates url to the group based on its id and name"""
group_slug = slugify(group['name'])
return reverse(
'users_by_group',
... |
aphaea/exc-MapReduce-UoE | three_wrd_seq_count/mapper.py | Python | mit | 441 | 0.011338 | #!/usr/bin/python
# Find all the three word sequences
import sys
for line in sys.stdin:
tok = line.strip().split()
if len(tok)>2:
for i in range(1, len(tok)-1):
word1, word2, word3 = tok[i-1], | tok[i], tok[i+1]
word_str = word1 + " " + word2 + " " + word3
print(word_str + "\t1")
| else:
continue
|
engdan77/edoAutoHomeMobile | twisted/internet/interfaces.py | Python | mit | 90,290 | 0.001207 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Interface documentation.
Maintainer: Itamar Shtull-Trauring
"""
from __future__ import division, absolute_import
from zope.interface import Interface, Attribute
from twisted.python import deprecate
from twisted.python.versions import Versi... | tuple gives answers. The | second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupMailExc... |
folivetti/PI-UFABC | AULA_01/Python/operadores.py | Python | mit | 2,187 | 0.038866 | # para os tipos numericos temos os seguintes operadores:
# + - * / % **
print "Numeros inteiros:"
x = 10
y = 3
print x, "+", y, "=", x + y
print x, "+", y, "=", x - y
print x, "+", y, "=", x*y
print x, "+", y, "=", x/y # repare como o resultado eh um inteiro
print x, "+", y, "=", x % y # esse eh o resto da divisao
pri... | nt x, "(",bin(x),") | ",y,"(",bin(y),") =", x|y # operador binario OU
print x, "(",bin(x),") ^ ",y,"(",bin(y),") =", x^y # operador binario XOU
print x," igual | a ",y,"? ", x==y
print x," diferente de ",y,"? ", x!=y
print x," maior que ",y,"? ", x>y
print x," menor que ",y,"? ", x<y
print x," maior ou igual a ",y,"? ", x>=y
print x," menor ou igual a ",y,"? ", x<=y
print "\nNumeros em ponto flutuante: "
x = 10.0
y = 3.0
print x, "+", y, "=", x + y
print x, "+", y, "=", x - y
... |
tomkralidis/pycsw | pycsw/ogc/fes/fes2.py | Python | mit | 19,080 | 0.002358 | # -*- coding: utf-8 -*-
# =================================================================
#
# Authors: Tom Kralidis <tomkralidis@gmail.com>
# Angelos Tzotsos <tzotsos@gmail.com>
#
# Copyright (c) 2015 Tom Kralidis
# Copyright (c) 2015 Angelos Tzotsos
#
# Permission is hereby granted, free of charge, to any p... | LOGGER.debug('fes20:Function detected')
if (elem.xpath('child::*')[0].attrib['name'] not in
MODEL['Functions']):
raise RuntimeError('Invalid fes20:Function: %s' %
(elem.xpath('child::*')[0].attrib['name']))
fname = elem.xp... | [0].attrib['name']
try:
LOGGER.debug('Testing existence of fes20:ValueReference')
pname = queryables[elem.find(util.nspath_eval('fes20:Function/fes20:ValueReference', nsmap)).text]['dbcol']
except Exception as err:
raise RuntimeError('Invalid Prop... |
mineo/picard | picard/util/icontheme.py | Python | gpl-2.0 | 2,350 | 0.00213 | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# 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 version 2
# of the License... | THOUT ANY WARRANTY; without even th | e implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Bo... |
arrayfire/arrayfire_python | arrayfire/statistics.py | Python | bsd-3-clause | 8,560 | 0.003271 | #######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
######################################################... | output: af.Array
Array containing the correlation coefficient of the input arrays.
"""
real = c_double_t(0)
imag = c_double_t(0)
safe_call(backend.get().af_corrcoef(c_pointer(real), c_pointer(imag), x.arr, y.arr))
real = real.value
imag = imag.value
return real if imag == 0 else r... | data: af.Array
Input array to return k elements from.
k: scalar. default: 0
The number of elements to return from input array.
dim: optional: scalar. default: 0
The dimension along which the top k elements are
extracted. Note: at the moment, topk() only supports the
... |
hasadna/anyway | alembic/versions/bd67c88713b8_user_permissions_management.py | Python | mit | 3,369 | 0.003562 | """user permissions management
Revision ID: bd67c88713b8
Revises: 10023013f155
Create Date: 2021-03-31 21:31:47.278834
"""
# revision identifiers, used by Alembic.
import datetime
from sqlalchemy import orm, text
from sqlalchemy.engine.reflection import Inspector
revision = "bd67c88713b8"
down_revision = "1002301... | n("create_date", sa.DateTime(), nullable=False, server_ | default=text("now()")),
sa.PrimaryKeyConstraint("user_id", "role_id"),
)
from anyway.models import Roles, Users, users_to_roles
bind = op.get_bind()
session = orm.Session(bind=bind)
role_admins = Roles(
name="admins",
description="This is the default admin role.",
... |
boh1996/LectioAPI | scrapers/materials.py | Python | mit | 2,102 | 0.03568 | #!/usr/bin/python
# -*- coding: utf8 -*-
from bs4 import BeautifulSoup as Soup
import urls
import re
import proxy
from datetime import *
import time
from time import mktime
import functions
def materials ( config ):
url = "https://www.lectio.dk/lectio/%s/MaterialOverview.aspx?holdelement_id=%s" % ( str(config["schoo... | und"
}
rows = soup.find("table", attrs={"id" : "m_Content_MaterialsStudents"}).findAll("tr")
materialsList = []
if len(rows) > 1:
rows.pop(0)
titleProg = re.compile(ur"(?P<authors>.*): (?P<title>.*), (?P<p | ublisher>.*)")
for row in rows:
elements = row.findAll("td")
title = unicode(elements[0].text.replace("\n", ""))
titleGroups = titleProg.match(title)
materialsList.append({
"title_text" : title,
"title" : titleGroups.group("title") if not titleGroups is None else title,
"publisher" : titleGro... |
DBrianKimmel/PyHouse | Project/src/Modules/Computer/Web/web_internet.py | Python | mit | 1,421 | 0.000704 | """
@name: Modules/Web/web_internet.py
@author: D. Brian Kimmel
@contact: D.BrianKimm | el@gmail.com
@copyright: (c) 2013-2020 by D. Brian Kimmel
@license: MIT License
@note: Created on Jun 3, 2013
@summary: Handle the "Internet" information for a house.
"""
__updated__ = '2020-01-02'
# Import system type stuff
from datetime import datetime
from nevow import athena
from nevow import loaders
im... | eb_utils import GetJSONComputerInfo
from Modules.Core import logging_pyh as Logger
from Modules.Core.Utilities import json_tools
# Handy helper for finding external resources nearby.
webpath = os.path.join(os.path.split(__file__)[0])
templatepath = os.path.join(webpath, 'template')
g_debug = 0
LOG = Logger.getLogger(... |
blakev/tappy | transifex.py | Python | bsd-2-clause | 1,750 | 0.000571 | # Copyright (c) 2015, Matt Layman
from ConfigParser import ConfigParser, NoOptionError, NoSectionError
import os
import sys
import requests
API_URL = 'https://www.transifex.com/api/2'
LANGUAGES = [
'es',
'fr',
'it', |
'nl',
]
def fetch_po_for(language, username, password):
print 'Downloading po file for {0} ...'.format(language)
po_api = '/project/tappy/resource/tappypot/translation/{0}/'.format(
language)
po_url = API_URL + po_api
params = {'file': '1'}
r = requests. | get(po_url, auth=(username, password), params=params)
if r.status_code == 200:
r.encoding = 'utf-8'
output_file = os.path.join(
here, 'tap', 'locale', language, 'LC_MESSAGES', 'tappy.po')
with open(output_file, 'wb') as out:
out.write(r.text.encode('utf-8'))
else:... |
mozilla/popcorn_maker | popcorn_gallery/notifications/models.py | Python | bsd-3-clause | 906 | 0 | from django.db import models
from django_extensions.db.fields import CreationDateTimeField
from tower import ugettext_lazy as _
from .managers import NoticeLiveManager
class Notice(models.Model):
LIVE = 1
REMOVED = 2 |
STATUS_CHOICES = (
(LIVE, _('Published')),
(REMOVED, _('Unpublished')),
)
title = models.CharField(max_length=255)
body = models.TextField()
created = CreationDateTimeField()
status = models.Integer | Field(choices=STATUS_CHOICES, default=LIVE)
end_date = models.DateTimeField(blank=True, null=True,
help_text='Optional. Determines when the'
'notice dissapears')
# managers
objects = models.Manager()
live = NoticeLiveManager()
... |
JulyKikuAkita/PythonPrac | cs15211/BinaryTreeCameras.py | Python | apache-2.0 | 4,264 | 0.003752 | __source__ = 'https://leetcode.com/problems/binary-tree-cameras/'
# Time: O(N)
# Space: O(H)
#
# Description: Leetcode # 968. Binary Tree Cameras
#
# Given a binary tree, we install cameras on the nodes of the tree.
#
# Each camera at a node can monitor its parent, itself, and its immediate children.
#
# Calculate the... | min(L[1:]))
dp2 = 1 + mi | n(L) + min(R)
return dp0, dp1, dp2
return min(solve(root)[1:])
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
Java = '''
# Thought: https://leetcode.com/problems/binary-tree-cameras/solution/
#
Approa... |
TwilioDevEd/api-snippets | sync/rest/documents/create-document/create-document.7.x.py | Python | mit | 864 | 0 | # Download the Python helper library from twilio.com/docs/python/install
import os
from twilio.rest import Client
from datetime import datetime
# Your Account Sid and Auth Token from twilio.com/user/account
# To set up environmental variables, see http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
au... | arring': ["Lance Bass", "Joey Fatone"],
'genre': "Romance"
}
document = client.sync \
.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.documents \
.create(unique_name="MyFirstDocument",
data=data,
ttl=1 | 814400) # expires in 21 days
print(document.sid)
|
skosukhin/spack | var/spack/repos/builtin/packages/r-ncbit/package.py | Python | lgpl-2.1 | 1,646 | 0.000608 | ############ | ##################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory. |
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
... |
sakura-internet/saklient.python | saklient/cloud/errors/resourcepathnotfoundexception.py | Python | mit | 742 | 0.009174 | # -*- coding:utf-8 -*-
# This code is automatically transpiled by Saklient Translator
import six
from ...errors.httpnotfoundexception import HttpN | otFoundException
import saklient
str = six.text_type
# module saklient.cloud.errors.resourcepathnotfoundexception
class ResourcePathNotFoundException(HttpNotFoundException):
## 対象が見つかりません。パスに誤りがあります。
## @param {int} status
# @param {str} code=None
# @param {str} message=""
def __init__(self, ... | code=None, message=""):
super(ResourcePathNotFoundException, self).__init__(status, code, "対象が見つかりません。パスに誤りがあります。" if message is None or message == "" else message)
|
yongshengwang/builthue | apps/hbase/src/hbase/management/commands/hbase_setup.py | Python | apache-2.0 | 3,274 | 0.007025 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | er 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 s | pecific language governing permissions and
# limitations under the License.
import logging
import os
from datetime import datetime, timedelta
from django.core.management.base import NoArgsCommand
from django.utils.translation import ugettext as _
from desktop.lib.paths import get_apps_root
from hbased.ttypes import... |
cdrooom/odoo | addons/mail/mail_mail.py | Python | agpl-3.0 | 18,908 | 0.004337 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010-today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | ase the debugging of mailing issues.", readonly=1),
# Auto-detected based on create() - if 'mail_message_id' was passed then this mail is a notification
# and during unlink() we will not cascade delete the parent and its attachments
'notification': fields.boolean('Is Notification',
h... | t(self, cr, uid, fields, context=None):
# protection for `default_type` values leaking from menu action context (e.g. for invoices)
# To remove when automatic context propagation is removed in web client
if context and context.get('default_type') and context.get('default_type') not in self._all_... |
ovnicraft/odoo_addons | smile_access_control/tests/__init__.py | Python | agpl-3.0 | 1,040 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 Smile (<http://www.smile.fr>). All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under th... | GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even th | e implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################... |
jeremiahyan/odoo | addons/website_event_exhibitor/tests/common.py | Python | gpl-3.0 | 1,021 | 0 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.website_event.tests.common import TestEventOnlineCommon
class TestEventExhibitorCommon(TestEventOnlineCommon):
@classmethod
def setUpClass(cls):
super(TestEventExhibitorCommon, cls).se... | e': 'GigaTop',
'sequence': 1,
})
cls.sponsor_0_partner = cls.e | nv['res.partner'].create({
'name': 'EventSponsor',
'country_id': cls.env.ref('base.be').id,
'email': 'event.sponsor@example.com',
'phone': '04856112233',
})
cls.sponsor_0 = cls.env['event.sponsor'].create({
'partner_id': cls.sponsor_0_partner.... |
DaivdZhang/tinyControl | tcontrol/tests/test_discretization.py | Python | bsd-3-clause | 1,236 | 0 | from unittest import TestCase
from tcontrol.discretization import c2d
from ..tra | nsferfunction import tf
from ..model_conversion import *
from ..statespace import StateSpace
import numpy as np
from .tools.test_utility imp | ort assert_ss_equal
class TestDiscretization(TestCase):
def setUp(self):
self.s1 = tf([1], [1, 0, 1])
self.zoh = tf([0.4597, 0.4597], [1, 1.0806, 1], dt=1)
self.ss = tf2ss(tf([1], [1, 0, 1]))
def test_c2d_zoh(self):
d_sys = c2d(self.s1, 1, 'zoh')
self.assertLessEqual(n... |
versionone/VersionOne.SDK.Python | v1pysdk/v1meta.py | Python | bsd-3-clause | 9,214 | 0.018016 | try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
from client import *
from base_asset import BaseAsset
from cache_decorator import memoized
from special_class_methods import special_classes
from none_deref import NoneDeref
from string_utils import split_attribute
... | new_asset_class
def add_to_dirty_list(self, asset_instance):
self.dirtylist.append(asset_instance)
def commit(self):
errors = []
for asset in self.dirtylist:
try:
| asset._v1_commit()
except V1Error, e:
errors.append(e)
self.dirtylist = []
return errors
def generate_update_doc(self, newdata):
update_doc = Element('Asset')
for attrname, newvalue in newdata.items():
if newvalue is None: # single relation was ... |
jellegerbrandy/bioport-site | bioport/mail_validation.py | Python | gpl-3.0 | 1,103 | 0.004533 | ##########################################################################
# Copyright (C) 2009 - 2014 Huygens ING & Gerbrandy S.R.L.
#
# This file is part of bioport.
#
# bioport 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 ... | r version 3 of the
# License, or (at your option) any | later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Pub... |
opennode/nodeconductor | waldur_core/structure/tests/unittests/test_tasks.py | Python | mit | 2,443 | 0.001228 | from ddt import ddt, data
from django.test import TestCase
from six.moves import mock
from waldur_core.core import utils
from waldur_core.structure import tasks
from waldur_core.structure.tests import factories, models
class TestDetectVMCoordinatesTask(TestCase):
@mock.patch('requests.get')
def test_task_se... | NewInstance.States.CREATION_SCHEDULED,
service_project_link=link)
serialized_vm = utils.serialize_instance(vm)
mocked_retry = mock.Mock()
tasks.ThrottleProvisionTask.retry = mocked_retry |
tasks.ThrottleProvisionTask().si(
serialized_vm,
'create',
state_transition='begin_starting').apply()
self.assertEqual(mocked_retry.called, params['retried'])
|
cchristelis/inasafe | safe/impact_functions/volcanic/volcano_polygon_population/metadata_definitions.py | Python | gpl-3.0 | 4,986 | 0 | # coding=utf-8
"""InaSAFE Disaster risk tool by Australian Aid - Volcano Polygon on Population
Metadata Definitions.
Contact : ole.moller.nielsen@gmail.com
.. note:: 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 ... | 'date_implemented': 'N/A',
'hazard_input': tr(
'The hazard layer must be | a polygon layer. This layer '
'must have an attribute representing the volcano hazard '
'zone that can be specified in the impact function option. '
'There are three classes low, medium, and high. The default '
'values are "Kawasan Rawan Bencana I" for low... |
overdrive3000/skytools | python/skytools/plpy_applyrow.py | Python | isc | 6,707 | 0.006113 |
"""
PLPY helper module for applying row events from pgq.logutriga().
"""
import plpy
import pkgloader
pkgloader.require('skytools', '3.0')
import skytools
## TODO: automatic fkey detection
# find FK columns
FK_SQL = """
SELECT (SELECT array_agg( (SELECT attname::text FROM pg_attribute
W... |
q = skytools.mk_insert_sql(fields, tblname, pkey_cols)
elif cmd == 'U':
q = skytools.mk_update_sql(fields, tblname, pkey_cols)
elif cmd == 'D':
q = skytools.mk_delete_sql(fields, tblname, pkey_cols)
else:
| plpy.error('Huh')
plpy.execute(q)
return log
def ts_conflict_handler(gd, args):
"""Conflict handling based on timestamp column."""
conf = skytools.db_urldecode(args[0])
timefield = conf['timefield']
ev_type = args[1]
ev_data = args[2]
ev_extra1 = args[3]
ev_extra2 = args[4]
... |
lsaffre/blog | docs/blog/2016/0305.py | Python | agpl-3.0 | 1,941 | 0.00103 | # -*- coding: UTF-8 -*-
from __future__ import print_function
import csv
import os
ignored_views = set(["HHB", "FFO", "FFOI"])
seen_views = set([])
seen_aliases = set([])
seen_groups = set([])
tpl = "check_journal(u'{1}', u'{4}', u'{11}', u'{10}')"
print("""# -*- coding: UTF-8 -*-
from __future__ import print_functio... | csvfile:
reader = csv.reader(csvfile, delimiter=';', quotechar='"')
for row in reader:
row = [x.strip() for x in row]
alias | = row[2].strip()
group = row[10].strip()
view = row[11].strip()
if alias in ["IMP"]:
if view not in ignored_views:
seen_views.add(view)
seen_aliases.add(alias)
seen_groups.add(group)
print(tpl.format(*row))
... |
citrix-openstack-build/neutron-fwaas | neutron_fwaas/tests.skip/unit/services/firewall/drivers/linux/test_iptables_fwaas.py | Python | apache-2.0 | 11,580 | 0.00095 | # Copyright 2013 Dell Inc.
# 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 app... |
mock.call.add_chain(egr | ess_chain),
mock.call.add_rule(egress_chain, invalid_rule),
mock.call.add_rule(egress_chain, est_rule),
mock.call.add_rule(ingress_chain, rule1),
mock.call.add_rule(egress_chain, rule1),
mock.call.add_rule(ingress_c... |
giorgiop/scikit-learn | sklearn/metrics/pairwise.py | Python | bsd-3-clause | 46,491 | 0.000043 | # -*- coding: utf-8 -*-
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Mathieu Blondel <mathieu@mblondel.org>
# Robert Layton <robertlayton@gmail.com>
# Andreas Mueller <amueller@ais.uni-bonn.de>
# Philippe Gervais <philippe.gervais@inria.fr>
# Lars Buitinck
... |
estimator = 'check_pairwise_arrays'
if dtype is None:
dtype = dtype_float
if Y is X or Y is None:
X = Y = check_array(X, accept_sparse='csr', dtype=dtype,
warn_on_dtype=warn_on_dtype, estimator=estimator)
else:
X = check_array(X | , accept_sparse='csr', dtype=dtype,
warn_on_dtype=warn_on_dtype, estimator=estimator)
Y = check_array(Y, accept_sparse='csr', dtype=dtype,
warn_on_dtype=warn_on_dtype, estimator=estimator)
if precomputed:
if X.shape[1] != Y.shape[0]:
raise... |
sgallagher/reviewboard | reviewboard/webapi/resources/base_file_attachment.py | Python | mit | 2,246 | 0 | from __future__ import unicode_literals
from django.utils import six
from reviewboard.attachments.models import FileAttachment
from reviewboard.webapi.base import WebAPIResource
class BaseFileAttachmentResource(WebAPIResource):
| """A base res | ource representing file attachments."""
added_in = '1.6'
model = FileAttachment
name = 'file_attachment'
fields = {
'id': {
'type': int,
'description': 'The numeric ID of the file.',
},
'caption': {
'type': six.text_type,
'descript... |
matevzmihalic/wlansi-store | wlansi_store/cms_app.py | Python | agpl-3.0 | 264 | 0.011364 | from cms.app_base import CMSApp
from | cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
class ProductApphook(CMSApp):
name = _("Product Apphook")
urls = ["wlansi_store.urls"]
apphook_pool.register(ProductApphoo | k) |
zzzoidberg/landscape | finance/consts.py | Python | mit | 78 | 0 | # -* | - coding: UTF-8 -*-
"""
Package-wide constants.
"""
CALL = 'C'
PUT = 'P | '
|
nilovna/EnceFAL | project/encefal/migrations/0003_auto__add_unique_vendeur_code_permanent.py | Python | gpl-3.0 | 8,651 | 0.007629 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding unique constraint on 'Vendeur', fields ['code_permanent']
db.create_unique(u'encefal_vendeur', ['co... | 'titre': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'vendeur': ('djan | go.db.models.fields.related.ManyToManyField', [], {'related_name': "'livres'", 'symmetrical': 'False', 'through': u"orm['encefal.Exemplaire']", 'db_column': "'vendeur'", 'to': u"orm['encefal.Vendeur']"})
},
u'encefal.session': {
'Meta': {'object_name': 'Session'},
'actif': ('djan... |
kidaa/kythe | third_party/grpc/src/python/src/grpc/framework/common/cardinality.py | Python | apache-2.0 | 1,930 | 0.002591 | # Copyright 2015, Google Inc.
# All r | ights 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 conditions and the following disclaimer.
# * Redistri... | the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PR... |
jabumaho/MNIST-neural-network | plot_error.py | Python | gpl-3.0 | 235 | 0.004255 | from matplotlib import pyplot as plt
path | = "C:/Temp/mnisterrors/chunk" + str(input("chunk: ")) + ".txt"
with open(path, "r") as f:
errorhistory = [float(line.rstrip('\n')) for line in f]
plt.plo | t(errorhistory)
plt.show()
|
stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGL/GL/ARB/texture_gather.py | Python | lgpl-3.0 | 1,072 | 0.015858 | '''OpenGL extension ARB.texture_gather
This module customi | ses the behaviour of the
OpenGL.raw.GL.ARB.texture_gather to provide a more
Python-friendly API
Overview (from the spec)
This extension provides a new set of texture functions
(textureGather) to the shading language that determine 2x2 footprint
that are used for linear filtering in a texture lookup, and return ... | footprint.
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/ARB/texture_gather.txt
'''
from OpenGL import platform, constant, arrays
from OpenGL import extensions, wrapper
import ctypes
from OpenGL.raw.GL import _types, _glgets
from OpenGL.raw.GL.ARB.texture_gather im... |
xgin/letsencrypt | letsencrypt/reporter.py | Python | apache-2.0 | 3,253 | 0 | """Collects and displays information to the user."""
from __future__ import print_function
import collections
import logging
import os
import Queue
import sys
import textwrap
import zope.interface
from letsencrypt import interfaces
from letsencrypt import le_util
logger = logging.getLogger(__name__)
class Report... | """Low priority constant. See `add_message`."""
_msg_type = collections.namedtuple('ReporterMsg', 'priority text on_crash')
def __init__(self):
self.messages = Queue.PriorityQueue()
def add_message(self, msg, priority, on_crash=True):
"""Adds msg to the list of messages to be printed.
... | RITY`,
or `LOW_PRIORITY`.
:param bool on_crash: Whether or not the message should be
printed if the program exits abnormally.
"""
assert self.HIGH_PRIORITY <= priority <= self.LOW_PRIORITY
self.messages.put(self._msg_type(priority, msg, on_crash))
logger... |
rustychris/stompy | stompy/grid/quad_laplacian.py | Python | mit | 123,597 | 0.021538 | """
Create a nearly orthogonal quad mesh by solving for stream function
and velocity potential inside a given boundary.
Still trying to improve the formulation of the Laplacian. Psi
(stream function) and phi (velocity potential) are solved
simultaneously. There are other options, and each field
uniquely constraints ... | =int(self.g.is_boundary_node(n0))
M=len(N) - is_boundary
if is_boundary:
# roll N to start and end on boundary nodes:
nbr_boundary=[se | lf.g.is_boundary_node(n)
for n in N]
while not (nbr_boundary[0] and nbr_boundary[-1]):
N=np.roll(N,1)
nbr_boundary=np.roll(nbr_boundary,1)
# area of the triangles
A=[]
for m in range(M):
tri=[n0,N[m],N[(m... |
ctsit/barebones-flask-app | app/routes/pages.py | Python | bsd-3-clause | 11,826 | 0 | """
Goal: Define the routes for general pages
@authors:
Andrei Sura <sura.andrei@gmail.com>
Ruchi Vivek Desai <ruchivdesai@gmail.com>
Sanath Pasumarthy <sanath@ufl.edu>
@see https://flask-login.readthedocs.org/en/latest/
@see https://pythonhosted.org/Flask-Principal/
"""
import hashlib... | pp.models.user_agent_entity import UserAgentEntity
from wtforms import Form, TextField, PasswordField, HiddenField, validators
from flask_login import LoginManager
from flask_login import login_user, logout_user, current_user
from flask_principal import \
Identity, AnonymousIdentity, identity_changed, identity_loa... | ity import UserEntity
# set the login manager for the app
login_manager = LoginManager(app)
# Possible options: strong, basic, None
login_manager.session_protection = "strong"
login_manager.login_message = ""
login_manager.login_message_category = "info"
@login_manager.user_loader
def load_user(user_id):
"""Ret... |
bashkirtsevich/autocode | text_preprocessing/es_predict.py | Python | gpl-3.0 | 1,121 | 0.001898 | import json
import requests
from transliterate import translit
_eng_chars = "~!@#$%^&qwertyuiop[]asdfghj | kl;'zxcvbnm,./QWERTYUIOP{}ASDFGHJKL:\"|Z | XCVBNM<>?"
_rus_chars = "ё!\"№;%:?йцукенгшщзхъфывапролджэячсмитьбю.ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭ/ЯЧСМИТЬБЮ,"
_trans_table = dict(zip(_eng_chars, _rus_chars))
def _fix_layout(s):
return "".join([_trans_table.get(c, c) for c in s])
def es_predict(es_url, keywords):
query = set(
keywords +
[_fix_layo... |
m1ojk/nicedoormat | test_email.py | Python | mit | 898 | 0.004454 | #!/usr/bin/env python
# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
import logging
from helper.pi_tool import PiTool
logging.basicConfig(filename='log/test_email.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s',... | "bgr")
#image = PiTool.get_roi_doorhole(rawCaptur | e.array)
image = rawCapture.array
image = PiTool.get_doorhole_roi(image)
# display the image on screen and wait for a keypress
#cv2.imshow("Image", image)
#cv2.waitKey(0)
PiTool.save_and_email(image, "test_email")
|
nayas360/pyterm | bin/type.py | Python | mit | 1,002 | 0 | # type command prints file contents
from lib.utils import *
def _help():
usage = '''
Usage: type (file)
Print content of (file)
Use '%' in front of global
vars to use value as file
name.
'''
print(usage)
def main(argv):
if len(argv) < 1 or '-h' in argv:
_help()
return
# The shell ... | mand name in the arg list
# so the next line is not needed
# anymore
# argv.pop(0)
# The shell does the work of replacing
# vars already. Code segment below
# is not required anymore.
# argv=replace_vars(argv)
argv = make_s(argv)
path = get_path() + argv
if os.path.isfile(path)... | ______________<START>_________________\n')
print(make_s2(data))
print('__________________<END>__________________\n')
return
elif os.path.isdir(path):
err(3, add=argv + ' is a directory')
else:
err(2, path)
|
wheeler-microfluidics/svg_model | svg_model/svgload/svg_parser.py | Python | lgpl-2.1 | 7,624 | 0.002361 | '''
This is a New BSD License.
http://www.opensource.org/licenses/bsd-license.php
Copyright (c) 2008-2009, Jonathan Hartley (tartley@tartley.com)
Copyright (c) 2012, Christian Fobel (christian@fobel.net)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitte... | path in self.paths.itervalues():
for loop in svg_path.loops:
for vert in loop.verts:
yield vert
class SvgParser(object):
'''
parse(filename) returns an Svg object, populated from the <path> tags
in the file.
'''
def parse_file(self, filename, on_err... | urn self.parse(xml_root, on_error)
def parse(self, xml_root, on_error=None):
'''
Parse all <path> elements from xml_root.
Optional on_error arg specifies a callback function to be run when
an error occurs during parsing.
The specified on_error function must accept 3 argumen... |
Jacy-Wang/MyLeetCode | PowerofFour342.py | Python | gpl-2.0 | 232 | 0 | c | lass Solution(object):
def isPowerOfFour(self, num):
"""
:type num: i | nt
:rtype: bool
"""
if num < 1:
return False
return num & (num - 1) == 0 and num & 0x55555555 > 0
|
rick446/MongoTools | mongotools/mim/__init__.py | Python | mit | 67 | 0 | from | .mim import Connection, match, MatchDoc, MatchList, BsonAri | th
|
youtube/cobalt | third_party/llvm-project/lldb/packages/Python/lldbsuite/test/lldbinline.py | Python | bsd-3-clause | 7,168 | 0.000279 | from __future__ import print_function
from __future__ import absolute_import
# System modules
import os
# Third-party modules
# LLDB modules
import lldb
from .lldbtest import *
from . import configuration
from . import lldbutil
from .decorators import *
def source_type(filename):
_, extension = os.path.splitex... | return
class InlineTest(TestBase):
# Internal implementation
| def BuildMakefile(self):
makefilePath = self.getBuildArtifact("Makefile")
if os.path.exists(makefilePath):
return
categories = {}
for f in os.listdir(self.getSourceDir()):
t = source_type(f)
if t:
if t in list(categories.keys()):
... |
sinharrajesh/dbtools | google-plus-analysis/clarify.py | Python | apache-2.0 | 1,344 | 0.004464 | #!/usr/bin/python
import json
import logging
import sys
from datetime import datetime
import csv
if __name__ == '__main__':
_loggingLevel = logging.DEBUG ## How much trace
logger = logging.getLogger(__name__)
logging.basicConfig(level=_loggingLevel)
| a = {}
| altmetricFile = sys.argv[1]
with open(altmetricFile) as afData:
for line in afData:
data = line.rstrip('\n')
a[data] = 0
with open(sys.argv[2], 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter='$', quotechar='\'')
for line in spamreader:
... |
cxxgtxy/tensorflow | tensorflow/python/eager/remote_test.py | Python | apache-2.0 | 24,106 | 0.008919 | # Copyright 2019 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... | with self.assertRaises(errors.InvalidArgumentError) as cm:
with ops.device('/job:worker/replica:0/task:0/cpu:0'):
ambiguous_device(constant_op.constant([2])).numpy()
self.assertIn('the output node must match exactly one device',
cm.exception.message)
def testStreaming(self):
... | back."""
with ops.device('job:worker/replica:0/task:0/device:CPU:0'):
x = array_ops.ones([2, 2])
y = array_ops.zeros([2, 2])
num_iters = 200
for _ in range(num_iters):
y = x + y
# Ask for y's shape after every 10 additions on average.
# This exercises waiting for rem... |
google-research/jax3d | jax3d/projects/nesf/nerfstatic/utils/camera_utils_test.py | Python | apache-2.0 | 1,892 | 0.0037 | # Copyright 2022 The jax3d Authors.
#
# 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 wr... | mera.pixel_centers2rays()
expected_rays = types.Rays(
scene_id=None,
origin=np_array([
[[2., 0., 1.],
[2., 0., 1.]],
[[2., 0., 1.],
[2., 0., 1.]],
]),
direction=np_array([
[[-0.27698026, -0.24996764, -0.92779206],
[-0.2750864, -0.2... | 193]],
[[-0.27663719, -0.25217938, -0.92729576],
[-0.27474675, -0.25160123, -0.92801457]],
]),
)
chex.assert_tree_all_close(rays, expected_rays, ignore_nones=True)
|
UManPychron/pychron | pychron/hardware/linear_axis.py | Python | apache-2.0 | 2,566 | 0 | # ===============================================================================
# Copyright 2015 Jake Ross
#
# 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... | ._cdevice:
return self._cdevice.stal | led()
def slew(self, modifier):
if self._cdevice:
self._slewing = True
self._cdevice.slew(modifier)
def stop(self):
if self._cdevice:
self._slewing = False
self._cdevice.stop_drive()
def _get_min_limit(self):
return abs(self._positio... |
hasauino/multi_kobuki_gazebo | scripts/tot_r1.py | Python | mit | 2,113 | 0.056791 | #!/usr/bin/env python
#--------Include modules---------------
from copy import copy
import rospy
from visualization_msgs.msg import Marker
from std_msgs.msg import String
from geometry_msgs.msg import Point
from nav_msgs.msg import OccupancyGrid
import actionlib_msgs.msg
from move_base_msgs.msg import MoveBaseAction,... | -------------------------------------------
def node():
rospy.init_node('distanceCounter1', anonymous=False)
#-------------------------------------------
rate = rospy.Rate(50)
listener = tf.TransformListener()
listener.waitForTransform('/robot_1/odom', '/robot_1/base_... | orm('/robot_1/odom', '/robot_1/base_link', rospy.Time(0))
except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):
trans=[0,0]
xinx=trans[0]
xiny=trans[1]
xprev=array([xinx,xiny])
distance=0
t0=time()
#-------------------------------RRT-------------------------------... |
aesaae/ardupilot_str | Tools/ardupilotwaf/git_submodule.py | Python | gpl-3.0 | 3,169 | 0.002524 | #!/usr/bin/env python
# encoding: utf-8
"""
Waf tool for defining ardupilot's submodules, so that they are kept up to date.
Submodules can be considered dynamic sources, since they are updated during the
build. Furthermore, they can be used to generate other dynamic sources (mavlink
headers generation, for example). T... | cnode.abspath()
tsk.env.SUBMODULE_PATH = module_node.abspath()
_submodules_tasks[name] | = tsk
return _submodules_tasks[name]
@feature('git_submodule')
@before_method('process_source')
def process_module_dependencies(self):
self.git_submodule = getattr(self, 'git_submodule', '')
if not self.git_submodule:
self.bld.fatal('git_submodule: empty or missing git_submodule argument')
se... |
miltondp/ukbrest | tests/test_password_hasher.py | Python | gpl-3.0 | 5,529 | 0.000723 | import os
import unittest
from shutil import copyfile
from ruamel.yaml import YAML
from ukbrest.common.utils.auth import PasswordHasher
from tests.utils import get_repository_path
class WSGIFunctions(unittest.TestCase):
def load_data(self, filepath):
yaml = YAML()
with open(filepath, 'r') as f:
... | orig_users = self.load_data(orig_user_file)
| # run
ph = PasswordHasher(users_file, method='pbkdf2:sha256')
ph.process_users_file()
# evaluate
assert os.path.isfile(users_file)
users = self.load_data(users_file)
assert len(users) == 3
for user, password in users.items():
assert user in orig_use... |
bameda/monarch | back/settings/common.py | Python | agpl-3.0 | 3,078 | 0.00195 | import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
ADMINS = (
("David Barra... | D_HOSTS = ['*']
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUA... | ript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
# Media files
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.con... |
royragsdale/picoCTF | picoCTF-web/api/cache.py | Python | mit | 4,558 | 0.000658 | """Caching Library using redis."""
import logging
from functools import wraps
from flask import current_app
from walrus import Walrus
import api
import hashlib
import pickle
from api import PicoException
log = logging.getLogger(__name__)
__redis = {
"walrus": None,
"cache": None,
"zsets": {"scores": No... | ):
if kwargs.get("reset_cache", False):
kwargs.pop("reset_cache", None)
return __insert_cache(f, *args, **kwargs)
else:
return get_cache().cached(**cached_kwargs)(f)(*args, **kwargs)
return wrapper
if _f is None:
return decora... | miter, use '>' illegal team name char
return "{}>{}>{}".format(team["team_name"], team["affiliation"], team["tid"])
def decode_scoreboard_item(item, with_weight=False, include_key=False):
"""
:param item: tuple of ZSet (key, score)
:param with_weight: keep decimal weighting of score, or return as int
... |
etkirsch/legends-of-erukar | erukar/system/engine/lifeforms/Player.py | Python | agpl-3.0 | 1,072 | 0.027052 | from .Lifeform import Lifeform
from erukar.system.engine import Indexer
from erukar.ext.math.Distance import Distance
class Player(Lifeform, Indexer):
def __init__(self, world=None):
Indexer.__init__(self)
super().__init__(world)
self.faction = 'iurian'
self.uid = '' # Player UID
... |
def alias(self):
return self.uid
def lifeform(self):
return self
def generate_tile(self, dimensions, tile_id):
h, w = di | mensions
radius = int(w/3)-1
circle = list(Distance.points_in_circle(radius, (int(h/2),int(w/2))))
inner_circle = list(Distance.points_in_circle(int(w/4)-1, (int(h/2),int(w/2))))
for y in range(h):
for x in range(w):
if (x,y) in circle:
if ... |
yujikato/DIRAC | src/DIRAC/ResourceStatusSystem/Policy/test/Test_RSS_Policy_JobEfficiencyPolicy.py | Python | gpl-3.0 | 3,905 | 0.06274 | ''' Test | _RSS_Policy_JobEfficiencyPolicy
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
import DIRAC.ResourceStatusSystem.Policy.JobEfficiencyPolicy as moduleTested
###############################################################################... |
'''
Setup
'''
self.moduleTested = moduleTested
self.testClass = self.moduleTested.JobEfficiencyPolicy
def tearDown( self ):
'''
Tear down
'''
del self.moduleTested
del self.testClass
################################################################################
clas... |
DmitryADP/diff_qc750 | vendor/nvidia/tegra/3rdparty/python-support-files/src/Lib/random.py | Python | gpl-2.0 | 31,938 | 0.002536 | """Random variable generators.
integers
--------
uniform within range
sequences
---------
pick random element
pick random sample
generate random permutation
distributions on the real line:
------------------------------
uniform
... | ; in Python this is usually not what you want.
Do not supply the 'int', 'default', and 'maxwidth' arguments.
"""
# This code is a bit messy to make it fast for the
# common case while still doing adequate error checking.
istart = int(start)
if istart != start:
... | if stop is default:
if istart > 0:
if istart >= maxwidth:
return self._randbelow(istart)
return int(self.random() * istart)
raise ValueError, "empty range for randrange()"
# stop argument supplied.
istop = int(stop)
... |
vipints/oqtans | oqtans_tools/PALMapper/0.5/galaxy/genomemapper_wrapper.py | Python | bsd-3-clause | 4,421 | 0.013798 | #! /usr/bin/python
"""
Runs GenomeMapper on single-end or paired-end data.
"""
import optparse, os, sys, tempfile
def stop_err( msg ):
sys.stderr.write( "%s\n" % msg )
sys.exit()
def __main__():
#Parse Command Line
parser = optparse.OptionParser()
parser.add_option('', '--threads', dest='thread... | cmd1 = 'gmindex -v -i %s %s' % (options.ref, indexing_cmds)
try:
os.system(cmd1)
except Exception, erf:
stop_err('Error indexing reference sequence\n' + str(erf))
if options.params == 'pre_set':
aligning_cmds = '-v '
else:
try:
print... | ormat)[options.format!='None'],
('','-a')[options.reportall!='None'],
('','-M %s' % options.maxmismatches)[options.maxmismatches!='None'],
('','-G %s' % options.maxgaps)[options.maxgaps!='None'],
('','-E ... |
bobjacobsen/SPShasta | userfiles/ConfigureCtcControlLogic.py | Python | gpl-2.0 | 21,226 | 0.015076 | # Configure SP Shasta CTC machine support
#
# Exensively uses the jmri.jmrit.ussctc package capabilities
#
# Author: Bob Jacobsen, copyright 2016-17
#
import jmri
from jmri.jmrit.ussctc import *
import jarray
import java.util
def arrayList(contents) :
retval = java.util.ArrayList()
for item in contents :
... | pNames = groupList
# set up listeners
self.callon.addPropertyChangeListener(self)
for name in self.groupNames :
signals.getSignalHead(name).addPropertyChangeListener(self) # need to fix it if held
return
def propertyChange(self, event):
if (event.source == self.c | allon) :
if (self.callon.state == THROWN) :
for name in self.groupNames :
logic = jmri.jmrit.blockboss.BlockBossLogic.getExisting(signals.getSignalHead(name))
print "Setting logic", logic
logic.setRestrictingSpeed1(True)
logic.setRest... |
tfroehlich82/saleor | saleor/wsgi/__init__.py | Python | bsd-3-clause | 1,225 | 0.001633 | """
WSGI config for saleor 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`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
| that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'saleor.settings')
# This application object is used by any WSGI server configured to u... |
nromashchenko/amquery | amquery/utils/decorators/__init__.py | Python | mit | 265 | 0 | from ._decorators import singleton,\
hide_field
__license__ = "MIT" |
__version__ = "0.2.1"
__author__ = "Nikolay Romashchenko"
__maintainer__ = "Nikolay Ro | mashchenko"
__email__ = "nikolay.romashchenko@gmail.com"
__status__ = "Development"
|
gpotter2/scapy | doc/scapy/_ext/linkcode_res.py | Python | gpl-2.0 | 3,293 | 0.002126 | import inspect
import os
import sys
import scapy
# -- Linkcode resolver -----------------------------------------------------
# This is HEAVILY inspired by numpy's
# https://github.com/numpy/numpy/blob/73fe877ff967f279d470b81ad447b9f3056c1335/doc/source/conf.py#L390
# Copyright (c) 2005-2020, NumPy Developers.
# Al... | LAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION | ) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
def linkcode_resolve(domain, info):
"""
Determine the URL correspondin... |
astrofle/CRRLpy | examples/synth_spec/makemodel.py | Python | mit | 4,292 | 0.011883 | #!/usr/bin/env python
"""
Example of a model fitting script.
The user should modify the model
according to the characteristics of
the signal of interest.
Part of the code is taken from the
kmpfit examples:
http://www.astro.rug.nl/software/kapteyn/kmpfittutorial.html#profile-fitting
"""
import numpy as np
import argp... | u_0'].set(value=-37.6, expr='V1_nu_0+9.4', vary=False)
# Line area
pars['V1_A'].set(value=-1e-2, max=-1e-8)
#pars['V2_A'].set(value=-1e-2, max=-1e-8)
# Line width
pars['V1_alphaD'].set(value=dD, vary=True, min=0.)
#pars['V2_alphaD'].set(value=dD, vary=True, min=0.)
pars['V1_alphaL'].set(valu... | =0, max=250.)
#pars['V2_alphaL'].set(value=1, vary=True, min=0, max=250.)
# Fit the model using a weight
fit = mod.fit(my, pars, nu=mx, weights=mw)
fit1 = Voigt(mx, fit.params['V1_alphaD'].value, fit.params['V1_alphaL'].value,
fit.params['V1_nu_0'].value, fit.params['V1_A'].v... |
em92/pickup-rating | qllr/blueprints/player/__init__.py | Python | mit | 2,763 | 0.002533 | # -*- coding: utf-8 -*-
from typing import Tuple
from asyncpg import Connection
from starlette.requests import Request
from starlette.responses import JSONResponse, RedirectResponse
from starlette.routing import Route
from qllr.app import App
from qllr.endpoints import Endpoint, HTTPEndpoint
from qllr.templating imp... | e_id)
return RedirectResponse(request.url_for("ScoreboardHtml", match_id=match_id))
routes = [
Route("/{steam_id:int}.json", endpoint=PlayerJson),
Route("/{steam_id:int}", endpoint=PlayerHtml),
Route("/{steam_id:int}/matches", endpoint=PlayerMatchesDeprecatedRoute),
Route("/{steam_id:int} | /matches/", endpoint=PlayerMatchesDeprecatedRoute),
Route("/{steam_id:int}/matches/{page:int}/", endpoint=PlayerMatchesDeprecatedRoute),
Route("/{steam_id:int}/matches/{gametype}/", endpoint=PlayerMatchesDeprecatedRoute),
Route(
"/{steam_id:int}/matches/{gametype}/{page:int}/",
endpoint=Play... |
VirrageS/io-kawiarnie | caffe/caffe/models.py | Python | mit | 931 | 0 | """Module with Caffe models."""
from django.db import models
from employees.models import Employee
class Caffe(models.Model):
"""Stores one cafe."""
name = models.CharField(max_length=100, unique=True)
city = models.CharField(max_length=100)
street = models.CharField(max_length=100)
# CharField... | for extra characters like '-'
postal_code = models.CharField(max_length=20)
# CharFields in case house numbers like '1A'
building_number = models.CharField(max_length=10)
house_number = models.CharField(max_length=10, blank=True)
created_on = models.TimeField(auto_now_add=True)
creator = models.... | _name='my_caffe',
default=None,
blank=False,
null=True)
def __str__(self):
return '{}, {}'.format(self.name, self. city)
|
yotchang4s/cafebabepy | src/main/python/ctypes/test/test_find.py | Python | bsd-3-clause | 3,948 | 0.000507 | import unittest
import os.path
import sys
import test.support
from ctypes import *
from ctypes.util import find_library
# On some systems, loading the OpenGL libraries needs the RTLD_GLOBAL mode.
class Test_OpenGL_libs(unittest.TestCase):
@classmethod
def setUpClass(cls):
lib_gl = lib_glu = lib_gle = N... | if self.glu is None:
self.skipTest('lib_glu not available')
self.glu.gluBeginCurve
def test_gle(self):
if self.gle is None:
self.skipTest('lib_gle not available')
self.gle.gleGetJoinStyle
def test_shell_injection(self):
result = find_library('; echo He... | lf.assertFalse(os.path.lexists(test.support.TESTFN))
self.assertIsNone(result)
@unittest.skipUnless(sys.platform.startswith('linux'),
'Test only valid for Linux')
class LibPathFindTest(unittest.TestCase):
def test_find_on_libpath(self):
import subprocess
import tempfil... |
aldialimucaj/Streaker | docs/source/conf.py | Python | mit | 11,449 | 0.006376 | # -*- coding: utf-8 -*-
#
# Streaker documentation build configuration file, created by
# sphinx-quickstart on Sun Mar 6 12:34:57 2016.
#
# 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.
#
# ... | mentclass [howto, m | anual, or own class]).
latex_documents = [
(master_doc, 'Streaker.tex', u'Streaker Documentation',
u'Aldi Alimucaj', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headi... |
fmin2958/POCS | panoptes/camera/canon_indi.py | Python | mit | 6,347 | 0.002521 | import re
import yaml
import subprocess
import os
import datetime
from . import AbstractCamera
from ..utils.logger import has_logger
from ..utils.config import load_config
from ..utils.indi import PanIndi
@has_logger
class Camera(AbstractCamera):
def __init__(self, device_name, client=PanIndi(), config=dict(), ... | de(1, self.name, None)
self.logger.info("Connected to camera")
self.init()
def init(self):
self.logger.info("Setting defaults for camera")
self.client.get_property_value(self.name, 'UPLOAD_MODE')
# self.client.sendNewText(self.name, 'UPLOAD_MODE', 'Local', 'On')
s... | result = self.set('/main/settings/reviewtime', 0) # Screen off
# result = self.set('/main/settings/capturetarget', 1) # SD Card
# result = self.set('/main/settings/ownername', 'Project PANOPTES')
# result = self.set('/main/settings/copyright', 'Project PANOPTES 2015')
#
... |
tedlaz/pyted | misthodosia/m13/f_pro.py | Python | gpl-3.0 | 1,976 | 0.013122 | # -*- coding: utf-8 -*-
'''
Created on 22 Ιαν 2013
@author: tedlaz
'''
from PyQt4 import QtGui, QtCore
fr | om gui import ui_pro
class dlg(QtGui.QDialog):
def __init__(self, args=None, parent=None):
super(dlg, self).__init__(parent)
self.ui = ui_pro.Ui_Dialog()
self.ui.setup | Ui(self)
self.makeConnections()
if parent:
self.db = parent.db
else:
self.db = ''
def makeConnections(self):
QtCore.QObject.connect(self.ui.b_save, QtCore.SIGNAL("clicked()"),self.saveToDb)
def saveToDb(self):
fro... |
UdeM-LBIT/GAPol | lib/ga/evolve/Selectors.py | Python | gpl-3.0 | 3,696 | 0.0046 | """
:mod:`Selectors` -- selection methods module
==============================================================
This module have the *selection methods*, like roulette wheel, tournament, ranking, etc.
"""
import random
import Consts
def GRankSelector(population, **args):
""" The Rank Selector - This selector w... | on, **args) for i in xrange(poolSize)]
choosen = min(tournament_pool, key=lambda ind: ind.fitness)
return choosen
def GTournamentSelectorAlternative(population, **args):
""" The alternative Tournament Selector
This Tournament Selector don't uses the Roulette Wheel
It accepts the *tournamentP... | )
tournament_pool = [population[random.randint(0, len_pop - 1)] for i in xrange(pool_size)]
choosen = min(tournament_pool, key=lambda ind: ind.fitness)
return choosen
def GRouletteWheel(population, **args):
""" The Roulette Wheel selector """
psum = None
if args["popID"] != GRouletteWheel.... |
RudolfCardinal/crate | crate_anon/linkage/bulk_hash.py | Python | gpl-3.0 | 6,042 | 0 | #!/usr/bin/env python
"""
crate_anon/linkage/bulk_hash.py
===============================================================================
Copyright (C) 2015-2021 Rudolf Cardinal (rudolf@pobox.com).
This file is part of CRATE.
CRATE is free software: you can redistribute it and/or modify
it under th... | digest:
print(hmac_obj.digest()) # 8-bit binary
print(hmac_obj | .hexdigest()) # hexadecimal
# Hex carries 4 bits per character. There are other possibilities,
# notably:
# - Base64 with 6 bits per character;
# - Base32 with 5 bits per character.
"""
import argparse
import logging
from typing import Optional, TextIO
from cardinal_pythonlib.file_io import (
g... |
guotie/flask-acl | setup.py | Python | mit | 1,588 | 0.019521 | """
flask.ext.acl
=============
This extension provides an Access Control implementation for `tipfy <http://www.tipfy.org/>`_.
Links
-----
* `Documentation <http://www.tipfy.org/wiki/extensions/acl/>`_
* `Source Code Repository <http://code.google.com/p/tipfy-ext-acl/>`_
* `Issue Tracker <http://code.google.com/p/tip... | ',
author_email = 'guotie.9@gmail.com',
zip_safe = False,
platforms = 'any',
packages = [
'flask',
'flask.ext',
],
namespace_packages = [
'flask',
'flask.ext', |
],
include_package_data = True,
install_requires = [
'flask',
'flask.ext.sqlalchemy',
'flask.ext.cache',
],
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI ... |
PolicyStat/jobtastic | test_projects/django/testproj/urls.py | Python | mit | 307 | 0.003257 | from django.conf.urls import | patterns, include, url
try:
from djcelery.views import apply
urlpatterns = patterns('',
url(r'^apply/(?P<task_name>.+?)/', apply, name='celery-apply'),
url(r'^celery/', include('djcelery.urls')),
)
except ImportError:
urlpatterns = patter | ns('')
|
debugger06/MiroX | lib/test/widgetstateconstantstest.py | Python | gpl-2.0 | 2,572 | 0.002722 | from miro.test.framework import MiroTestCase
from miro.frontends.widgets.widgetstatestore import WidgetStateStore
from miro.frontends.widgets.itemlist import SORT_KEY_MAP
class WidgetStateConstants(MiroTestCase):
def setUp(self):
MiroTestCase.setUp(self)
self.display_types = set(WidgetStateStore.ge... | f.display_types:
for view_type in (WidgetStateStore.get_list_view_type(),
| WidgetStateStore.get_standard_view_type(),
WidgetStateStore.get_album_view_type()):
available_columns.update(
WidgetStateStore.get_columns_available(
display_type, display_id, view_type))
# make... |
msfrank/mandelbrot | mandelbrot/timerange.py | Python | gpl-3.0 | 6,251 | 0.004799 | # Copyright 2014 Michael Frank <msfrank@syntaxjockey.com>
#
# This file is part of Mandelbrot.
#
# Mandelbrot 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 opti... | imePlusDelta)
NowPlusDelta = pp.Suppress(pp.Literal('+')) + TimeValue | + TimeUnit
def parseNowPlusDelta(tokens):
start = datetime.datetime.now(UTC)
value = int(tokens[0])
magnify = tokens[1]
delta = datetime.timedelta(seconds=magnify(value))
return [start, start + delta]
NowPlusDelta.setParseAction(parseNowPlusDelta)
DateTimeWindow = ClosedDateTimeRange | DateTimePlus... |
xkollar/spacewalk | spacecmd/src/lib/misc.py | Python | gpl-2.0 | 28,096 | 0.000285 | #
# Licensed under the GNU General Public License Version 3
#
# 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 version 3 of the License, or
# (at your option) any later version.
#
# This p... | ['id', 'name', 'ip', 'hostname',
'device', 'vendor', 'driver', 'uuid']
####################
def help_systems(self):
print HELP_SYSTEM_OPTS
def help_time(self):
print HELP_TIME_OPTS
####################
def | help_clear(self):
print 'clear: clear the screen'
print 'usage: clear'
def do_clear(self, args):
os.system('clear')
####################
def help_clear_caches(self):
print 'clear_caches: Clear the internal caches kept for systems' + \
' and packages'
print 'usage: clear_caches'
def ... |
NaPs/Kolekto | kolekto/commands/restore.py | Python | mit | 657 | 0 | import json
from kolekto.printer import printer
from kolekto.commands import Command
class Restore(Command):
""" Restore metadata from a json dump.
"""
help = 'Restore metadata from a json dump'
def prepare(self):
self.add_arg('file', help='The json dump file to restore')
def run(self... | :
dump = json.load(fdump)
for movie in dump:
mdb.save(movie['hash'], movie['movie'])
printer.verbose('Loaded {hash}', hash=movie['hash'])
printer.p('Loaded | {nb} movies.', nb=len(dump))
|
enthought/etsproxy | enthought/type_manager/hook.py | Python | bsd-3-clause | 95 | 0 | # proxy module
from __future__ | import absolute_import
from apptools.type_manag | er.hook import *
|
mcinglis/libpp | templates/render.py | Python | agpl-3.0 | 2,004 | 0.001497 |
from __future__ import print_function
from argparse import ArgumentParser, Namespace
TEMPLATE_SEPARATOR = '#####'
OUTPUT_PREFIX = '''
// This file is the result of rendering `{filepath}`.
// You should make changes to this code by editing that template; not
// this file.
'''
def main(argv):
args = parse_args... | format(limit=limit, **(context(limit))`')
.format(TEMPLATE_SEPARATOR))
p.add_argument('limit', type=int)
p.add_argument('filepath', type=str)
p.add_argument('-o', '--output', default='/dev/stdout',
help='The path to the file to write the rendered template to.')
| return p.parse_args(raw_args)
def render(filepath, limit):
text = read_file(filepath)
template, code = text.split('\n' + TEMPLATE_SEPARATOR + '\n', 2)
context_func = execute(code, filepath)['context']
context = context_func(limit)
return (OUTPUT_PREFIX.format(filepath=filepath)
+ temp... |
stephan-rayner/HIL-TestStation | Tests/e3120/Maintenance/TransitionIntoState0.py | Python | mit | 3,533 | 0.012171 | """
Wind Turbine Company - 2013
Author: Stephan Rayner
Email: stephan.rayner@gmail.com
"""
import time
from test.Base_Test import Base_Test
class Maintenance_153Validation(Base_Test):
def setUp(self):
self.WindSpeedValue = "4.5"
self.interface.reset()
self.interface.write("Yaw_Generation... | SD_46" in self.TEST_CONDITION,"Shutdown 46 did not fire")
print "\nPlease Wait One Minute\n"
while((self._readpxUtils(read_Vars) == ["0", | "0"]) and (elapseTime < 120)):
elapseTime = time.time() - initialTime
expectedRunningTime = 60
tollerance = 10
self.TEST_CONDITION = self._readpxUtils(read_Vars)
#
self.assertEqual(self.TEST_CONDITION,["1","1"])
#
self.assertLessEqual(abs(expectedRunningTime-elaps... |
HackerEarth/django-allauth | allauth/socialaccount/providers/stackexchange/urls.py | Python | mit | 178 | 0.005618 | from | allauth.socialaccount.providers.oauth2.urls import default_urlpatterns
from provider import StackExchangeProvider |
urlpatterns = default_urlpatterns(StackExchangeProvider)
|
luotao1/Paddle | python/paddle/regularizer.py | Python | apache-2.0 | 5,630 | 0.007282 | # Copyright (c) 2020 PaddlePaddle 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 app... | set in ``ParamAttr`` , it only takes effect for trainable parameters in this layer. When set in
``optimizer`` , it takes effect for all trainable parameters. When set together, ``ParamAttr`` has
higher priority than ``optimizer`` , which means that for a trainable parameter, if regularizer is defined
in ... | y Regularization is as follows:
.. math::
loss = 0.5 * coeff * reduce\_sum(square(x))
Args:
regularization_coeff(float, optional): regularization coeff. Default:0.0
Examples:
.. code-block:: python
# Example1: set Regularizer in optimizer
import paddle
... |
ocarneiro/minecraft-pi | lab/blinky.py | Python | apache-2.0 | 441 | 0 | import time
import RPi.GPIO as GPIO
LED_VERDE = 22
LED_VERMELHO = 18
GPIO.setmode(GPIO.BOARD)
GPIO.setup(LED_VERDE, GPIO.OUT)
GPIO.output(LED_VERDE, GPIO.LOW)
GPIO.setup(LED_VERMELHO, GPIO.OUT)
GPIO.output(LED_VERM | ELHO, GPIO.LOW)
while True:
GPIO.output(LED_VERDE, GPIO.HIGH)
GPIO.output(LED_VERMELHO, GPIO.LOW)
time.sleep(0.5)
GPIO.output(LED_VERDE, GPIO.LOW)
GPIO.output(LED_VERMELHO, GPI | O.HIGH)
time.sleep(0.5)
|
nikitanovosibirsk/vedro | vedro/plugins/terminator/__init__.py | Python | apache-2.0 | 63 | 0 | fro | m ._terminator import Terminator |
__all__ = ("Terminator",)
|
CityGenerator/Megacosm-Generator | tests/test_generator.py | Python | gpl-2.0 | 8,144 | 0.007859 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"Fully test this module's functionality through the use of fixtures."
from megacosm.generators import Generator
import unittest2 as unittest
import json
from mock import Mock, patch, MagicMock
import fakeredis
import fixtures
from config import TestConfiguration
from ppr... | rand_value from a key that doesn't exist at all. '''
generator = Generator(self.redis)
with self.assertRaisesRegexp(Exception, "the key \(somekey\) doesn't appear to exist or isn't a list"):
generator.rand_value('somekey')
def test_dump_vars(self):
'''Ensure that the generator d... | s())
self.assertEqual(vars(generator), generator.dump_vars())
def test_generate_features(self):
'''test Feature Generation from a namekey'''
generator = Generator(self.redis, {'bogus_size_roll': 1})
self.assertNotIn('bogus', generator.dump_vars())
generator.generate_features... |
christianheinrichs/learning-lpthw | ex01/ex1-sd1.py | Python | gpl-3.0 | 226 | 0 | #!/usr/b | in/env python2
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print 'Yay! Printing.'
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'
print "Some | text"
|
atuljain/coderbounty | website/migrations/0017_comment.py | Python | agpl-3.0 | 819 | 0.001221 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0016_auto_20151128_2006'),
]
operations = [
migrations.CreateModel(
name='Comment',
field... | Key(to='website.Is | sue')),
],
),
]
|
SouthForkResearch/CHaMP_Metrics | tools/topometrics/methods/thalweg.py | Python | gpl-3.0 | 6,178 | 0.003237 | import logging
from shapely.geometry import *
from lib.raster import Raster
import numpy as np
from os import path
import sys
sys.path.append(path.abspath(path.join(path.dirname(__file__), "../../..")))
from lib.shapefileloader import Shapefile
from lib.exception import DataException, MissingException
from lib.metrics ... | @staticmethod
def lookupRasterValues(points, raster):
"""
Given an array of points with real-world coordinates, lookup values in raster
then mask out any nan/nodata values
:param points:
:param raster:
:re | turn:
"""
pointsdict = { "points": points, "values": [] }
for pt in pointsdict['points']:
pointsdict['values'].append(raster.getPixelVal(pt.coords[0]))
# Mask out the np.nan values
pointsdict['values'] = np.ma.masked_invalid(pointsdict['values'])
return poi... |
ctk3b/InterMol | intermol/desmond/__init__.py | Python | mit | 3,879 | 0.003094 | from collections import OrderedDict
import logging
import os
import shutil
import subprocess
import simtk.unit as units
from intermol.desmond.desmond_parser import load, save
DES_PATH = ''
logger = logging.getLogger('InterMolLog')
# terms we are ignoring for now.
#'en': 'Raw Potential',
#'E_x': 'Extended En.',
un... | OND with command:\n %s' % ' '.join(cmd))
with open('desmond_stdout.txt', 'w') as out, open('desmond_stderr.txt', 'w') as err:
exit = subprocess.call(cmd, std | out=out, stderr=err)
if exit:
logger.error('Energy evaluation failed. See %s/desmond_stderr.txt' % direc)
os.chdir(cwd) # return directory up a level again
raise Exception('Energy evaluation failed for {0}'.format(cms))
tot_energy = get_desmond_energy_from_file(energy_file)
# for n... |
fedspendingtransparency/data-act-broker-backend | tests/unit/dataactvalidator/test_fabs45_detached_award_financial_assistance.py | Python | cc0-1.0 | 3,014 | 0.006636 | from tests.unit.dataactcore.factories.staging import DetachedAwardFinancialAssistanceFactory
from tests.unit.dataactvalidator.utils import number_of_errors, query_columns
_FILE = 'fabs45_detached_award_financial_assistance'
def test_column_headers(database):
expected_subset = {'row_number', 'indirect_federal_sha... | vided, IndirectCostFederalShareAmount should be less than or equal to
FederalActionObligation.
| """
# One or both not provided, rule ignored
det_award_1 = DetachedAwardFinancialAssistanceFactory(indirect_federal_sharing=None, federal_action_obligation=None)
det_award_2 = DetachedAwardFinancialAssistanceFactory(indirect_federal_sharing=123, federal_action_obligation=None)
det_award_3 = DetachedAw... |
SANBI-SA/tools-sanbi-uwc | tools/novo_sort/novo_sort.py | Python | gpl-3.0 | 986 | 0.008114 | #!/usr/bin/env python
from __future__ import print_function
import argparse
from subprocess import check_call, CalledProcessError
import shlex
import sys
import logging
log = logging.getLogger( __name__ )
def novo_sort( bam_filename, output_filename ):
cmdline_str = "novosort -c 8 -m 8G -s -f {} -o {}".format( ba... | = shlex.shlex(value)
lex.quotes = '" | '
lex.whitespace_split = True
lex.commenters = ''
return list(lex)
def main():
parser = argparse.ArgumentParser(description="Re-sorting aligned files by read position")
parser.add_argument('output_filename')
parser.add_argument('--bam_filename')
args = parser.parse_args()
novo_sort(ar... |
GeoNode/geonode-notification | notification/migrations/0001_initial.py | Python | mit | 2,390 | 0.003766 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... | True)),
('pickled_data', models.TextField()),
],
),
migrations.CreateModel(
name='NoticeSetting',
| fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('medium', models.CharField(max_length=1, verbose_name='medium', choices=[(0, b'email')])),
('send', models.BooleanField(verbose_name='send')),
],
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.