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
clarkperkins/stackdio
stackdio/api/stacks/workflows.py
Python
apache-2.0
9,270
0.001834
# -*- coding: utf-8 -*- # Copyright 2017, Digital Reasoning # # 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...
] else: raise AttributeError(item) class LaunchWorkflowOptions(WorkflowOptions): DEFAULTS = { 'max_attempts': 3, # Skips launching if set to False 'launch': True, 'provision': True, # Launches in parallel mode if set to True 'parallel': True, ...
'simulate_launch_failures': False, 'simulate_ssh_failures': False, 'failure_percent': 0.3, } class DestroyWorkflowOptions(WorkflowOptions): DEFAULTS = { 'parallel': True, } class BaseWorkflow(object): _options_class = WorkflowOptions def __init__(self, stack, host_id...
GoogleCloudPlatform/appengine-config-transformer
yaml_conversion/lib/google/appengine/api/yaml_object.py
Python
apache-2.0
10,552
0.007487
# Copyright 2015 Google 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 applicable law or ...
lib.google.appengine.api import validation from yaml_conversion.lib.google.appengine.api import yaml_listener from yaml_conversion.lib.google.appengine.api import yaml_builder from yaml_conversion.lib.google.appengine.api import yaml_errors import yaml class _ObjectMapper(object): """Wrapper used for mapping attri...
om a yaml file to an object. This wrapper is required because objects do not know what property they are associated with a creation time, and therefore can not be instantiated with the correct class until they are mapped to their parents. """ def __init__(self): """Object mapper starts off with empty va...
lorensen/VTKExamples
src/Python/GeometricObjects/ConvexPointSet.py
Python
apache-2.0
2,484
0
# !/usr/bin/env python # -*- coding: utf-8 -*- import vtk def main(): cps = vtk.vtkConvexPointSet() points = vtk.vtkPoints() points.InsertNextPoint(0, 0, 0) points.InsertNextPoint(1, 0, 0) points.InsertNextPoint(1, 1, 0) points.InsertNextPoint(0, 1, 0) points.InsertNextPoint(0, 0, 1) ...
pointMapper.SetInputData(polyData) pointMapper.SetSourceConnection(sphere.GetO
utputPort()) pointActor = vtk.vtkActor() pointActor.SetMapper(pointMapper) pointActor.GetProperty().SetColor(colors.GetColor3d("Peacock")) # Create a renderer, render window, and interactor renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.SetWindowName("Convex...
HDE/python-lambda-local
lambda_local/event.py
Python
mit
206
0
''' Copyright 2015-2020 HENNGE K.K. (formerly known as HDE, Inc.) Licensed under MIT. ''' import json def read_event
(path): with open(path) as event: data = json.load(event) return d
ata
hms-dbmi/exac_browser
src/precompute_histogram.py
Python
mit
3,502
0.002856
# Adapted from Daniel Birnbaum's histogram script import argparse import gzip import pipes import sys from collections import Counter import numpy metrics = ['DP', 'GQ'] def main(args): f = gzip.open(args.vcf) if args.vcf.endswith('.gz') else open(args.vcf) if args.output is None: args.output = args.vcf.rep...
le_info[idx] != '.': distr.append(sample_info[idx]) mids, hist = get_hist_from_distribution(distr, midpoints, num_bins) return map(str, mids), map(str, hist) def get_hist_from_distribution(distr, midpoints, num_bins): distr = [convert_to_int(x) for x in distr] if any([type(x) ...
edges = hist[1] mids = [(edges[i]+edges[i+1])/2 for i in range(len(edges)-1)] return mids, hist[0] else: return hist[1], hist[0] if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--vcf', '--input', '-i', help='Input VCF ...
openstack/heat
heat/tests/openstack/sahara/test_data_source.py
Python
apache-2.0
4,214
0
# # 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 # distributed under t...
rsrc_defn, self.stack) ex = self.assertRaises(exception.StackValidationFailed, ds.validate) error_msg = ('Property error: resources.data-source.properties.' 'credentials: Property user not assigned') self.assertEqual(error_msg, str(ex
))
fahhem/mbed-os
tools/export/kds/__init__.py
Python
apache-2.0
1,603
0.001248
""" mbed SDK Copyright (c) 2011-2016 ARM Limited 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...
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. """ from os.path import splitext, basename
from tools.export.exporters import Exporter, deprecated_exporter @deprecated_exporter class KDS(Exporter): NAME = 'Kinetis Design Studio' TOOLCHAIN = 'GCC_ARM' TARGETS = [ 'K64F', 'HEXIWEAR', 'K22F', ] def generate(self): libraries = [] for lib in self.res...
Mikescher/Project-Euler_Befunge
compiled/Python3/Euler_Problem-080.py
Python
mit
5,544
0.059163
#!/usr/bin/env python3 # transpiled with BefunCompile v1.3.0 (c) 2017 import gzip, base64 _g = ("AR+LCAAAAAAABACtkrFyhCAQhl+FQ6+RMbdy4kXCMCnyECkYTJEZWioqHz4/RM85c13UUWB32f32h8Q+85t/BzzVP54j6jP2fgTJyxEk4QgSOoLEj7WtWGXuhvTgTrtw" + "s9rMzlGzNPmq5d/ciU6vXmNrbrjtWq1HoYIbRRd15aearM6ma1BKnPE1ydJIUVotKSIJ3I2k0FZpqv180m0XlXh...
n 9 def _34(): sa(sp()-1) sa(sr()); sa(0) v0=sp() v1=sp() sa(v0) sa(v1) sa(sp()+9) sa(1) v0=sp() v1=sp() gw(v1,v0,sp()) sa(sr()); sa(0) v0=sp() v1=sp() sa(v0) sa(v1) sa(sp()+9) sa(3) v0=sp() v1=sp() gw(v1,v0,sp()) sa(sr()...
a(0) v0=sp() v1=sp() sa(v0) sa(v1) sa(sp()+9) sa(5) v0=sp() v1=sp() gw(v1,v0,sp()) sa(sr()); return 6 m=[_0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34] c=0 while c<35: c=m[c]()
swharden/SWHLab
doc/uses/EPSCs-and-IPSCs/variance method/2016-12-16 tryout2.py
Python
mit
4,500
0.032222
""" This script investigates how calculating phasic currents from voltage clamp recordings may benefit from subtracting-out the "noise" determined from a subset of the quietest pieces of the recording, rather than using smoothing or curve fitting to guess a guassian-like RMS noise function. """ import os import sys s...
PER_MS*250) plt.figure(figsize=(15,5)) plt.plot(Y) plt.plot(baseline,color='r',alpha=.5,lw=5) plt.savefig("baseline.png") plt.figure(figsize=(15,5)) plt.plot(Y-baseline) plt.axhline(0,color='r',alpha=.5,lw=5) plt.savefig("baseline2.png") plt.show() if __name__=="__main_...
erage(Y)) histRange=(histCenter-padding,histCenter+padding) histBins=int(abs(histRange[0]-histRange[1])/HIST_RESOLUTION) # FIRST CALCULATE THE 10-PERCENTILE CURVE data=quietParts(Y,10) # assume 10% is a good percentile to use hist,bins=np.histogram(data,bins=histBins,range=histRange,dens...
wtarimo/CFCScorePredictor
Fixture.py
Python
artistic-2.0
1,032
0.022287
""" William Tarimo COSI 157 - Final Project: CFC Score Predictor Fixture Class: Implements a soccer game fixture 11/30/2012 """ class Fixture(objec
t): """Implements a soccer game fixture""" def __init__(self,game,opponent="",time="",venue="",result=[],cfcScorers=[],oppositionScorers=[]): self.game = game self.opponent = opponent
self.time = time self.venue = venue self.result = [] if result=='[]' else [int(x) for x in result[1:-1].split(", ")] self.cfcScorers = [] if cfcScorers=='[]' else [int(x) for x in cfcScorers[1:-1].split(", ")] self.oppositionScorers = [] if oppositionScorers=='[]' else [int(x)...
miing/mci_migo
acceptance/tests/new_account/new_account_8_confirmation_requires_login.py
Python
agpl-3.0
862
0
from sst.actions import ( assert_element, asser
t_title, check_flags, click_button, get_element, go_to,
wait_for, ) from u1testutils import mail from u1testutils.sso import mail as sso_mail from u1testutils.sst import config from acceptance import helpers check_flags('allow_unverified') config.set_base_url_from_env() edit_account_anchor = {'data-qa-id': 'edit_account'} email_address = mail.make_unique_test_email_a...
phoebeargon/BigDataForEducation
big_data_for_education/users/models.py
Python
mit
837
0.001195
from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class User(AbstractUser): # First Name a...
= models.CharField(_('Name of User'), blank=True, max_length=255) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) class Document(models.Model): description = models.CharField(max_leng
th=255, blank=True) document = models.FileField(upload_to='documents/%Y/%m/%d/') uploaded_at = models.DateTimeField(auto_now_add=True)
ismaelgaudioso/pihome
Events/draw.py
Python
mit
193
0.020725
from Events.e
vent import * class DrawEvent(Event): """ The event for when the CPU Spinner wants the main vi
ew to update the display """ def __init__(self): self.name = "Draw Event"
drufat/sympy
sympy/printing/tests/test_theanocode.py
Python
bsd-3-clause
9,802
0.006223
from sympy.external import import_module from sympy.utilities.pytest import raises, SKIP from sympy.core.compatibility import range theano = import_module('theano') if theano: import numpy as np ts = theano.scalar tt = theano.tensor xt, yt, zt = [tt.scalar(name, 'floatX') for name in 'xyz'] else: #...
B: [(n//2, n//2), (n//2, n//2)]} cutinputs = [sympy.blockcut(i, *cutsiz
es[i]) for i in inputs] cutoutput = output.subs(dict(zip(inputs, cutinputs))) dtypes = dict(zip(inputs, [dtype]*len(inputs))) f = theano_function(inputs, [output], dtypes=dtypes, cache={}) fblocked = theano_function(inputs, [sympy.block_collapse(cutoutput)], dtypes=dtypes...
DakRomo/2017Challenges
challenge_0/python/slandau/hello_world.py
Python
mit
77
0
#!/usr/bin/env pyth
on3 if __name__ == '__main__': print('Hello W
orld!')
OTL/jps
test/test_utils.py
Python
apache-2.0
2,258
0
import jps import json import time class MessageHolder(object): def __init__(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = Mes...
s3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_...
s.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge"...
ulope/nearest_pypi
wsgi.py
Python
mit
104
0
fr
om werkzeug.contrib.fixers import Proxy
Fix from app import app app.wsgi_app = ProxyFix(app.wsgi_app)
rsalmaso/huey
huey/contrib/kyototycoon.py
Python
mit
3,659
0
from functools import partial import time from ukt import KT_NONE from ukt import KyotoTycoon from huey.api import Huey from huey.constants import EmptyData from huey.storage import BaseStorage from huey.utils import decode class KyotoTycoonStorage(BaseStorage): priority = True def __init__(self, name='hue...
urn {key[plen:]: value for key, value in result.items()} def flush_results(self): prefix = self.prefix_key('') keys = self.kt.match_prefix(prefix, db=self._db) return self.kt.remove_bulk(keys, self._db) def flush_all(self):
self.flush_queue() self.flush_schedule() self.flush_results() class KyotoTycoonHuey(Huey): storage_class = KyotoTycoonStorage
asm-products/pants-party
subscriptions/admin.py
Python
agpl-3.0
100
0
from django.contrib import ad
min from models import Subscription admin.site.register(Subscription)
pombredanne/voc
tests/datatypes/test_float.py
Python
bsd-3-clause
6,425
0.000156
from .. utils import TranspileTestCase, UnaryOperationTestCase, BinaryOperati
onTestCase, InplaceOperationTestCase class FloatTests(TranspileTestCase): def test_setattr(self): self.assertCodeExecution(""" x = 3.14159 try: x.attr = 42 except AttributeError as err: print(err) """) def test_getattr(se...
elf.assertCodeExecution(""" x = 3.14159 try: print(x.attr) except AttributeError as err: print(err) """) def test_repr(self): self.assertCodeExecution(""" x = 350000000000000000.0 print(x) x ...
timpalpant/KaggleBillionWordImputation
scripts/predict_missing_word.space.py
Python
gpl-3.0
770
0.009091
#!/usr/bin/env
python ''' Predict missing words with n-gram model ''' import sys, argparse from itertools import izip from util import tokenize_words def opts(): parser =
argparse.ArgumentParser(description=__doc__) parser.add_argument('sample', type=argparse.FileType('r'), help='Sentences with one missing word') parser.add_argument('removed', type=argparse.FileType('r'), help='File with predicted indices of missing words') return parser if __name__ == "__m...
eino-makitalo/odoo
openerp/addons/base/ir/ir_fields.py
Python
agpl-3.0
17,664
0.002434
# -*- coding: utf-8 -*- import cStringIO import datetime import functools import itertools import time import psycopg2 import pytz from openerp import models, api, _ from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, ustr REFERENCING_FIELDS = set([None, 'id', '.id']) def only_ref_f...
an integer for field '%%(field)s'"), value ) @api.model def _str_to_float(self, model, field, value): try: return float(value), [] except ValueError: raise self._format_import_error( ValueError,
_(u"'%s' does not seem to be a number for field '%%(field)s'"), value ) @api.model def _str_id(self, model, field, value): return value, [] _str_to_reference = _str_to_char = _str_to_text = _str_to_binary = _str_to_html = _str_id @api.model def _str_to...
thombashi/DataProperty
test/test_function.py
Python
mit
4,806
0.000625
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ import pytest from dataproperty import get_integer_digit, get_number_of_digit nan = float("nan") inf = float("inf") class Test_get_integer_digit: @pytest.mark.parametrize( ["value", "expected"], [ [0, 1], ...
["0", (1, 0)], ["-0", (1, 0)], [10, (2, 0)], [-10, (2, 0)], ["10", (2, 0)], ["-10", (2, 0)], [10.1, (2, 1
)], [-10.1, (2, 1)], ["10.1", (2, 1)], ["-10.1", (2, 1)], [10.01, (2, 2)], [-10.01, (2, 2)], [10.001, (2, 3)], [-10.001, (2, 3)], [100.1, (3, 1)], [-100.1, (3, 1)], [100.01, (3, 2)], [-100...
NovikovMA/python_training
model/address.py
Python
apache-2.0
2,625
0.002667
# -*- coding: utf-8 -*- __author__ = 'M.Novikov' from sys import maxsize class Address: def __init__(self, id=None, first_name=None, middle_name=None, last_name=None, nickname=None, title=None, company=None, address=None, tel_home=None, tel_mobile=None, tel_work=None, tel_fax=N...
l_from_home_page = all_email_from_home_page def __repr__(self): return "%s: %s %s" % (self.id, self.last_name, self.first_name) def __eq__(self, other): return (self.id is None or other.id is None or self.id == other.id)\ and self.first_name == other.first_name\ a...
and (self.all_phones_from_home_page is None or other.all_phones_from_home_page is None or self.all_phones_from_home_page == other.all_phones_from_home_page)\ and (self.all_email_from_home_page is None or other.all_email_from_home_page is None or self.all_email_from_home_page == other.all_email_from...
DemiMarie/SlipRock
.ycm_extra_conf.py
Python
isc
6,434
0.017718
# This file is NOT licensed under the GPLv3, which is the license for the rest # of YouCompleteMe. # # Here's the license text for this file: # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either...
if flag.startswith( path_flag ): path = flag[ len( path_flag ): ] new_flag = path_flag + os.path.join( working_directory, path ) break
if new_flag: new_flags.append( new_flag ) return new_flags def IsHeaderFile( filename ): extension = os.path.splitext( filename )[ 1 ] return extension in [ '.h', '.hxx', '.hpp', '.hh' ] def GetCompilationInfoForFile( filename ): # The compilation_commands.json file generated by CMake does not have ...
lycopersin/x6hr-python
x6hr.py
Python
gpl-3.0
17,896
0.013093
#!/usr/bin/python # -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: x6hr.py # Purpose: log reader of SUUNTO H6HR # Author: tomoya kamata (iware pref. japan) # Created: 15 Mar 2010 # Copyright: GPL. please read COPYING file # ma...
lut.append(i) return lut def read_hiking_log(self, index): p = self.read_register
(0x0fc8 + (index - 1) * 128, 0x30) log = {} log['start'] = "20%02d/%d/%d %02d:%02d" % (p[1],p[2],p[3],p[4],p[5]) log['interval'] = p[6] log['hrdata'] = p[7] == 1 log['total ascent'] = p[8] * 256 + p[9] log['total descent'] = p[10] * 256 + p[11] log['laps'] ...
iw3hxn/LibrERP
sale_order_analysis/__openerp__.py
Python
agpl-3.0
1,472
0.000679
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # # Copyright (C) 2015 Didotech srl (<http://www.didotech.com>). # # All Rights Reserved # # This program is free software: you can redistr...
#################################################################### { "name": "Sale Order Analysis", "version": "3.1.1.2", "author": "Didotech SRL", "website": "http://www.didotech.com", "category": "Sales Management", "description": """ Module permits to create a simple analysis on sa...
active": False, "installable": True, }
censusreporter/censusreporter
censusreporter/apps/census/templatetags/results.py
Python
mit
1,848
0.001082
from collections import defaultdict from django import template from django.utils.safestring import mark_safe from censusreporter.apps.census.utils import parse_table_id, generic_table_description, table_link
register = template.Library() @register.filter def format_subtables_for_results(table_ids): parts = [] deferred_racials = defaultdict(list) deferred_pr = [] for table in table_ids: parsed = parse_table_id(table) if parsed['racial']: key = parsed['table_type'] ...
rico']: key += 'PR' deferred_racials[key].append(parsed) elif parsed['puerto_rico']: deferred_pr.append(table) else: parts.append(table_link(table, generic_table_description(table))) for table in deferred_pr: parts.append(table_link(table,...
rchakra3/x9115rc3
hw/code/1/ok.py
Python
gpl-2.0
1,020
0.028431
""" Source: https://github.com/txt/mase/blob/master/src/ok.md # Unit tests in Python Python has some great unit testing tools. The one shown below is a "less-is-more" approach and is based on [Kent Beck video on how to write a test engine in just a few lines of code](https://www.youtube.com/watch?v=nIonZ6-4nuU). Fo...
PASS = %s%%" % ( t,f,int(round(t*100/(t+f+0.001)))) def __init__(i,test): unittest.tries += 1 try: test(
) except Exception,e: unittest.fails += 1 i.report(test) def report(i,test): import traceback print traceback.format_exc() print unittest.score(),':',test.__name__
OreCruncher/DynamicSurroundings
rtd/source/conf.py
Python
mit
5,517
0.000363
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------...
----------------- # Output file base name for HTML help builder. htmlhelp_basename = 'DynamicSurroundingsdoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size
('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the ...
sciunto-org/scifig
libscifig/collogging.py
Python
gpl-3.0
1,446
0.009682
#!/usr/bin/env python # -*- coding: utf-8 -*- # Code adapted from https://stackoverflow.com/questions/21923249/logging-formatting-right-justify-level-name import logging BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) #The background is set with 40 plus the number of the color, and the foreground wi...
Q record.msg = message_color
return logging.Formatter.format(self, record)
tequa/ammisoft
ammimain/WinPython-64bit-2.7.13.1Zero/python-2.7.13.amd64/Scripts/f2py.py
Python
bsd-3-clause
827
0
#!C:\Users\DMora
n\Downloads\WinPython-64bit-2.7.13.1Zero\python-2.7.13.amd64\python.exe # See http://cens.ioc.ee/projects/f2py2e/ from __future__ import division, print_function import os import sys for mode in ["g3-numpy", "2e-numeric", "2e-numarray", "2e-numpy"]: try: i = sys.argv.index("--" + mode) del sys.argv...
t ValueError: pass os.environ["NO_SCIPY_IMPORT"] = "f2py" if mode == "g3-numpy": sys.stderr.write("G3 f2py support is not implemented, yet.\\n") sys.exit(1) elif mode == "2e-numeric": from f2py2e import main elif mode == "2e-numarray": sys.argv.append("-DNUMARRAY") from f2py2e import main el...
herow/planning_qgis
python/plugins/processing/algs/qgis/MeanCoords.py
Python
gpl-2.0
4,557
0.001097
# -*- coding: utf-8 -*- """ *************************************************************************** MeanCoords.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ****************************...
azz, values) in means.iteritems(): outFeat = QgsF
eature() cx = values[0] / values[2] cy = values[1] / values[2] meanPoint = QgsPoint(cx, cy) outFeat.setGeometry(QgsGeometry.fromPoint(meanPoint)) outFeat.setAttributes([cx, cy, clazz]) writer.addFeature(outFeat) del writer
MrPablozOne/kaira
gui/cmdutils.py
Python
gpl-3.0
2,053
0.003897
# # Copyright (C) 2010 Stanislav Bohm # # This file is part of Kaira. # # Kaira 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, version 3 of the License, or # (at your option) any later versi...
nces_count() def main(): parser = argparse.ArgumentParser(description='Kaira gui command line controller') parser.add_argument('--export', metavar='filename', type=str) parser.add_argument('--output', metavar='directory', type=str) parser.add_argument("--trace", action='store_true') parser.add_argu...
ype=str) parser.add_argument("--lib", action='store_true') args = parser.parse_args() if args.export: export(os.path.abspath(args.export), args.output, args.trace, args.lib) return if args.tracelog: check_tracelog(args.tracelog) if __name__ == "__main__": main()
MapuH/Interactive-Programming-In-Python
simplegui-demo.py
Python
mit
613
0.014682
try: import simplegui except ImportError: import SimpleGUI
CS2Pygame.simpleguics2pygame as simplegui message = "Welcome!" # Handlers for mouse click def click(): global message message = "Good job!" def reset(): global message message = "Welcome!" # Handler to draw on canvas def draw(canvas): canvas.draw_text(message, [50,112], 48, "Red") # Create a frame an...
tart the frame animation frame.start()
andres-hurtado-lopez/naranjaverdeprod
app/produccion/__init__.py
Python
mit
163
0.006135
#!/usr/bin/env python # -*- coding: utf-8 -*- from bottle import template, redirect import utils def GET(**p
arams): return template('materiales_
index.html')
jawilson/home-assistant
homeassistant/components/cloudflare/config_flow.py
Python
apache-2.0
6,680
0.000599
"""Config flow for Cloudflare integration.""" from __future__ import annotations import logging from typing import Any from pycfdns import CloudflareUpdater from pycfdns.exceptions import ( CloudflareAuthenticationException, CloudflareConnectionException, CloudflareZoneException, ) import voluptuous as vo...
import config_validation as cv from homeassistant.h
elpers.aiohttp_client import async_get_clientsession from .const import CONF_RECORDS, DOMAIN _LOGGER = logging.getLogger(__name__) DATA_SCHEMA = vol.Schema( { vol.Required(CONF_API_TOKEN): str, } ) def _zone_schema(zones: list | None = None): """Zone selection schema.""" zones_list = [] ...
arthurSena/processors
tests/processors/base/processors/test_trial.py
Python
mit
1,381
0.006517
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import pytest import uuid from processors.base import helpers import processors.nct.extractors as nct_extractors from processors.base.processors.t...
'trial_id': trial, 'is_primary': True, 'source_id': euctr_source, 'identi
fiers': {'nct': nct_record}, }) conn['database']['records'].update(current_primary, ['id']) process_trials(conn, 'nct', extractors) updated_current_primary = conn['database']['records'].find_one(id=record) new_record = conn['database']['records'].find_one(id=nct_record_attrs['me...
CRImier/pyLCI
output/output.py
Python
apache-2.0
717
0.004184
from helpers import read_config import importlib screen = None def init(): """ This function is called by main.py to read the output configuration, pick the corresponding drivers and initialize a Screen object. It also sets ``screen`` global of ``output`` module with created ``
Screen`` object.""" global screen config = read_config("config.json") output_config = config["output"][0] driver_name = output_config["driver"] driver_module = importlib.import_module("out
put.drivers."+driver_name) args = output_config["args"] if "args" in output_config else [] kwargs = output_config["kwargs"] if "kwargs" in output_config else {} screen = driver_module.Screen(*args, **kwargs)
heqiao2010/demo
exlogutil/ExLogUtilPy/ExLogUtil/__init__.py
Python
gpl-3.0
45
0.022222
__autho
r__ = 'joel' __all__ = ["ExLogUtil"]
dloman/FiestaMonsterz
Drawing/Drawable.py
Python
gpl-3.0
1,861
0.017195
from Utility.Utility import DoesntHaveMethod ################################################################################ ################################################################################ class Drawable(object): ############################################################################## def __...
nctor, GetPositionFunctor): self.DrawFunctor = DrawFunctor self.GetPositionFunctor = GetPositionFunctor ############################################################################## @property def DrawFunctor(self): return self.__DrawFunctor ########################################################...
DrawFunctor): if not callable(DrawFunctor): raise TypeError(str(type(DrawFunctor)) + " must be a callable type") self.__DrawFunctor = DrawFunctor ############################################################################## @property def GetPositionFunctor(self): return self.__GetPositionFunct...
shravanshandilya/catching-up-with-python
Recipes/class_example.py
Python
mit
245
0.093878
class F
riend: def walk(self,shravan=""): ''' >>> Friend().walk() walking ''' print "walking", def talk(self): print "talking", def fight(self): print "fighting", f1=Friend() f1.walk() import do
ctest doctest.testmod()
spyder-ide/spyder-terminal
spyder_terminal/api.py
Python
mit
764
0
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) Spyder Project Contributors # # Licensed under the
terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- """Spyder Terminal Plugin.""" class TerminalMainWidgetActions: NewTerminal = 'new_terminal_toolbar_action' NewTerminalForCWD = 'new_terminal' NewTerminalForProje
ct = 'new_terminal_project_action' NewTerminalForFile = 'new_terminal_file_action' RenameTab = 'rename_tab_action' Copy = 'copy' Paste = 'paste' Clear = 'clear' ZoomIn = 'zoom_in' ZoomOut = 'zoom_out' class TermViewMenus: Context = 'context_menu'
CINPLA/expipe-dev
python-neo/neo/io/nestio.py
Python
gpl-3.0
32,456
0.000216
# -*- coding: utf-8 -*- """ Class for reading output files from NEST simulations ( http://www.nest-simulator.org/ ). Tested with NEST2.10.0 Depends on: numpy, quantities Supported: Read Authors: Julia Sprenger, Maximilian Schmidt, Johanna Senk """ # needed for Python3 compatibility from __future__ import absolute_...
if 'dat' not in self.avail_formats: raise ValueError('Can not load analogsignals. No DAT file '
'provided.') # checking gid input parameters gid_list, id_column = self._check_input_gids(gid_list, id_column) # checking time input parameters t_start, t_stop = self._check_input_times(t_start, t_stop, mandatory=False) # chec...
valmynd/MediaFetcher
src/plugins/youtube_dl/youtube_dl/extractor/tweakers.py
Python
gpl-3.0
1,742
0.029851
from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( int_or_none, determine_ext, mimetype2ext, ) class TweakersIE(InfoExtractor): _VALID_URL = r'https?://tweakers\.net/video/(?P<id>\d+)' _TEST = { 'url': 'https://tweakers.net/video/9926/new-nintendo-3ds-xl-op-alle-fr...
get('src') if not source_url:
continue ext = mimetype2ext(source.get('type')) or determine_ext(source_url) formats.append({ 'format_id': format_id, 'url': source_url, 'width': width, 'height': height, 'ext': ext, }) self._sort_formats(formats) return { 'id': video_id, 'title': title, 'description':...
mortcanty/SARDocker
src/build/lib.linux-x86_64-2.7/auxil/png.py
Python
mit
142,825
0.002962
#!/usr/bin/env python # $URL: http://pypng.googlecode.com/svn/trunk/code/png.py $ # $Rev: 201 $ # png.py - PNG encoder/decoder in pure Python # # Copyright (C) 2006 Johann C. Rocholl <johann@browsershots.org> # Portions Copyright (C) 2009 David Jones <drj@pobox.com> # And probably portions Copyright (C) 2006 Nicko va...
struct import sys import zlib # http://www.python.org/doc/2.4
.4/lib/module-warnings.html import warnings __all__ = ['Reader', 'Writer', 'write_chunks'] # The PNG signature. # http://www.w3.org/TR/PNG/#5PNG-file-signature _signature = struct.pack('8B', 137, 80, 78, 71, 13, 10, 26, 10) _adam7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4,...
ucdavis-agecon/gunicorn-init
tree/etc/gunicorn/py/example.py
Python
mit
272
0.018382
# Example taken from the http://gunicorn.org/configure.html # page.
import os def numCPUs(): if not hasattr(os, "sysconf"): raise RuntimeError("No sysconf detected.") return os.sysconf("SC_
NPROCESSORS_ONLN") bind = "127.0.0.1:8000" workers = numCPUs() * 2 + 1
sam-roth/Keypad
keypad/abstract/editor.py
Python
gpl-3.0
4,153
0.004816
import abc from ..control import BufferController from ..buffers import Buffer from .application import app, AbstractApplication from ..control.interactive import interactive from ..core import Signal import logging class AbstractEditor(metaclass=abc.ABCMeta): def __init__(self, view, config): self.__vie...
s == 'DELETE Unknown Characters': self.__buffer_controller.write_to_path(ed.path, codec_errors='ignore') else: raise except OSError as exc: if not prompt_on_error: raise res = app().message_box(self, ...
will remain open)'], kind=AbstractApplication.MessageBoxKind.warning) raise self.saved() def load(self, path, *, codec_errors='strict'): ''' Load the file from the path given. ''' from ..core.notification_queue import ...
josenavas/american-gut-web
amgut/handlers/human_survey.py
Python
bsd-3-clause
7,184
0.000139
from json import dumps, loads import logging from tornado.web import authenticated from tornado.escape import url_escape from amgut import media_locale, text_locale from amgut.connections import ag_data, redis from amgut.handlers.base_handlers import BaseHandler from amgut.lib.util import store_survey, make_survey_cl...
d'])) else: # old consent so no idea of age range and text, only juv/non-juv raise NotImplementedError("Old consent, no text available") return message class HumanSurveyHandler(BaseHandler): @authenticated def post(self): # see if we're coming from an edit human_survey...
self.get_argument('survey_id', None) page_number = int(self.get_argument('page_number')) sitebase = media_locale['SITEBASE'] if human_survey_id is None: # we came from consent human_survey_id = self.get_secure_cookie('human_survey_id') if human_survey_id is ...
guegue/forocacao
forocacao/app/context_processors.py
Python
bsd-3-clause
1,036
0.003861
from django.conf import settings from forocacao.app.models import Event, Content def get_or_none(model, objects, *args, **kwargs): try: return objects.get(*args, **kwargs) except model.DoesNotExist: return None def current_event(request): ''' A context processor to add the "current ev...
ntext ''' try: current_event = Event.objects.filter(status='frontpage')[0] return { 'event': current_event, 'current_event': current_event.name, 'current_slug': current_event.slug, 'current_info': get_or_none(Content, current_event.contents, page=...
rn a dict, no matter what! return { 'event': None, 'current_event': '', 'current_slug': '', 'current_info': '', 'current_footer': '', }
LLNL/spack
var/spack/repos/builtin/packages/py-azure-mgmt-resource/package.py
Python
lgpl-2.1
853
0.001172
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class PyAzureMgmtResource(PythonPackage): """Microsoft Azure Resource Management Client Library for Python.""" h...
= "azure-mgmt-resource/azure-mgmt-resource-10.0.0.zip" version('10.0.0', sha256='bd9a3938f5423741329436d2da09693
845c2fad96c35fadbd7c5ae5213208345') depends_on('py-setuptools', type='build') depends_on('py-msrest@0.5.0:', type=('build', 'run')) depends_on('py-msrestazure@0.4.32:1', type=('build', 'run')) depends_on('py-azure-common@1.1:1', type=('build', 'run')) depends_on('py-azure-mgmt-nspkg', when='^python...
openstack/ceilometer
ceilometer/network/services/lbaas.py
Python
apache-2.0
15,220
0
# # Copyright 2014 Cisco Systems,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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
onf.service_types.neutron_lbaas_version warnings.warn('Support for Neutron LBaaS has been deprecated ' 'and will be removed in a future release.', category=DeprecationWarning, stacklevel=3) def get_load_balancer_status_id(self, value): if self.lb_version...
self.get_status_id(value) elif self.lb_version == 'v2': status = value.lower() resource_status = LOAD_BALANCER_STATUS_V2.get(status, -1) return resource_status class LBPoolPollster(BaseLBPollster): """Pollster to capture Load Balancer pool status samples.""" FIELDS = ...
uclouvain/osis
program_management/ddd/service/write/postpone_program_tree_service_mini_training.py
Python
agpl-3.0
2,696
0.002597
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
amTreeVersionRepository() ) # WHEN while from_year < end_postponement_year: identity_next_year = copy_program_tree_service.copy_program_tree_to_next_year( copy_cmd=CopyProgramTreeToNextYearCommand( code=postpone_cmd.from_c
ode, year=from_year, ) ) # THEN identities_created.append(identity_next_year) from_year += 1 return identities_created
asajeffrey/servo
tests/wpt/web-platform-tests/worklets/resources/credentials.py
Python
mpl-2.0
591
0
# Returns a valid response when a request has appropriate credentials. def main(request, response): cookie = request.cookies.first(b"cookieName", None) expected_value = request.GET.first(b"value", None) source_origin = request.headers.get(b"origin", None) response_headers = [(b"Content-Type", b"text/ja...
w-Origin", source_origin), (b"Access-Control-Allow-Credentials", b"true")] if cookie == expected_value: return (200, response_headers, u"") return (404,
response_headers)
wooga/airflow
tests/providers/opsgenie/hooks/test_opsgenie_alert.py
Python
apache-2.0
5,041
0.000198
# # 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...
aults_host(self): hook = OpsgenieAlertHook() hook.get_conn() self.assertEqual('https://api.opsgenie.com', hook.base_url) @requests_mock.mock() def test_call_with_success(self, m): hook = OpsgenieAlertHook(opsgenie_conn_id=self.conn_id) m.post( self.opsgenie_a...
json=self._mock_success_response_body ) resp = hook.execute(payload=self._payload) self.assertEqual(resp.status_code, 202) self.assertEqual(resp.json(), self._mock_success_response_body) @requests_mock.mock() def test_api_key_set(self, m): hook = OpsgenieAler...
tobi-wan-kenobi/bumblebee-status
bumblebee_status/modules/core/debug.py
Python
mit
503
0
# pylint: disable=C0111,R0903 """Shows that debug is enabled""" import platform import core.module import core.widget import core.decorators class Module(core.module.Module): @core.decorators.every(minutes=60) def __init__(self, config, theme): super().__init__(config, t
heme, core.widget.Widget(self.full_text)) def full_text(self, widgets): return "debug" def state
(self, widget): return "warning" # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
novapost/django-pimpmytheme
example/example/settings.py
Python
mit
3,921
0
""" Django settings for example project. For more information on this file, see https://docs.djangoproject.com/en/1.6/t
opics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref
/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import sys BASE_DIR = os.path.dirname(os.path.dirname(__file__)) sys.path.append(os.path.join(BASE_DIR, "..")) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/ho...
suraj-jayakumar/lstm-rnn-ad
src/testdata/random_data_time_series/generate_data.py
Python
apache-2.0
1,042
0.019194
# -*- coding: utf-8 -*- """ Created on Tue Feb 23 11:15:12 2016 @author: suraj """ import random import numpy as np import pickle import matplotlib.pyplot as plt attachRateList = [] for i in range(3360): attachRateList.append(random.uniform(4,6)) attachRateList = np.array(attachRateList) encoded_attach_rate...
ange(3360)] encoded_time_number_list = np.fft.fft(time_number_list) final_list_x = np.array([[encoded_day_number_list.real[i],encoded_day_number_list.imag[i],encoded_time_number_list.real[i],encoded_time_number_list.imag[i],encoded_attach_rate_list.real[i],encoded_attach_rate_list.imag[i]] for i in range(3360)]) fin...
l_list_x,open('x_att.p','wb')) pickle.dump(final_list_y,open('y_att.p','wb'))
jasperges/blenderseed
properties/nodes/kelemen_brdf.py
Python
mit
5,574
0
# # This source file is part of appleseed. # Visit http://appleseedhq.net/ for additional information and resources. # # This software is released under the MIT license. # # Copyright (c) 2014-2017 The appleseedhq Organization # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this s...
") def draw_buttons(self, context, layout): pass def draw_buttons_ext(self, context, layout): pass def copy(self, node):
pass def free(self): asUpdate("Removing node ", self) def draw_label(self): return self.bl_label def register(): bpy.utils.register_class(AppleseedKelemenMultiplierSocket) bpy.utils.register_class(AppleseedKelemenReflectanceSocket) bpy.utils.register_class(AppleseedKelemenR...
configuresystems/restful-api-with-flask
app/modules/todo/tests.py
Python
mit
5,136
0
from flask import url_for from app.testing import BaseTestCase import json class TodoTests(BaseTestCase): def test_get_all_tasks(self): """Test intended to pull all tasks, ensure status 200 response, and that the list is a lenght of 2""" with self.client: tasks = [{'title': "Ge...
ponse.json.get('tasks')), 2) def test_get_task(self): """Test indended to ensure status 200 and pull the task with an id of 1, then check its title""" with self.client: tasks = {'title': "Test Single Get", 'description': "Can we get it successfully" ...
/json"}, data=json.dumps(tasks)) with self.client: response = self.client.get(url_for('get_task', id=1)) self.assert200(response) self.assertEqual(response.json.get('task')['title'], "Test Single Get") def t...
yhteentoimivuuspalvelut/ytp-tools
continuous-deployment/visualization/generate_build_duration_summary.py
Python
agpl-3.0
2,157
0.003245
#!/usr/bin/env python import sys import os import glob from collections import defaultdict from operator import itemgetter import json import logging logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s') log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) def parse_task_durations_from_log_...
og.warn("could not find excepted log files for build {0}, skipping build".format(build_directory)) continue for playbook_logfile in logfile_list[1:3]: with open(playbook_logfile, 'r') as logfile: for task_line in logfile: split = task_line.replace('\n...
split = split[1].split(' | ') if len(split) == 2: results['{0} ({1})'.format(split[1], split[0])].append({"x": timestamp, "y": duration}) elif len(split) == 1: results['{0} (no role)'.format(split[0])].append({"x...
dpgaspar/Flask-AppBuilder
examples/simpleform/app/__init__.py
Python
bsd-3-clause
382
0
i
mport logging from flask import Flask from flask_appbuilder import AppBuilder, SQLA """ Logging configuration """ logging.basicConfig(format="%(asctime)s:%(levelname)s:%(name)s:%(message)s") logging.getLogger().setLevel(logging.DEBUG) app = Flask(__name__) app.config.from_object("config") db = SQLA(app) appbuilder...
er(app, db.session) from . import views # noqa
OpenSciViz/cloudstack
openstack/src/python/nova-libvirt/backup/utils.py
Python
mit
18,922
0.000106
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # Copyright (c) 2011 Piston Cloud Computing, Inc # Copyright (c) 2011 OpenStack Foundation # (c) Cop...
RESIZE_SNAPSHOT_NAME = 'nova-resize' def execute(*args, **kwargs): return utils.execute(*args, **kwargs) def get_iscsi_initiator(): return volumeutils.get_iscsi_initiator() def create_image(disk_format, path, size): """Create a disk image :param disk_format: Disk image format (as known by qemu-im...
age. May be given as an int or a string. If given as an int, it will be interpreted as bytes. If it's a string, it should consist of a number with an optional suffix ('K' for Kibibytes, M for Mebibytes, 'G' for Gibibytes, 'T' for Tebibytes). ...
fabric8-analytics/fabric8-analytics-worker
tests/storages/test_postgres.py
Python
gpl-3.0
4,228
0.003075
"""Test the Postgress interface - data storage and retrieval.""" import datetime import flexmock import selinon from f8a_worker.defaults import configuration from f8a_worker.enums import EcosystemBackend from f8a_worker.models import (Ecosystem, Package, Version, Analysis, WorkerResult, ...
n) self.p = Package(ecosystem=self.e, name=self.pn) self.v = Version(package=self.p, identifier=self.vi) self.a = Analysis(version=self.v, finished_at=datetime.datetime.utcnow()) self.a2 = Analysis(version=self.v, finished_at=datetime.datetime.utcnow() + dateti...
gres(connection_string=configuration.POSTGRES_CONNECTION) assert method def test_retrieve_normal(self): """Test the ability to retrieve data from Postgress.""" wid = 'x' w = 'y' tr = {'1': '2'} wr = WorkerResult(analysis=self.a, worker_id=wid, worker=w, task_result=t...
itsapi/pycraft
events.py
Python
gpl-2.0
1,083
0.003693
from random import random import render, player def process_events(events, server): new_blocks = {} for event in events: if event['time_remaining'] <= 0: new_blocks.update(event['func'](server, *eve
nt['args'])) events.remove(event) else: event['time_remaining'] -= 1 return new_blocks def boom(server, x, y): new_blocks = {} radius = 5 blast_strength = 85 for tx in range(x - radius*2, x + radius*2): new_blocks[tx] = {} for ty in rang
e(y - radius, y + radius): if (render.in_circle(tx, ty, x, y, radius) and tx in server.map_ and ty >= 0 and ty < len(server.map_[tx]) and player.can_strength_break(server.map_[tx][ty], blast_strength)): if not render.in_circle(tx, ty, x, y, radius - 1): ...
sipwise/repoapi
repoapi/signals.py
Python
gpl-3.0
6,714
0
# Copyright (C) 2022 The Sipwise Team - http://sipwise.com # # 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 pr...
log.warn("ppa unset, skip removal") return GerritRepoInfo = apps.get_model("repoapi", "GerritRepoInfo") gri = GerritRepoInfo.objects ppa, created = gri.get_or_create( param_ppa=instance.param_ppa, gerrit_change=instance.gerrit_change, defaults={"projectname": instanc...
g.debug("ppa created", ppa=str(ppa)) elif ppa.projectname == "unknown": ppa.projectname = instance.projectname ppa.save() log.info("ppa projectname updated") def gerrit_repo_del(instance): log = logger.bind( instance=str(instance), ) if instance.param_ppa == "$ppa": ...
nyu-mhealth/project-smsurvey
main/smsurvey/core/services/question_service.py
Python
gpl-3.0
2,074
0.001929
import pickle import boto3 from botocore.exceptions import ClientError from smsurvey.core.model.question import Question from smsurvey.core.model.question import QuestionOperationException from smsurvey import config class QuestionService: def __init__(self, cache_name=config.question_backend_name, local=confi...
( TableName=self.cache_
name, Key={ 'question_number': {'S': str(question_number)}, 'protocol_id': {'S': str(protocol_id)} } ) except ClientError as e: print(e.response['Error']['Message']) raise QuestionOperationException("Erro...
mmcardle/MServe
django-mserve/jobservice/tasks.py
Python
lgpl-2.1
4,498
0.012228
######################################################################## # # University of Southampton IT Innovation Centre, 2011 # # Copyright in this library belongs to the University of Southampton # University Road, Highfield, Southampton, UK, SO17 1BJ # # This software may not be used, sold, licensed, transferred,...
buf): self.contents.append(buf) #= "%s%i: %s" % (self.contents, self.line, buf) def __str__(self): return ", ".join(self.contents) @task def copyfromurl(inputs,outputs,options={},callbacks=[]): url = options["url"] logging.info(url) tfile = tempfile.NamedTemporaryFile('wb',delete=Fal...
LLOWLOCATION, 1) c.setopt(c.WRITEFUNCTION, f.write) c.setopt(c.HEADERFUNCTION, retrieved_headers.store) c.perform() status = c.getinfo(c.HTTP_CODE) c.close() f.close() logging.debug(retrieved_headers) filename = "Imported File" for header in retrieved_headers.contents: if h...
Trii/NoseGAE
examples/function_manual_config/test.py
Python
bsd-2-clause
348
0.002874
fr
om webtest import TestApp import helloworld import os def test_index(): test_index.testbed.init_taskqueue_stub(task_retry_seconds=42, root_path=os.path.dirname(__file__)) app = TestApp(helloworld.app) # fires off a task queue and should pass without exceptions response = app.get('/') ass
ert 'Hello world!' in str(response)
wukong-m2m/NanoKong
tools/inteldemo201202/setThreshold.py
Python
gpl-2.0
542
0.012915
#!/usr/bin/python import sys import pynvc def setThreshold(destination, threshold): pynvc.sendWithRetryAndCheckedReceiveAPPMSG(
destination=destination, command=2, allowedReplies=[12], payload=[threshold]) if __name__ == "__main__": pynvc.init() if len(sys.argv)<3 or int(sys.argv[2]) < 0 or int(sys.argv[2]) >
255: print "setThreshold <nodeid> <threshold>" print "0<=threshold<=255" else: setThreshold(int(sys.argv[1]), int(sys.argv[2]))
jessamynsmith/boards-backend
blimp_boards/utils/request.py
Python
agpl-3.0
192
0
def get_ip_address(request): ip_addre
ss = request.META.get('HTTP_X_FORWARDED_FOR') if ip_address: return ip_address.split(',')[-1] r
eturn request.META.get('REMOTE_ADDR')
valentin-krasontovitsch/ansible
test/runner/lib/env.py
Python
gpl-3.0
6,627
0.002113
"""Show information about the test environment.""" from __future__ import absolute_import, print_function import datetime import json import os import platform import re import sys from lib.config import ( CommonConfig, ) from lib.util import ( display, find_executable, raw_command, SubprocessEr...
or k, v in verbose.items() if k.startswith('%s.' % key)]) display.info(indent + '%s:' % key, verbosity=min_verbosity) show_dict(value, verbose, verbosity, key_path) else: display.info(indent + '%s: %s' % (key, value), verbosity=verbosity) def get_ansible_version(args): ...
pe args: CommonConfig :rtype: str | None """ code = 'from __future__ import (print_function); from ansible.release import __version__; print(__version__)' cmd = [sys.executable, '-c', code] env = ansible_environment(args) try: ansible_version, _dummy = raw_command(cmd, env=env, capture=...
kantel/processingpy
sketches/modes/PythonMode/examples/Basics/Objects/CompositeObjects/ring.py
Python
mit
600
0.001667
class Ring(object): def start(self, xpos, ypos): self.x = xpos # x-coordina
te self.y = ypos # y-coordinate self.diameter = 1 # Diameter of the ring self.on = False # Turns the display on and off self.on = True def grow(self): if self.on: self.diamet
er += 0.5 if self.diameter > width * 2: self.diameter = 0.0 def display(self): if self.on: noFill() strokeWeight(4) stroke(155, 153) ellipse(self.x, self.y, self.diameter, self.diameter)
ingenioustechie/zamboni
mkt/webapps/views.py
Python
bsd-3-clause
7,946
0
from django import forms as django_forms from django.core.urlresolvers import reverse from django.http import Http404 import commonware import waffle from rest_framework import exceptions, response, serializers, status, viewsets from rest_framework.decorators import detail_route from rest_framework.response import Res...
h_icon.delay(obj.pk, obj.latest_version.all_files[0].pk) record_action('app-submitted', request, {'app-id': obj.pk}) log.info('App created: %s' % obj.pk) data = AppSerializer( context=self.get_serializer_context(), instance=obj).data return response.Response( dat...
k': obj.pk})}) def update(self, request, *args, **kwargs): # Fail if the app doesn't exist yet. self.get_object() r = super(AppViewSet, self).update(request, *args, **kwargs) # Be compatible with tastypie responses. if r.status_code == 200: r.status_code = 202 ...
nehal96/Deep-Learning-ND-Exercises
MiniFlow/5 - Cost/miniflow.py
Python
mit
4,928
0.000406
import numpy as np class Node(object): """ Base class for nodes in the network. Arguments: `inbound_nodes`: A list of nodes with edges into this node. """ def __init__(self, inbound_nodes=[]): """ Node's constructor (runs when the object is instantiated). Sets pro...
value feed to that Node. Returns a list of sorted nodes. """ input_nodes = [n for n in feed_dict.keys()] G = {} nodes = [n for n in input_nodes] while len(nodes) > 0: n = nodes.pop(0) if n not in G: G[n] = {'in':
set(), 'out': set()} for m in n.outbound_nodes: if m not in G: G[m] = {'in': set(), 'out': set()} G[n]['out'].add(m) G[m]['in'].add(n) nodes.append(m) L = [] S = set(input_nodes) while len(S) > 0: n = S.pop() if isins...
rmcgibbo/mdtraj
tests/test_restart.py
Python
lgpl-2.1
4,202
0.000476
############################################################################## # MDTraj: A Python Library for Loading, Saving, and Manipulating # Molecular Dynamics Trajectories. # Copyright 2012-2013 Stanford University and the Authors # # Authors: Jason Swails # Contributors: # # MDTraj is free software: you ...
xyz = np.random.randn(1, 10, 3) time = np.random.randn(1) boxlengths = np.random.randn(1, 3) boxangles = np.random.randn(1, 3) with AmberRestartFile(temp1, 'w', force_overwrite=True) as f: f.write(xyz, time, boxlengths, boxangles) with AmberRestartFile(temp1) as f: a, b, c, d = f....
assert eq(a, xyz) assert eq(b, time) assert eq(c, boxlengths) assert eq(d, boxangles) def test_read_write_2(): xyz = np.random.randn(1, 10, 3) time = np.random.randn(1) boxlengths = np.random.randn(1, 3) boxangles = np.random.randn(1, 3) with AmberNetCDFRestartFile(temp2, ...
alejandro-mc/BDM-hw8
application.py
Python
mit
2,660
0.018045
##Imports import pyspark import rtree import geopandas as gpd import shapely.geometry as geom import sys ### yellow_tripdata_2011-05.csv ### 0 vendor_id,pickup_datetime,dropoff_datetime,passenger_count, ### 4 trip_distance,pickup_longitude,pickup_latitude,rate_code, ### 8 store_and_fwd_flag,dropoff_longitude,dropo...
((point_destination.x,point_destination.y))) for ind in matches: if any(map(lambda x: x.contains(poin
t_destination), hoods.geometry[ind])): boro_name = hoods.borough[ind] yield ((neiborhood_name,boro_name), 1) def top3Reducer(lst1,lst2): return heapq.nlargest(3,lst1+lst2,lambda x: x[1]) if __name__=='__main__': if len(sys.argv)<3: print "Usage: <input files> <output ...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_12_01/aio/operations/_public_ip_addresses_operations.py
Python
mit
43,544
0.004983
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
source group. :type resource_group_name: str :param public_ip_address_name: The name of the subnet. :type public_ip_addre
ss_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False fo...
quattor/aquilon
tests/broker/orderedsuite.py
Python
apache-2.0
30,308
0.000132
#!/usr/bin/env python # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008-2019 Contributor # # 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 co...
_add_os import TestAddOS from .test_add_parameter import TestAddParameter from .test_add_parameter_definition import TestAddParameterDefinition from .test_add_parameter_feature import TestAddParameterFeature from .test_add_personality import TestAddPersonality from .test_add_rack import TestAddRack from .test_add_reboo...
uired_service import TestAddRequiredService from .test_add_resourcegroup import TestAddResourceGroup from .test_add_role import TestAddRole from .test_add_room import TestAddRoom from .test_add_router_address import TestAddRouterAddress from .test_add_sandbox import TestAddSandbox from .test_add_service import TestAddS...
slosar/april
Run/wqdriver_eboss.py
Python
gpl-2.0
410
0.004878
#!/usr/bin/env python # this scripts runs everything on the
bnl cluster import os import sys from wqdriver import wqsubmit if len(sys.argv) > 1: lst = sys.argv[1:] else: lst = ['TakadaFlat'] for l in lst: if l == 'TakadaFlat': wqsubmit('pre', 'PolyOk', 'BBAO+SN', 5, 30000) wqsubmit('pr
e', 'PolyOkc', 'BBAO+SN', 5, 30000) wqsubmit('pre', 'PolyOkf', 'BBAO+SN', 5, 30000)
HBPNeurorobotics/nest-simulator
pynest/nest/tests/test_labeled_synapses.py
Python
gpl-2.0
6,034
0
# -*- coding: utf-8 -*- # # test_labeled_synapses.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 L...
if s.endswith("_lbl")] for syn in la
beled_synapse_models: a = self.default_network() # set a label during connection nest.Connect(a, a, {"rule": "one_to_one"}, { "model": syn, "synapse_label": 123}) c = nest.GetConnections(a, a) self.assertTrue( all([ ...
anbangr/trusted-juju
juju/charm/tests/test_directory.py
Python
agpl-3.0
8,532
0
import gc import os import hashlib import inspect import shutil import tempfile import yaml import zipfile from juju.errors import CharmError, FileNotFound from juju.charm.errors import InvalidCharmFile from juju.charm.metadata import MetaData from juju.charm.directory import CharmDirectory from juju.charm.bundle impo...
.", log.getvalue()) def test_competing_revisions(self): dir_ = self.copy_charm() self.set_metadata_revision(dir_, 999) log = self.capture_logging("juju.charm") charm = CharmDirectory(dir_) self.assertEquals(charm.get_revision(), 1) self.assertIn( ...
_revision(self): dir_ = self.copy_charm() charm = CharmDirectory(dir_) charm.set_revision(123) self.assertEquals(charm.get_revision(), 123) with open(os.path.join(dir_, "revision")) as f: self.assertEquals(f.read(), "123\n") def test_info(self): directory...
testmana2/test
MultiProject/__init__.py
Python
gpl-3.0
531
0
# -*- coding: utf-8 -*- # Copyright (c) 2008 - 2015 Detlev Offenbach <detlev@die-offenbachs.de> # """ Package implementing the multi project management module of eric6. The multi project management module consists of the
main part, which is used for reading and writ
ing of eric6 multi project files (*.e5m) and for performing all operations on the multi project. It is accompanied by various UI related modules implementing different dialogs and a browser for the display of projects belonging to the current multi project. """
xuru/pyvisdk
pyvisdk/do/dvs_port_created_event.py
Python
mit
1,163
0.009458
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def DvsPortCreatedEvent(vim, *args, **kwargs): '''New ports
are created in the distributed virtual switch.''' obj = vim.client.factory.create('ns0:DvsPortCreatedEvent') # do some validation checking... if (len(args) + len(kwargs)) < 5: raise IndexError('Expected at least 6 arguments got: %d' % len(args)) required = [ 'portKey', 'chainId', 'created...
optional = [ 'changeTag', 'computeResource', 'datacenter', 'ds', 'dvs', 'fullFormattedMessage', 'host', 'net', 'vm', 'dynamicProperty', 'dynamicType' ] for name, arg in zip(required+optional, args): setattr(obj, name, arg) for name, value in kwargs.items(): if name in required + opt...
DemocracyLab/CivicTechExchange
salesforce/contact.py
Python
mit
1,381
0.001448
from common.models import Tag from .client import SalesforceClient import json import requests import threading ''' Contributor model maps to the Contact object in Salesforce ''' client = SalesforceClient() def run(request): response = SalesforceClient().send(request) def save(contributor: object): data = {...
tributor.about_me, 'technologies__c': Tag.tags_field_descriptions(contributor.user_technologies) } req = requests.Request( method="PATCH", url=f'{client.contact_endpoint}/platform_id__c/{contributor.id}', data=json.dumps(data), ) thread = threading.Thread(target=run, arg...
method="DELETE", url=f'{client.contact_endpoint}/platform_id__c/{contributor.id}' ) thread = threading.Thread(target=run, args=(req,)) thread.daemon = True thread.start()
sivaprakashniet/push_pull
p2p/lib/python2.7/site-packages/celery/tests/concurrency/test_prefork.py
Python
bsd-3-clause
8,523
0
from __future__ import absolute_import import errno import socket import time from itertools import cycle fro
m mock import Mock, call, patch from nose import SkipTest from celery.five import items, range from celery.utils.functional import noop from celery.tests.case import AppCase try: from celery.concurrency import prefork as mp from celery.concurrency import asynpool except ImportError: class _mp(object): ...
def __init__(self, *args, **kwargs): pass def start(self): pass def stop(self): pass def apply_async(self, *args, **kwargs): pass mp = _mp() # noqa asynpool = None # noqa class Object(object)...
jekhokie/scriptbox
python--learnings/coding-practice/swap_sort_array.py
Python
mit
684
0.005848
#!/usr/bin/env python # # Given an array of elements, determine how many pair-swaps (minimum) are needed # to get array in sorted ascending order. # #!/bin/python3 import math import os
import random import re import sys # Complete the minimumSwaps function below. def minimumSwaps(arr): swaps = 0 for i in range(len(arr) - 1): cur_val = i + 1 # swap needed if arr[i] != cur_val: swaps += 1 arr[arr.index(cur_val)] = arr[i] arr[i]
= cur_val return swaps if __name__ == '__main__': n = int(input()) arr = list(map(int, input().rstrip().split())) res = minimumSwaps(arr) print(res)
allmende/synnefo
snf-django-lib/snf_django/lib/api/urls.py
Python
gpl-3.0
1,762
0.000568
# Copyright (C) 2010-2014 GRNET S.A. # # 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 program is distributed i...
entries = r.url_patterns else: # first level view in patterns ? entries = [r] for entry in entries:
if isinstance(entry, urlresolvers.RegexURLResolver): _patch_resolver(entry) #if isinstance(entry, urlresolvers.RegexURLPattern): # let it break... else: _patch_pattern(entry) def api_patterns(*args, **kwargs): """ Protect all url patterns from csrf attacks. ...
CptLemming/django-socket-server
tests/test_models.py
Python
bsd-3-clause
390
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_django-socket-server ------------ Tests for `django-socket-server` models module. """ import os import shutil from django.test import TestCase from socket_server import models class TestSocket_server(TestCase):
def setUp(self): pass
def test_something(self): pass def tearDown(self): pass
tristanfisher/ffi4wd
tests/test_cython.py
Python
agpl-3.0
647
0.017002
import sys sys.path.append('..') sys.path.append('.') import cProfile from jumper
.blueprints.backends.fixture_data import test_cities_eleven_tuples as test_11_cities from jumper.blueprints.backends.modules.cython \ import ffi_cython_py_compat as ffi_py from jumper.blueprints.backends.modules.cython \ import ffi_cython as ffi_cy def test_profile_backend_cypy(): cmd = "ffi_py.backend_c...
t_11_cities is test data cmd = "ffi_cy.backend_cython(test_11_cities)" cProfile.run(cmd) test_profile_backend_cypy() #test_profile_backend_cython()
tivaliy/python-gerritclient
gerritclient/tests/utils/fake_commit.py
Python
apache-2.0
1,630
0
# # Copyright 2018 Vitalii Kulanov # # 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 ...
mplied. See the # License for the specific language governing permissions and limitations # under the License. def get_fake_commit(commit_id=None): return { "commit": commit_id or "184ebe53805e102605d11f6b143486d15c23a09c", "parents": [ { "commit": "1eee2c9d8f3524...
"subject": "Migrate contributor agreements to All-Projects." } ], "author": { "name": "Shawn O. Pearce", "email": "sop@google.com", "date": "2012-04-24 18:08:08.000000000", "tz": -420 }, "committer": { "name": "Sh...
makinacorpus/django
tests/mail/tests.py
Python
bsd-3-clause
35,289
0.003065
# coding: utf-8 from __future__ import unicode_literals import asyncore import email import os import shutil import smtpd import sys import tempfile import threading from django.core import mail from django.core.mail import (EmailMessage, mail_admins, mail_managers, EmailMultiAlternatives, send_mail, send_mas...
['to@example.com']) message = email.message() # Note that in Python 3, maximum line length has increased from 76 to 78 self.assertEqual(message['Subject'].encode(), b'Long subject lines that get wrapped should contain a space continuation\n character to get expected behavior in Outlook and Thund...
des(self): """ Specifying dates or message-ids in the extra headers overrides the default values (#9233) """ headers = {"date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} email = EmailMessage('subject', 'content', 'from@example.com', ['to@example.com'], heade...
helloqiu/AsyncFTP
asyncftp/console/app.py
Python
mit
2,207
0
# -*- coding: utf-8 -*- import json from flask import Flask from flask import request from flask import jsonify import time from psutil import net_io_counters from asyncftp import __version__ import threading from asyncftp.Logger import _LogFormatter t = time.time() net = net_io_counters() formatter = _LogFormatter(co...
'host': server.host, 'port': str(server.port), 'version': __version__, 'refuse_ip': server.ip_refuse }) if request.method == 'POST': data = json.loads(request.data.decode('utf-8')) for ip in data['refuse_ip']: ...
turn 'ok' @app.route('/api/log', methods=['GET']) def log(): if request.method == 'GET': result = str() while not queue.empty(): record = queue.get(block=False) result += formatter.format(record) + '\n' global log_message l...
Rahul91/Pytweets
setup.py
Python
mit
666
0.087087
#!/usr/bin/python2.7 """Twitter Project""" __version__ = '1.
1.1' from setuptools import find_packages, setup setup(name = 'Pytweets', package = ['Pytweets'], version = '0.3', descripiton = 'A test module:Pytweets', Summary = 'A test module:dPytweets'
, long_description = 'A module for printing all the tweets/re-tweets you/anyone have/has done till date.', platforms = ["Linux"], author = "Rahul Mishra", author_email = "priyrahulmishra@gmail.com", url= "https://github.com/Rahul91/pytweet", download_url = "https://github.com/Rahul91/pytweet/tarball/0.1", licens...
davischau/CMPUT410Lab6
bookmarks/main/urls.py
Python
apache-2.0
295
0.037288
from django.conf.urls import patterns,url from main import views urlpatterns = patterns('', url(r'^$',views.index,name='index'), url(r'^tags/$',views.tags,name='tags'), url(r'^tags/(?P<tag_name>\w+
)/$',views.tag,name='tag'),
url(r'^add_link/$',views.add_link,name='add_link'), )
JulienMcJay/eclock
windows/Python27/Lib/site-packages/pywin32-218-py2.7-win32.egg/win32comext/shell/test/testShellItem.py
Python
gpl-2.0
2,921
0.003766
# Test IShellItem and related interfaces from win32com.shell import shell, shellcon, knownfolders import unittest class TestShellItem(unittest.TestCase): def assertShellItemsEqual(self, i1, i2): n1 = i1.GetDisplayName(shellcon.SHGDN_FORPARSING) n2 = i2.GetDisplayName(shellcon.SHGDN_FORPARSING) ...
ing_relative(self): desktop_pidl = shell.SHGetSpecialFolde
rLocation(0, shellcon.CSIDL_DESKTOP) desktop_item = shell.SHCreateItemFromIDList(desktop_pidl, shell.IID_IShellItem) sf = shell.SHGetDesktopFolder() flags = shellcon.SHCONTF_FOLDERS | shellcon.SHCONTF_NONFOLDERS children = sf.EnumObjects(0, flags) child_pidl = children.next() ...
lfcnassif/MultiContentViewer
release/modules/ext/libreoffice/program/python-core-3.3.0/lib/fractions.py
Python
lgpl-3.0
23,033
0.00026
# Originally contributed by Sjoerd Mullender. # Significantly modified by Jeffrey Yasskin <jyasskin at gmail.com>. """Fraction, infinite-precision, real numbers.""" from decimal import Decimal import math import numbers import operator import re import sys __all__ = ['Fraction', 'gcd'] def gcd(a, b): """Calcu...
US = sys.hash_info.modulus # Value to be used for rationals that reduce to infinity modu
lo # _PyHASH_MODULUS. _PyHASH_INF = sys.hash_info.inf _RATIONAL_FORMAT = re.compile(r""" \A\s* # optional whitespace at the start, then (?P<sign>[-+]?) # an optional sign, then (?=\d|\.\d) # lookahead for digit or .digit (?P<num>\d*) # numera...
yosef-gao/zhuaxia
zhuaxia/commander.py
Python
mit
7,171
0.012848
# -*- coding:utf-8 -*- import sys import config ,util ,logging ,log,downloader import xiami as xm import netease import re from threadpool import ThreadPool from time import sleep from os import path from threadpool import Terminate_Watcher from proxypool import ProxyPool LOG = log.get_logger("zxLogger") dl_songs = ...
% len(topsong.songs)) msg = u' => '.join(msgs) global total, done done +=1 pre = ('[%d/%d] ' % (done, total)) if not verbose else '' if not msg: #unknown url LOG.error(u'%s [虾]不能识别的url [%s].' %
(pre,url)) else: LOG.info(u'%s%s'% (pre,msg)) def from_file(xm_obj,m163, infile): """ download objects (songs, albums...) from an input file. """ urls = [] with open(infile) as f: urls = f.readlines() global total, done total = len(urls) print border LOG.info(u' 文件包...
WillisXChen/django-oscar
oscar/lib/python2.7/site-packages/behave/model_describe.py
Python
bsd-3-clause
3,364
0
# -*- coding: utf-8 -*- """ Provides textual descriptions for :mod:`behave.model` elements. """ from behave.textutil import indent # ----------------------------------------------------------------------------- # FUNCTIONS: # -------------------------------------------------------
---------------------- def escape_cell(cell): """ Escape table cell contents. :param cell: Table cell (as unicode string). :return: Escaped cell (as unicode string). """ cell = cell.replace(u'\\', u'\\\\') cell = cell.replace(u'\n', u'\\n') cell = cell.replace(u'|', u'\\|') return c...
): """ Escape triple-quotes, used for multi-line text/doc-strings. """ return text.replace(u'"""', u'\\"\\"\\"') # ----------------------------------------------------------------------------- # CLASS: # ----------------------------------------------------------------------------- class ModelDescripto...
sunfounder/SunFounder_SensorKit_for_RPi2
Python/24_touch_switch.py
Python
gpl-2.0
1,264
0.04193
#!/usr/bin/env python3 import RPi.GPIO as GPIO TouchPin = 11 Gpin = 13 Rpin = 12 tmp = 0 def setup(): GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output GPIO.setu...
O.output(Gpin, 0) if x == 1: GPIO.output(Rpin, 0) GPIO.output(Gpin, 1) def Print(x): global tmp if x != tmp: if x == 0: print (' **********') print (' * ON *') print (' **********') if x == 1: print (' **********') print (' * OFF *') print (' **********') tmp ...
n, GPIO.HIGH) # Green led off GPIO.output(Rpin, GPIO.HIGH) # Red led off GPIO.cleanup() # Release resource if __name__ == '__main__': # Program start from here setup() try: loop() except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be exec...