Dataset Viewer
Auto-converted to Parquet
commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
e905334869af72025592de586b81650cb3468b8a
sentry/queue/client.py
sentry/queue/client.py
""" sentry.queue.client ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from kombu import BrokerConnection from kombu.common import maybe_declare from kombu.pools import producers from sentry.conf import settings from sentry.queue.queues import task_queues, task_exchange class Broker(object): def __init__(self, config): self.connection = BrokerConnection(**config) def delay(self, func, *args, **kwargs): payload = { "func": func, "args": args, "kwargs": kwargs, } with producers[self.connection].acquire(block=False) as producer: for queue in task_queues: maybe_declare(queue, producer.channel) producer.publish(payload, exchange=task_exchange, serializer="pickle", compression="bzip2", queue='default', routing_key='default', ) broker = Broker(settings.QUEUE)
""" sentry.queue.client ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from kombu import BrokerConnection from kombu.common import maybe_declare from kombu.pools import producers from sentry.conf import settings from sentry.queue.queues import task_queues, task_exchange class Broker(object): def __init__(self, config): self.connection = BrokerConnection(**config) with producers[self.connection].acquire(block=False) as producer: for queue in task_queues: maybe_declare(queue, producer.channel) def delay(self, func, *args, **kwargs): payload = { "func": func, "args": args, "kwargs": kwargs, } with producers[self.connection].acquire(block=False) as producer: producer.publish(payload, exchange=task_exchange, serializer="pickle", compression="bzip2", queue='default', routing_key='default', ) broker = Broker(settings.QUEUE)
Declare queues when broker is instantiated
Declare queues when broker is instantiated
Python
bsd-3-clause
imankulov/sentry,BuildingLink/sentry,zenefits/sentry,korealerts1/sentry,kevinastone/sentry,fotinakis/sentry,fuziontech/sentry,ngonzalvez/sentry,mvaled/sentry,Kronuz/django-sentry,ngonzalvez/sentry,looker/sentry,felixbuenemann/sentry,ngonzalvez/sentry,nicholasserra/sentry,camilonova/sentry,jokey2k/sentry,llonchj/sentry,fuziontech/sentry,llonchj/sentry,NickPresta/sentry,boneyao/sentry,SilentCircle/sentry,Kryz/sentry,JamesMura/sentry,SilentCircle/sentry,wujuguang/sentry,JTCunning/sentry,rdio/sentry,1tush/sentry,alexm92/sentry,imankulov/sentry,wujuguang/sentry,jokey2k/sentry,jean/sentry,chayapan/django-sentry,looker/sentry,beeftornado/sentry,chayapan/django-sentry,gg7/sentry,chayapan/django-sentry,JamesMura/sentry,1tush/sentry,zenefits/sentry,ewdurbin/sentry,NickPresta/sentry,alex/sentry,camilonova/sentry,kevinastone/sentry,pauloschilling/sentry,boneyao/sentry,korealerts1/sentry,rdio/sentry,daevaorn/sentry,drcapulet/sentry,TedaLIEz/sentry,Kronuz/django-sentry,wong2/sentry,felixbuenemann/sentry,1tush/sentry,hongliang5623/sentry,looker/sentry,BayanGroup/sentry,BuildingLink/sentry,BuildingLink/sentry,BayanGroup/sentry,kevinlondon/sentry,daevaorn/sentry,looker/sentry,llonchj/sentry,gencer/sentry,fotinakis/sentry,BuildingLink/sentry,korealerts1/sentry,felixbuenemann/sentry,boneyao/sentry,alex/sentry,fuziontech/sentry,nicholasserra/sentry,beeftornado/sentry,SilentCircle/sentry,ifduyue/sentry,gencer/sentry,jean/sentry,pauloschilling/sentry,camilonova/sentry,wong2/sentry,mvaled/sentry,JamesMura/sentry,ewdurbin/sentry,JackDanger/sentry,beeftornado/sentry,BuildingLink/sentry,argonemyth/sentry,zenefits/sentry,alex/sentry,gg7/sentry,jean/sentry,vperron/sentry,NickPresta/sentry,mvaled/sentry,JackDanger/sentry,songyi199111/sentry,vperron/sentry,daevaorn/sentry,ifduyue/sentry,kevinlondon/sentry,BayanGroup/sentry,JackDanger/sentry,kevinastone/sentry,Natim/sentry,zenefits/sentry,pauloschilling/sentry,Natim/sentry,argonemyth/sentry,alexm92/sentry,Natim/sentry,Kronuz/django-sentry,gg7/sentry,hongliang5623/sentry,looker/sentry,daevaorn/sentry,TedaLIEz/sentry,alexm92/sentry,vperron/sentry,ifduyue/sentry,mvaled/sentry,jean/sentry,JamesMura/sentry,hongliang5623/sentry,songyi199111/sentry,argonemyth/sentry,JTCunning/sentry,gencer/sentry,nicholasserra/sentry,ifduyue/sentry,Kryz/sentry,Kryz/sentry,beni55/sentry,TedaLIEz/sentry,kevinlondon/sentry,NickPresta/sentry,mvaled/sentry,drcapulet/sentry,jean/sentry,gencer/sentry,songyi199111/sentry,beni55/sentry,beni55/sentry,SilentCircle/sentry,mvaled/sentry,mitsuhiko/sentry,ewdurbin/sentry,wujuguang/sentry,fotinakis/sentry,drcapulet/sentry,fotinakis/sentry,wong2/sentry,ifduyue/sentry,zenefits/sentry,JTCunning/sentry,rdio/sentry,imankulov/sentry,jokey2k/sentry,gencer/sentry,rdio/sentry,JamesMura/sentry,mitsuhiko/sentry
950ac9130bafe1fced578bf61d746b047830bfa0
automata/base/exceptions.py
automata/base/exceptions.py
#!/usr/bin/env python3 """Exception classes shared by all automata.""" class AutomatonException(Exception): """The base class for all automaton-related errors.""" pass class InvalidStateError(AutomatonException): """A state is not a valid state for this automaton.""" pass class InvalidSymbolError(AutomatonException): """A symbol is not a valid symbol for this automaton.""" pass class MissingStateError(AutomatonException): """A state is missing from the automaton definition.""" pass class MissingSymbolError(AutomatonException): """A symbol is missing from the automaton definition.""" pass class InitialStateError(AutomatonException): """The initial state fails to meet some required condition.""" pass class FinalStateError(AutomatonException): """A final state fails to meet some required condition.""" pass class RejectionException(AutomatonException): """The input was rejected by the automaton after validation.""" pass
#!/usr/bin/env python3 """Exception classes shared by all automata.""" class AutomatonException(Exception): """The base class for all automaton-related errors.""" pass class InvalidStateError(AutomatonException): """A state is not a valid state for this automaton.""" pass class InvalidSymbolError(AutomatonException): """A symbol is not a valid symbol for this automaton.""" pass class MissingStateError(AutomatonException): """A state is missing from the automaton definition.""" pass class MissingSymbolError(AutomatonException): """A symbol is missing from the automaton definition.""" pass class InitialStateError(AutomatonException): """The initial state fails to meet some required condition.""" pass class FinalStateError(AutomatonException): """A final state fails to meet some required condition.""" pass class RejectionException(AutomatonException): """The input was rejected by the automaton.""" pass
Remove "validation" from RejectionException docstring
Remove "validation" from RejectionException docstring
Python
mit
caleb531/automata
c3f8860c717a139d396b0d902db989ab7b8369ba
stock_inventory_hierarchical/__openerp__.py
stock_inventory_hierarchical/__openerp__.py
# -*- coding: utf-8 -*- # © 2013-2016 Numérigraphe SARL # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], "images": ["inventory_form.png", "inventory_form_actions.png", "wizard.png"], 'license': 'AGPL-3', 'installable': True }
# -*- coding: utf-8 -*- # © 2013-2016 Numérigraphe SARL # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], "images": ["images/inventory_form.png", "images/inventory_form_actions.png", "images/wizard.png"], 'license': 'AGPL-3', 'installable': True }
Fix image path in manifest
Fix image path in manifest
Python
agpl-3.0
kmee/stock-logistics-warehouse,factorlibre/stock-logistics-warehouse,open-synergy/stock-logistics-warehouse,acsone/stock-logistics-warehouse,avoinsystems/stock-logistics-warehouse
cd56fb2c1a0f4b6dd40ce03545e57c6fd2e1c519
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup packages = [ 'upho', 'upho.phonon', 'upho.harmonic', 'upho.analysis', 'upho.structure', 'upho.irreps', 'upho.qpoints', 'group', ] scripts = [ 'scripts/upho_weights', 'scripts/upho_sf', 'scripts/upho_qpoints', 'scripts/upho_fit', ] setup(name='upho', version='0.5.3', author="Yuji Ikeda", author_email="[email protected]", packages=packages, scripts=scripts, install_requires=['numpy', 'h5py', 'phonopy'])
#!/usr/bin/env python from distutils.core import setup packages = [ 'upho', 'upho.phonon', 'upho.harmonic', 'upho.analysis', 'upho.structure', 'upho.irreps', 'upho.qpoints', 'group', ] scripts = [ 'scripts/upho_weights', 'scripts/upho_sf', 'scripts/upho_qpoints', 'scripts/upho_fit', ] setup(name='upho', version='0.5.3', author="Yuji Ikeda", author_email="[email protected]", packages=packages, scripts=scripts, install_requires=['numpy', 'h5py', 'phonopy'])
Modify the author email address
Modify the author email address
Python
mit
yuzie007/upho,yuzie007/ph_unfolder
70a642c0597fb2f929fc83d821c8b1f095ed1328
proxy/plugins/plugins.py
proxy/plugins/plugins.py
packetFunctions = {} commands = {} onStart = [] onConnection = [] onConnectionLoss = [] class packetHook(object): def __init__(self, pktType, pktSubtype): self.pktType = pktType self.pktSubtype = pktSubtype def __call__(self, f): global packetFunctions packetFunctions[(self.pktType, self.pktSubtype)] = f class commandHook(object): """docstring for commandHook""" def __init__(self, command): self.command = command def __call__(self, f): global commands commands[self.command] = f def onStartHook(f): global onStart onStart.append(f) return f def onConnectionHook(f): global onConnection onConnection.append(f) return f def onConnectionLossHook(f): global onConnectionLoss onConnectionLoss.append(f) return f
packetFunctions = {} commands = {} onStart = [] onConnection = [] onConnectionLoss = [] class packetHook(object): def __init__(self, pktType, pktSubtype): self.pktType = pktType self.pktSubtype = pktSubtype def __call__(self, f): global packetFunctions if (self.pktType, self.pktSubtype) not in packetFunctions: packetFunctions[(self.pktType, self.pktSubtype)] = [] packetFunctions[(self.pktType, self.pktSubtype)].append(f) class commandHook(object): """docstring for commandHook""" def __init__(self, command): self.command = command def __call__(self, f): global commands commands[self.command] = f def onStartHook(f): global onStart onStart.append(f) return f def onConnectionHook(f): global onConnection onConnection.append(f) return f def onConnectionLossHook(f): global onConnectionLoss onConnectionLoss.append(f) return f
Allow mutiple hooks for packets
Allow mutiple hooks for packets
Python
agpl-3.0
alama/PSO2Proxy,alama/PSO2Proxy,flyergo/PSO2Proxy,alama/PSO2Proxy,cyberkitsune/PSO2Proxy,cyberkitsune/PSO2Proxy,flyergo/PSO2Proxy,cyberkitsune/PSO2Proxy
44e31e2153f4eec2863f9d712ab60f0ef00d1779
mongo_connector/get_last_oplog_timestamp.py
mongo_connector/get_last_oplog_timestamp.py
#!/usr/bin/python import pymongo import bson import time import sys from mongo_connector import util mongo_url = 'mongodb://localhost:27017' if len(sys.argv) == 1: print "First argument is mongodb connection string, i.e. localhost:27017. Assuming localhost:27017..." if len(sys.argv) >= 2: mongo_url = sys.argv[1] client = pymongo.MongoClient(mongo_url) rs_name = client.admin.command('ismaster')['setName'] print 'Found Replica Set name: {}'.format(str(rs_name)) print 'Now checking for the latest oplog entry...' oplog = client.local.oplog.rs last_oplog = oplog.find().sort('$natural', pymongo.DESCENDING).limit(-1).next() print 'Found the last oplog ts: {}'.format(str(last_oplog['ts'])) last_ts = util.bson_ts_to_long(last_oplog['ts']) out_str='["{}", {}]'.format(str(rs_name), str(last_ts) ) print 'Writing all to file oplog.timestamp.last in the format required for mongo-connector' f = open('./oplog.timestamp.last', 'w') f.write(out_str) f.close() print 'All done!'
#!/usr/bin/python import pymongo import bson import time import sys from mongo_connector import util mongo_url = 'mongodb://localhost:27017' if len(sys.argv) == 1: print "First argument is mongodb connection string, i.e. localhost:27017. Assuming localhost:27017..." if len(sys.argv) >= 2: mongo_url = sys.argv[1] client = pymongo.MongoClient(mongo_url) rs_name = client.admin.command('ismaster')['setName'] print('Found Replica Set name: {}'.format(str(rs_name))) print('Now checking for the latest oplog entry...') oplog = client.local.oplog.rs last_oplog = oplog.find().sort('$natural', pymongo.DESCENDING).limit(-1).next() print('Found the last oplog ts: {}'.format(str(last_oplog['ts']))) last_ts = util.bson_ts_to_long(last_oplog['ts']) out_str='["{}", {}]'.format(str(rs_name), str(last_ts) ) print('Writing all to file oplog.timestamp.last in the format required for mongo-connector') f = open('./oplog.timestamp.last', 'w') f.write(out_str) f.close() print('All done!')
Update for compatibility with python 3
Update for compatibility with python 3
Python
apache-2.0
10gen-labs/mongo-connector,ShaneHarvey/mongo-connector,mongodb-labs/mongo-connector,10gen-labs/mongo-connector,mongodb-labs/mongo-connector,ShaneHarvey/mongo-connector
af91b7c2612fab598ba50c0c0256f7e552098d92
reportlab/docs/genAll.py
reportlab/docs/genAll.py
#!/bin/env python """Runs the three manual-building scripts""" if __name__=='__main__': import os, sys d = os.path.dirname(sys.argv[0]) #need a quiet mode for the test suite if '-s' in sys.argv: # 'silent quiet = '-s' else: quiet = '' if not d: d = '.' if not os.path.isabs(d): d = os.path.normpath(os.path.join(os.getcwd(),d)) for p in ('reference/genreference.py', 'userguide/genuserguide.py', 'graphguide/gengraphguide.py', '../tools/docco/graphdocpy.py'): os.chdir(d) os.chdir(os.path.dirname(p)) os.system('%s %s %s' % (sys.executable,os.path.basename(p), quiet))
#!/bin/env python import os def _genAll(d=None,quiet=''): if not d: d = '.' if not os.path.isabs(d): d = os.path.normpath(os.path.join(os.getcwd(),d)) for p in ('reference/genreference.py', 'userguide/genuserguide.py', 'graphguide/gengraphguide.py', '../tools/docco/graphdocpy.py'): os.chdir(d) os.chdir(os.path.dirname(p)) os.system('%s %s %s' % (sys.executable,os.path.basename(p), quiet)) """Runs the manual-building scripts""" if __name__=='__main__': import sys #need a quiet mode for the test suite if '-s' in sys.argv: # 'silent quiet = '-s' else: quiet = '' _genAll(os.path.dirname(sys.argv[0]),quiet)
Allow for use in daily.py
Allow for use in daily.py
Python
bsd-3-clause
makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile
7c2a640d2c3ab9218d8334f4939d7c1af919c318
setup.py
setup.py
import os import sys from distutils.core import setup if sys.version_info < (3,): print('\nSorry, but Adventure can only be installed under Python 3.\n') sys.exit(1) README_PATH = os.path.join(os.path.dirname(__file__), 'adventure', 'README.txt') with open(README_PATH, encoding="utf-8") as f: README_TEXT = f.read() setup( name='adventure', version='1.4', description='Colossal Cave adventure game at the Python prompt', long_description=README_TEXT, author='Brandon Craig Rhodes', author_email='[email protected]', url='https://bitbucket.org/brandon/adventure/overview', packages=['adventure', 'adventure/tests'], package_data={'adventure': ['README.txt', '*.dat', 'tests/*.txt']}, classifiers=[ 'Development Status :: 6 - Mature', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Topic :: Games/Entertainment', ], )
import os import sys from distutils.core import setup if sys.version_info < (3,): print('\nSorry, but Adventure can only be installed under Python 3.\n') sys.exit(1) README_PATH = os.path.join(os.path.dirname(__file__), 'adventure', 'README.txt') with open(README_PATH, encoding="utf-8") as f: README_TEXT = f.read() setup( name='adventure', version='1.4', description='Colossal Cave adventure game at the Python prompt', long_description=README_TEXT, author='Brandon Craig Rhodes', author_email='[email protected]', url='https://github.com/brandon-rhodes/python-adventure', packages=['adventure', 'adventure/tests'], package_data={'adventure': ['README.txt', '*.dat', 'tests/*.txt']}, classifiers=[ 'Development Status :: 6 - Mature', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Topic :: Games/Entertainment', ], )
Update outdated link to repository, per @cknv
Update outdated link to repository, per @cknv
Python
apache-2.0
devinmcgloin/advent,devinmcgloin/advent
eda2686d7a59acf5fc7f6d72b710ccc8b20801a9
setup.py
setup.py
# -*- coding: utf-8 -*- from distutils.core import setup long_description = open('README.rst').read() setup( name='django-tagging-autocomplete', version='0.4.2', description='Autocompletion for django-tagging', long_description=long_description, author='Ludwik Trammer', author_email='[email protected]', url='https://github.com/ludwiktrammer/django-tagging-autocomplete/', packages=['tagging_autocomplete'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] )
# -*- coding: utf-8 -*- import os from distutils.core import setup from distutils.command.install import INSTALL_SCHEMES long_description = open('README.rst').read() # install data files where source files are installed for scheme in INSTALL_SCHEMES.values(): scheme['data'] = scheme['purelib'] def find_data_files(filepath): return sum([ [(path, [os.path.join(path, name)]) for name in names] for path, _, names in os.walk(filepath)], []) setup( name='django-tagging-autocomplete', version='0.4.2', description='Autocompletion for django-tagging', long_description=long_description, author='Ludwik Trammer', author_email='[email protected]', url='https://github.com/ludwiktrammer/django-tagging-autocomplete/', packages=['tagging_autocomplete'], data_files=find_data_files('tagging_autocomplete/static'), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] )
Install static files with distutils.
Install static files with distutils.
Python
mit
ludwiktrammer/django-tagging-autocomplete
e34969db596ff3dfa4bf78efb3f3ccfe771d9ef9
setup.py
setup.py
# Use setuptools if we can try: from setuptools.core import setup except ImportError: from distutils.core import setup PACKAGE = 'django_exceptional_middleware' VERSION = '0.2' data_files = [ ( 'exceptional_middleware/templates/http_responses', [ 'exceptional_middleware/templates/http_responses/default.html' ], ), ] setup( name=PACKAGE, version=VERSION, description="Django middleware to allow generating arbitrary HTTP status codes via exceptions.", packages=[ 'exceptional_middleware' ], data_files=data_files, license='MIT', author='James Aylett', url = 'http://tartarus.org/james/computers/django/', )
# Use setuptools if we can try: from setuptools.core import setup except ImportError: from distutils.core import setup PACKAGE = 'django_exceptional_middleware' VERSION = '0.4' package_data = { 'exceptional_middleware': [ 'templates/http_responses/*.html' ], } setup( name=PACKAGE, version=VERSION, description="Django middleware to allow generating arbitrary HTTP status codes via exceptions.", packages=[ 'exceptional_middleware' ], package_data=package_data, license='MIT', author='James Aylett', url = 'http://tartarus.org/james/computers/django/', )
Fix templates install. Bump to version 0.4 in the process (which is really my laziness).
Fix templates install. Bump to version 0.4 in the process (which is really my laziness).
Python
mit
jaylett/django_exceptional_middleware
c6265c2112ee9985af8b6b80fe0bee1811dc6abd
setup.py
setup.py
# -*- coding: utf-8 -*- from distutils.core import setup setup( name='oceanoptics', version='0.2.6', author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter', author_email='[email protected]', packages=['oceanoptics', 'oceanoptics.spectrometers'], description='A Python driver for Ocean Optics spectrometers.', long_description=open('README.md').read(), requires=['python (>= 2.7)', 'pyusb (>= 1.0)', 'numpy'], )
# -*- coding: utf-8 -*- from distutils.core import setup setup( name='oceanoptics', version='0.2.7', author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter, Ian Ross Williams', author_email='[email protected]', packages=['oceanoptics', 'oceanoptics.spectrometers'], description='A Python driver for Ocean Optics spectrometers.', long_description=open('README.md').read(), requires=['python (>= 2.7)', 'pyusb (>= 1.0)', 'numpy'], )
Add author and increase version number
Add author and increase version number
Python
mit
ap--/python-oceanoptics
ae1cf07cc703d85f3d3c77eab76c83baec17a74d
split.py
split.py
import re def split_string(string, seperator=' '): return string.split(seperator) def split_regex(string, seperator_pattern): return re.split(seperator_pattern, string) class FilterModule(object): ''' A filter to split a string into a list. ''' def filters(self): return { 'split' : split_string, 'split_regex' : split_regex, }
from ansible import errors import re def split_string(string, seperator=' '): try: return string.split(seperator) except Exception, e: raise errors.AnsibleFilterError('split plugin error: %s, string=%s' % str(e),str(string) ) def split_regex(string, seperator_pattern): try: return re.split(seperator_pattern, string) except Exception, e: raise errors.AnsibleFilterError('split plugin error: %s' % str(e)) class FilterModule(object): ''' A filter to split a string into a list. ''' def filters(self): return { 'split' : split_string, 'split_regex' : split_regex, }
Add standard Ansible exception handling
Add standard Ansible exception handling
Python
cc0-1.0
timraasveld/ansible-string-split-filter,ypid/ansible-string-split-filter
5bb9b2c9d5df410c85f4736c17224aeb2f05dd33
s2v3.py
s2v3.py
from s2v2 import * def calculate_sum(data_sample): total = 0 for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data). price = float(row[2]) total += price return total print('the sum total of prices for all ties in the dataset = ' + str(calculate_sum(data_from_csv))) # ok we're using the right import, but having two imports is confusing.
from s2v2 import * def calculate_sum(data_sample): total = 0 for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data). price = float(row[2]) total += price return total print('the sum total of prices for all ties in the dataset = ', calculate_sum(data_from_csv)) # ok we're using the right import, but having two imports is confusing. UPDDATE: No, I don't have to convert the calculate_sum result to a string to add text about it, I just need to use , instead of +
Update print result to use "," instead of "+" for context text
Update print result to use "," instead of "+" for context text
Python
mit
alexmilesyounger/ds_basics
7b422b2432bc8db3034e39073d2efa0bd69ec35f
test.py
test.py
import time import urllib import RPi.GPIO as GPIO # GPIO input pin to use LPR_PIN = 3 # URL to get image from SOURCE = 'http://192.168.0.13:8080/photoaf.jpg' # Path to save image locally FILE = 'img.jpg' # Use GPIO pin numbers GPIO.setmode(GPIO.BCM) # Disable "Ports already in use" warning GPIO.setwarnings(False) # Set the pin to be an input GPIO.setup(LPR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Only save the image once per gate opening captured = False # Main loop while True: # Capture the image if not captured yet and switch is closed (open gate) if not captured and GPIO.input(LPR_PIN) is True: urllib.urlretrieve(SOURCE, FILE) print "Gate has been opened!" captured = True # If there was a capture and the switch is now open (closed gate) then # ready the loop to capture again. if captured and GPIO.input(LPR_PIN) is False: print "The gate has now closed!" captured = False time.sleep(1)
import time import urllib import RPi.GPIO as GPIO # GPIO input pin to use LPR_PIN = 3 # URL to get image from SOURCE = 'http://192.168.0.13:8080/photoaf.jpg' # Path to save image locally FILE = 'img.jpg' # Use GPIO pin numbers GPIO.setmode(GPIO.BCM) # Disable "Ports already in use" warning GPIO.setwarnings(False) # Set the pin to be an input GPIO.setup(LPR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Try statement to cleanup GPIO pins try: # Only save the image once per gate opening captured = False # Main loop while True: # Capture the image if not captured yet and switch is closed (open gate) if not captured and GPIO.input(LPR_PIN) is True: urllib.urlretrieve(SOURCE, FILE) print "Gate has been opened!" captured = True # If there was a capture and the switch is now open (closed gate) then # ready the loop to capture again. if captured and GPIO.input(LPR_PIN) is False: print "The gate has now closed!" captured = False time.sleep(1) except KeyboardInterrupt: GPIO.cleanup()
Add try statement to cleanup pins and invert pull/up down
Add try statement to cleanup pins and invert pull/up down
Python
mit
adampiskorski/lpr_poc
75f6963082ed686f4d91ec8df3961048d9428c6b
test.py
test.py
import unittest from enigma import Enigma, Steckerbrett, Umkehrwalze, Walzen class RotorTestCase(unittest.TestCase): pass def run_tests(): runner = unittest.TextTestRunner() suite = unittest.TestLoader().loadTestsFromTestCase(RotorTestCase) runner.run(suite) if __name__ == '__main__': # pragma: no cover run_tests()
import unittest from enigma import Enigma, Steckerbrett, Umkehrwalze, Walzen class RotorTestCase(unittest.TestCase): def test_rotor_encoding(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q') self.assertEqual('E', rotor.encode('A')) def run_tests(): runner = unittest.TextTestRunner() suite = unittest.TestLoader().loadTestsFromTestCase(RotorTestCase) runner.run(suite) if __name__ == '__main__': # pragma: no cover run_tests()
Test if default rotor encodes forward properly
Test if default rotor encodes forward properly
Python
mit
ranisalt/enigma
3ba5b6491bf61e2d2919f05bbf5cef088a754aeb
molecule/default/tests/test_installation.py
molecule/default/tests/test_installation.py
""" Role tests """ import os import pytest from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize('name', [ ('vsftpd'), ('db5.3-util'), ]) def test_installed_packages(host, name): """ Test if packages installed """ assert host.package(name).is_installed def test_service(host): """ Test service state """ service = host.service('vsftpd') assert service.is_enabled # if host.system_info.codename in ['jessie', 'xenial']: if host.file('/etc/init.d/vsftpd').exists: assert 'is running' in host.check_output('/etc/init.d/vsftpd status') else: assert service.is_running def test_process(host): """ Test process state """ assert len(host.process.filter(comm='vsftpd')) == 1 def test_socket(host): """ Test ports """ assert host.socket('tcp://127.0.0.1:21').is_listening def test_user(host): """ Test ftp user exists """ ftp_user = host.user('ftp') assert ftp_user.exists assert ftp_user.shell == '/bin/false'
""" Role tests """ import os import pytest from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize('name', [ ('vsftpd'), ('db5.3-util'), ]) def test_installed_packages(host, name): """ Test if packages installed """ assert host.package(name).is_installed def test_service(host): """ Test service state """ service = host.service('vsftpd') assert service.is_enabled # if host.system_info.codename in ['jessie', 'xenial']: if host.file('/etc/init.d/vsftpd').exists: assert 'is running' in host.check_output('/etc/init.d/vsftpd status') else: assert service.is_running def test_process(host): """ Test process state """ assert len(host.process.filter(comm='vsftpd')) == 1 def test_socket(host): """ Test ports """ assert host.socket('tcp://127.0.0.1:21').is_listening def test_user(host): """ Test ftp user exists """ ftp_user = host.user('ftp') assert ftp_user.exists assert ftp_user.shell in ['/usr/sbin/nologin', '/bin/false']
Add nologin in expected user shell test
Add nologin in expected user shell test
Python
mit
infOpen/ansible-role-vsftpd
b4c9b76d132668695b77d37d7db3071e629fcba7
makerscience_admin/models.py
makerscience_admin/models.py
# -*- coding: utf-8 -*- from django.db import models from solo.models import SingletonModel class MakerScienceStaticContent (SingletonModel): about = models.TextField(null=True, blank=True) about_team = models.TextField(null=True, blank=True) about_contact = models.TextField(null=True, blank=True) about_faq = models.TextField(null=True, blank=True) about_cgu = models.TextField(null=True, blank=True) class PageViews(models.Model): client = models.CharField(max_length=255) resource_uri = models.CharField(max_length=255)
# -*- coding: utf-8 -*- from django.db import models from django.db.models.signals import post_delete from solo.models import SingletonModel from accounts.models import ObjectProfileLink from makerscience_forum.models import MakerSciencePost class MakerScienceStaticContent (SingletonModel): about = models.TextField(null=True, blank=True) about_team = models.TextField(null=True, blank=True) about_contact = models.TextField(null=True, blank=True) about_faq = models.TextField(null=True, blank=True) about_cgu = models.TextField(null=True, blank=True) class PageViews(models.Model): client = models.CharField(max_length=255) resource_uri = models.CharField(max_length=255) def clear_makerscience(sender, instance, **kwargs): if sender == MakerSciencePost: ObjectProfileLink.objects.filter(content_type__model='post', object_id=instance.parent.id).delete() instance.parent.delete() post_delete.connect(clear_makerscience, sender=MakerSciencePost)
Allow to clear useless instances
Allow to clear useless instances
Python
agpl-3.0
atiberghien/makerscience-server,atiberghien/makerscience-server
9fa296bfad85b42c04c325f1dfdd1caaa31bbd1b
NSYSU.py
NSYSU.py
cast=["Cleese","Palin","Jones","Idle"] print(cast) cast.pop() print(cast) cast.extend(["Gillan","Chanpman"]) print(cast)
#test code cast=["Cleese","Palin","Jones","Idle"] print(cast) cast.pop() print(cast) cast.extend(["Gillan","Chanpman"]) print(cast)
Add modify code Google News Crawer
Add modify code Google News Crawer
Python
epl-1.0
KuChanTung/Python
c3e81aee9852a94befdec9d9b2d3f9cd3d7914e2
dbaas/system/tasks.py
dbaas/system/tasks.py
# -*- coding: utf-8 -*- from dbaas.celery import app from util.decorators import only_one from models import CeleryHealthCheck #from celery.utils.log import get_task_logger #LOG = get_task_logger(__name__) import logging LOG = logging.getLogger(__name__) @app.task(bind=True) def set_celery_healthcheck_last_update(self): LOG.info("Setting Celery healthcheck last update") CeleryHealthCheck.set_last_update() return
# -*- coding: utf-8 -*- from dbaas.celery import app from util.decorators import only_one from models import CeleryHealthCheck from notification.models import TaskHistory import logging LOG = logging.getLogger(__name__) @app.task(bind=True) @only_one(key="celery_healthcheck_last_update", timeout=20) def set_celery_healthcheck_last_update(self): try: task_history = TaskHistory.register(request=self.request, user=None) LOG.info("Setting Celery healthcheck last update") CeleryHealthCheck.set_last_update() task_history.update_status_for(TaskHistory.STATUS_SUCCESS, details="Finished") except Exception, e: LOG.warn("Oopss...{}".format(e)) task_history.update_status_for(TaskHistory.STATUS_ERROR, details=e) finally: return
Change task to create a taskHistory object
Change task to create a taskHistory object
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
c713273fe145418113d750579f8b135dc513c3b8
config.py
config.py
import os if os.environ.get('DATABASE_URL') is None: SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db' else: SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
import os SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
Delete default case for SQLALCHEMY_DATABASE_URI
Delete default case for SQLALCHEMY_DATABASE_URI if user doesn't set it, he coud have some problems with SQLite
Python
mit
Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot
c61d5e84863dd67b5b76ec8031e624642f4c957c
main.py
main.py
from .ide.command import plugin_unloaded from .ide.error import * from .ide.rebuild import * from .ide.server import * from .ide.settings import plugin_loaded from .ide.text_command import * from .ide.type_hints import * from .ide.utility import *
from .ide.auto_complete import * from .ide.command import plugin_unloaded from .ide.error import * from .ide.rebuild import * from .ide.server import * from .ide.settings import plugin_loaded from .ide.text_command import * from .ide.type_hints import *
Fix issue with wrong import
Fix issue with wrong import
Python
mit
b123400/purescript-ide-sublime
78be1f58d618077f42d04390baf97938d01df44f
models/analyze_pic_server.py
models/analyze_pic_server.py
# import analyze from analyze import check_blob_in_direct_path import os import sys sys.path.insert(0, os.getcwd()) from get_images_from_pi import get_image, get_image_x_times get_image() check_blob_in_direct_path(os.getcwd() + "/images/greg.jpg")
from analyze import check_blob_in_direct_path import os import sys sys.path.insert(0, os.getcwd()) from get_images_from_pi import get_image, get_image_x_times get_image() check_blob_in_direct_path(os.getcwd() + "/images/greg.jpg")
Delete line loading an unnecessary module
Delete line loading an unnecessary module
Python
mit
jwarshaw/RaspberryDrive
4e75e742475236cf7358b4481a29a54eb607dd4d
spacy/tests/regression/test_issue850.py
spacy/tests/regression/test_issue850.py
''' Test Matcher matches with '*' operator and Boolean flag ''' from __future__ import unicode_literals import pytest from ...matcher import Matcher from ...vocab import Vocab from ...attrs import LOWER from ...tokens import Doc @pytest.mark.xfail def test_issue850(): matcher = Matcher(Vocab()) IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True) matcher.add_pattern( "FarAway", [ {LOWER: "bob"}, {'OP': '*', IS_ANY_TOKEN: True}, {LOWER: 'frank'} ]) doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'cat', 'frank']) match = matcher(doc) assert len(match) == 1 start, end, label, ent_id = match assert start == 0 assert end == 4
''' Test Matcher matches with '*' operator and Boolean flag ''' from __future__ import unicode_literals from __future__ import print_function import pytest from ...matcher import Matcher from ...vocab import Vocab from ...attrs import LOWER from ...tokens import Doc def test_basic_case(): matcher = Matcher(Vocab( lex_attr_getters={LOWER: lambda string: string.lower()})) IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True) matcher.add_pattern( "FarAway", [ {LOWER: "bob"}, {'OP': '*', LOWER: 'and'}, {LOWER: 'frank'} ]) doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank']) match = matcher(doc) assert len(match) == 1 ent_id, label, start, end = match[0] assert start == 0 assert end == 4 @pytest.mark.xfail def test_issue850(): '''The problem here is that the variable-length pattern matches the succeeding token. We then don't handle the ambiguity correctly.''' matcher = Matcher(Vocab( lex_attr_getters={LOWER: lambda string: string.lower()})) IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True) matcher.add_pattern( "FarAway", [ {LOWER: "bob"}, {'OP': '*', IS_ANY_TOKEN: True}, {LOWER: 'frank'} ]) doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank']) match = matcher(doc) assert len(match) == 1 ent_id, label, start, end = match[0] assert start == 0 assert end == 4
Update regression test for variable-length pattern problem in the matcher.
Update regression test for variable-length pattern problem in the matcher.
Python
mit
aikramer2/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,explosion/spaCy,recognai/spaCy,raphael0202/spaCy,recognai/spaCy,honnibal/spaCy,raphael0202/spaCy,recognai/spaCy,honnibal/spaCy,aikramer2/spaCy,raphael0202/spaCy,explosion/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,explosion/spaCy,recognai/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,spacy-io/spaCy,recognai/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,explosion/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,raphael0202/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy
fa8783f3307582dafcf636f5c94a7e4cff05724b
bin/tree_print_fasta_names.py
bin/tree_print_fasta_names.py
#! /usr/bin/env python3 import os import shutil import datetime import sys import argparse from ete3 import Tree import logging DEFAULT_FORMAT = 1 class TreeIndex: def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT): self.tree_newick_fn=tree_newick_fn self.tree=read_newick(tree_newick_fn,format=format) def process_node(self,node): if node.is_leaf(): if hasattr(node,"fastapath"): fastas_fn=node.fastapath.split("@") for fasta_fn in fastas_fn: print(fasta_fn) else: children=node.get_children() for child in children: self.process_node(child) if __name__ == "__main__": assert(len(sys.argv)==2) newick_fn=sys.argv[1] ti=TreeIndex( tree_newick_fn=newick_fn, ) ti.process_node(ti.tree.get_tree_root())
#! /usr/bin/env python3 import os import shutil import datetime import sys from ete3 import Tree DEFAULT_FORMAT = 1 class TreeIndex: def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT): self.tree_newick_fn=tree_newick_fn self.tree=Tree(tree_newick_fn,format=format) def process_node(self,node): if node.is_leaf(): if hasattr(node,"fastapath"): fastas_fn=node.fastapath.split("@") for fasta_fn in fastas_fn: print(fasta_fn) else: children=node.get_children() for child in children: self.process_node(child) if __name__ == "__main__": assert(len(sys.argv)==2) newick_fn=sys.argv[1] ti=TreeIndex( tree_newick_fn=newick_fn, ) ti.process_node(ti.tree.get_tree_root())
Fix error in loading trees
Fix error in loading trees Former-commit-id: 6fda03a47c5fa2d65c143ebdd81e158ba5e1ccda
Python
mit
karel-brinda/prophyle,karel-brinda/prophyle,karel-brinda/prophyle,karel-brinda/prophyle
a20c6d072d70c535ed1f116fc04016c834ea9c14
doc/en/_getdoctarget.py
doc/en/_getdoctarget.py
#!/usr/bin/env python import py def get_version_string(): fn = py.path.local(__file__).join("..", "..", "..", "_pytest", "__init__.py") for line in fn.readlines(): if "version" in line: return eval(line.split("=")[-1]) def get_minor_version_string(): return ".".join(get_version_string().split(".")[:2]) if __name__ == "__main__": print (get_minor_version_string())
#!/usr/bin/env python import py def get_version_string(): fn = py.path.local(__file__).join("..", "..", "..", "_pytest", "__init__.py") for line in fn.readlines(): if "version" in line and not line.strip().startswith('#'): return eval(line.split("=")[-1]) def get_minor_version_string(): return ".".join(get_version_string().split(".")[:2]) if __name__ == "__main__": print (get_minor_version_string())
Fix getdoctarget to ignore comment lines
Fix getdoctarget to ignore comment lines
Python
mit
etataurov/pytest,gabrielcnr/pytest,mbirtwell/pytest,vodik/pytest,The-Compiler/pytest,omarkohl/pytest,Bjwebb/pytest,davidszotten/pytest,gabrielcnr/pytest,mdboom/pytest,ionelmc/pytest,malinoff/pytest,hpk42/pytest,tareqalayan/pytest,userzimmermann/pytest,rouge8/pytest,tgoodlet/pytest,abusalimov/pytest,bukzor/pytest,icemac/pytest,pfctdayelise/pytest,JonathonSonesen/pytest,ionelmc/pytest,alfredodeza/pytest,chiller/pytest,skylarjhdownes/pytest,RonnyPfannschmidt/pytest,Haibo-Wang-ORG/pytest,lukas-bednar/pytest,mhils/pytest,mhils/pytest,chiller/pytest,oleg-alexandrov/pytest,oleg-alexandrov/pytest,MengJueM/pytest,chillbear/pytest,rmfitzpatrick/pytest,tomviner/pytest,Bachmann1234/pytest,pytest-dev/pytest,doordash/pytest,eli-b/pytest,codewarrior0/pytest,flub/pytest,bukzor/pytest,ropez/pytest,Haibo-Wang-ORG/pytest,abusalimov/pytest,mdboom/pytest,MengJueM/pytest,icemac/pytest,The-Compiler/pytest,vmalloc/dessert,codewarrior0/pytest,jb098/pytest,chillbear/pytest,jb098/pytest,omarkohl/pytest,doordash/pytest,mbirtwell/pytest,nicoddemus/pytest,tomviner/pytest,nicoddemus/pytest,ropez/pytest,jaraco/pytest,rouge8/pytest,markshao/pytest,txomon/pytest,lukas-bednar/pytest,Bachmann1234/pytest,userzimmermann/pytest,MichaelAquilina/pytest,vodik/pytest,hpk42/pytest,ddboline/pytest,hackebrot/pytest,JonathonSonesen/pytest,Akasurde/pytest,Bjwebb/pytest
efd6fad89131c4d3070c68013ace77f11647bd68
opal/core/search/__init__.py
opal/core/search/__init__.py
""" OPAL core search package """ from opal.core.search import urls from opal.core import plugins from opal.core import celery # NOQA class SearchPlugin(plugins.OpalPlugin): """ The plugin entrypoint for OPAL's core search functionality """ urls = urls.urlpatterns javascripts = { 'opal.services': [ 'js/search/services/filter.js', 'js/search/services/filters_loader.js', 'js/search/services/filter_resource.js', "js/search/services/paginator.js", ], 'opal.controllers': [ 'js/search/controllers/search.js', 'js/search/controllers/extract.js', "js/search/controllers/save_filter.js", ] } plugins.register(SearchPlugin)
""" OPAL core search package """ from opal.core import celery # NOQA from opal.core.search import plugin
Move Opal.core.search plugin into a plugins.py ahead of full plugin 2.0 refactor
Move Opal.core.search plugin into a plugins.py ahead of full plugin 2.0 refactor
Python
agpl-3.0
khchine5/opal,khchine5/opal,khchine5/opal
56a8b900570200e63ee460dd7e2962cba2450b16
preparation/tools/build_assets.py
preparation/tools/build_assets.py
from copy import copy import argparse from preparation.resources.Resource import names_registered, resource_by_name from hb_res.storage import get_storage, ExplanationStorage def generate_asset(resource, out_storage: ExplanationStorage): out_storage.clear() for explanation in resource: r = copy(explanation) for functor in resource.modifiers: if r is None: break r = functor(r) if r is not None: out_storage.add_entry(r) def rebuild_trunk(trunk: str): resource = resource_by_name(trunk + 'Resource')() with get_storage(trunk) as out_storage: print("Starting {} generation".format(trunk)) generate_asset(resource, out_storage) print("Finished {} generation".format(trunk)) def make_argparser(): parser = argparse.ArgumentParser(description='Rebuild some asset') names = [name.replace('Resource', '') for name in names_registered()] parser.add_argument('resources', metavar='RESOURCE', nargs='+', choices=names + ['all'], help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names))) return parser def main(args=None): if not isinstance(args, argparse.Namespace): parser = make_argparser() args = parser.parse_args(args) assert all not in args.resources or len(args.resources) == 1 for name in args.resources: rebuild_trunk(name) if __name__ == '__main__': main()
from copy import copy import argparse from preparation.resources.Resource import names_registered, resource_by_name from hb_res.storage import get_storage, ExplanationStorage def generate_asset(resource, out_storage: ExplanationStorage): out_storage.clear() for explanation in resource: r = copy(explanation) for functor in resource.modifiers: if r is None: break r = functor(r) if r is not None: out_storage.add_entry(r) def rebuild_trunk(trunk: str): resource = resource_by_name(trunk + 'Resource')() with get_storage(trunk) as out_storage: print("Starting {} generation".format(trunk)) generate_asset(resource, out_storage) print("Finished {} generation".format(trunk)) def make_argparser(): parser = argparse.ArgumentParser(description='Rebuild some asset') names = [name.replace('Resource', '') for name in names_registered()] parser.add_argument('resources', metavar='RESOURCE', nargs='+', choices=names + ['all'], help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names))) return parser def main(args=None): if not isinstance(args, argparse.Namespace): parser = make_argparser() args = parser.parse_args(args) assert 'all' not in args.resources or len(args.resources) == 1 if 'all' in args.resources: args.resources = [name.replace('Resource', '') for name in names_registered()] for name in args.resources: rebuild_trunk(name) if __name__ == '__main__': main()
Fix bug with 'all' argument
Fix bug with 'all' argument
Python
mit
hatbot-team/hatbot_resources
aae01cdcbd239397dad46b2d5fac91eb4219479f
project/apps/forum/serializers.py
project/apps/forum/serializers.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from machina.core.db.models import get_model from rest_framework import serializers Forum = get_model('forum', 'Forum') class ForumSerializer(serializers.ModelSerializer): description = serializers.SerializerMethodField() class Meta: model = Forum fields = [ 'id', 'name', 'slug', 'type', 'description', 'image', 'link', 'link_redirects', 'posts_count', 'topics_count', 'link_redirects_count', 'last_post_on', 'display_sub_forum_list', 'lft', 'rght', 'tree_id', 'level', 'parent', ] def get_description(self, obj): return obj.description.rendered
# -*- coding: utf-8 -*- from __future__ import unicode_literals from machina.core.db.models import get_model from rest_framework import serializers Forum = get_model('forum', 'Forum') class ForumSerializer(serializers.ModelSerializer): description = serializers.SerializerMethodField() previous_sibling = serializers.SerializerMethodField() next_sibling = serializers.SerializerMethodField() class Meta: model = Forum fields = [ 'id', 'name', 'slug', 'type', 'description', 'image', 'link', 'link_redirects', 'posts_count', 'topics_count', 'link_redirects_count', 'last_post_on', 'display_sub_forum_list', 'lft', 'rght', 'tree_id', 'level', 'parent', 'previous_sibling', 'next_sibling', ] def get_description(self, obj): return obj.description.rendered def get_previous_sibling(self, obj): sibling = obj.get_previous_sibling() return sibling.pk if sibling else None def get_next_sibling(self, obj): sibling = obj.get_next_sibling() return sibling.pk if sibling else None
Add siblings to forum serializer
Add siblings to forum serializer
Python
mit
ellmetha/machina-singlepageapp,ellmetha/machina-singlepageapp
6167215e4ed49e8a4300f327d5b4ed4540d1a420
numba/tests/npyufunc/test_parallel_env_variable.py
numba/tests/npyufunc/test_parallel_env_variable.py
from numba.np.ufunc.parallel import get_thread_count from os import environ as env from numba.core import config import unittest class TestParallelEnvVariable(unittest.TestCase): """ Tests environment variables related to the underlying "parallel" functions for npyufuncs. """ _numba_parallel_test_ = False def test_num_threads_variable(self): """ Tests the NUMBA_NUM_THREADS env variable behaves as expected. """ key = 'NUMBA_NUM_THREADS' current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS)) threads = "3154" env[key] = threads try: config.reload_config() except RuntimeError as e: # This test should fail if threads have already been launched self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0]) else: try: self.assertEqual(threads, str(get_thread_count())) self.assertEqual(threads, str(config.NUMBA_NUM_THREADS)) finally: # reset the env variable/set to default env[key] = current config.reload_config() if __name__ == '__main__': unittest.main()
from numba.np.ufunc.parallel import get_thread_count from os import environ as env from numba.core import config import unittest class TestParallelEnvVariable(unittest.TestCase): """ Tests environment variables related to the underlying "parallel" functions for npyufuncs. """ _numba_parallel_test_ = False def test_num_threads_variable(self): """ Tests the NUMBA_NUM_THREADS env variable behaves as expected. """ key = 'NUMBA_NUM_THREADS' current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS)) threads = "3154" env[key] = threads try: config.reload_config() except RuntimeError as e: # This test should fail if threads have already been launched self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0]) else: self.assertEqual(threads, str(get_thread_count())) self.assertEqual(threads, str(config.NUMBA_NUM_THREADS)) finally: # reset the env variable/set to default. Should not fail even if # threads are launched because the value is the same. env[key] = current config.reload_config() if __name__ == '__main__': unittest.main()
Fix the parallel env variable test to reset the env correctly
Fix the parallel env variable test to reset the env correctly
Python
bsd-2-clause
seibert/numba,seibert/numba,stonebig/numba,cpcloud/numba,sklam/numba,gmarkall/numba,stuartarchibald/numba,numba/numba,stonebig/numba,seibert/numba,stuartarchibald/numba,sklam/numba,gmarkall/numba,sklam/numba,sklam/numba,stonebig/numba,IntelLabs/numba,IntelLabs/numba,stuartarchibald/numba,cpcloud/numba,numba/numba,stuartarchibald/numba,IntelLabs/numba,stuartarchibald/numba,cpcloud/numba,gmarkall/numba,numba/numba,seibert/numba,IntelLabs/numba,gmarkall/numba,numba/numba,numba/numba,sklam/numba,gmarkall/numba,stonebig/numba,cpcloud/numba,stonebig/numba,IntelLabs/numba,seibert/numba,cpcloud/numba
3681660935d77d392a7ed470a8e85470e33aaca0
extract_options.py
extract_options.py
from pymongo import MongoClient def main(): client = MongoClient() db = client.cityhotspots db.drop_collection('dineroptions') diners_collection = db.diners doc = {} diner_options_collection = db.dineroptions doc['categories'] = diners_collection.distinct('category') doc['cuisines'] = diners_collection.distinct('cuisine') doc['districts'] = diners_collection.distinct('address.district') diner_options_collection.insert(doc) if __name__ == '__main__': main()
from pymongo import MongoClient def main(): client = MongoClient() db = client.cityhotspots db.drop_collection('dineroptions') diners_collection = db.diners doc = {} diner_options_collection = db.dineroptions doc['categories'] = diners_collection.distinct('category') doc['cuisines'] = diners_collection.distinct('cuisine') doc['districts'] = diners_collection.distinct('address.district') doc['max_price'] = list(diners_collection.aggregate([{ "$group": { "_id": None, "max": {"$max": "$price_max"} } }]))[0]['max'] doc['min_price'] = list(diners_collection.aggregate([{ "$group": { "_id": None, "min": {"$min": "$price_min"} } }]))[0]['min'] diner_options_collection.insert(doc) if __name__ == '__main__': main()
Add min_price and max_price fields
Add min_price and max_price fields
Python
mit
earlwlkr/POICrawler
504205d02ef2f5b66da225390fdb34b8b736ce57
ideascube/migrations/0009_add_a_system_user.py
ideascube/migrations/0009_add_a_system_user.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.db import migrations def add_user(*args): User = get_user_model() User(serial='__system__', full_name='System', password='!!').save() class Migration(migrations.Migration): dependencies = [ ('ideascube', '0008_user_sdb_level'), ('search', '0001_initial'), ] operations = [ migrations.RunPython(add_user, None), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def add_user(apps, *args): User = apps.get_model('ideascube', 'User') User(serial='__system__', full_name='System', password='!!').save() class Migration(migrations.Migration): dependencies = [ ('ideascube', '0008_user_sdb_level'), ('search', '0001_initial'), ] operations = [ migrations.RunPython(add_user, None), ]
Load user from migration registry when creating system user
Load user from migration registry when creating system user Always load models from the registry in migration files. I hate the idea of touching a migration already released, but this one prevents us from adding new properties to User. If we load the User directly (not from registry) when creating the user model, we'll try to create a user with column that does not exist at the time of this migration.
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
d8d2e4b763fbd7cedc42046f6f45395bf15caa79
samples/plugins/scenario/scenario_plugin.py
samples/plugins/scenario/scenario_plugin.py
# Copyright 2013: Mirantis 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from rally.task.scenarios import base class ScenarioPlugin(base.Scenario): """Sample plugin which lists flavors.""" @base.atomic_action_timer("list_flavors") def _list_flavors(self): """Sample of usage clients - list flavors You can use self.context, self.admin_clients and self.clients which are initialized on scenario instance creation. """ self.clients("nova").flavors.list() @base.atomic_action_timer("list_flavors_as_admin") def _list_flavors_as_admin(self): """The same with admin clients.""" self.admin_clients("nova").flavors.list() @base.scenario() def list_flavors(self): """List flavors.""" self._list_flavors() self._list_flavors_as_admin()
# Copyright 2013: Mirantis 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from rally.plugins.openstack import scenario from rally.task import atomic class ScenarioPlugin(scenario.OpenStackScenario): """Sample plugin which lists flavors.""" @atomic.action_timer("list_flavors") def _list_flavors(self): """Sample of usage clients - list flavors You can use self.context, self.admin_clients and self.clients which are initialized on scenario instance creation. """ self.clients("nova").flavors.list() @atomic.action_timer("list_flavors_as_admin") def _list_flavors_as_admin(self): """The same with admin clients.""" self.admin_clients("nova").flavors.list() @scenario.configure() def list_flavors(self): """List flavors.""" self._list_flavors() self._list_flavors_as_admin()
Fix the scenario plugin sample
Fix the scenario plugin sample We forgot to fix scenario plugin sample when we were doing rally.task.scenario refactoring Change-Id: Iadbb960cf168bd3b9cd6c1881a5f7a8dffd7036f
Python
apache-2.0
group-policy/rally,eayunstack/rally,openstack/rally,amit0701/rally,paboldin/rally,eonpatapon/rally,cernops/rally,afaheem88/rally,yeming233/rally,vganapath/rally,gluke77/rally,aforalee/RRally,yeming233/rally,openstack/rally,gluke77/rally,gluke77/rally,eayunstack/rally,openstack/rally,aforalee/RRally,cernops/rally,group-policy/rally,openstack/rally,vganapath/rally,amit0701/rally,vganapath/rally,redhat-openstack/rally,eonpatapon/rally,amit0701/rally,gluke77/rally,paboldin/rally,redhat-openstack/rally,paboldin/rally,group-policy/rally,afaheem88/rally,eayunstack/rally,aplanas/rally,vganapath/rally,aplanas/rally
68a621005c5a520b7a97c4cad462d43fb7f3aaed
paws/views.py
paws/views.py
from .request import Request from .response import Response, response import logging log = logging.getLogger() class View: def __call__(self, event, context): request = Request(event, context) resp = self.prepare(request) if resp: return resp kwargs = event.get('pathParameters') or {} func = getattr(self, request.method.lower()) try: resp = func(request, **kwargs) except: import traceback log.error(self) log.error(traceback.format_exc()) return response(body='Internal server Error', status=500) if isinstance(resp, Response): resp = resp.render() return resp def prepare(self, request): pass
from .request import Request from .response import Response, response import logging log = logging.getLogger() class View: def __call__(self, event, context): kwargs = event.get('pathParameters') or {} self.dispatch(request, **kwargs) def dispatch(self, request, **kwargs): func = getattr(self, request.method.lower()) try: resp = func(request, **kwargs) except: import traceback log.error(self) log.error(traceback.format_exc()) return response(body='Internal server Error', status=500) if isinstance(resp, Response): resp = resp.render() return resp def prepare(self, request): pass
Break out dispatch, and drop prepare. Easier testing
Break out dispatch, and drop prepare. Easier testing
Python
bsd-3-clause
funkybob/paws
d4d448adff71b609d5efb269d1a9a2ea4aba3590
radio/templatetags/radio_js_config.py
radio/templatetags/radio_js_config.py
import random import json from django import template from django.conf import settings register = template.Library() # Build json value to pass as js config @register.simple_tag() def trunkplayer_js_config(user): js_settings = getattr(settings, 'JS_SETTINGS', None) js_json = {} if js_settings: for setting in js_settings: set_val = getattr(settings, setting, '') js_json[setting] = set_val js_json['user_is_staff'] = user.is_staff if user.is_authenticated(): js_json['user_is_authenticated'] = True else: js_json['user_is_authenticated'] = False js_json['radio_change_unit'] = user.has_perm('radio.change_unit') return json.dumps(js_json)
import random import json from django import template from django.conf import settings from radio.models import SiteOption register = template.Library() # Build json value to pass as js config @register.simple_tag() def trunkplayer_js_config(user): js_settings = getattr(settings, 'JS_SETTINGS', None) js_json = {} if js_settings: for setting in js_settings: set_val = getattr(settings, setting, '') js_json[setting] = set_val for opt in SiteOption.objects.filter(javascript_visible=True): js_json[opt.name] = opt.value_boolean_or_string() js_json['user_is_staff'] = user.is_staff if user.is_authenticated(): js_json['user_is_authenticated'] = True else: js_json['user_is_authenticated'] = False js_json['radio_change_unit'] = user.has_perm('radio.change_unit') return json.dumps(js_json)
Allow SiteOption to load into the JS
Allow SiteOption to load into the JS
Python
mit
ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player
0a13a9a8a779102dbcb2beead7d8aa9143f4c79b
tests/pytests/unit/client/ssh/test_shell.py
tests/pytests/unit/client/ssh/test_shell.py
import os import subprocess import pytest import salt.client.ssh.shell as shell @pytest.fixture def keys(tmp_path): pub_key = tmp_path / "ssh" / "testkey.pub" priv_key = tmp_path / "ssh" / "testkey" yield {"pub_key": str(pub_key), "priv_key": str(priv_key)} @pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh") @pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True) class TestSSHShell: def test_ssh_shell_key_gen(self, keys): """ Test ssh key_gen """ shell.gen_key(keys["priv_key"]) for fp in keys.keys(): assert os.path.exists(keys[fp]) # verify there is not a passphrase set on key ret = subprocess.check_output( ["ssh-keygen", "-f", keys["priv_key"], "-y"], timeout=30, ) assert ret.decode().startswith("ssh-rsa")
import subprocess import types import pytest import salt.client.ssh.shell as shell @pytest.fixture def keys(tmp_path): pub_key = tmp_path / "ssh" / "testkey.pub" priv_key = tmp_path / "ssh" / "testkey" return types.SimpleNamespace(pub_key=pub_key, priv_key=priv_key) @pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh") @pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True) def test_ssh_shell_key_gen(keys): """ Test ssh key_gen """ shell.gen_key(str(keys.priv_key)) assert keys.priv_key.exists() assert keys.pub_key.exists() # verify there is not a passphrase set on key ret = subprocess.check_output( ["ssh-keygen", "-f", str(keys.priv_key), "-y"], timeout=30, ) assert ret.decode().startswith("ssh-rsa")
Use commit suggestion to use types
Use commit suggestion to use types Co-authored-by: Pedro Algarvio <[email protected]>
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
09d780474d00f3a8f4c2295154d74dae2023c1d3
samples/storage_sample/storage/__init__.py
samples/storage_sample/storage/__init__.py
"""Common imports for generated storage client library.""" # pylint:disable=wildcard-import import pkgutil from apitools.base.py import * from storage_v1 import * from storage_v1_client import * from storage_v1_messages import * __path__ = pkgutil.extend_path(__path__, __name__)
"""Common imports for generated storage client library.""" # pylint:disable=wildcard-import import pkgutil from apitools.base.py import * from storage_v1_client import * from storage_v1_messages import * __path__ = pkgutil.extend_path(__path__, __name__)
Drop the CLI from the sample storage client imports.
Drop the CLI from the sample storage client imports.
Python
apache-2.0
cherba/apitools,craigcitro/apitools,b-daniels/apitools,betamos/apitools,kevinli7/apitools,houglum/apitools,pcostell/apitools,thobrla/apitools,google/apitools
08d838e87bd92dacbbbfe31b19c628b9d3b271a8
src/plone.example/plone/example/todo.py
src/plone.example/plone/example/todo.py
# -*- encoding: utf-8 -*- from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass
# -*- encoding: utf-8 -*- from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", default=u'' ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", default=False ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass
Set default values for fields
Set default values for fields
Python
bsd-2-clause
plone/plone.server,plone/plone.server
29a964a64230e26fca550e81a1ecba3dd782dfb1
python/vtd.py
python/vtd.py
import libvtd.trusted_system def UpdateTrustedSystem(file_name): """Make sure the TrustedSystem object is up to date.""" global my_system my_system = libvtd.trusted_system.TrustedSystem() my_system.AddFile(file_name)
import libvtd.trusted_system def UpdateTrustedSystem(file_name): """Make sure the TrustedSystem object is up to date.""" global my_system if 'my_system' not in globals(): my_system = libvtd.trusted_system.TrustedSystem() my_system.AddFile(file_name) my_system.Refresh()
Refresh system instead of clobbering it
Refresh system instead of clobbering it Otherwise, if we set the Contexts, they'll be gone before we can request the NextActions!
Python
apache-2.0
chiphogg/vim-vtd
b532ffff18e95b6014921d88b6df075e8ac2c4ec
problib/example1/__init__.py
problib/example1/__init__.py
from sympy import symbols, cos, sin, latex from mathdeck import rand, answer metadata = { 'author': 'Bob Hope', 'institution': 'University of Missouri', 'subject': 'algebra', 'minor subject': 'polynomial equations', 'tags': ['simplify','roots','intervals'] } r = rand.Random() # choose three random integers between 0 and 10. root1 = r.randint(0,10) root2 = r.randint(0,10) root3 = r.randint(0,10) # # # specify our variables x = symbols('x') p = ((x-root1)*(x-root2)).expand(basic=True) template_variables = { 'p': latex(p), } a1 = answer.Answer() a1.value = cos(x)**2-sin(x)**2 a1.type = 'function' a1.variables = ['x'] a1.domain = 'R' a2 = answer.Answer() a2.value = 'x+1' a2.type = "function" a2.variables = ['x','y'] answers = { 'ans1': a1, 'ans2': a2 }
from sympy import symbols, cos, sin, latex from mathdeck import rand, answer metadata = { 'author': 'Bob Hope', 'institution': 'University of Missouri', 'subject': 'algebra', 'minor subject': 'polynomial equations', 'tags': ['simplify','roots','intervals'] } r = rand.Random() # choose three random integers between 0 and 10. root1 = r.randint(0,10) root2 = r.randint(0,10) root3 = r.randint(0,10) # # # specify our variables x = symbols('x') p = ((x-root1)*(x-root2)).expand(basic=True) func = cos(x)**2-sin(x)**2 a1 = answer.Answer( value=func, type='function', vars=['x']) a2 = answer.Answer(value='x+1',type='function',vars=['x']) answers = { 'ans1': a1, 'ans2': a2 } template_variables = { 'p': latex(p), }
Update mathdeck problib for new Answer refactoring
Update mathdeck problib for new Answer refactoring
Python
apache-2.0
patrickspencer/mathdeck,patrickspencer/mathdeck
3a9568b4d4de969b1e2031e8d2d3cdd7bd56824f
zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py
zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py
# -*- coding: utf-8 -*- from django.conf import settings from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: if not settings.PRODUCTION: return Realm = apps.get_model('zerver', 'Realm') UserProfile = apps.get_model('zerver', 'UserProfile') if Realm.objects.count() == 0: # Database not yet populated, do nothing: return if Realm.objects.filter(string_id="zulipinternal").exists(): return internal_realm = Realm.objects.get(string_id="zulip") # For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots: welcome_bot = UserProfile.objects.get(email="[email protected]") assert welcome_bot.realm.id == internal_realm.id internal_realm.string_id = "zulipinternal" internal_realm.name = "System use only" internal_realm.save() class Migration(migrations.Migration): dependencies = [ ('zerver', '0236_remove_illegal_characters_email_full'), ] operations = [ migrations.RunPython(rename_zulip_realm_to_zulipinternal) ]
# -*- coding: utf-8 -*- from django.conf import settings from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: if not settings.PRODUCTION: return Realm = apps.get_model('zerver', 'Realm') UserProfile = apps.get_model('zerver', 'UserProfile') if Realm.objects.count() == 0: # Database not yet populated, do nothing: return if Realm.objects.filter(string_id="zulipinternal").exists(): return if not Realm.objects.filter(string_id="zulip").exists(): # If the user renamed the `zulip` system bot realm (or deleted # it), there's nothing for us to do. return internal_realm = Realm.objects.get(string_id="zulip") # For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots: welcome_bot = UserProfile.objects.get(email="[email protected]") assert welcome_bot.realm.id == internal_realm.id internal_realm.string_id = "zulipinternal" internal_realm.name = "System use only" internal_realm.save() class Migration(migrations.Migration): dependencies = [ ('zerver', '0236_remove_illegal_characters_email_full'), ] operations = [ migrations.RunPython(rename_zulip_realm_to_zulipinternal) ]
Fix zulipinternal migration corner case.
migrations: Fix zulipinternal migration corner case. It's theoretically possible to have configured a Zulip server where the system bots live in the same realm as normal users (and may have in fact been the default in early Zulip releases? Unclear.). We should handle these without the migration intended to clean up naming for the system bot realm crashing. Fixes #13660.
Python
apache-2.0
brainwane/zulip,andersk/zulip,hackerkid/zulip,synicalsyntax/zulip,andersk/zulip,hackerkid/zulip,punchagan/zulip,shubhamdhama/zulip,showell/zulip,zulip/zulip,synicalsyntax/zulip,kou/zulip,rht/zulip,showell/zulip,brainwane/zulip,punchagan/zulip,shubhamdhama/zulip,hackerkid/zulip,andersk/zulip,kou/zulip,brainwane/zulip,brainwane/zulip,andersk/zulip,showell/zulip,shubhamdhama/zulip,kou/zulip,punchagan/zulip,zulip/zulip,kou/zulip,showell/zulip,brainwane/zulip,eeshangarg/zulip,timabbott/zulip,eeshangarg/zulip,hackerkid/zulip,shubhamdhama/zulip,zulip/zulip,timabbott/zulip,brainwane/zulip,eeshangarg/zulip,rht/zulip,zulip/zulip,timabbott/zulip,rht/zulip,synicalsyntax/zulip,andersk/zulip,showell/zulip,shubhamdhama/zulip,rht/zulip,hackerkid/zulip,rht/zulip,hackerkid/zulip,eeshangarg/zulip,kou/zulip,synicalsyntax/zulip,brainwane/zulip,shubhamdhama/zulip,eeshangarg/zulip,andersk/zulip,rht/zulip,timabbott/zulip,punchagan/zulip,showell/zulip,eeshangarg/zulip,synicalsyntax/zulip,punchagan/zulip,timabbott/zulip,zulip/zulip,andersk/zulip,punchagan/zulip,zulip/zulip,hackerkid/zulip,timabbott/zulip,synicalsyntax/zulip,zulip/zulip,showell/zulip,eeshangarg/zulip,kou/zulip,punchagan/zulip,synicalsyntax/zulip,rht/zulip,kou/zulip,timabbott/zulip,shubhamdhama/zulip
97e3b202bbe6726a4056facb8b4690b0710029a9
handroll/tests/test_site.py
handroll/tests/test_site.py
# Copyright (c) 2015, Matt Layman import os import tempfile from handroll.site import Site from handroll.tests import TestCase class TestSite(TestCase): def test_finds_valid_site_root_from_templates(self): original = os.getcwd() valid_site = tempfile.mkdtemp() open(os.path.join(valid_site, 'template.html'), 'w').close() os.chdir(valid_site) site = Site() self.assertEqual(valid_site, site.path) os.chdir(original) def test_finds_valid_site_root_from_conf(self): original = os.getcwd() valid_site = tempfile.mkdtemp() open(os.path.join(valid_site, Site.CONFIG), 'w').close() os.chdir(valid_site) site = Site() self.assertEqual(valid_site, site.path) os.chdir(original) def test_site_has_absolute_path(self): original = os.getcwd() tempdir = tempfile.mkdtemp() site_path = os.path.join(tempdir, 'site') os.mkdir(site_path) os.chdir(tempdir) site = Site('site') self.assertEqual(site_path, site.path) os.chdir(original)
# Copyright (c) 2015, Matt Layman import os import tempfile from handroll.site import Site from handroll.tests import TestCase class TestSite(TestCase): def test_finds_valid_site_root_from_templates(self): original = os.getcwd() valid_site = os.path.realpath(tempfile.mkdtemp()) open(os.path.join(valid_site, 'template.html'), 'w').close() os.chdir(valid_site) site = Site() self.assertEqual(valid_site, site.path) os.chdir(original) def test_finds_valid_site_root_from_conf(self): original = os.getcwd() valid_site = os.path.realpath(tempfile.mkdtemp()) open(os.path.join(valid_site, Site.CONFIG), 'w').close() os.chdir(valid_site) site = Site() self.assertEqual(valid_site, site.path) os.chdir(original) def test_site_has_absolute_path(self): original = os.getcwd() tempdir = os.path.realpath(tempfile.mkdtemp()) site_path = os.path.join(tempdir, 'site') os.mkdir(site_path) os.chdir(tempdir) site = Site('site') self.assertEqual(site_path, site.path) os.chdir(original)
Use a real path when testing sites.
Use a real path when testing sites. Mac OS X returns link paths when calling `mkdtemp`. Calling realpath allows the site path comparison to be consistent across platforms.
Python
bsd-2-clause
handroll/handroll
7e44a8bd38105144111624710819a1ee54891222
campos_checkin/__openerp__.py
campos_checkin/__openerp__.py
# -*- coding: utf-8 -*- # Copyright 2017 Stein & Gabelgaard ApS # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': 'Campos Checkin', 'description': """ CampOS Check In functionality""", 'version': '8.0.1.0.0', 'license': 'AGPL-3', 'author': 'Stein & Gabelgaard ApS', 'website': 'www.steingabelgaard.dk', 'depends': [ 'campos_jobber_final', 'campos_transportation', 'campos_crewnet', 'web_ir_actions_act_window_message', #'web_tree_dynamic_colored_field', ], 'data': [ 'wizards/campos_checkin_grp_wiz.xml', 'views/event_registration.xml', 'wizards/campos_checkin_wiz.xml', 'security/campos_checkin.xml', 'views/campos_event_participant.xml', 'views/campos_mat_report.xml', ], 'demo': [ ], }
# -*- coding: utf-8 -*- # Copyright 2017 Stein & Gabelgaard ApS # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': 'Campos Checkin', 'description': """ CampOS Check In functionality""", 'version': '8.0.1.0.0', 'license': 'AGPL-3', 'author': 'Stein & Gabelgaard ApS', 'website': 'www.steingabelgaard.dk', 'depends': [ 'campos_jobber_final', 'campos_transportation', 'campos_crewnet', 'web_ir_actions_act_window_message', #'web_tree_dynamic_colored_field', ], 'data': [ 'wizards/campos_checkin_wiz.xml', 'security/campos_checkin.xml', 'views/campos_event_participant.xml', 'views/campos_mat_report.xml', 'wizards/campos_checkin_grp_wiz.xml', 'views/event_registration.xml', ], 'demo': [ ], }
Fix order for menu ref
Fix order for menu ref
Python
agpl-3.0
sl2017/campos
3cd99c23099a625da711e3ac458a46a7b364d83c
hystrix/pool.py
hystrix/pool.py
from __future__ import absolute_import from concurrent.futures import ThreadPoolExecutor import logging import six log = logging.getLogger(__name__) class PoolMetaclass(type): __instances__ = dict() __blacklist__ = ('Pool', 'PoolMetaclass') def __new__(cls, name, bases, attrs): if name in cls.__blacklist__: return super(PoolMetaclass, cls).__new__(cls, name, bases, attrs) pool_key = attrs.get('pool_key') or '{}Pool'.format(name) new_class = super(PoolMetaclass, cls).__new__(cls, pool_key, bases, attrs) setattr(new_class, 'pool_key', pool_key) if pool_key not in cls.__instances__: cls.__instances__[pool_key] = new_class return cls.__instances__[pool_key] class Pool(six.with_metaclass(PoolMetaclass, ThreadPoolExecutor)): pool_key = None def __init__(self, pool_key=None, max_workers=5): super(Pool, self).__init__(max_workers)
from __future__ import absolute_import from concurrent.futures import ProcessPoolExecutor import logging import six log = logging.getLogger(__name__) class PoolMetaclass(type): __instances__ = dict() __blacklist__ = ('Pool', 'PoolMetaclass') def __new__(cls, name, bases, attrs): if name in cls.__blacklist__: return super(PoolMetaclass, cls).__new__(cls, name, bases, attrs) pool_key = attrs.get('pool_key') or '{}Pool'.format(name) new_class = super(PoolMetaclass, cls).__new__(cls, pool_key, bases, attrs) setattr(new_class, 'pool_key', pool_key) if pool_key not in cls.__instances__: cls.__instances__[pool_key] = new_class return cls.__instances__[pool_key] class Pool(six.with_metaclass(PoolMetaclass, ProcessPoolExecutor)): pool_key = None def __init__(self, pool_key=None, max_workers=5): super(Pool, self).__init__(max_workers)
Change Pool to use ProcessPoolExecutor
Change Pool to use ProcessPoolExecutor
Python
apache-2.0
wiliamsouza/hystrix-py,wiliamsouza/hystrix-py
c52edc120f38acb079fa364cdb684fc2052d4727
corehq/messaging/smsbackends/trumpia/urls.py
corehq/messaging/smsbackends/trumpia/urls.py
from django.conf.urls import url from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView urlpatterns = [ url(r'^sms/(?P<api_key>[\w-]+)/?$', TrumpiaIncomingView.as_view(), name=TrumpiaIncomingView.urlname), ]
from django.conf.urls import url from corehq.apps.hqwebapp.decorators import waf_allow from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView urlpatterns = [ url(r'^sms/(?P<api_key>[\w-]+)/?$', waf_allow('XSS_QUERYSTRING')(TrumpiaIncomingView.as_view()), name=TrumpiaIncomingView.urlname), ]
Annotate trumpia url to say it allows XML in the querystring
Annotate trumpia url to say it allows XML in the querystring
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
14546b0ba1dd7f5a9ea623fde85737fa95bd2843
test/integration/test_node_propagation.py
test/integration/test_node_propagation.py
from kitten.server import KittenServer from gevent.pool import Group from mock import MagicMock class TestPropagation(object): def setup_method(self, method): self.servers = Group() for port in range(4): ns = MagicMock() ns.port = 9812 + port server = KittenServer(ns) self.servers.spawn(server.listen_forever) def test_node_propagation(self): """ Tests that check node propagation 1) Spin up four servers. 2) Make the first one send a sync request to all three others. 3) Count the numbers of requests made. 4) Check databases to see that they all know each other. """ pass
from kitten.server import KittenServer from gevent.pool import Group from mock import MagicMock class TestPropagation(object): def setup_method(self, method): self.servers = Group() for port in range(4): ns = MagicMock() ns.port = 9812 + port server = KittenServer(ns) self.servers.spawn(server.listen_forever) def teardown_method(self, method): self.servers.kill(timeout=1) def test_node_propagation(self): """ Tests that check node propagation 1) Spin up four servers. 2) Make the first one send a sync request to all three others. 3) Count the numbers of requests made. 4) Check databases to see that they all know each other. """ pass
Add teardown of integration test
Add teardown of integration test
Python
mit
thiderman/network-kitten
d159f8201b9d9aeafd24f07a9e39855fc537182d
cocoscore/tools/data_tools.py
cocoscore/tools/data_tools.py
import pandas as pd def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True): """ Load a sentence data set as pandas DataFrame from a given path. :param data_frame_path: the path to load the pandas DataFrame from :param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ... :param class_labels: if True, the class label is assumed to be present as the last column :return: a pandas DataFrame loaded from the given path """ column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text'] if class_labels: column_names.append('class') data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False, names=column_names) if sort_reindex: data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort') data_df.reset_index(inplace=True, drop=True) assert data_df.isnull().sum().sum() == 0 return data_df
import pandas as pd def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True, match_distance=False): """ Load a sentence data set as pandas DataFrame from a given path. :param data_frame_path: the path to load the pandas DataFrame from :param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ... :param class_labels: if True, the class label is assumed to be present as the second-to-last column :param match_distance: if True, the distance between the closest match is assumed to be present as the last column :return: a pandas DataFrame loaded from the given path """ column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text'] if class_labels: column_names.append('class') if match_distance: column_names.append('distance') data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False, names=column_names) if sort_reindex: data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort') data_df.reset_index(inplace=True, drop=True) assert data_df.isnull().sum().sum() == 0 return data_df
Add match_distance flag to load_data_frame()
Add match_distance flag to load_data_frame()
Python
mit
JungeAlexander/cocoscore
d6dcd5ede1004b4f3dfbaba09e46a6728e8287a7
qipipe/qiprofile/sync.py
qipipe/qiprofile/sync.py
from qiprofile_rest_client.helpers import database from qiprofile_rest_client.model.subject import Subject from . import (clinical, imaging) def sync_session(project, collection, subject, session, filename): """ Updates the qiprofile database from the XNAT database content for the given session. :param project: the XNAT project name :param collection: the image collection name :param subject: the subject number :param session: the XNAT session name, without subject prefix :param filename: the XLS input file location """ # Get or create the database subject. sbj_pk = dict(project=project, collection=collection, number=subject) sbj = database.get_or_create(Subject, sbj_pk) # Update the clinical information from the XLS input. clinical.sync(sbj, filename) # Update the imaging information from XNAT. imaging.sync(sbj, session)
from qiprofile_rest_client.helpers import database from qiprofile_rest_client.model.subject import Subject from qiprofile_rest_client.model.imaging import Session from . import (clinical, imaging) def sync_session(project, collection, subject, session, filename): """ Updates the qiprofile database from the XNAT database content for the given session. :param project: the XNAT project name :param collection: the image collection name :param subject: the subject number :param session: the XNAT session number :param filename: the XLS input file location """ # Get or create the subject database subject. key = dict(project=project, collection=collection, number=subject) sbj = database.get_or_create(Subject, key) # Update the clinical information from the XLS input. clinical.sync(sbj, filename) # Update the imaging information from XNAT. imaging.sync(sbj, session)
Use the REST client get_or_create helper function.
Use the REST client get_or_create helper function.
Python
bsd-2-clause
ohsu-qin/qipipe
24c83c6a7a1981184545a72b3691a29121d81050
lib-dynload/lz4/__init__.py
lib-dynload/lz4/__init__.py
import sys import os p1, p2 = sys.version_info[:2] curpath = os.path.abspath( sys.argv[0] ) if os.path.islink(curpath): curpath = os.readlink(curpath) currentdir = os.path.dirname( curpath ) build_dir = os.path.abspath( os.path.join(currentdir, "lib-dynload", "lz4", "build") ) if not os.path.isdir(build_dir): build_dir = os.path.abspath( os.path.join(currentdir, "..", "lib-dynload", "lz4", "build") ) if not os.path.isdir(build_dir): build_dir = os.path.abspath( os.path.join(currentdir, "..", "..", "lib-dynload", "lz4", "build") ) dirs = os.listdir(build_dir) for d in dirs: if d.find("-%s.%s" % (p1, p2)) != -1 and d.find("lib.") != -1: sys.path.insert(0, os.path.join(build_dir, d) ) import importlib module = importlib.import_module("_lz4.block._block") compress = module.compress decompress = module.decompress sys.path.pop(0) break
import sys import os p1, p2 = sys.version_info[:2] curpath = os.path.abspath( sys.argv[0] ) if os.path.islink(curpath): curpath = os.readlink(curpath) currentdir = os.path.dirname( curpath ) build_dir = os.path.abspath( os.path.join(currentdir, "lib-dynload", "lz4", "build") ) if not os.path.isdir(build_dir): build_dir = os.path.abspath( os.path.join(currentdir, "..", "lib-dynload", "lz4", "build") ) if not os.path.isdir(build_dir): build_dir = os.path.abspath( os.path.join(currentdir, "..", "..", "lib-dynload", "lz4", "build") ) dirs = os.listdir(build_dir) for d in dirs: if d.find("-%s.%s" % (p1, p2)) != -1 and d.find("lib.") != -1: sys.path.insert(0, os.path.join(build_dir, d, "_lz4", "block") ) import importlib module = importlib.import_module("_block") compress = module.compress decompress = module.decompress sys.path.pop(0) break
Fix load of compiled lz4 module
Fix load of compiled lz4 module
Python
mit
sergey-dryabzhinsky/dedupsqlfs,sergey-dryabzhinsky/dedupsqlfs,sergey-dryabzhinsky/dedupsqlfs,sergey-dryabzhinsky/dedupsqlfs
920e2fbb7e99c17dbe8d5b71e9c9b26a718ca444
ideascube/search/apps.py
ideascube/search/apps.py
from django.apps import AppConfig from django.db.models.signals import pre_migrate, post_migrate from .utils import create_index_table, reindex_content def create_index(sender, **kwargs): if isinstance(sender, SearchConfig): create_index_table(force=True) def reindex(sender, **kwargs): if isinstance(sender, SearchConfig): reindex_content(force=False) class SearchConfig(AppConfig): name = 'ideascube.search' verbose_name = 'Search' def ready(self): pre_migrate.connect(create_index, sender=self) post_migrate.connect(reindex, sender=self)
from django.apps import AppConfig from django.db.models.signals import pre_migrate, post_migrate from .utils import create_index_table, reindex_content def create_index(sender, **kwargs): if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)): create_index_table(force=True) def reindex(sender, **kwargs): if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)): reindex_content(force=False) class SearchConfig(AppConfig): name = 'ideascube.search' verbose_name = 'Search' def ready(self): pre_migrate.connect(create_index, sender=self) post_migrate.connect(reindex, sender=self)
Make (pre|post)_migrate scripts for the index table only if working on 'transient'.
Make (pre|post)_migrate scripts for the index table only if working on 'transient'. Django run (pre|post)_migrate script once per database. As we have two databases, the create_index is launch twice with different kwargs['using'] ('default' and 'transient'). We should try to create the index table only when we are working on the transient database. Most of the time, this is not important and create a new index table twice is not important. However, if we run tests, the database are configured and migrate one after the other and the 'transient' database may be miss-configured at a time. By creating the table only at the right time, we ensure that everything is properly configured.
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
8545423373dee1f4b801375922b67bc2417cb426
ooni/resources/update.py
ooni/resources/update.py
import os from twisted.internet import reactor, defer, protocol from twisted.web.client import RedirectAgent, Agent from ooni.settings import config from ooni.resources import inputs, geoip agent = RedirectAgent(Agent(reactor)) class SaveToFile(protocol.Protocol): def __init__(self, finished, filesize, filename): self.finished = finished self.remaining = filesize self.outfile = open(filename, 'wb') def dataReceived(self, bytes): if self.remaining: display = bytes[:self.remaining] self.outfile.write(display) self.remaining -= len(display) else: self.outfile.close() def connectionLost(self, reason): self.outfile.close() self.finished.callback(None) @defer.inlineCallbacks def download_resource(resources): for filename, resource in resources.items(): print "Downloading %s" % filename filename = os.path.join(config.resources_directory, filename) response = yield agent.request("GET", resource['url']) finished = defer.Deferred() response.deliverBody(SaveToFile(finished, response.length, filename)) yield finished if resource['action'] is not None: yield defer.maybeDeferred(resource['action'], filename, *resource['action_args']) print "%s written." % filename def download_inputs(): return download_resource(inputs) def download_geoip(): return download_resource(geoip)
import os from twisted.internet import defer from twisted.web.client import downloadPage from ooni.settings import config from ooni.resources import inputs, geoip @defer.inlineCallbacks def download_resource(resources): for filename, resource in resources.items(): print "Downloading %s" % filename filename = os.path.join(config.resources_directory, filename) yield downloadPage(resource['url'], filename) if resource['action'] is not None: yield defer.maybeDeferred(resource['action'], filename, *resource['action_args']) print "%s written." % filename def download_inputs(): return download_resource(inputs) def download_geoip(): return download_resource(geoip)
Simplify the code for downloading resources.
Simplify the code for downloading resources. Use downloadPage instead of our own class.
Python
bsd-2-clause
0xPoly/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,juga0/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,kdmurray91/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe
360efe51bc45f189c235bed6b2b7bfdd4fd1bfbd
flask-restful/api.py
flask-restful/api.py
from flask import Flask, request from flask_restful import Resource, Api, reqparse from indra import reach from indra.statements import * import json app = Flask(__name__) api = Api(app) parser = reqparse.RequestParser() parser.add_argument('txt') parser.add_argument('json') class InputText(Resource): def post(self): args = parser.parse_args() txt = args['txt'] rp = reach.process_text(txt, offline=False) st = rp.statements json_statements = {} json_statements['statements'] = [] for s in st: s_json = s.to_json() json_statements['statements'].append(s_json) json_statements = json.dumps(json_statements) return json_statements, 201 api.add_resource(InputText, '/parse') class InputStmtJSON(Resource): def post(self): args = parser.parse_args() print(args) json_data = args['json'] json_dict = json.loads(json_data) st = [] for j in json_dict['statements']: s = Statement.from_json(j) print(s) st.append(s) return 201 api.add_resource(InputStmtJSON, '/load') if __name__ == '__main__': app.run(debug=True)
import json from bottle import route, run, request, post, default_app from indra import trips, reach, bel, biopax from indra.statements import * @route('/trips/process_text', method='POST') def trips_process_text(): body = json.load(request.body) text = body.get('text') tp = trips.process_text(text) if tp and tp.statements: stmts = json.dumps([json.loads(st.to_json()) for st in tp.statements]) res = {'statements': stmts} return res else: res = {'statements': []} return res @route('/reach/process_text', method='POST') def reach_process_text(): body = json.load(request.body) text = body.get('text') rp = reach.process_text(text) if rp and rp.statements: stmts = json.dumps([json.loads(st.to_json()) for st in rp.statements]) res = {'statements': stmts} return res else: res = {'statements': []} return res @route('/reach/process_pmc', method='POST') def reach_process_pmc(): body = json.load(request.body) pmcid = body.get('pmcid') rp = reach.process_pmc(pmcid) if rp and rp.statements: stmts = json.dumps([json.loads(st.to_json()) for st in rp.statements]) res = {'statements': stmts} return res else: res = {'statements': []} return res if __name__ == '__main__': app = default_app() run(app)
Reimplement using bottle and add 3 endpoints
Reimplement using bottle and add 3 endpoints
Python
bsd-2-clause
sorgerlab/indra,sorgerlab/indra,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,johnbachman/indra,johnbachman/indra,pvtodorov/indra,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra,bgyori/indra,johnbachman/belpy,bgyori/indra,sorgerlab/indra,pvtodorov/indra,sorgerlab/belpy,sorgerlab/belpy,johnbachman/indra
e78910c8b9ecf48f96a693dae3c15afa32a12da1
casexml/apps/phone/views.py
casexml/apps/phone/views.py
from django_digest.decorators import * from casexml.apps.phone import xml from casexml.apps.case.models import CommCareCase from casexml.apps.phone.restore import generate_restore_response from casexml.apps.phone.models import User from casexml.apps.case import const @httpdigest def restore(request): user = User.from_django_user(request.user) restore_id = request.GET.get('since') return generate_restore_response(user, restore_id) def xml_for_case(request, case_id, version="1.0"): """ Test view to get the xml for a particular case """ from django.http import HttpResponse case = CommCareCase.get(case_id) return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE, const.CASE_ACTION_UPDATE], version), mimetype="text/xml")
from django.http import HttpResponse from django_digest.decorators import * from casexml.apps.phone import xml from casexml.apps.case.models import CommCareCase from casexml.apps.phone.restore import generate_restore_response from casexml.apps.phone.models import User from casexml.apps.case import const @httpdigest def restore(request): user = User.from_django_user(request.user) restore_id = request.GET.get('since') return generate_restore_response(user, restore_id) def xml_for_case(request, case_id, version="1.0"): """ Test view to get the xml for a particular case """ case = CommCareCase.get(case_id) return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE, const.CASE_ACTION_UPDATE], version), mimetype="text/xml")
Revert "moving httpresponse to view"
Revert "moving httpresponse to view" This reverts commit a6f501bb9de6382e35372996851916adac067fa0.
Python
bsd-3-clause
SEL-Columbia/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,SEL-Columbia/commcare-hq
4aa6987d3048d6de36ddc07b63a02a3ddf3ab410
integration/integration.py
integration/integration.py
# Python Packages import random # External Packages import numpy as np def sin_theta_sum(theta): return np.sin(theta) def gen_random_value(count, rmin, rmax): value = 0 for i in range(count): value += np.random.uniform(rmin, rmax) # test_range(rmin, rmax, value) return value def run_monte_carlo(samples, function, func_coeff, func_vars): value = 0 for i in range(samples): if i % 10000 == 0: print(i) value += function(func_vars) value = value*func_coeff/samples return value def sin_monte_element(rmax): value = gen_random_value(8, 0, rmax) result = sin_theta_sum(value) return result def main(): rmax = np.pi/8 samples = 10000000 coefficient = 1000000 volume = np.power(np.pi/8, 8) func_coeff = coefficient*volume func_vars = rmax result = run_monte_carlo(samples, sin_monte_element, func_coeff, func_vars) print(result) def test_range(rmin, rmax, value): if (value <= rmin or value >= rmax): print(False) main()
# Python Packages import random # External Packages import numpy as np def sin_theta_sum(variables): theta = 0 for var in variables: theta += var return np.sin(theta) def gen_random_variables(count, rmin, rmax): variables = [] for i in range(count): variables.append(np.random.uniform(rmin, rmax)) # test_range(rmin, rmax, value) return variables def run_monte_carlo(samples, function, func_coeff, func_vars): value = 0 for i in range(samples): if i % 10000 == 0: print(i) value += function(func_vars) value = value*func_coeff/samples return value def sin_monte_element(rmax): value = gen_random_variables(8, 0, rmax) result = sin_theta_sum(value) return result def main(): rmax = np.pi/8 samples = 10000000 coefficient = 1000000 volume = np.power(rmax, 8) func_coeff = coefficient*volume func_vars = rmax result = run_monte_carlo(samples, sin_monte_element, func_coeff, func_vars) print(result) def test_range(rmin, rmax, value): if (value <= rmin or value >= rmax): print(False) main()
Adjust code to restore generality.
Adjust code to restore generality. Discussions suggest runtime is not catestrophically slow, so return generality to the code for sake of my sanity.
Python
mit
lemming52/white_knight
63f6e4d50116d5ca2bfc82c1c608e08040055b5e
subdue/core/__init__.py
subdue/core/__init__.py
__all__ = [ 'color', 'BANNER', 'DEFAULT_DRIVER_CODE' 'die', 'verbose', 'use_colors', 'set_color_policy', ] import sys as _sys from . import color as _color BANNER = """\ _ _ ___ _ _| |__ __| |_ _ ___ / __| | | | '_ \ / _` | | | |/ _ \\ \__ \ |_| | |_) | (_| | |_| | __/ |___/\__,_|_.__/ \__,_|\__,_|\___| """ DEFAULT_DRIVER_CODE = """\ #!/usr/bin/env python from subdue.sub import main main() """ verbose = False def set_color_policy(policy): _color.color_policy = policy def die(msg): _sys.stderr.write(msg) _sys.stderr.write("\n") _sys.stderr.flush() _sys.exit(1)
__all__ = [ 'BANNER', 'DEFAULT_DRIVER_CODE' 'die', 'verbose', 'set_color_policy', ] import sys as _sys from . import color as _color BANNER = """\ _ _ ___ _ _| |__ __| |_ _ ___ / __| | | | '_ \ / _` | | | |/ _ \\ \__ \ |_| | |_) | (_| | |_| | __/ |___/\__,_|_.__/ \__,_|\__,_|\___| """ DEFAULT_DRIVER_CODE = """\ #!/usr/bin/env python from subdue.sub import main main() """ verbose = False def set_color_policy(policy): _color.color_policy = policy def die(msg): _sys.stderr.write(msg) _sys.stderr.write("\n") _sys.stderr.flush() _sys.exit(1)
Remove old exports from subdue.core
Remove old exports from subdue.core
Python
mit
jdevera/subdue
459bf08b9fe4ae5a879a138bd2497abb23bf5910
modules/expansion/cve.py
modules/expansion/cve.py
import json import requests misperrors = {'error': 'Error'} mispattributes = {'input': ['vulnerability'], 'output': ['']} moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion hover module to expand information about CVE id.', 'module-type': ['hover']} moduleconfig = [] cveapi_url = 'https://cve.circl.lu/api/cve/' def handler(q=False): if q is False: return False print (q) request = json.loads(q) if not request.get('vulnerability'): misperrors['error'] = 'Vulnerability id missing' return misperrors r = requests.get(cveapi_url+request.get('vulnerability')) if r.status_code == 200: vulnerability = json.loads(r.text) else: misperrors['error'] = 'cve.circl.lu API not accessible' return misperrors['error'] return vulnerability def introspection(): return mispattributes def version(): moduleinfo['config'] = moduleconfig return moduleinfo
import json import requests misperrors = {'error': 'Error'} mispattributes = {'input': ['vulnerability'], 'output': ['text']} moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion hover module to expand information about CVE id.', 'module-type': ['hover']} moduleconfig = [] cveapi_url = 'https://cve.circl.lu/api/cve/' def handler(q=False): if q is False: return False print (q) request = json.loads(q) if not request.get('vulnerability'): misperrors['error'] = 'Vulnerability id missing' return misperrors r = requests.get(cveapi_url+request.get('vulnerability')) if r.status_code == 200: vulnerability = json.loads(r.text) if vulnerability.get('summary'): summary = vulnerability['summary'] else: misperrors['error'] = 'cve.circl.lu API not accessible' return misperrors['error'] r = {'results': [{'types': mispattributes['output'], 'values': summary}]} return r def introspection(): return mispattributes def version(): moduleinfo['config'] = moduleconfig return moduleinfo
Return a text attribute for an hover only module
Return a text attribute for an hover only module
Python
agpl-3.0
VirusTotal/misp-modules,MISP/misp-modules,MISP/misp-modules,amuehlem/misp-modules,MISP/misp-modules,Rafiot/misp-modules,Rafiot/misp-modules,amuehlem/misp-modules,Rafiot/misp-modules,amuehlem/misp-modules,VirusTotal/misp-modules,VirusTotal/misp-modules
43efd1f110daa8f2f16475e4e6edbdf18ff28286
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ben Edwards # Copyright (c) 2015 Ben Edwards # # License: MIT # """This module exports the PugLint plugin class.""" from SublimeLinter.lint import NodeLinter, util, highlight class PugLint(NodeLinter): """Provides an interface to pug-lint.""" cmd = 'pug-lint @ *' regex = r'^.+?:(?P<line>\d+)(:(?P<col>\d+) | )(?P<message>.+)' multiline = False tempfile_suffix = 'pug' error_stream = util.STREAM_BOTH defaults = { 'selector': 'text.pug, source.pypug, text.jade', '--reporter=': 'inline' } default_type = highlight.WARNING
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ben Edwards # Copyright (c) 2015 Ben Edwards # # License: MIT # """This module exports the PugLint plugin class.""" from SublimeLinter.lint import NodeLinter, WARNING class PugLint(NodeLinter): """Provides an interface to pug-lint.""" cmd = 'pug-lint ${temp_file} ${args}' regex = r'^.+?:(?P<line>\d+)(:(?P<col>\d+) | )(?P<message>.+)' multiline = False tempfile_suffix = 'pug' error_stream = util.STREAM_BOTH defaults = { 'selector': 'text.pug, source.pypug, text.jade', '--reporter=': 'inline' } default_type = WARNING
Update to catch up with Sublime-Linter API
Update to catch up with Sublime-Linter API
Python
mit
benedfit/SublimeLinter-contrib-pug-lint,benedfit/SublimeLinter-contrib-jade-lint
03380a1042443465d6f1d74afb5fd120dbc3379b
manage.py
manage.py
#!/usr/bin/env python3 from manager import Manager manager = Manager() @manager.command def build(threads=1): print("Starting a build with %d threads ..." % threads) @manager.command def clean(): pass if __name__ == '__main__': manager.main()
#!/usr/bin/env python3 from manager import Manager from multiprocessing import Pool manager = Manager() def func(period): from time import sleep sleep(period) @manager.command def build(threads=1): pool = Pool(threads) print("Starting a build with %d threads ..." % threads) pool.map(func, [1, 1, 1, 1, 1]) @manager.command def clean(): pass if __name__ == '__main__': manager.main()
Add parallelizing code to build
Add parallelizing code to build
Python
mit
tanayseven/personal_website,tanayseven/personal_website,tanayseven/personal_website,tanayseven/personal_website
1cbe91b1f4e4ef126dfce3ecd56016f33e7ad836
manage.py
manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": if "--settings" not in sys.argv: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pinry.settings.development") from django.core.management import execute_from_command_line if 'test' in sys.argv: from django.conf import settings settings.IS_TEST = True execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys if __name__ == "__main__": if not any(arg.startswith("--settings") for arg in sys.argv): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pinry.settings.development") from django.core.management import execute_from_command_line if 'test' in sys.argv: from django.conf import settings settings.IS_TEST = True execute_from_command_line(sys.argv)
Fix django development settingns again
Fix: Fix django development settingns again
Python
bsd-2-clause
pinry/pinry,lapo-luchini/pinry,lapo-luchini/pinry,lapo-luchini/pinry,pinry/pinry,pinry/pinry,lapo-luchini/pinry,pinry/pinry
a5003b6f45d262923a1c00bd9a9c1addb3854178
lapostesdk/apis/apibase.py
lapostesdk/apis/apibase.py
import requests from importlib import import_module class ApiBase(object): def __init__(self, api_key, product, version='v1', entity=None): self.product = product self.version = version self.entity = entity self.api_url = 'https://api.laposte.fr/%(product)s/%(version)s/' % { 'product': self.product, 'version': self.version} self.headers = {'X-Okapi-Key': api_key} def get(self, resource, params={}): response = self._get(resource, params) if self.entity is None: return response module = import_module('lapostesdk.entities') obj = getattr(module, self.entity) instance = obj() instance.hydrate(response) return instance def _get(self, resource, params={}): r = requests.get(self.api_url + resource, params=params, headers=self.headers) return r.json()
import requests from importlib import import_module class ApiBase(object): def __init__(self, api_key, product, version='v1', entity=None): self.product = product self.version = version self.entity = entity self.api_url = 'https://api.laposte.fr/%(product)s/%(version)s/' % { 'product': self.product, 'version': self.version} self.headers = {'X-Okapi-Key': api_key} def get(self, resource, params={}): response = self._get(resource, params) if self.entity is None: return response return self.create_object(response, self.entity) def _get(self, resource, params={}): r = requests.get(self.api_url + resource, params=params, headers=self.headers) return r.json() def create_object(self, response, entity): module = import_module('lapostesdk.entities') obj = getattr(module, self.entity) instance = obj() instance.hydrate(response) return instance
Move object creation outside of get method
Move object creation outside of get method
Python
mit
geelweb/laposte-python-sdk
c0b19b1ed8655b540ba8431bb1224056ed5890df
pyscraper/patchfilter.py
pyscraper/patchfilter.py
#! /usr/bin/python2.3 # vim:sw=8:ts=8:et:nowrap import os import shutil def ApplyPatches(filein, fileout): # Generate short name such as wrans/answers2003-03-31.html (rest, name) = os.path.split(filein) (rest, dir) = os.path.split(rest) fileshort = os.path.join(dir, name) # Look for a patch file from our collection (which is # in the pyscraper/patches folder in Public Whip CVS) patchfile = os.path.join("patches", fileshort + ".patch") if not os.path.isfile(patchfile): return False while True: # Apply the patch shutil.copyfile(filein, fileout) # delete temporary file that might have been created by a previous patch failure filoutorg = fileout + ".orig" if os.path.isfile(filoutorg): os.remove(filoutorg) status = os.system("patch --quiet %s <%s" % (fileout, patchfile)) if status == 0: return True print "Error running 'patch' on file %s, blanking it out" % fileshort os.rename(patchfile, patchfile + ".old~") blankfile = open(patchfile, "w") blankfile.close()
#! /usr/bin/python2.3 # vim:sw=8:ts=8:et:nowrap import os import shutil def ApplyPatches(filein, fileout): # Generate short name such as wrans/answers2003-03-31.html (rest, name) = os.path.split(filein) (rest, dir) = os.path.split(rest) fileshort = os.path.join(dir, name) # Look for a patch file from our collection (which is # in the pyscraper/patches folder in Public Whip CVS) patchfile = os.path.join("patches", fileshort + ".patch") if not os.path.isfile(patchfile): return False while True: # Apply the patch shutil.copyfile(filein, fileout) # delete temporary file that might have been created by a previous patch failure filoutorg = fileout + ".orig" if os.path.isfile(filoutorg): os.remove(filoutorg) status = os.system("patch --quiet %s <%s" % (fileout, patchfile)) if status == 0: return True raise Exception, "Error running 'patch' on file %s" % fileshort #print "blanking out %s" % fileshort #os.rename(patchfile, patchfile + ".old~") #blankfile = open(patchfile, "w") #blankfile.close()
Remove code which blanks patch files
Remove code which blanks patch files
Python
agpl-3.0
openaustralia/publicwhip-matthew,openaustralia/publicwhip-matthew,openaustralia/publicwhip-matthew,openaustralia/publicwhip-matthew,openaustralia/publicwhip-matthew,openaustralia/publicwhip-matthew,openaustralia/publicwhip-matthew,openaustralia/publicwhip-matthew,openaustralia/publicwhip-matthew
1b385ce127f0a1802b0effa0054b44f58b3317b0
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/accounts/urls.py
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/accounts/urls.py
from django.contrib.auth import views from django.urls import path, re_path from accounts.forms import LoginForm, PasswordResetForm, SetPasswordForm urlpatterns = [ path( "login/", views.LoginView.as_view( template_name="accounts/login.html", authentication_form=LoginForm ), name="login", ), path("logout/", views.LogoutView.as_view(), name="logout"), # Password reset path( "account/password_reset/", views.PasswordResetView.as_view(form_class=PasswordResetForm), name="password_reset", ), path( "account/password_reset/done/", views.PasswordResetDoneView.as_view(), name="password_reset_done", ), re_path( r"^account/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$", views.PasswordResetConfirmView.as_view(form_class=SetPasswordForm), name="password_reset_confirm", ), path( "account/reset/done/", views.PasswordResetCompleteView.as_view(), name="password_reset_complete", ), ]
from django.contrib.auth import views from django.urls import path from accounts.forms import LoginForm, PasswordResetForm, SetPasswordForm urlpatterns = [ path( "login/", views.LoginView.as_view( template_name="accounts/login.html", authentication_form=LoginForm ), name="login", ), path("logout/", views.LogoutView.as_view(), name="logout"), # Password reset path( "account/password_reset/", views.PasswordResetView.as_view(form_class=PasswordResetForm), name="password_reset", ), path( "account/password_reset/done/", views.PasswordResetDoneView.as_view(), name="password_reset_done", ), path( r"account/reset/<uidb64>/<token>/", views.PasswordResetConfirmView.as_view(form_class=SetPasswordForm), name="password_reset_confirm", ), path( "account/reset/done/", views.PasswordResetCompleteView.as_view(), name="password_reset_complete", ), ]
Fix webapp password reset link
DEVOPS-42: Fix webapp password reset link
Python
isc
thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template
9b10f600b5611380f72fe2aeacfe2ee6f02e4e3a
kicad_footprint_load.py
kicad_footprint_load.py
import pcbnew import sys import os pretties = [] for dirname, dirnames, filenames in os.walk(sys.argv[1]): # don't go into any .git directories. if '.git' in dirnames: dirnames.remove('.git') for filename in filenames: if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] == '.kicad_mod'): pretties.append(os.path.realpath(dirname)) break src_plugin = pcbnew.IO_MGR.PluginFind(1) for libpath in pretties: #Ignore paths with unicode as KiCad can't deal with them in enumerate list_of_footprints = src_plugin.FootprintEnumerate(libpath, False)
import pcbnew import sys import os pretties = [] for dirname, dirnames, filenames in os.walk(sys.argv[1]): # don't go into any .git directories. if '.git' in dirnames: dirnames.remove('.git') for filename in filenames: if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] == '.kicad_mod'): pretties.append(os.path.realpath(dirname)) break src_plugin = pcbnew.IO_MGR.PluginFind(1) for libpath in pretties: list_of_footprints = src_plugin.FootprintEnumerate(libpath)
Switch to old invocation of FootprintEnumerate
Switch to old invocation of FootprintEnumerate
Python
mit
monostable/haskell-kicad-data,monostable/haskell-kicad-data,kasbah/haskell-kicad-data
eafd43442cc697bf2278f6df67c1577cc8f5bf56
support/jenkins/buildAllModuleCombination.py
support/jenkins/buildAllModuleCombination.py
import os from subprocess import call from itertools import product, repeat # To be called from the OpenSpace main folder modules = os.listdir("modules") modules.remove("base") # Get 2**len(modules) combinatorical combinations of ON/OFF settings = [] for args in product(*repeat(("ON", "OFF"), len(modules))): settings.append(args) # Create all commands cmds = [] for s in settings: cmd = ["cmake", "-DGHOUL_USE_DEVIL=NO", "-DOPENSPACE_MODULE_BASE=ON"] for m,s in zip(modules, s): cmd.append("-DOPENSPACE_MODULE_" + m.upper() + "=" + s) cmds.append(cmd) # Build cmake and compile for c in cmds: call(cmd) call(["make", "clean"]) call(["make", "-j4"])
import os from subprocess import call from itertools import product, repeat # To be called from the OpenSpace main folder modules = os.listdir("modules") modules.remove("base") # Get 2**len(modules) combinatorical combinations of ON/OFF settings = [] for args in product(*repeat(("ON", "OFF"), len(modules))): settings.append(args) # Create all commands cmds = [] for s in settings: cmd = ["cmake", "-DGHOUL_USE_DEVIL=NO", "-DOPENSPACE_MODULE_BASE=ON"] for m,s in zip(modules, s): cmd.append("-DOPENSPACE_MODULE_" + m.upper() + "=" + s) cmds.append(cmd) # Build cmake and compile for c in cmds: print "CMake:" , cmd call(cmd) call(["make", "clean"]) call(["make", "-j4"])
Print progress of combinatorical build
Print progress of combinatorical build
Python
mit
OpenSpace/OpenSpace,OpenSpace/OpenSpace,OpenSpace/OpenSpace,OpenSpace/OpenSpace
f5fd283497afb5030632108ce692e8acde526188
datalake_ingester/reporter.py
datalake_ingester/reporter.py
import boto.sns import simplejson as json import logging from memoized_property import memoized_property import os from datalake_common.errors import InsufficientConfiguration class SNSReporter(object): '''report ingestion events to SNS''' def __init__(self, report_key): self.report_key = report_key self.logger = logging.getLogger(self._log_name) @classmethod def from_config(cls): report_key = os.environ.get('DATALAKE_REPORT_KEY') if report_key is None: raise InsufficientConfiguration('Please configure a report_key') return cls(report_key) @property def _log_name(self): return self.report_key.split(':')[-1] @memoized_property def _connection(self): region = os.environ.get('AWS_REGION') if region: return boto.sns.connect_to_region(region) else: return boto.connect_sns() def report(self, ingestion_report): message = json.dumps(ingestion_report) self.logger.info('REPORTING: %s', message) self._connection.publish(topic=self.report_key, message=message)
import boto.sns import simplejson as json import logging from memoized_property import memoized_property import os class SNSReporter(object): '''report ingestion events to SNS''' def __init__(self, report_key): self.report_key = report_key self.logger = logging.getLogger(self._log_name) @classmethod def from_config(cls): report_key = os.environ.get('DATALAKE_REPORT_KEY') if report_key is None: return None return cls(report_key) @property def _log_name(self): return self.report_key.split(':')[-1] @memoized_property def _connection(self): region = os.environ.get('AWS_REGION') if region: return boto.sns.connect_to_region(region) else: return boto.connect_sns() def report(self, ingestion_report): message = json.dumps(ingestion_report) self.logger.info('REPORTING: %s', message) self._connection.publish(topic=self.report_key, message=message)
Allow the ingester to work without a report key
Allow the ingester to work without a report key
Python
apache-2.0
planetlabs/datalake-ingester,planetlabs/atl,planetlabs/datalake,planetlabs/datalake,planetlabs/datalake,planetlabs/datalake
2eab4c48962da52766c3d6f8051ad87aa505a90c
bonfiremanager/models.py
bonfiremanager/models.py
from django.db import models class Event(models.Model): name = models.CharField(max_length=1024, unique=True) slug = models.SlugField(max_length=1024) def __str__(self): return self.name class TimeSlot(models.Model): event = models.ForeignKey(Event) bookable = models.BooleanField(default=True) end = models.DateTimeField() name = models.CharField(max_length=1024) start = models.DateTimeField() def __str__(self): return "{0} ({1})".format(self.name, self.event) class Room(models.Model): event = models.ForeignKey(Event) directions = models.TextField() name = models.CharField(max_length=1024) def __str__(self): return "{0} ({1})".format(self.name, self.event) class Talk(models.Model): room = models.ForeignKey(Room, null=True, blank=True) timeslot = models.ForeignKey(TimeSlot, null=True, blank=True) description = models.TextField() slug = models.SlugField(max_length=1024) title = models.CharField(max_length=1024, unique=True) def __str__(self): return "{0} in {1}".format(self.title, self.room)
from django.db import models class Event(models.Model): name = models.CharField(max_length=1024, unique=True) slug = models.SlugField(max_length=1024) def __str__(self): return self.name class TimeSlot(models.Model): event = models.ForeignKey(Event) bookable = models.BooleanField(default=True) end = models.DateTimeField() name = models.CharField(max_length=1024) start = models.DateTimeField() def __str__(self): return "{0} ({1})".format(self.name, self.event) class Room(models.Model): event = models.ForeignKey(Event) directions = models.TextField() name = models.CharField(max_length=1024) def __str__(self): return "{0} ({1})".format(self.name, self.event) class Talk(models.Model): room = models.ForeignKey(Room, null=True, blank=True) timeslot = models.ForeignKey(TimeSlot, null=True, blank=True) description = models.TextField() slug = models.SlugField(max_length=1024) title = models.CharField(max_length=1024, unique=True) def __str__(self): return "{0} in {1} at {2}".format(self.title, self.room, self.timeslot)
Update Talk model __str__ to include time
Update Talk model __str__ to include time
Python
agpl-3.0
yamatt/bonfiremanager
f45fc8854647754b24df5f9601920368cd2d3c49
tests/chainerx_tests/unit_tests/test_cuda.py
tests/chainerx_tests/unit_tests/test_cuda.py
import pytest from chainerx import _cuda try: import cupy except Exception: cupy = None class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook): name = 'CupyTestMemoryHook' def __init__(self): self.used_bytes = 0 self.acquired_bytes = 0 def alloc_preprocess(self, **kwargs): self.acquired_bytes += kwargs['mem_size'] def malloc_preprocess(self, **kwargs): self.used_bytes += kwargs['mem_size'] @pytest.mark.cuda() def test_cupy_share_allocator(): with CupyTestMemoryHook() as hook: cp_allocated = cupy.arange(10) used_bytes = hook.used_bytes acquired_bytes = hook.acquired_bytes # Create a new array after changing the allocator to the memory pool # of ChainerX and make sure that no additional memory has been # allocated by CuPy. _cuda.cupy_share_allocator() chx_allocated = cupy.arange(10) cupy.testing.assert_array_equal(cp_allocated, chx_allocated) assert used_bytes == hook.used_bytes assert acquired_bytes == hook.acquired_bytes
import pytest from chainerx import _cuda try: import cupy except Exception: cupy = None class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook): name = 'CupyTestMemoryHook' def __init__(self): self.used_bytes = 0 self.acquired_bytes = 0 def alloc_preprocess(self, **kwargs): self.acquired_bytes += kwargs['mem_size'] def malloc_preprocess(self, **kwargs): self.used_bytes += kwargs['mem_size'] @pytest.mark.cuda() def test_cupy_share_allocator(): with CupyTestMemoryHook() as hook: cp_allocated = cupy.arange(10) used_bytes = hook.used_bytes acquired_bytes = hook.acquired_bytes assert used_bytes > 0 assert acquired_bytes > 0 # Create a new array after changing the allocator to the memory pool # of ChainerX and make sure that no additional memory has been # allocated by CuPy. _cuda.cupy_share_allocator() chx_allocated = cupy.arange(10) cupy.testing.assert_array_equal(cp_allocated, chx_allocated) assert used_bytes == hook.used_bytes assert acquired_bytes == hook.acquired_bytes
Add safety checks in test
Add safety checks in test
Python
mit
wkentaro/chainer,hvy/chainer,niboshi/chainer,okuta/chainer,chainer/chainer,wkentaro/chainer,chainer/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,hvy/chainer,pfnet/chainer,hvy/chainer,chainer/chainer,keisuke-umezawa/chainer,okuta/chainer,chainer/chainer,tkerola/chainer,keisuke-umezawa/chainer,wkentaro/chainer,niboshi/chainer,hvy/chainer,okuta/chainer,niboshi/chainer,niboshi/chainer,okuta/chainer,wkentaro/chainer
429f38497da0fd520e5bc5bd82e6d4ed5a405521
real_estate_agency/real_estate_agency/views.py
real_estate_agency/real_estate_agency/views.py
from django.shortcuts import render, render_to_response from django.template import RequestContext from new_buildings.models import Builder, ResidentalComplex, NewApartment from new_buildings.forms import SearchForm from feedback.models import Feedback def corporation_benefit_plan(request): return render(request, 'corporation_benefit_plan.html') def index(request): # Only 2 requests to DB feedbacks = Feedback.objects.all()[:4].select_related().prefetch_related('social_media_links') # Only 2 requests to DB residental_complexes = ResidentalComplex.objects.filter( is_popular=True).prefetch_related('type_of_complex') context = { 'feedbacks': feedbacks, 'form': SearchForm, 'residental_complexes': residental_complexes, } return render(request, 'index.html', context, ) def privacy_policy(request): return render(request, 'privacy_policy.html') def thanks(request): return render(request, 'thanks.html')
from django.shortcuts import render from new_buildings.models import ResidentalComplex from new_buildings.forms import NewBuildingsSearchForm from feedback.models import Feedback def corporation_benefit_plan(request): return render(request, 'corporation_benefit_plan.html') def index(request): # Only 2 requests to DB feedbacks = Feedback.objects.all( )[:4].select_related().prefetch_related('social_media_links') # Only 2 requests to DB residental_complexes = ResidentalComplex.objects.filter( is_popular=True).prefetch_related('type_of_complex') context = { 'feedbacks': feedbacks, 'form': NewBuildingsSearchForm, 'residental_complexes': residental_complexes, } return render(request, 'index.html', context, ) def privacy_policy(request): return render(request, 'privacy_policy.html') def thanks(request): return render(request, 'thanks.html')
Use NewBuildingsSearchForm as main page search form.
Use NewBuildingsSearchForm as main page search form. intead of non-complete SearchForm.
Python
mit
Dybov/real_estate_agency,Dybov/real_estate_agency,Dybov/real_estate_agency
667f92e8686fd1eb004a7c608acb45c70a9dd2f0
lib/rapidsms/message.py
lib/rapidsms/message.py
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text # initialize some empty attributes self.received = None self.sent = None self.responses = [] def __unicode__(self): return self.text @property def backend(self): # backend is read-only, since it's an # immutable property of this object return self._backend def send(self): """Send this message via self.backend, returning True if the message was sent successfully.""" return self.backend.router.outgoing(self) def flush_responses (self): for response in self.responses: response.send() def respond(self, text): """Send the given text back to the original caller of this message on the same route that it came in on""" if self.caller: response = copy.copy(self) response.text = text self.responses.append(response) return True else: return False
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text self.responses = [] def __unicode__(self): return self.text @property def backend(self): # backend is read-only, since it's an # immutable property of this object return self._backend def send(self): """Send this message via self.backend, returning True if the message was sent successfully.""" return self.backend.router.outgoing(self) def flush_responses (self): for response in self.responses: response.send() self.responses.remove(response) def respond(self, text): """Send the given text back to the original caller of this message on the same route that it came in on""" if self.caller: response = copy.copy(self) response.text = text self.responses.append(response) return True else: return False
Remove unused attributes; also, empty responses after it's flushed.
Remove unused attributes; also, empty responses after it's flushed.
Python
bsd-3-clause
lsgunth/rapidsms,rapidsms/rapidsms-core-dev,dimagi/rapidsms-core-dev,ken-muturi/rapidsms,ehealthafrica-ci/rapidsms,catalpainternational/rapidsms,eHealthAfrica/rapidsms,dimagi/rapidsms-core-dev,caktus/rapidsms,catalpainternational/rapidsms,rapidsms/rapidsms-core-dev,lsgunth/rapidsms,ehealthafrica-ci/rapidsms,peterayeni/rapidsms,caktus/rapidsms,catalpainternational/rapidsms,unicefuganda/edtrac,peterayeni/rapidsms,peterayeni/rapidsms,ehealthafrica-ci/rapidsms,unicefuganda/edtrac,ken-muturi/rapidsms,dimagi/rapidsms,caktus/rapidsms,peterayeni/rapidsms,lsgunth/rapidsms,eHealthAfrica/rapidsms,dimagi/rapidsms,eHealthAfrica/rapidsms,ken-muturi/rapidsms,unicefuganda/edtrac,lsgunth/rapidsms,catalpainternational/rapidsms
fe317230b6d2636b8a736c63be7769dd82663914
libraries/SwitchManager.py
libraries/SwitchManager.py
class SwitchManager(object): def extract_all_nodes(self, content): return [e['node'] for e in content['nodeProperties']] def extract_all_properties(self, content): pass
""" Library for the robot based system test tool of the OpenDaylight project. Authors: Baohua Yang@IBM, Denghui Huang@IBM Updated: 2013-11-10 """ class SwitchManager(object): def extract_all_nodes(self, content): """ Return all nodes. """ if isinstance(content,dict) or not content.has_key('nodeProperties'): return None else: return [e.get('node') for e in content['nodeProperties']] def extract_all_properties(self, content): pass
Add input check when getting all nodes.
Add input check when getting all nodes.
Python
epl-1.0
yeasy/robot_tool
99177cdc64bdec740557007800b610bff07ce46a
shivyc.py
shivyc.py
#!/usr/bin/env python3 """Main executable for ShivyC compiler For usage, run "./shivyc.py --help". """ import argparse def get_arguments(): """Set up the argument parser and return an object storing the argument values. return - An object storing argument values, as returned by argparse.parse_args() """ parser = argparse.ArgumentParser(description="Compile C files.") # The file name of the C file to compile. The file name gets saved to the # file_name attribute of the returned object, but this parameter appears as # "filename" (no underscore) on the command line. parser.add_argument("file_name", metavar="filename") return parser.parse_args() def compile_code(source: str) -> str: """Compile the provided source code into assembly. source - The C source code to compile. return - The asm output """ return source def main(): """Load the input files, and dispatch to the compile function for the main processing. """ arguments = get_arguments() try: c_file = open(arguments.file_name) except IOError: print("shivyc: error: no such file or directory: '{}'" .format(arguments.file_name)) else: compile_code(c_file.read()) c_file.close() if __name__ == "__main__": main()
#!/usr/bin/env python3 """Main executable for ShivyC compiler For usage, run "./shivyc.py --help". """ import argparse def get_arguments(): """Set up the argument parser and return an object storing the argument values. return - An object storing argument values, as returned by argparse.parse_args() """ parser = argparse.ArgumentParser(description="Compile C files.") # The file name of the C file to compile. The file name gets saved to the # file_name attribute of the returned object, but this parameter appears as # "filename" (no underscore) on the command line. parser.add_argument("file_name", metavar="filename") return parser.parse_args() def compile_code(source: str) -> str: """Compile the provided source code into assembly. source - The C source code to compile. return - The asm output """ return source def main(): """Load the input files and dispatch to the compile function for the main processing. The main function handles interfacing with the user, like reading the command line arguments, printing errors, and generating output files. The compilation logic is in the compile_code function to facilitate testing. """ arguments = get_arguments() try: c_file = open(arguments.file_name) except IOError: print("shivyc: error: no such file or directory: '{}'" .format(arguments.file_name)) else: compile_code(c_file.read()) c_file.close() if __name__ == "__main__": main()
Improve commenting on main function
Improve commenting on main function
Python
mit
ShivamSarodia/ShivyC,ShivamSarodia/ShivyC,ShivamSarodia/ShivyC
a34c9628c3f383e7b6f5eb521a9493f2b51d8811
plata/reporting/views.py
plata/reporting/views.py
from decimal import Decimal import StringIO from django.contrib.admin.views.decorators import staff_member_required from django.http import HttpResponse from django.shortcuts import get_object_or_404 from pdfdocument.utils import pdf_response import plata import plata.reporting.product import plata.reporting.order @staff_member_required def product_xls(request): output = StringIO.StringIO() workbook = plata.reporting.product.product_xls() workbook.save(output) response = HttpResponse(output.getvalue(), mimetype='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=products.xls' return response @staff_member_required def order_pdf(request, order_id): order = get_object_or_404(plata.shop_instance().order_model, pk=order_id) order.shipping_cost = 8 / Decimal('1.076') order.shipping_discount = 0 order.recalculate_total(save=False) pdf, response = pdf_response('order-%09d' % order.id) plata.reporting.order.order_pdf(pdf, order) return response
from decimal import Decimal import StringIO from django.contrib.admin.views.decorators import staff_member_required from django.http import HttpResponse from django.shortcuts import get_object_or_404 from pdfdocument.utils import pdf_response import plata import plata.reporting.product import plata.reporting.order @staff_member_required def product_xls(request): output = StringIO.StringIO() workbook = plata.reporting.product.product_xls() workbook.save(output) response = HttpResponse(output.getvalue(), mimetype='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=products.xls' return response @staff_member_required def order_pdf(request, order_id): order = get_object_or_404(plata.shop_instance().order_model, pk=order_id) pdf, response = pdf_response('order-%09d' % order.id) plata.reporting.order.order_pdf(pdf, order) return response
Remove hardcoded shipping modification in order PDF view
Remove hardcoded shipping modification in order PDF view
Python
bsd-3-clause
stefanklug/plata,armicron/plata,armicron/plata,allink/plata,armicron/plata
78066748ef61554acd05e8776161b0ac7eb654cc
bootstrap/hooks.py
bootstrap/hooks.py
# coding: utf-8 from os.path import join, dirname, pardir, abspath import subprocess BOOTSTRAP = abspath(dirname(__file__)) ROOT = abspath(join(BOOTSTRAP, pardir)) # Path where venv will be created. It's imported by bootstrapX.Y.py VIRTUALENV = abspath(join(BOOTSTRAP, pardir)) ACTIVATE = join(VIRTUALENV, 'bin', 'activate_this.py') WITH_VENV = join(BOOTSTRAP, 'with_venv.sh') def with_venv(*args): """ Runs the given command inside virtualenv. """ cmd = list(args) cmd.insert(0, WITH_VENV) return subprocess.call(cmd) def after_install(options, home_dir): with_venv('pip', 'install', '-r', join(ROOT, 'requirements.txt')) print "Done! Activate your virtualenv: source bin/activate"
# coding: utf-8 from os.path import join, dirname, pardir, abspath from shutil import copy import subprocess BOOTSTRAP = abspath(dirname(__file__)) ROOT = abspath(join(BOOTSTRAP, pardir)) # Path where venv will be created. It's imported by bootstrapX.Y.py VIRTUALENV = abspath(join(BOOTSTRAP, pardir)) ACTIVATE = join(VIRTUALENV, 'bin', 'activate_this.py') WITH_VENV = join(BOOTSTRAP, 'with_venv.sh') def with_venv(*args): """ Runs the given command inside virtualenv. """ cmd = list(args) cmd.insert(0, WITH_VENV) return subprocess.call(cmd) def after_install(options, home_dir): copy(join(BOOTSTRAP, 'postactivate'), VIRTUALENV) with_venv('pip', 'install', '-r', join(ROOT, 'requirements.txt')) print "Done! Activate your virtualenv: source bin/activate"
Copy postactivate file to VIRTUALENV directory.
Copy postactivate file to VIRTUALENV directory.
Python
mit
henriquebastos/virtualenv-bootstrap,henriquebastos/virtualenv-bootstrap
3d3853d15e8a497bd104ae816498509cf8143662
number_to_words.py
number_to_words.py
class NumberToWords(object): """ Class for converting positive integer values to a textual representation of the submitted number for value of 0 up to 999999999. """ MAX = 999999999 SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] LARGE_NUMBERS = ['', 'thousand', 'million'] def convert(self, number): """ Take an integer and return it converted to a textual representation. Args: number (int): The number to be converted. Returns: sentence (string): The textual representation of `number`. """
class NumberToWords(object): """ Class for converting positive integer values to a textual representation of the submitted number for value of 0 up to 999999999. """ MAX = 999999999 SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] LARGE_NUMBERS = ['', 'thousand', 'million'] EXCEPTION_STRING = "This method expects positive integer values between " \ + "0 and {0}".format(MAX) def convert(self, number): """ Take an integer and return it converted to a textual representation. Args: number (int): The number to be converted. Returns: sentence (string): The textual representation of `number`. Raises: ValueError: If `number` is not a positive integer or is greater than `MAX`. """ if not isinstance(number, (int, long)): raise ValueError(self.EXCEPTION_STRING)
Add check to convert() so that only integers are acceptable input
Add check to convert() so that only integers are acceptable input - Using python 2.7 so check for both `int` and `long` - Update function definition to document expected exception conditions and exception type.
Python
mit
ianfieldhouse/number_to_words
92b7f334907bdd4bce3593eb9faee0dc0ae3ef8f
testing/test_get_new.py
testing/test_get_new.py
from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher from .pytest_skipif import needinternet from .pytest_makevers import fixture_update_dir import os @needinternet def test_check_vers_update(fixture_update_dir): package=fixture_update_dir("0.0.1") launch = Launcher('',r'http://rlee287.github.io/pyautoupdate/testing/') launch._get_new() with open(os.path.abspath("downloads/blah.py"), "r") as file_code: file_text=file_code.read() assert "new version" in file_text
from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher from .pytest_skipif import needinternet from .pytest_makevers import fixture_update_dir import pytest import os @pytest.mark.trylast @needinternet def test_check_vers_update(fixture_update_dir): package=fixture_update_dir("0.0.1") launch = Launcher('',r'http://rlee287.github.io/pyautoupdate/testing/') launch._get_new() with open(os.path.abspath("downloads/blah.py"), "r") as file_code: file_text=file_code.read() assert "new version" in file_text
Mark get new test as needing to be last
Mark get new test as needing to be last
Python
lgpl-2.1
rlee287/pyautoupdate,rlee287/pyautoupdate
7b1a0022b41dbf17de352e4686458e5250b28e49
quantityfield/widgets.py
quantityfield/widgets.py
import re from django.forms.widgets import MultiWidget, Select, NumberInput from . import ureg class QuantityWidget(MultiWidget): def get_choices(self, allowed_types=None): allowed_types = allowed_types or dir(ureg) return [(x, x) for x in allowed_types] def __init__(self, attrs=None, base_units=None, allowed_types=None): choices = self.get_choices(allowed_types) self.base_units = base_units attrs = attrs or {} attrs.setdefault('step', 'any') widgets = ( NumberInput(attrs=attrs), Select(attrs=attrs, choices=choices) ) super(QuantityWidget, self).__init__(widgets, attrs) def decompress(self, value): non_decimal = re.compile(r'[^\d.]+') if value: number_value = non_decimal.sub('', str(value)) return [number_value, self.base_units] return [None, self.base_units]
import re from django.forms.widgets import MultiWidget, Select, NumberInput from . import ureg class QuantityWidget(MultiWidget): def get_choices(self, allowed_types=None): allowed_types = allowed_types or dir(ureg) return [(x, x) for x in allowed_types] def __init__(self, attrs=None, base_units=None, allowed_types=None): choices = self.get_choices(allowed_types) self.base_units = base_units attrs = attrs or {} attrs.setdefault('step', 'any') widgets = ( NumberInput(attrs=attrs), Select(attrs=attrs, choices=choices) ) super(QuantityWidget, self).__init__(widgets, attrs) def decompress(self, value): non_decimal = re.compile(r'[^\d.]+') if value: number_value = non_decimal.sub('', str(value)) return [number_value, self.base_units] return [None, self.base_units]
Fix indentation error from conversion to spaces
Fix indentation error from conversion to spaces
Python
mit
bharling/django-pint,bharling/django-pint
9ced61716167505875d3938ae01c08b61acc9392
randterrainpy/terrain.py
randterrainpy/terrain.py
"""This module is for the Terrain class, used for storing randomly generated terrain.""" class Terrain(object): """Container for a randomly generated area of terrain. Attributes: width (int): Width of generated terrain. length (int): Length of generated terrain. height_map (list): Map of heights of terrain. Values range from 0 to 1. """ def __init__(self, width, length): """Initializer for Terrain. Args: width (int): Width of terrain. length (int): Height of terrain. """ self.width = width self.length = length self.height_map = [[0 for _ in self.width]] * self.length def __getitem__(self, item): """Get an item at x-y coordinates. Args: item (tuple): 2-tuple of x and y coordinates. Returns: float: Height of terrain at coordinates, between 0 and 1. """ return self.height_map[item[1]][item[0]] def __setitem__(self, key, value): """Set the height of an item. Args: key (tuple): 2-tuple of x and y coordinates. value (float): New height of map at x and y coordinates, between 0 and 1. """ self.height_map[key[1]][key[0]] = value
"""This module is for the Terrain class, used for storing randomly generated terrain.""" class Terrain(object): """Container for a randomly generated area of terrain. Attributes: width (int): Width of generated terrain. length (int): Length of generated terrain. height_map (list): Map of heights of terrain. Values range from 0 to 1. """ def __init__(self, width, length): """Initializer for Terrain. Args: width (int): Width of terrain. length (int): Height of terrain. """ self.width = width self.length = length self.height_map = [[0 for _ in self.width]] * self.length def __getitem__(self, item): """Get an item at x-y coordinates. Args: item (tuple): 2-tuple of x and y coordinates. Returns: float: Height of terrain at coordinates, between 0 and 1. """ return self.height_map[item[1]][item[0]] def __setitem__(self, key, value): """Set the height of an item. Args: key (tuple): 2-tuple of x and y coordinates. value (float): New height of map at x and y coordinates, between 0 and 1. """ self.height_map[key[1]][key[0]] = value def __add__(self, other): """Add two terrains, height by height. Args: other (Terrain): Other terrain to add self to. Must have same dimensions as self. Returns: Terrain: Terrain of self and other added together. """ result = Terrain(self.width, self.length) for i in range(self.width): for j in range(self.length): result[i, j] = self[i, j] + other[i, j] return result
Add addition method to Terrain
Add addition method to Terrain
Python
mit
jackromo/RandTerrainPy
2e845dfd2695b1913f4603d88039049fa1eef923
repositories.py
repositories.py
repositories = [ { "owner": "talk-to", "name": "Knock" } ]
REPOSITORIES = [ { "owner": "talk-to", "name": "Knock" } ]
Use capitalised name for constant
Use capitalised name for constant
Python
mit
ayushgoel/LongShot
680b8680f5d2dbc7ccb742cf09bf6f688afcbd96
parse_brewpi_json.py
parse_brewpi_json.py
#!/usr/bin/python import os import os.path import json import re import tabulate def get_json_file(): dir='/var/www/html' json_list = [] for root, dirs, files in os.walk( dir ): for f in files: if f.endswith( '.json' ): json_list.append( os.path.join( root, f ) ) sorted_list = sorted( json_list, key=os.path.getmtime ) return sorted_list[-1] jfile = get_json_file() with open( jfile ) as fh: data = json.load( fh ) rex = re.compile( 'Time|BeerTemp|FridgeTemp|RoomTemp|RedTemp|RedSG' ) col_nums = [] for k,v in enumerate( data[ 'cols' ] ): name = v['id'] if rex.search( name ): col_nums.append( k ) headers = [ data['cols'][i]['id'] for i in col_nums ] rows = [] for row in data['rows']: values = [] for i in col_nums: elem = row['c'][i] val = None if elem is not None: val = elem['v'] values.append( val ) #datalist = [ row['c'][i]['v'] for i in col_nums ] rows.append( values ) print tabulate.tabulate( rows, headers=headers )
#!/usr/bin/python import os import os.path import json import re import tabulate def get_json_file(): dir='/var/www/html' json_list = [] for root, dirs, files in os.walk( dir ): for f in files: if f.endswith( '.json' ): json_list.append( os.path.join( root, f ) ) sorted_list = sorted( json_list, key=os.path.getmtime ) return sorted_list[-1] jfile = get_json_file() print( "\n{0}\n".format( os.path.basename( jfile ) ) ) with open( jfile ) as fh: data = json.load( fh ) rex = re.compile( 'Time|BeerTemp|FridgeTemp|RoomTemp|RedTemp|RedSG' ) col_nums = [] for k,v in enumerate( data[ 'cols' ] ): name = v['id'] if rex.search( name ): col_nums.append( k ) headers = [ data['cols'][i]['id'] for i in col_nums ] rows = [] for row in data['rows']: values = [] for i in col_nums: elem = row['c'][i] val = None if elem is not None: val = elem['v'] values.append( val ) #datalist = [ row['c'][i]['v'] for i in col_nums ] rows.append( values ) print( tabulate.tabulate( rows, headers=headers ) )
Add json filename to output.
Add json filename to output.
Python
mit
andylytical/brewpi-scripts,andylytical/brewpi-scripts
de40597b406b27c64077dc714b5890f83758d05d
multiplication-table.py
multiplication-table.py
""" multiplication-table.py Author: <your name here> Credit: <list sources used, if any> Assignment: Write and submit a Python program that prints a multiplication table. The user must be able to determine the width and height of the table before it is printed. The final multiplication table should look like this: Width of multiplication table: 10 Height of multiplication table: 8 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 """
""" multiplication-table.py Author: <your name here> Credit: <list sources used, if any> Assignment: Write and submit a Python program that prints a multiplication table. The user must be prompted to give the width and height of the table before it is printed. The final multiplication table should look like this: Width of multiplication table: 10 Height of multiplication table: 8 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 """
Reword about user giving dimensions
Reword about user giving dimensions
Python
mit
HHS-IntroProgramming/Multiplication-table,HHS-IntroProgramming/Multiplication-table
aa7109d038a86f6a19a9fb4af96bd1199cd81330
functest/opnfv_tests/openstack/snaps/snaps_utils.py
functest/opnfv_tests/openstack/snaps/snaps_utils.py
# Copyright (c) 2015 All rights reserved # This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # # http://www.apache.org/licenses/LICENSE-2.0 from snaps.openstack.utils import neutron_utils, nova_utils def get_ext_net_name(os_creds): """ Returns the first external network name :param: os_creds: an instance of snaps OSCreds object :return: """ neutron = neutron_utils.neutron_client(os_creds) ext_nets = neutron_utils.get_external_networks(neutron) return ext_nets[0].name if ext_nets else "" def get_active_compute_cnt(os_creds): """ Returns the number of active compute servers :param: os_creds: an instance of snaps OSCreds object :return: the number of active compute servers """ nova = nova_utils.nova_client(os_creds) computes = nova_utils.get_availability_zone_hosts(nova, zone_name='nova') return len(computes)
# Copyright (c) 2015 All rights reserved # This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # # http://www.apache.org/licenses/LICENSE-2.0 from functest.utils.constants import CONST from snaps.openstack.utils import neutron_utils, nova_utils def get_ext_net_name(os_creds): """ Returns the configured external network name or the first retrieved external network name :param: os_creds: an instance of snaps OSCreds object :return: """ neutron = neutron_utils.neutron_client(os_creds) ext_nets = neutron_utils.get_external_networks(neutron) if (hasattr(CONST, 'EXTERNAL_NETWORK')): extnet_config = CONST.__getattribute__('EXTERNAL_NETWORK') for ext_net in ext_nets: if ext_net.name == extnet_config: return extnet_config return ext_nets[0].name if ext_nets else "" def get_active_compute_cnt(os_creds): """ Returns the number of active compute servers :param: os_creds: an instance of snaps OSCreds object :return: the number of active compute servers """ nova = nova_utils.nova_client(os_creds) computes = nova_utils.get_availability_zone_hosts(nova, zone_name='nova') return len(computes)
Support to specify the valid external network name
Support to specify the valid external network name In some deployments, the retrieved external network by the def get_external_networks in Snaps checked by "router:external" is not available. So it is necessary to specify the available external network as an env by user. Change-Id: I333e91dd106ed307541a9a197280199fde86bd30 Signed-off-by: Linda Wang <[email protected]>
Python
apache-2.0
opnfv/functest,mywulin/functest,opnfv/functest,mywulin/functest
acd4238dce39464e99964227dca7758cffedca39
gaphor/UML/classes/tests/test_containmentconnect.py
gaphor/UML/classes/tests/test_containmentconnect.py
"""Test connection of containment relationship.""" from gaphor import UML from gaphor.diagram.tests.fixtures import allow, connect from gaphor.UML.classes import PackageItem from gaphor.UML.classes.containment import ContainmentItem def test_containment_package_glue(create): """Test containment glue to two package items.""" pkg1 = create(PackageItem, UML.Package) pkg2 = create(PackageItem, UML.Package) containment = create(ContainmentItem) glued = allow(containment, containment.head, pkg1) assert glued connect(containment, containment.head, pkg1) glued = allow(containment, containment.tail, pkg2) assert glued
"""Test connection of containment relationship.""" from gaphor import UML from gaphor.diagram.tests.fixtures import allow, connect from gaphor.UML.classes import ClassItem, PackageItem from gaphor.UML.classes.containment import ContainmentItem def test_containment_package_glue(create): """Test containment glue to two package items.""" pkg1 = create(PackageItem, UML.Package) pkg2 = create(PackageItem, UML.Package) containment = create(ContainmentItem) glued = allow(containment, containment.head, pkg1) assert glued connect(containment, containment.head, pkg1) glued = allow(containment, containment.tail, pkg2) assert glued def test_containment_package_class(create, diagram): """Test containment connecting to a package and a class.""" package = create(ContainmentItem, UML.Package) line = create(ContainmentItem) ac = create(ClassItem, UML.Class) connect(line, line.head, package) connect(line, line.tail, ac) assert diagram.connections.get_connection(line.tail).connected is ac assert len(package.subject.ownedElement) == 1 assert ac.subject in package.subject.ownedElement
Add test for connecting containment to package and a class
Add test for connecting containment to package and a class [skip ci] Signed-off-by: Dan Yeaw <[email protected]>
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
413ba364dc35a7186953d02bb7cc8cf705371873
contentious/constants.py
contentious/constants.py
from django.conf import settings SELF_CLOSING_HTML_TAGS = getattr(settings, 'CONTENTIOUS_SELF_CLOSING_HTML_TAGS', ['img', 'br', 'hr', 'meta']) #Note, the Javascript plugin has its own seprate copy of this: TREAT_CONTENT_AS_HTML_TAGS = getattr(settings, 'CONTENTIOUS_TREAT_CONTENT_AS_HTML_TAGS', ['div', 'select', 'ul'])
from django.conf import settings SELF_CLOSING_HTML_TAGS = ['img', 'br', 'hr', 'meta'] #Note, the Javascript plugin has its own seprate copy of this: TREAT_CONTENT_AS_HTML_TAGS = getattr(settings, 'CONTENTIOUS_TREAT_CONTENT_AS_HTML_TAGS', ['div', 'select', 'ul'])
Remove SELF_CLOSING_HTML_TAGS as a configurable option
Remove SELF_CLOSING_HTML_TAGS as a configurable option
Python
bsd-2-clause
potatolondon/contentious,potatolondon/contentious
182cd3b73382bb150111198e5fcbfa43a6bd416f
cbagent/collectors/libstats/typeperfstats.py
cbagent/collectors/libstats/typeperfstats.py
from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task class TPStats(RemoteStats): METRICS = ( ("rss", 1), # already in bytes ) def __init__(self, hosts, workers, user, password): super().__init__(hosts, workers, user, password) self.typeperf_cmd = "typeperf \"\\Process(*{}*)\\Working Set\" -sc 1|sed '3q;d'" @parallel_task(server_side=True) def get_samples(self, process): samples = {} if process == "beam.smp": stdout = self.run(self.typeperf_cmd.format("erl")) values = stdout.split(',')[1:5] elif process == "memcached": stdout = self.run(self.typeperf_cmd.format(process)) values = stdout.split(',')[1:2] else: return samples sum_rss = 0 if stdout: for v in values: v = float(v.replace('"', '')) sum_rss += v metric, multiplier = self.METRICS[0] title = "{}_{}".format(process, metric) samples[title] = float(sum_rss) * multiplier return samples
from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task class TPStats(RemoteStats): METRICS = ( ("rss", 1), # already in bytes ) def __init__(self, hosts, workers, user, password): super().__init__(hosts, workers, user, password) self.typeperf_cmd = "typeperf \"\\Process(*{}*)\\Working Set\" -sc 1|sed '3q;d'" @parallel_task(server_side=True) def get_server_samples(self, process): samples = {} if process == "beam.smp": stdout = self.run(self.typeperf_cmd.format("erl")) values = stdout.split(',')[1:5] elif process == "memcached": stdout = self.run(self.typeperf_cmd.format(process)) values = stdout.split(',')[1:2] else: return samples sum_rss = 0 if stdout: for v in values: v = float(v.replace('"', '')) sum_rss += v metric, multiplier = self.METRICS[0] title = "{}_{}".format(process, metric) samples[title] = float(sum_rss) * multiplier return samples def get_client_samples(self, process): pass
Add missing methods to TPStats
Add missing methods to TPStats Change-Id: I332a83f3816ee30597288180ed344da3161861f8 Reviewed-on: http://review.couchbase.org/79675 Tested-by: Build Bot <[email protected]> Reviewed-by: Pavel Paulau <[email protected]>
Python
apache-2.0
pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
106