commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
5b681f55896af1aec9f71bc86c1f17f60a66e4bd
pyfr/syutil.py
pyfr/syutil.py
# -*- coding: utf-8 -*- import sympy as sy def lagrange_basis(points, sym): """Generates a basis of polynomials, :math:`l_i(x)`, such that .. math:: l_i(x) = \delta^x_{p_i} where :math:`p_i` is the i'th entry in *points* and :math:`x \in p`. """ n = len(points) lagrange_poly = sy.inter...
# -*- coding: utf-8 -*- import sympy as sy def lagrange_basis(points, sym): """Generates a basis of polynomials, :math:`l_i(x)`, such that .. math:: l_i(x) = \delta^x_{p_i} where :math:`p_i` is the i'th entry in *points* and :math:`x \in p`. """ n = len(points) lagrange_poly = sy.inter...
Add a function for generating normalised Jacobi polynomials.
Add a function for generating normalised Jacobi polynomials.
Python
bsd-3-clause
BrianVermeire/PyFR,tjcorona/PyFR,iyer-arvind/PyFR,tjcorona/PyFR,tjcorona/PyFR,Aerojspark/PyFR
--- +++ @@ -14,3 +14,12 @@ return [lagrange_poly(n, sym, points, [0]*i + [1] + [0]*(n-i-1)).expand() for i in xrange(n)] + + +def norm_jacobi(n, a, b, sym): + G, F = sy.gamma, sy.factorial + + N2 = sy.S(2)**(a + b + 1)/(2*n + a + b + 1)\ + * (G(n + a + 1)*G(n + b + 1))/(F(n)*G(n + a + ...
2714cf4ff5639761273c91fd360f3b0c7cbf1f8b
github_ebooks.py
github_ebooks.py
#!/usr/bin/python import sys def main(argv): return 0 if __name__ == "__main__": sys.exit(main(sys.argv))
#!/usr/bin/python import sys import argparse import codecs from Database import Database def readFromFile(path, db): f = codecs.open(path, 'r', 'utf-8') commits = [] for line in f: line = line.strip() commits.append((hash(line), line)) db.addCommits(commits) def printCommits(db): for (hash, msg) ...
Add a way to scrape commits from a file.
Add a way to scrape commits from a file.
Python
mit
Fifty-Nine/github_ebooks
--- +++ @@ -1,7 +1,45 @@ #!/usr/bin/python import sys +import argparse +import codecs + +from Database import Database + +def readFromFile(path, db): + f = codecs.open(path, 'r', 'utf-8') + + commits = [] + for line in f: + line = line.strip() + commits.append((hash(line), line)) + + db.addCommits(commits...
26b587086ad4e3eb3c9e15c2c3d96d6f7e5dba21
compshop/urls.py
compshop/urls.py
"""compshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-ba...
"""compshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-ba...
Move catalogue to products URL namespace
Move catalogue to products URL namespace
Python
bsd-3-clause
kevgathuku/compshop,kevgathuku/compshop,andela-kndungu/compshop,andela-kndungu/compshop,andela-kndungu/compshop,kevgathuku/compshop,andela-kndungu/compshop,kevgathuku/compshop
--- +++ @@ -18,10 +18,10 @@ from django.conf.urls.static import static from django.contrib import admin -from store.views import ProductCatalogue, ProductList +from store.views import ProductList urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', ProductList.as_view(), name='home')...
e8ba913722218c86b2b705d8351795a409a514ac
pale/arguments/__init__.py
pale/arguments/__init__.py
from .base import BaseArgument, ListArgument from .boolean import BooleanArgument from .number import IntegerArgument from .scope import ScopeArgument from .string import StringArgument, StringListArgument from .url import URLArgument
from .base import BaseArgument, ListArgument from .boolean import BooleanArgument from .number import FloatArgument, IntegerArgument from .scope import ScopeArgument from .string import StringArgument, StringListArgument from .url import URLArgument
Add FloatArgument to arguments module
Add FloatArgument to arguments module
Python
mit
Loudr/pale
--- +++ @@ -1,6 +1,6 @@ from .base import BaseArgument, ListArgument from .boolean import BooleanArgument -from .number import IntegerArgument +from .number import FloatArgument, IntegerArgument from .scope import ScopeArgument from .string import StringArgument, StringListArgument from .url import URLArgument
330c90c9bc8b4c6d8df4d15f503e9a483513e5db
install/setup_pi_box.py
install/setup_pi_box.py
import os import sys import shutil if not os.path.exists('/opt/Pi-Box'): os.makedirs('/opt/Pi-Box') shutil.copy('./main.py', '/opt/Pi-Box') if not os.path.exists('/opt/Pi-Box/dropbox.txt'): print('Dropbox token file (dropbox.txt) not found.') print('Authorize Pi-Box and obtain the token file: blah, blah, blah') ...
import os import sys import shutil if not os.path.exists('/opt/Pi-Box'): os.makedirs('/opt/Pi-Box') shutil.copy('./main.py', '/opt/Pi-Box') if not os.path.exists('/opt/Pi-Box/dropbox.txt'): print('Authorize Pi-Box and obtain the token file: http://raspberry-pi-box.herokuapp.com/') print('Copy Dropbox token file (...
Add URL to setup script
Add URL to setup script
Python
mit
projectweekend/Pi-Box,projectweekend/Pi-Box
--- +++ @@ -8,9 +8,8 @@ shutil.copy('./main.py', '/opt/Pi-Box') if not os.path.exists('/opt/Pi-Box/dropbox.txt'): - print('Dropbox token file (dropbox.txt) not found.') - print('Authorize Pi-Box and obtain the token file: blah, blah, blah') - print('Save the file in: /opt/Pi-Box') + print('Authorize Pi-Box and ob...
69cd2732bb629a52da81b865497089c19f29407a
examples/juniper/get-interface-status.py
examples/juniper/get-interface-status.py
#!/usr/bin/env python # Python script to fetch interface name and their operation status from ncclient import manager def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, dev...
#!/usr/bin/env python # Python script to fetch interface name and their operation status from ncclient import manager def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, dev...
Remove unused statement & format for python3
Remove unused statement & format for python3
Python
apache-2.0
GIC-de/ncclient,leopoul/ncclient,earies/ncclient,einarnn/ncclient,vnitinv/ncclient,ncclient/ncclient,nwautomator/ncclient
--- +++ @@ -17,11 +17,10 @@ response = conn.rpc(rpc) interface_name = response.xpath('//physical-interface/name') interface_status = response.xpath('//physical-interface/oper-status') - interface_dict = dict() for name, status in zip(interface_name, interface_status): name = name.text....
91865fc50b66dc261cf05bba21a371e1130b25f5
integration-test/605-crosswalk-sidewalk.py
integration-test/605-crosswalk-sidewalk.py
# http://www.openstreetmap.org/way/367477828 assert_has_feature( 16, 10471, 25331, 'roads', { 'id': 367477828, 'kind': 'path', 'crossing': 'zebra' }) # Way: The Embarcadero (397140734) # http://www.openstreetmap.org/way/397140734 assert_has_feature( 16, 10486, 25326, 'roads', { 'id': 397140734, 'kind':...
# http://www.openstreetmap.org/way/444491374 assert_has_feature( 16, 10475, 25332, 'roads', { 'id': 444491374, 'kind': 'path', 'crossing': 'traffic_signals' }) # Way: The Embarcadero (397140734) # http://www.openstreetmap.org/way/397140734 assert_has_feature( 16, 10486, 25326, 'roads', { 'id': 39714073...
Update osm way used due to data change
Update osm way used due to data change
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
--- +++ @@ -1,7 +1,7 @@ -# http://www.openstreetmap.org/way/367477828 +# http://www.openstreetmap.org/way/444491374 assert_has_feature( - 16, 10471, 25331, 'roads', - { 'id': 367477828, 'kind': 'path', 'crossing': 'zebra' }) + 16, 10475, 25332, 'roads', + { 'id': 444491374, 'kind': 'path', 'crossing': 't...
71db89cad06dc0aa81e0a7178712e8beb7e7cb01
turbustat/tests/test_cramer.py
turbustat/tests/test_cramer.py
# Licensed under an MIT open source license - see LICENSE ''' Test functions for Cramer ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testCramer...
# Licensed under an MIT open source license - see LICENSE ''' Test functions for Cramer ''' import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances def test_cramer(): tester = \ Cramer_Distance(dataset1...
Remove importing UnitCase from Cramer tests
Remove importing UnitCase from Cramer tests
Python
mit
Astroua/TurbuStat,e-koch/TurbuStat
--- +++ @@ -5,9 +5,6 @@ Test functions for Cramer ''' -from unittest import TestCase - -import numpy as np import numpy.testing as npt from ..statistics import Cramer_Distance @@ -15,27 +12,26 @@ dataset1, dataset2, computed_data, computed_distances -class testCramer(TestCase): +def test_cramer(): + ...
b4525469d227e1878e9ded3f541577b3487b7d9e
run_game.py
run_game.py
#!/usr/bin/env python """Point of execution for play. Configures module path and libraries and then calls lib.main.main. """ import sys sys.path.insert(0, 'pyglet-c9188efc2e30') import getopt import os import ookoobah.main def run(): ookoobah.main.main() if __name__ == "__main__": # Change to the game dir...
#!/usr/bin/env python """Point of execution for play. Configures module path and libraries and then calls lib.main.main. """ import os import sys import getopt if __name__ == "__main__": # Change to the game directory os.chdir(os.path.dirname(os.path.join(".", sys.argv[0]))) sys.path.insert(0, 'pyglet-c...
Fix pyglet and game loading.
Fix pyglet and game loading.
Python
mit
vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah
--- +++ @@ -5,19 +5,13 @@ """ +import os import sys -sys.path.insert(0, 'pyglet-c9188efc2e30') - import getopt -import os -import ookoobah.main - -def run(): - ookoobah.main.main() if __name__ == "__main__": # Change to the game directory os.chdir(os.path.dirname(os.path.join(".", sys.argv[0]))...
10ec59777c0b364e05dc022ac3178d0c6d0ca916
plugin/formatters.py
plugin/formatters.py
import json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return json.dumps(data, indent=indent, separators=(',', ': ')), None...
import json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return True, json.dumps(data, indent=indent, separators=(',', ': '))...
Fix parsing of JSON formatting errors
Fix parsing of JSON formatting errors
Python
mit
Rypac/sublime-format
--- +++ @@ -8,6 +8,6 @@ indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) - return json.dumps(data, indent=indent, separators=(',', ': ')), None + return True, json.dumps(data, indent=indent, separators=(',', ': ')), None e...
ae3092cfeb99f89e98517e9db29d8f013fceb1c5
touchdown/tests/test_ssh_client.py
touchdown/tests/test_ssh_client.py
# Copyright 2015 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
# Copyright 2015 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
Disable tests that don't work on travis
Tests: Disable tests that don't work on travis
Python
apache-2.0
yaybu/touchdown
--- +++ @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +import unittest + import mock from touchdown.tests.fixtures.ssh_connection import SshConnectionFixture @@ -20,6 +22,7 @@ class TestSshClient(WorkspaceTestCase): + @unittest...
ac571170c4ba8db7899c0323778933edc46dd025
salt/runners/pillar.py
salt/runners/pillar.py
# -*- coding: utf-8 -*- ''' Functions to interact with the pillar compiler on the master ''' # Import salt libs import salt.pillar import salt.utils.minions def show_top(minion=None, saltenv='base'): ''' Returns the compiled top data for pillar for a specific minion. If no minion is specified, we use th...
# -*- coding: utf-8 -*- ''' Functions to interact with the pillar compiler on the master ''' # Import salt libs import salt.pillar import salt.utils.minions def show_top(minion=None, saltenv='base'): ''' Returns the compiled top data for pillar for a specific minion. If no minion is specified, we use th...
Use the new get_minion_data function
Use the new get_minion_data function
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -19,7 +19,7 @@ salt-run pillar.show_top ''' - id_, grains = salt.utils.minions.get_grains(minion) + id_, grains, _ = salt.utils.minions.get_minion_data(minion, __opts__) pillar = salt.pillar.Pillar( __opts__, grains,
e70856cb18fa86f955dda6cb18cddbdc431a5577
chipy_org/libs/social_auth_pipelines.py
chipy_org/libs/social_auth_pipelines.py
from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = Fals...
from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = Fals...
Revert "Fixes to the create_user pipeline"
Revert "Fixes to the create_user pipeline" This reverts commit 49dd1b5205498425f7af247f7c390a48a423db4c.
Python
mit
chicagopython/chipy.org,brianray/chipy.org,brianray/chipy.org,bharathelangovan/chipy.org,bharathelangovan/chipy.org,chicagopython/chipy.org,agfor/chipy.org,tanyaschlusser/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,agfor/chipy.org,chicagopython/chipy.org,brianray/chipy.org,bharat...
--- +++ @@ -9,16 +9,14 @@ ''' Check if a user with this email already exists. If they do, don't create an account. ''' - - if is_new: + + if not user: if User.objects.filter(email = details.get('email')).exists(): - msg = ugettext('This email is already in use.') + ...
e097c4f6c6333a7017642d376f8dd158b4a963b2
package_monitor/migrations/0007_add_django_version_info.py
package_monitor/migrations/0007_add_django_version_info.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('package_monitor', '0006_add_python_version_info'), ] operations = [ migrations.AddField( model_name='packagevers...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('package_monitor', '0006_add_python_version_info'), ] operations = [ migrations.AddField( model_name='packagevers...
Fix up migrations, part 2
Fix up migrations, part 2
Python
mit
yunojuno/django-package-monitor,yunojuno/django-package-monitor
--- +++ @@ -18,7 +18,7 @@ ), migrations.AlterField( model_name='packageversion', - name=b'python_support', + name='python_support', field=models.CharField(help_text=b'Python version support as specified in the PyPI classifiers.', max_length=100, null=T...
e09af91b45355294c16249bcd3c0bf07982cd39c
websaver/parsed_data/models.py
websaver/parsed_data/models.py
from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = model...
from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo =...
Add fpp k/d data to the model.
Add fpp k/d data to the model.
Python
mit
aiirohituzi/myWebCrawler,aiirohituzi/myWebCrawler,aiirohituzi/myWebCrawler
--- +++ @@ -3,15 +3,23 @@ # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) + solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) + ...
1ee8f9dcb74d65e22bf785692a696ec743bcb932
pyatmlab/__init__.py
pyatmlab/__init__.py
#!/usr/bin/env python from . import meta __version__ = "0.1.0+" __doc__ = """This is pyatmlab """ from pint import UnitRegistry ureg = UnitRegistry()
#!/usr/bin/env python from . import meta __version__ = "0.1.0+" __doc__ = """This is pyatmlab """ from pint import UnitRegistry ureg = UnitRegistry() ureg.define("micro- = 1e-6 = µ-")
Use µ- prefix rather than u-
Use µ- prefix rather than u-
Python
bsd-3-clause
olemke/pyatmlab,gerritholl/pyatmlab
--- +++ @@ -9,3 +9,4 @@ from pint import UnitRegistry ureg = UnitRegistry() +ureg.define("micro- = 1e-6 = µ-")
fe547c93a476b5093930ff08fef8fe48a16dc930
examples/monitoring/ligier_mirror.py
examples/monitoring/ligier_mirror.py
#!/usr/bin/env python # coding=utf-8 # vim: ts=4 sw=4 et """ ============= Ligier Mirror ============= Subscribes to given tag(s) and sends them to another Ligier. """ # Author: Tamas Gal <tgal@km3net.de> # License: MIT from __future__ import division import socket from km3pipe import Pipeline, Module from km3pipe....
#!/usr/bin/env python # coding=utf-8 # vim: ts=4 sw=4 et """ ============= Ligier Mirror ============= Subscribes to given tag(s) and sends them to another Ligier. This script is also available as a command line utility in km3pipe, which can be accessed by the command ``ligiermirror``. """ # Author: Tamas Gal <tgal@k...
Add ref to ligiermirror CLU
Add ref to ligiermirror CLU
Python
mit
tamasgal/km3pipe,tamasgal/km3pipe
--- +++ @@ -7,6 +7,8 @@ ============= Subscribes to given tag(s) and sends them to another Ligier. +This script is also available as a command line utility in km3pipe, which can +be accessed by the command ``ligiermirror``. """ # Author: Tamas Gal <tgal@km3net.de>
8e5a84a62662779cbf3965f5460b320f68d66c6a
alg_strongly_connected_graph.py
alg_strongly_connected_graph.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division def dfs_recur(): pass def traverse_dfs_recur(): pass def transpose_graph(): pass def strongly_connected_graph(): """Find strongly connected graph by Kosaraju's Algorithm.""" def main(): pass i...
from __future__ import absolute_import from __future__ import print_function from __future__ import division def dfs_recur(): pass def traverse_dfs_recur(): pass def transpose_graph(): pass def strongly_connected_graph(): """Find strongly connected graphs by Kosaraju's Algorithm.""" def main(): adjace...
Add adjacency_dict for strongly connected graphs
Add adjacency_dict for strongly connected graphs
Python
bsd-2-clause
bowen0701/algorithms_data_structures
--- +++ @@ -13,11 +13,21 @@ pass def strongly_connected_graph(): - """Find strongly connected graph by Kosaraju's Algorithm.""" + """Find strongly connected graphs by Kosaraju's Algorithm.""" def main(): - pass + adjacency_dict = { + 'A': {'B'}, + 'B': {'C', 'E'}, + 'C': {'C...
201863f214e54feca811185151bf953d1eedca6d
app/ml_models/affect_ai_test.py
app/ml_models/affect_ai_test.py
import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure ...
import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 ai = affect_ai.affect_AI(15, 5) # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with som...
Write part of a test
chore: Write part of a test
Python
mit
OmegaHorizonResearch/agile-analyst
--- +++ @@ -3,10 +3,12 @@ # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 +ai = affect_ai.affect_AI(15, 5) # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with...
6c3f869150e5797c06b5f63758280b60e296d658
core/admin.py
core/admin.py
from django.contrib import admin from django.contrib.admin.forms import AdminAuthenticationForm from django import forms class NavigatorLoginForm(AdminAuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'autocomplete': 'off'})) admin.site.login_form = NavigatorLoginForm
from django.contrib import admin from django.contrib.admin.forms import AdminAuthenticationForm from django import forms class NavigatorLoginForm(AdminAuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'autocomplete': 'off'})) admin.site.login_form = NavigatorLoginForm def get_actio...
Remove the bulk delete action if the user does not have delete permissions on the model being viewed
Remove the bulk delete action if the user does not have delete permissions on the model being viewed
Python
mit
uktrade/navigator,uktrade/navigator,uktrade/navigator,uktrade/navigator
--- +++ @@ -8,3 +8,27 @@ admin.site.login_form = NavigatorLoginForm + + +def get_actions_replacer(orig_func): + def fixed_get_actions(self, request): + """ + Remove the delete action (if present) if user does not have the + necessary permission + """ + + # Get the base actio...
8b51c9904fd09354ff5385fc1740d9270da8287c
should-I-boot-this.py
should-I-boot-this.py
#!/usr/bin/env python3 # -*- coding:utf-8 -* # import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Check if we need to stop here ...
#!/usr/bin/env python3 # -*- coding:utf-8 -* # import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Is the lab existing? if os.env...
Allow boots for unknown labs
jenkins: Allow boots for unknown labs Signed-off-by: Florent Jacquet <692930aa2e4df70616939784b5b6c25eb1f2335c@free-electrons.com>
Python
lgpl-2.1
kernelci/lava-ci-staging,kernelci/lava-ci-staging,kernelci/lava-ci-staging
--- +++ @@ -16,7 +16,12 @@ config = configparser.ConfigParser() config.read('labs.ini') -# Check if we need to stop here +# Is the lab existing? +if os.environ['LAB'] not in config.sections(): + print("Unknown lab (%s). Allowing boot of %s." % (os.environ['LAB'], os.environ['TREE'])) + sys.exit(0) + +# Is t...
2434c06d806fd10832ebae73408021dbc1470269
test_settings.py
test_settings.py
from os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', ...
from os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', ...
Test all the Jmbo content types
Test all the Jmbo content types
Python
bsd-3-clause
praekelt/jmbo-foundry,praekelt/jmbo-foundry,praekelt/jmbo-foundry
--- +++ @@ -14,22 +14,20 @@ } } -# See setup.py for an explanation as to why these aren't enabled by default -''' +# Foundry provides high-level testing tools for other content types INSTALLED_APPS += ( 'banner', - #'jmbo_calendar', # requires atlas + 'jmbo_calendar', 'chart', - #'compet...
038a905e58c42881c12d53911eb70926cfbc76f2
nsq/util.py
nsq/util.py
'''Some utilities used around town''' import struct def pack(message): '''Pack the provided message''' if isinstance(message, basestring): # Return # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message else: # Return # [ 4...
'''Some utilities used around town''' import struct def pack_string(message): '''Pack a single message in the TCP protocol format''' # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message def pack_iterable(messages): '''Pack an iterable of messages in the T...
Fix failing test about passing nested iterables to pack
Fix failing test about passing nested iterables to pack
Python
mit
dlecocq/nsq-py,dlecocq/nsq-py
--- +++ @@ -3,20 +3,29 @@ import struct +def pack_string(message): + '''Pack a single message in the TCP protocol format''' + # [ 4-byte message size ][ N-byte binary data ] + return struct.pack('>l', len(message)) + message + + +def pack_iterable(messages): + '''Pack an iterable of messages in the T...
513560a051d9388cd39384860ddce6a938501080
bad.py
bad.py
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") num_cooks = 100 num_sells = 50 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') while True: try: c...
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") # Amount you'd like to have in terms of cash and # drugs to start the game init_drugs = 10000 init_cash = 10000 # Number of cooks and sells to do in a r...
Allow user to set their initial amount of cash and drugs
Allow user to set their initial amount of cash and drugs
Python
apache-2.0
brint/cheating_bad
--- +++ @@ -5,12 +5,20 @@ driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") -num_cooks = 100 -num_sells = 50 +# Amount you'd like to have in terms of cash and +# drugs to start the game +init_drugs = 10000 +init_cash = 10000 + +# Number of cooks and sells to do in a row +num_cooks = 500 +n...
428e1e669e8b5e59da2c4d87716ffd329b4a084a
test/bluezutils.py
test/bluezutils.py
import dbus SERVICE_NAME = "org.bluez" ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter" def get_managed_objects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects() def find_adapter(pattern=None): return fin...
import dbus SERVICE_NAME = "org.bluez" ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter" DEVICE_INTERFACE = SERVICE_NAME + ".Device" def get_managed_objects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects() ...
Add helper function to find devices
test: Add helper function to find devices Add a helper function to the utility library as an alternative to the convenience method Adapter.FindDevice() in the D-Bus API.
Python
lgpl-2.1
silent-snowman/bluez,pstglia/external-bluetooth-bluez,ComputeCycles/bluez,mapfau/bluez,ComputeCycles/bluez,mapfau/bluez,pstglia/external-bluetooth-bluez,pkarasev3/bluez,pkarasev3/bluez,pkarasev3/bluez,pstglia/external-bluetooth-bluez,pkarasev3/bluez,ComputeCycles/bluez,mapfau/bluez,ComputeCycles/bluez,silent-snowman/bl...
--- +++ @@ -2,6 +2,7 @@ SERVICE_NAME = "org.bluez" ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter" +DEVICE_INTERFACE = SERVICE_NAME + ".Device" def get_managed_objects(): bus = dbus.SystemBus() @@ -23,3 +24,24 @@ obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, ADAPTER_INTERFACE) r...
8cd193b9e842918c03aa25ce0eaf1cca1c843c95
rrsm/StateMachine.py
rrsm/StateMachine.py
class StateMachine(object): def __init__(self,RequiredStates,InitialState=0): self.States = RequiredStates self.StateCodes = dict([(v,k) for k,v in RequiredStates.iteritems()]) # This is done for speed of the rest of the class self.SwitchTo(InitialState) ...
class StateMachine(object): def __init__(self,RequiredStates,InitialState=0): if type(RequiredStates) is dict: self.States = RequiredStates self.StateCodes = dict([(code,state) for state,code in RequiredStates.iteritems()]) # This is done for speed of the rest of the class ...
Enable Dictionaries or Lists to create the Machine
Enable Dictionaries or Lists to create the Machine
Python
mit
jnmclarty/rrsm
--- +++ @@ -1,9 +1,13 @@ class StateMachine(object): def __init__(self,RequiredStates,InitialState=0): - self.States = RequiredStates - self.StateCodes = dict([(v,k) for k,v in RequiredStates.iteritems()]) # This is done for speed of the rest of the class - + if type(RequiredS...
6d5eaee8b1c13eb08cbf48b4c72c5b2d8f0d96b4
test/runner.py
test/runner.py
import sys import os import test.cache as tc import test.dateandtime as td import test.nagios as tn import test.generaloption as tg import unittest suite = unittest.TestSuite([x.suite() for x in (tc, td, tn, tg)]) try: import xmlrunner rs = xmlrunner.XMLTestRunner(output="test-reports").run(suite) except Imp...
# -*- encoding: utf-8 -*- import sys import os import test.cache as tc import test.dateandtime as td import test.nagios as tn import test.generaloption as tg import test.nagios_results as tr import unittest suite = unittest.TestSuite([x.suite() for x in (tc, td, tn, tg, tr)]) try: import xmlrunner rs = xmlru...
Rename the nagios-results test suite into a valid identifier.
Rename the nagios-results test suite into a valid identifier. This way, we can run its tests from within a test.runner module.
Python
lgpl-2.1
hpcugent/vsc-processcontrol,hpcugent/vsc-processcontrol
--- +++ @@ -1,12 +1,14 @@ +# -*- encoding: utf-8 -*- import sys import os import test.cache as tc import test.dateandtime as td import test.nagios as tn import test.generaloption as tg +import test.nagios_results as tr import unittest -suite = unittest.TestSuite([x.suite() for x in (tc, td, tn, tg)]) +suite...
90a724313902e3d95f1a37d9102af1544c9bc61d
segments/set_term_title.py
segments/set_term_title.py
def add_term_title_segment(): term = os.getenv('TERM') if not (('xterm' in term) or ('rxvt' in term)): return if powerline.args.shell == 'bash': set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]' elif powerline.args.shell == 'zsh': set_title = '\\e]0;%n@%m: %~\\a' else: impor...
def add_term_title_segment(): term = os.getenv('TERM') if not (('xterm' in term) or ('rxvt' in term)): return if powerline.args.shell == 'bash': set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]' elif powerline.args.shell == 'zsh': set_title = '\033]0;%n@%m: %~\007' else: imp...
Fix use of escape characters in "set terminal title" segment.
Fix use of escape characters in "set terminal title" segment. Escape characters were incorrect for non-BASH shells.
Python
mit
nicholascapo/powerline-shell,b-ryan/powerline-shell,junix/powerline-shell,wrgoldstein/powerline-shell,rbanffy/powerline-shell,b-ryan/powerline-shell,mart-e/powerline-shell,blieque/powerline-shell,paulhybryant/powerline-shell,tswsl1989/powerline-shell,torbjornvatn/powerline-shell,MartinWetterwald/powerline-shell,iKrishn...
--- +++ @@ -6,10 +6,10 @@ if powerline.args.shell == 'bash': set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]' elif powerline.args.shell == 'zsh': - set_title = '\\e]0;%n@%m: %~\\a' + set_title = '\033]0;%n@%m: %~\007' else: import socket - set_title = '\\e]0;%s@%s: %s\\a...
680679ed2b05bd5131016d13f66f73249e51a102
tests/utils.py
tests/utils.py
from uuid import uuid4 from valohai_cli.utils import get_random_string def get_project_data(n_projects): return { 'results': [ {'id': str(uuid4()), 'name': get_random_string()} for i in range(n_projects) ], }
from uuid import uuid4 from valohai_cli.utils import get_random_string def get_project_data(n_projects): return { 'results': [ {'id': str(uuid4()), 'name': get_random_string()} for i in range(n_projects) ], } def make_call_stub(retval=None): calls = [] def c...
Add generic monkeypatch call stub
Add generic monkeypatch call stub
Python
mit
valohai/valohai-cli
--- +++ @@ -10,3 +10,14 @@ for i in range(n_projects) ], } + + +def make_call_stub(retval=None): + calls = [] + + def call_stub(*args, **kwargs): + calls.append({'args': args, 'kwargs': kwargs}) + return retval + + call_stub.calls = calls + return call_stub
035ff2c50c5611406af172c6215f712086b75335
tfr/sklearn.py
tfr/sklearn.py
from sklearn.base import BaseEstimator, TransformerMixin from .signal import SignalFrames from .reassignment import pitchgram class PitchgramTransformer(BaseEstimator, TransformerMixin): def __init__(self, sample_rate=44100, frame_size=4096, hop_size=2048, bin_range=[-48, 67], bin_division=1): se...
from sklearn.base import BaseEstimator, TransformerMixin from .signal import SignalFrames from .reassignment import pitchgram class PitchgramTransformer(BaseEstimator, TransformerMixin): def __init__(self, sample_rate=44100, frame_size=4096, hop_size=2048, output_frame_size=None, bin_range=[-48, ...
Add the output_frame_size parameter to PitchgramTransformer.
Add the output_frame_size parameter to PitchgramTransformer. Without it the deserialization via jsonpickle fails.
Python
mit
bzamecnik/tfr,bzamecnik/tfr
--- +++ @@ -6,12 +6,13 @@ class PitchgramTransformer(BaseEstimator, TransformerMixin): def __init__(self, sample_rate=44100, frame_size=4096, hop_size=2048, + output_frame_size=None, bin_range=[-48, 67], bin_division=1): self.sample_rate = sample_rate self.frame_size = frame_...
cb7db2933c180b7f7862352a759a2a90a48d247f
metric/models.py
metric/models.py
from django.db import models class Metric(models.Model): class Meta: db_table = 'metric' def __unicode__(self): return self.name name = models.CharField(max_length=128) explanation_url = models.CharField(max_length=256) units = models.CharField(max_length=128) class Environment...
from django.db import models class Metric(models.Model): class Meta: db_table = 'metric' def __unicode__(self): return self.name name = models.CharField(max_length=128) explanation_url = models.CharField(max_length=256) units = models.CharField(max_length=128) class Environment...
Fix 'zero length field name in format' error
Fix 'zero length field name in format' error
Python
mit
dhh1128/ascent-dashboard,dhh1128/ascent-dashboard
--- +++ @@ -30,7 +30,7 @@ unique_together = ('metric', 'sample_date') def __unicode__(self): - return '{}/{}: {}'.format(self.sample_date, self.metric.name, self.value) + return '{0}/{1}: {2}'.format(self.sample_date, self.metric.name, self.value) metric = models.ForeignKey(Metric...
3fba63784b83c24a88a4d26606f22865122c806e
run.py
run.py
import os from horus.apps import create_app config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)) , 'config.py') print config_file app = create_app(config_file) if __name__ == '__main__': app.run()
import os from horus.apps import create_app config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)) , 'config.py') app = create_app(config_file) if __name__ == '__main__': app.run(debug=True)
Set debug mode to True in development
Set debug mode to True in development
Python
mit
kxxoling/horus,kxxoling/horus,kxxoling/horus
--- +++ @@ -4,9 +4,8 @@ config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)) , 'config.py') -print config_file app = create_app(config_file) if __name__ == '__main__': - app.run() + app.run(debug=True)
eab1de115f010922531a5a2c5f023bf2294f2af4
sendgrid/__init__.py
sendgrid/__init__.py
"""A small django app around sendgrid and its webhooks""" from utils import SendgridEmailMessage, SendgridEmailMultiAlternatives from models import Email from signals import email_event __version__ = '0.1.0' __all__ = ('SendgridEmailMessage', 'SendgridEmailMultiAlternatives', 'Email', 'email_event')
"""A small django app around sendgrid and its webhooks""" __version__ = '0.1.0'
Revert "add __all__ parameter to main module"
Revert "add __all__ parameter to main module" This reverts commit bc9e574206e75b1a50bd1b8eb4bd56f96a18cf51.
Python
bsd-2-clause
resmio/django-sendgrid
--- +++ @@ -1,8 +1,3 @@ """A small django app around sendgrid and its webhooks""" -from utils import SendgridEmailMessage, SendgridEmailMultiAlternatives -from models import Email -from signals import email_event - __version__ = '0.1.0' -__all__ = ('SendgridEmailMessage', 'SendgridEmailMultiAlternatives', 'Email'...
906766ad4bee0f0db560300982a71c222b59a677
example_config.py
example_config.py
""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', ...
""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', ...
Add missing required heroku config variable
Add missing required heroku config variable
Python
agpl-3.0
pluralsight/guides-cms,paulocheque/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms
--- +++ @@ -9,7 +9,7 @@ # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', - 'GITHUB_SECRET') + 'GITHUB_SECRET', ...
fcdc3974015499f822d9e3355a6fe937c18eaf9a
src/nodeconductor_assembly_waldur/slurm_invoices/models.py
src/nodeconductor_assembly_waldur/slurm_invoices/models.py
from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPac...
from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPac...
Add verbose name for SLURM package
Add verbose name for SLURM package [WAL-1141]
Python
mit
opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind
--- +++ @@ -9,6 +9,10 @@ class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): + class Meta(object): + verbose_name = _('SLURM package') + verbose_name_plural = _('SLURM packages') + PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10
d6acda58c696c5b348da8c6a4fef3bf06cea0e58
weight/models.py
weight/models.py
# This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manage...
# This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manage...
Add default ordering to weight entries
Add default ordering to weight entries
Python
agpl-3.0
kjagoo/wger_stark,wger-project/wger,wger-project/wger,wger-project/wger,kjagoo/wger_stark,wger-project/wger,rolandgeider/wger,petervanderdoes/wger,petervanderdoes/wger,petervanderdoes/wger,kjagoo/wger_stark,petervanderdoes/wger,DeveloperMal/wger,DeveloperMal/wger,DeveloperMal/wger,rolandgeider/wger,DeveloperMal/wger,kj...
--- +++ @@ -25,6 +25,9 @@ weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) + # Metaclass to set some other properties + class Meta: + ordering = ["creation_date", ] def __unicode__(self): """Return a more human-readable repr...
9c24683e9594e62f9ba901481c66e40c39a20b4a
tools/metrics/histograms/validate_format.py
tools/metrics/histograms/validate_format.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Verifies that the histograms XML file is well-formatted.""" import extract_histograms def main(): # This will raise an exception if the file is not w...
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Verifies that the histograms XML file is well-formatted.""" import extract_histograms import os.path def main(): # This will raise an exception if th...
Make it possible to run the histograms XML validator from directories other than tools/metrics/histograms.
Make it possible to run the histograms XML validator from directories other than tools/metrics/histograms. Review URL: https://codereview.chromium.org/80433003 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@236508 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,anirudhSK/chromium,anirudhSK/chromium,hgl888/chromium-crosswalk,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,cr...
--- +++ @@ -5,11 +5,14 @@ """Verifies that the histograms XML file is well-formatted.""" import extract_histograms +import os.path def main(): # This will raise an exception if the file is not well-formatted. - histograms = extract_histograms.ExtractHistograms('histograms.xml') + xml_file = os.path.join...
40c97fa33c8739bd27b03891782b542217534904
ognskylines/commands/database.py
ognskylines/commands/database.py
from ognskylines.dbutils import engine from ognskylines.model import Base from manager import Manager manager = Manager() @manager.command def init(): """Initialize the database.""" Base.metadata.create_all(engine) print('Done.') @manager.command def drop(sure=0): """Drop all tables.""" if sure...
from ognskylines.dbutils import engine from ognskylines.model import Base from manager import Manager manager = Manager() @manager.command def init(): """Initialize the database.""" Base.metadata.create_all(engine) print('Done.') @manager.command def drop(sure='n'): """Drop all tables.""" if su...
Change confirmation flag to '--sure y'
CLI: Change confirmation flag to '--sure y'
Python
agpl-3.0
kerel-fs/ogn-skylines-gateway,kerel-fs/ogn-skylines-gateway
--- +++ @@ -13,9 +13,10 @@ @manager.command -def drop(sure=0): +def drop(sure='n'): """Drop all tables.""" - if sure: + if sure == 'y': Base.metadata.drop_all(engine) print('Dropped all tables.') else: + print("Add argument '--sure y' to drop all tables.")
335f1de1120e658f4e87dcbbcaf882146df895bb
zounds/__init__.py
zounds/__init__.py
from node.duration import \ Hours, Minutes, Seconds, Milliseconds, Microseconds, Picoseconds from node.audio_metadata import MetaData, AudioMetaDataEncoder from node.ogg_vorbis import \ OggVorbis, OggVorbisDecoder, OggVorbisEncoder, OggVorbisFeature, \ OggVorbisWrapper from node.audiostream import AudioS...
from node.duration import \ Hours, Minutes, Seconds, Milliseconds, Microseconds, Picoseconds from node.audio_metadata import MetaData, AudioMetaDataEncoder from node.ogg_vorbis import \ OggVorbis, OggVorbisDecoder, OggVorbisEncoder, OggVorbisFeature, \ OggVorbisWrapper from node.audiostream import AudioS...
Add onset detection processing node to top-level exports
Add onset detection processing node to top-level exports
Python
mit
JohnVinyard/zounds,JohnVinyard/zounds,JohnVinyard/zounds,JohnVinyard/zounds
--- +++ @@ -15,7 +15,7 @@ from node.onset import \ MeasureOfTransience, MovingAveragePeakPicker, SparseTimestampDecoder, \ - SparseTimestampEncoder, TimeSliceDecoder, TimeSliceFeature + SparseTimestampEncoder, TimeSliceDecoder, TimeSliceFeature, ComplexDomain from node.preprocess import \ MeanSt...
3c25f2802f70a16869e93fb301428c31452c00f0
plyer/platforms/macosx/uniqueid.py
plyer/platforms/macosx/uniqueid.py
from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) ...
from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) ...
Fix TypeError if `LANG` is not set in on osx
Fix TypeError if `LANG` is not set in on osx In macosx.uniqueid, `$LANG` is retrieved with `old_lang = environ.get('LANG')`. This means that if `LANG` is not set, `old_lang` will be none. When plyer later tries to restore the original value of lang, `putenv` will complain that we're not supplying a string. I've corre...
Python
mit
kivy/plyer,kived/plyer,KeyWeeUsr/plyer,johnbolia/plyer,johnbolia/plyer,kivy/plyer,KeyWeeUsr/plyer,kived/plyer,KeyWeeUsr/plyer,kivy/plyer
--- +++ @@ -16,7 +16,11 @@ ioreg_process.stdout.close() output = grep_process.communicate()[0] - environ['LANG'] = old_lang + if old_lang is None: + environ.pop('LANG') + else: + environ['LANG'] = old_lang + if output: return outpu...
844e63b78df318e88fe9d262c7e0a09fcfef8c76
handroll/tests/test_configuration.py
handroll/tests/test_configuration.py
# Copyright (c) 2014, Matt Layman import inspect import tempfile import unittest from handroll import configuration class FakeArgs(object): def __init__(self): self.outdir = None self.timing = None class TestConfiguration(unittest.TestCase): def test_loads_from_outdir_argument(self): ...
# Copyright (c) 2014, Matt Layman import inspect import tempfile import unittest from handroll import configuration class FakeArgs(object): def __init__(self): self.outdir = None self.timing = None class TestConfiguration(unittest.TestCase): def test_loads_from_outdir_argument(self): ...
Delete a stray Python 2 print statement.
Delete a stray Python 2 print statement.
Python
bsd-2-clause
handroll/handroll
--- +++ @@ -29,7 +29,6 @@ conf_file = inspect.cleandoc( """[site] outdir = out""") - print conf_file args = FakeArgs() with tempfile.NamedTemporaryFile(delete=False) as f: f.write(conf_file)
076aa11e353440b0c61a763c4b1bb2e4b57b9a30
custom/enikshay/ucr/views.py
custom/enikshay/ucr/views.py
from __future__ import absolute_import from __future__ import division from datetime import datetime from django.db.models import Min from corehq.apps.userreports.models import AsyncIndicator from corehq.apps.userreports.reports.view import CustomConfigurableReport class MonitoredReport(CustomConfigurableReport): ...
from __future__ import absolute_import from __future__ import division from datetime import datetime from django.db.models import Min from corehq.apps.userreports.models import AsyncIndicator from corehq.apps.userreports.reports.view import CustomConfigurableReport class MonitoredReport(CustomConfigurableReport): ...
Use implicit ordering of AsyncIndicator model
Use implicit ordering of AsyncIndicator model
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
--- +++ @@ -28,13 +28,12 @@ """ now = datetime.utcnow() - oldest_indicator = ( - AsyncIndicator.objects - .filter(indicator_config_ids__contains=[self.spec.config_id]) - .aggregate(Min('date_created')) - ) - if oldest_indicator['date_created__m...
efcb8603251514286388427277a4ab4e22c9b0e5
main.py
main.py
#!/usr/bin/env python from generateSymbolTable import generate_default_symbol_table from scanner import scan_source_files from glob import glob filenames = ["symbolScanner.c"] filenames = glob("/Users/hortont/Desktop/particles/*.c") symbolTable = generate_default_symbol_table() (wantSymbols, haveSymbols) = scan_sour...
#!/usr/bin/env python from generateSymbolTable import generate_default_symbol_table, Library, Framework from scanner import scan_source_files from glob import glob filenames = ["symbolScanner.c"] filenames = glob("/Users/hortont/Desktop/particles/*.c") symbolTable = generate_default_symbol_table() (wantSymbols, have...
Choose one when there are multiple options, preferring (for now) System
Choose one when there are multiple options, preferring (for now) System
Python
bsd-2-clause
hortont424/guesscc,hortont424/guesscc
--- +++ @@ -1,6 +1,6 @@ #!/usr/bin/env python -from generateSymbolTable import generate_default_symbol_table +from generateSymbolTable import generate_default_symbol_table, Library, Framework from scanner import scan_source_files from glob import glob @@ -20,6 +20,15 @@ if len(libsContaining) == 0: ...
0ec6bebb4665185854ccf58c99229bae41ef74d4
pybtex/tests/bibtex_parser_test.py
pybtex/tests/bibtex_parser_test.py
from pybtex.database import BibliographyData from pybtex.core import Entry from pybtex.database.input.bibtex import Parser from cStringIO import StringIO test_data = [ ( ''' ''', BibliographyData(), ), ( '''@ARTICLE{ test, title={Polluted ...
from pybtex.database import BibliographyData from pybtex.core import Entry from pybtex.database.input.bibtex import Parser from cStringIO import StringIO test_data = [ ( ''' ''', BibliographyData(), ), ( '''@ARTICLE{ test, title={Polluted ...
Add a test for quoted strings with {"quotes"} in .bib files.
Add a test for quoted strings with {"quotes"} in .bib files.
Python
mit
live-clones/pybtex
--- +++ @@ -18,6 +18,13 @@ }''', BibliographyData({u'test': Entry('article', {u'title': 'Polluted with {DDT}.'})}), ), + ( + '''@ARTICLE{ + test, + title="Nested braces and {"quotes"}", + }''', + BibliographyData({u'test': Entry('article', ...
48f1d12f97be8a7bca60809967b88f77ba7d6393
setup.py
setup.py
from distutils.core import setup distobj = setup( name="Axiom", version="0.1", maintainer="Divmod, Inc.", maintainer_email="support@divmod.org", url="http://divmod.org/trac/wiki/AxiomProject", license="MIT", platforms=["any"], description="An in-process object-relational database", ...
from distutils.core import setup import axiom distobj = setup( name="Axiom", version=axiom.version.short(), maintainer="Divmod, Inc.", maintainer_email="support@divmod.org", url="http://divmod.org/trac/wiki/DivmodAxiom", license="MIT", platforms=["any"], description="An in-process obje...
Use new Epsilon versioned feature.
Use new Epsilon versioned feature.
Python
mit
twisted/axiom,hawkowl/axiom
--- +++ @@ -1,11 +1,13 @@ from distutils.core import setup + +import axiom distobj = setup( name="Axiom", - version="0.1", + version=axiom.version.short(), maintainer="Divmod, Inc.", maintainer_email="support@divmod.org", - url="http://divmod.org/trac/wiki/AxiomProject", + url="http://d...
88791b8ec57c5a19e6be6daccfd09b6cb53bdbe8
setup.py
setup.py
#!/usr/bin/env python import re from codecs import open try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'slugid', ] version = '' with open('slugid/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', ...
#!/usr/bin/env python import re from codecs import open try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'slugid', ] version = '' with open('slugid/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', ...
Add Homepage and Source project URLs for PyPI
Add Homepage and Source project URLs for PyPI
Python
mpl-2.0
taskcluster/slugid.py
--- +++ @@ -36,4 +36,9 @@ 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', ), + project_urls={ + 'Homepage': 'http://taskcluster.github.io/slugid.py', + 'Source': 'https://github.com/taskcluster/slugid.py', + }, + )
8ab509811887a3495a55951ece04c2e1e5af38eb
cass-prototype/reddit/models.py
cass-prototype/reddit/models.py
import uuid from cassandra.cqlengine import columns, models class Blog(models.Model): blog_id = columns.UUID(primary_key=True, default=uuid.uuid4) created_at = columns.DateTime() user = columns.Text(index=True) description = columns.Text(required=False)
""" In a real app, we should probably split all these models into separate apps. Since this is a prototype, we have it all here to more easily understand Resource: https://datastax.github.io/python-driver/cqlengine/models.html """ import uuid from cassandra.cqlengine import columns, models, usertype, ValidationError...
Add more Data Models with different Column types
Add more Data Models with different Column types
Python
mit
WilliamQLiu/django-cassandra-prototype,WilliamQLiu/django-cassandra-prototype
--- +++ @@ -1,9 +1,69 @@ +""" +In a real app, we should probably split all these models into separate apps. +Since this is a prototype, we have it all here to more easily understand + +Resource: https://datastax.github.io/python-driver/cqlengine/models.html + +""" + import uuid -from cassandra.cqlengine import colum...
0a88885f322f49c9f4cc990a3147f1ee162e8fe4
cellcounter/statistics/views.py
cellcounter/statistics/views.py
from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import BasePermission from rest_framework.throttling import AnonRateThrottle from .serializers import CountInstanceSerializer from .models import CountInstance SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class OpenPostStaffGet(BasePe...
from rest_framework import status from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import BasePermission from rest_framework.throttling import AnonRateThrottle from rest_framework.response import Response from .serializers import CountInstanceSerializer from .models import CountIns...
Update create() method of view to include extra data
Update create() method of view to include extra data
Python
mit
haematologic/cellcounter,cellcounter/cellcounter,haematologic/cellcounter,cellcounter/cellcounter,haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter
--- +++ @@ -1,6 +1,9 @@ +from rest_framework import status from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import BasePermission from rest_framework.throttling import AnonRateThrottle +from rest_framework.response import Response + from .serializers import CountInstanceSerial...
cfe6638194d477968689f3062af398630170fd80
foodsaving/conversations/serializers.py
foodsaving/conversations/serializers.py
from rest_framework import serializers from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model = Conversation fields = [ 'id', 'participants', 'created_at' ...
from rest_framework import serializers from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model = Conversation fields = [ 'id', 'participants', 'created_at' ...
Validate user is in conversation on create message
Validate user is in conversation on create message
Python
agpl-3.0
yunity/yunity-core,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/foodsaving-backend
--- +++ @@ -44,6 +44,11 @@ } } + def validate_conversation(self, conversation): + if self.context['request'].user not in conversation.participants.all(): + raise serializers.ValidationError("You are not in this conversation") + return conversation + def create(...
4f94e7bc314e31f322c912762339fda047d04688
src/gpio-shutdown.py
src/gpio-shutdown.py
#!/usr/bin/env python3 import RPIO import subprocess PIN_MODE = RPIO.BCM SHUTDOWN_BTN_PIN = 4 PIN_PULL = RPIO.PUD_DOWN EDGE_DETECT = 'rising' def main(): RPIO.setmode(PIN_MODE) RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL) RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN, ...
#!/usr/bin/env python3 import RPIO import subprocess import time PIN_MODE = RPIO.BCM SHUTDOWN_BTN_PIN = 4 PIN_PULL = RPIO.PUD_DOWN EDGE_DETECT = 'rising' def main(): RPIO.setmode(PIN_MODE) RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL) RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN, ...
Add sleeping spin-wait to listener script
Add sleeping spin-wait to listener script This will prevent the script from exiting, thus defeating the entire purpose of using a separate GPIO button to shutdown
Python
epl-1.0
MSOE-Supermileage/datacollector,MSOE-Supermileage/datacollector,MSOE-Supermileage/datacollector
--- +++ @@ -2,6 +2,7 @@ import RPIO import subprocess +import time PIN_MODE = RPIO.BCM SHUTDOWN_BTN_PIN = 4 @@ -25,3 +26,10 @@ if __name__ == '__main__': main() + + # do an efficient spin-lock here so that we can continue waiting for an + # interrupt + while True: + # this sleep() is a...
cf18a3141f6b9d618cd35adc2f574965fba29c92
tests/testcases.py
tests/testcases.py
from __future__ import unicode_literals from __future__ import absolute_import from fig.packages.docker import Client from fig.service import Service from fig.cli.utils import docker_url from . import unittest class DockerClientTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client ...
from __future__ import unicode_literals from __future__ import absolute_import from fig.packages.docker import Client from fig.service import Service from fig.cli.utils import docker_url from . import unittest class DockerClientTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client ...
Remove images created by tests
Remove images created by tests
Python
apache-2.0
anweiss/docker.github.io,ekristen/compose,dilgerma/compose,aduermael/docker.github.io,Yelp/docker-compose,bsmr-docker/compose,bfirsh/fig,jgrowl/compose,nerro/compose,londoncalling/docker.github.io,ChrisChinchilla/compose,shubheksha/docker.github.io,prologic/compose,shubheksha/docker.github.io,danix800/docker.github.io,...
--- +++ @@ -17,6 +17,9 @@ if c['Names'] and 'figtest' in c['Names'][0]: self.client.kill(c['Id']) self.client.remove_container(c['Id']) + for i in self.client.images(): + if 'figtest' in i['Tag']: + self.client.remove_image(i) def ...
e51087bf04f56ae79a8af8ae059a2dbe28fb1d74
src/oscar/core/decorators.py
src/oscar/core/decorators.py
try: from types import ClassType except ImportError: # Python 3 CHECK_TYPES = (type,) else: # Python 2: new and old-style classes CHECK_TYPES = (type, ClassType) import warnings def deprecated(obj): if isinstance(obj, CHECK_TYPES): return _deprecated_cls(cls=obj) else: retu...
try: from types import ClassType except ImportError: # Python 3 CHECK_TYPES = (type,) else: # Python 2: new and old-style classes CHECK_TYPES = (type, ClassType) import warnings from oscar.utils.deprecation import RemovedInOscar15Warning def deprecated(obj): if isinstance(obj, CHECK_TYPES): ...
Set RemovedInOscar15Warning for existing deprecation warnings
Set RemovedInOscar15Warning for existing deprecation warnings
Python
bsd-3-clause
solarissmoke/django-oscar,django-oscar/django-oscar,sonofatailor/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,sasha0/django-oscar,sasha0/django-oscar,sonofatailor/django-oscar,sasha0/django-oscar,django-oscar/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,sonofatailor/django-oscar,...
--- +++ @@ -7,6 +7,8 @@ # Python 2: new and old-style classes CHECK_TYPES = (type, ClassType) import warnings + +from oscar.utils.deprecation import RemovedInOscar15Warning def deprecated(obj): @@ -18,10 +20,11 @@ def _deprecated_func(f): def _deprecated(*args, **kwargs): - message = "M...
b42e271885968239c1779df546c57597437aa2da
src/test/test_all.py
src/test/test_all.py
from astral.geocoder import all_locations from astral.sun import sun def test_AllLocations(test_database): for location in all_locations(test_database): sun(location.observer)
from astral.geocoder import all_locations from astral.sun import noon def test_AllLocations(test_database): for location in all_locations(test_database): noon(location.observer)
Use the `noon` function instead of `sun`.
Use the `noon` function instead of `sun`. All we're doing is check that we can call the function for all locations. This can fail for `sun` but does not for `noon`
Python
apache-2.0
sffjunkie/astral,sffjunkie/astral
--- +++ @@ -1,6 +1,6 @@ from astral.geocoder import all_locations -from astral.sun import sun +from astral.sun import noon def test_AllLocations(test_database): for location in all_locations(test_database): - sun(location.observer) + noon(location.observer)
5fc503c05ed9eadfc831e0521a40b16a9810d8fa
plenum/__metadata__.py
plenum/__metadata__.py
""" plenum package metadata """ __version_info__ = (0, 1, 157) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" }
""" plenum package metadata """ __version_info__ = (0, 1, 158) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" }
Increase plenum version to 0.1.158
Increase plenum version to 0.1.158
Python
apache-2.0
evernym/plenum,evernym/zeno
--- +++ @@ -1,7 +1,7 @@ """ plenum package metadata """ -__version_info__ = (0, 1, 157) +__version_info__ = (0, 1, 158) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0"
864f10669895ac28f17167a2be84bcab7fd9e389
conf/jupyter_notebook_config.py
conf/jupyter_notebook_config.py
import os c.NotebookApp.ip = '*' c.MultiKernelManager.kernel_manager_class = 'lc_wrapper.LCWrapperKernelManager' c.KernelManager.shutdown_wait_time = 10.0 if 'PASSWORD' in os.environ: from notebook.auth import passwd c.NotebookApp.password = passwd(os.environ['PASSWORD']) del os.environ['PASSWORD']
import os c.NotebookApp.ip = '*' c.MultiKernelManager.kernel_manager_class = 'lc_wrapper.LCWrapperKernelManager' c.KernelManager.shutdown_wait_time = 10.0 c.FileContentsManager.delete_to_trash = False if 'PASSWORD' in os.environ: from notebook.auth import passwd c.NotebookApp.password = passwd(os.environ['PASS...
Disable delete_to_trash to prevent an error while deleting
Disable delete_to_trash to prevent an error while deleting
Python
bsd-3-clause
NII-cloud-operation/Jupyter-LC_docker,NII-cloud-operation/Jupyter-LC_docker
--- +++ @@ -2,9 +2,9 @@ c.NotebookApp.ip = '*' c.MultiKernelManager.kernel_manager_class = 'lc_wrapper.LCWrapperKernelManager' c.KernelManager.shutdown_wait_time = 10.0 +c.FileContentsManager.delete_to_trash = False if 'PASSWORD' in os.environ: from notebook.auth import passwd c.NotebookApp.password =...
5fc4af3039caec0f245e04e5a219451dfb73fb9c
distarray/localapi/tests/test_format.py
distarray/localapi/tests/test_format.py
# encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- im...
# encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- im...
Add a test for read_magic.
Add a test for read_magic.
Python
bsd-3-clause
enthought/distarray,enthought/distarray
--- +++ @@ -32,3 +32,16 @@ result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) + + +class TestReadMagic(unittest.TestCase): + + def test_read_magic(self): + prefix = six.b('\x93DARRY') + prefix_len = 8 + fp = six.BytesIO(six.b('\x9...
b75e3646ccd1b61868a47017f14f25960e52578c
bot/action/standard/info/action.py
bot/action/standard/info/action.py
from bot.action.core.action import Action from bot.action.standard.info.formatter.chat import ChatInfoFormatter from bot.action.standard.info.formatter.user import UserInfoFormatter class MeInfoAction(Action): def process(self, event): formatter = UserInfoFormatter(self.api, event.message.from_, event.cha...
from bot.action.core.action import Action from bot.action.standard.info.formatter.chat import ChatInfoFormatter from bot.action.standard.info.formatter.user import UserInfoFormatter class MeInfoAction(Action): def process(self, event): formatter = UserInfoFormatter(self.api, event.message.from_, event.cha...
Create UserInfoAction that shows the info of the user which the message replies to, or the current user if there is no reply
Create UserInfoAction that shows the info of the user which the message replies to, or the current user if there is no reply
Python
agpl-3.0
alvarogzp/telegram-bot,alvarogzp/telegram-bot
--- +++ @@ -11,6 +11,20 @@ self.api.send_message(response.build_message().to_chat_replying(event.message)) +class UserInfoAction(Action): + def process(self, event): + message = event.message + replied_message = message.reply_to_message + if replied_message is None: + u...
cd79c8054fc30525628046b34649572d297e13b1
pages/tests/__init__.py
pages/tests/__init__.py
"""Django page CMS test suite module""" import unittest from pages.tests.test_functionnal import FunctionnalTestCase from pages.tests.test_unit import UnitTestCase from pages.tests.test_regression import RegressionTestCase from pages.tests.test_pages_link import LinkTestCase from pages.tests.test_auto_render import Aut...
"""Django page CMS test suite module""" import unittest from pages.tests.test_functionnal import FunctionnalTestCase from pages.tests.test_unit import UnitTestCase from pages.tests.test_regression import RegressionTestCase #from pages.tests.test_pages_link import LinkTestCase from pages.tests.test_auto_render import Au...
Test fail because of an import
Test fail because of an import
Python
bsd-3-clause
batiste/django-page-cms,remik/django-page-cms,remik/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,pombredanne/django-page-cms-1,akaihola/django-page-cms,akaihola/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,batiste/django-page...
--- +++ @@ -3,7 +3,7 @@ from pages.tests.test_functionnal import FunctionnalTestCase from pages.tests.test_unit import UnitTestCase from pages.tests.test_regression import RegressionTestCase -from pages.tests.test_pages_link import LinkTestCase +#from pages.tests.test_pages_link import LinkTestCase from pages.tes...
a0f030cd03d28d97924a3277722d7a51cf3a3e92
cms/test_utils/project/extensionapp/models.py
cms/test_utils/project/extensionapp/models.py
# -*- coding: utf-8 -*- from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyPageExtension) ...
# -*- coding: utf-8 -*- from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.contrib.auth.models import User from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) ...
Update extension app to include a M2M
Update extension app to include a M2M
Python
bsd-3-clause
kk9599/django-cms,jrclaramunt/django-cms,farhaadila/django-cms,FinalAngel/django-cms,leture/django-cms,yakky/django-cms,wuzhihui1123/django-cms,czpython/django-cms,jproffitt/django-cms,astagi/django-cms,DylannCordel/django-cms,evildmp/django-cms,jrclaramunt/django-cms,SachaMPS/django-cms,netzkolchose/django-cms,donce/d...
--- +++ @@ -1,11 +1,18 @@ # -*- coding: utf-8 -*- from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool +from django.contrib.auth.models import User from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blan...
f0d3ef7e6b98aa37f14a077a922e39121b7ab6a4
sipa.py
sipa.py
# -*- coding: utf-8 -*- """ sipa.py ~~~~~~~~~~~~~~ This file shall be used to start the Flask app. Specific things are handled in the `sipa` package. """ from sipa import app, logger from sipa.base import init_app init_app(app) logger.info('Starting sipa...') logger.warning('Running in Debug mode')...
# -*- coding: utf-8 -*- """ sipa.py ~~~~~~~~~~~~~~ This file shall be used to start the Flask app. Specific things are handled in the `sipa` package. """ import argparse from sipa import app, logger from sipa.base import init_app init_app(app) if __name__ == "__main__": parser = argparse.Argum...
Use argparse to enable some options
Use argparse to enable some options Fix #51 Now, `--debug`, `--port/-p` and `--exposed` are available. Note that most probably you will have to add `--exposed` to the command you use if you run sipa directly in something like a docker container.
Python
mit
MarauderXtreme/sipa,lukasjuhrich/sipa,agdsn/sipa,fgrsnau/sipa,fgrsnau/sipa,fgrsnau/sipa,agdsn/sipa,lukasjuhrich/sipa,MarauderXtreme/sipa,agdsn/sipa,lukasjuhrich/sipa,MarauderXtreme/sipa,agdsn/sipa,lukasjuhrich/sipa
--- +++ @@ -8,13 +8,25 @@ """ +import argparse from sipa import app, logger from sipa.base import init_app init_app(app) -logger.info('Starting sipa...') -logger.warning('Running in Debug mode') if __name__ == "__main__": - app.run(debug=True, host="0.0.0.0") + parser = argparse.ArgumentParser(de...
f14e3dfe844203946a33b9b3329e569d7114d7d6
demo.py
demo.py
#!/usr/bin/env python3 from flask import Flask, redirect, request from resumable import rebuild, split app = Flask(__name__) # for the purposes of this demo, we will explicitly pass request # and response (this is not needed in flask) @rebuild def controller(request): page = ''' <meta name="viewport" conte...
#!/usr/bin/env python3 from flask import Flask, redirect, request from resumable import rebuild, split app = Flask(__name__) # for the purposes of this demo, we will explicitly pass request # and response (this is not needed in flask) @rebuild def controller(_): page = ''' <meta name="viewport" content="wi...
Rename unused but needed variable
Rename unused but needed variable
Python
mit
Mause/resumable
--- +++ @@ -10,7 +10,7 @@ # for the purposes of this demo, we will explicitly pass request # and response (this is not needed in flask) @rebuild -def controller(request): +def controller(_): page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action...
eef768a538c82629073b360618d8b39bcbf4c474
tests/dojo_test.py
tests/dojo_test.py
import unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_...
import unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_...
Implement test for duplicate rooms
Implement test for duplicate rooms
Python
mit
EdwinKato/Space-Allocator,EdwinKato/Space-Allocator
--- +++ @@ -24,4 +24,8 @@ self.assertEqual(new_room_count - initial_room_count, 3) def test_addition_of_duplicate_room_names(self): - pass + initial_room_count = len(self.dojo.all_people) + room1 = self.dojo.create_room("office", "Blue") + room1 = self.dojo.create_room("off...
4e4ff0e235600b1b06bf607004538bd5ff6e5d30
listener.py
listener.py
import asynchat import asyncore import socket class Handler(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): s...
import asynchat import asyncore import socket class Reciver(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): s...
Fix naming of Handler to Reciever
Fix naming of Handler to Reciever
Python
mit
adamcik/pycat,adamcik/pycat
--- +++ @@ -2,7 +2,7 @@ import asyncore import socket -class Handler(asynchat.async_chat): +class Reciver(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) @@ -32,7 +32,7 @@ self.listen(5) def handle_accept(self): - Hand...
eeb23b7fde3f728355efcc446912b7c8357c0c08
util.py
util.py
def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, cols): l ...
import sys def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, c...
Use sys in error cases.
Use sys in error cases.
Python
mit
lightcrest/kahu-api-demo
--- +++ @@ -1,3 +1,5 @@ +import sys + def format_cols(cols): widths = [0] * len(cols[0])
0c6babde080f14c09d4a93d3a6138c36728c4651
contrib/dns_dump_hex_to_text.py
contrib/dns_dump_hex_to_text.py
#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.com> # # 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...
#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.com> # # 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...
Remove white space between print and ()
Remove white space between print and () TrivialFix Change-Id: I5219e319e9d7e5cc8307e45c60e1e2d2d25d9d5c
Python
apache-2.0
openstack/designate,openstack/designate,openstack/designate
--- +++ @@ -25,4 +25,4 @@ unhexed = binascii.unhexlify(sys.argv[1]) response = dns.message.from_wire(unhexed) -print (response.to_text()) +print(response.to_text())
78bebaa2902636e33409591675b1bede6c359aad
telepyth/__init__.py
telepyth/__init__.py
# encoding: utf8 # __init__.py from telepyth.client import TelePythClient from telepyth.utils import is_interactive if is_interactive(): from telepyth.magics import TelePythMagics
# encoding: utf8 # __init__.py from telepyth.client import TelePythClient from telepyth.utils import is_interactive TelepythClient = TelePythClient # make alias to origin definition if is_interactive(): from telepyth.magics import TelePythMagics
Add alias to TelePythClient which will be deprecated in the future.
Add alias to TelePythClient which will be deprecated in the future.
Python
mit
daskol/telepyth,daskol/telepyth
--- +++ @@ -4,5 +4,8 @@ from telepyth.client import TelePythClient from telepyth.utils import is_interactive + +TelepythClient = TelePythClient # make alias to origin definition + if is_interactive(): from telepyth.magics import TelePythMagics
fd4c62b157cfb4f5814e01640cd5d29837092cfc
pronto/parsers/base.py
pronto/parsers/base.py
import abc import os import typing import urllib.parse if typing.TYPE_CHECKING: from ..ontology import Ontology class BaseParser(abc.ABC): def __init__(self, ont: 'Ontology'): self.ont = ont @classmethod @abc.abstractmethod def can_parse(cls, path: str, buffer: bytes): """Return...
import abc import os import typing import urllib.parse if typing.TYPE_CHECKING: from ..ontology import Ontology class BaseParser(abc.ABC): def __init__(self, ont: 'Ontology'): self.ont = ont @classmethod @abc.abstractmethod def can_parse(cls, path: str, buffer: bytes): """Return...
Improve local import detection in `BaseParser.process_imports`
Improve local import detection in `BaseParser.process_imports`
Python
mit
althonos/pronto
--- +++ @@ -24,17 +24,24 @@ return NotImplemented def process_imports(self): + + basepath = os.path.dirname(self.ont.path or "") + if self.ont.import_depth != 0: for ref in self.ont.metadata.imports: s = urllib.parse.urlparse(ref).scheme i...
f78be67a4efec7f343f51418410e9d73b358df19
tatooine.py
tatooine.py
from flask import Flask import consul import socket import pprint import redis # Consul key CONSUL_REDIS_KEY = "redis" app = Flask(__name__) def GetRedisFromConsul(): MyConsul = consul.Consul(host='172.17.42.1', port=8500) Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY) pprint.pprint(C...
from flask import Flask import consul import socket import pprint import redis # Consul key CONSUL_REDIS_KEY = "redis" app = Flask(__name__) def GetRedisFromConsul(): MyConsul = consul.Consul(host='172.17.42.1', port=8500) Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY) pprint.pprint(C...
Convert binary string to UTF-8
Convert binary string to UTF-8
Python
mit
skale-5/tatooine
--- +++ @@ -16,8 +16,8 @@ pprint.pprint(ConsulRetObj) - ServiceAddress = ConsulRetObj[0]['Address'] - ServicePort = ConsulRetObj[0]['ServicePort'] + ServiceAddress = ConsulRetObj[0]['Address'].decode("utf-8") + ServicePort = ConsulRetObj[0]['ServicePort'].decode("utf-8") return Servi...
5b554752aaabd59b8248f9eecfc03458dd9f07d0
coding/admin.py
coding/admin.py
from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("...
from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("...
Add date drill down to coding assignment activity list
Add date drill down to coding assignment activity list
Python
mit
inducer/codery,inducer/codery
--- +++ @@ -40,4 +40,6 @@ list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") + date_hierarchy = "action_time" + admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
72e5b32a0306ad608b32eaaa4817b0e5b5ef3c8d
project/asylum/utils.py
project/asylum/utils.py
# -*- coding: utf-8 -*- import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: return None if not setting_value:...
# -*- coding: utf-8 -*- import calendar import datetime import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: retur...
Add helper for iterating over months and move date proxy here
Add helper for iterating over months and move date proxy here the proxy is now needed by two commands
Python
mit
rambo/asylum,hacklab-fi/asylum,HelsinkiHacklab/asylum,jautero/asylum,hacklab-fi/asylum,rambo/asylum,HelsinkiHacklab/asylum,jautero/asylum,rambo/asylum,hacklab-fi/asylum,hacklab-fi/asylum,jautero/asylum,rambo/asylum,jautero/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum
--- +++ @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +import calendar +import datetime import importlib import random @@ -26,3 +28,19 @@ random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret + + +# Adapted from http://www.ianlewis.org/en/python-dat...
18c3ec079b5e805f6d0115df55076707bcef48c6
pyconde/core/models.py
pyconde/core/models.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals try: # register a signal do update permissions every migration. # This is based on app django_extensions update_permissions command from south.signals import post_migrate def update_permissions_after_migration(app,**kwargs): """ ...
Add South post_migrate signal to work with permission changes
Add South post_migrate signal to work with permission changes
Python
bsd-3-clause
EuroPython/djep,EuroPython/djep,pysv/djep,pysv/djep,EuroPython/djep,pysv/djep,EuroPython/djep,pysv/djep,pysv/djep
--- +++ @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + + +try: + # register a signal do update permissions every migration. + # This is based on app django_extensions update_permissions command + from south.signals import post_migrate + + def update_permissions_after_...
c7d56731125bf7a67d10304ae7be47d333f1165b
akllt/common/templatetags/aklltcommontags.py
akllt/common/templatetags/aklltcommontags.py
from django import template from django.utils.safestring import mark_safe from akllt.common import formrenderer register = template.Library() # pylint: disable=invalid-name @register.simple_tag(name='formrenderer', takes_context=True) def formrenderer_filter(context, form): return mark_safe(formrenderer.render_...
from django import template from django.utils.safestring import mark_safe from akllt.common import formrenderer register = template.Library() # pylint: disable=invalid-name @register.simple_tag(name='formrenderer', takes_context=True) def formrenderer_filter(context, form): return mark_safe(formrenderer.render...
Add additional space before inline comment.
Add additional space before inline comment.
Python
agpl-3.0
python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt
--- +++ @@ -3,7 +3,7 @@ from akllt.common import formrenderer -register = template.Library() # pylint: disable=invalid-name +register = template.Library() # pylint: disable=invalid-name @register.simple_tag(name='formrenderer', takes_context=True)
5af9f2cd214f12e2d16b696a0c62856e389b1397
test/test_doc.py
test/test_doc.py
import types from mpi4py import MPI import mpiunittest as unittest ModuleType = type(MPI) ClassType = type(MPI.Comm) FunctionType = type(MPI.Init) MethodDescrType = type(MPI.Comm.Get_rank) GetSetDescrType = type(MPI.Comm.rank) def getdocstr(mc, docstrings): if type(mc) in (ModuleType, ClassType): name = g...
import types from mpi4py import MPI import mpiunittest as unittest ModuleType = type(MPI) ClassType = type(MPI.Comm) FunctionType = type(MPI.Init) MethodDescrType = type(MPI.Comm.Get_rank) GetSetDescrType = type(MPI.Comm.rank) def getdocstr(mc, docstrings, namespace=None): name = getattr(mc, '__name__', None) ...
Improve test script, report namespaces for stuff missing docstrings
Improve test script, report namespaces for stuff missing docstrings
Python
bsd-2-clause
pressel/mpi4py,pressel/mpi4py,pressel/mpi4py,mpi4py/mpi4py,pressel/mpi4py,mpi4py/mpi4py,mpi4py/mpi4py
--- +++ @@ -8,17 +8,18 @@ MethodDescrType = type(MPI.Comm.Get_rank) GetSetDescrType = type(MPI.Comm.rank) -def getdocstr(mc, docstrings): +def getdocstr(mc, docstrings, namespace=None): + name = getattr(mc, '__name__', None) + if name is None: return + if name in ('__builtin__', 'builtins'): return + ...
07d113e4604994bf1857b3ae7201571776b65154
etl/make_feature_tsv.py
etl/make_feature_tsv.py
# Graciously adopted from https://github.com/ucscXena/xenaH5 # # Generates a tsv compatible for making a create table statement from a # 10xgenomics HDF5 file. # # Usage # # python maketsv.py fname 0 # # Will generate a tsv file with the 0th slice of the h5 file named # `out0.tsv`. import string, sys import h5py impor...
# Graciously adopted from https://github.com/ucscXena/xenaH5 # # Generates a tsv compatible for making a create table statement from a # 10xgenomics HDF5 file. # # Usage # # python maketsv.py fname 0 # # Will generate a tsv file with the 0th slice of the h5 file named # `out0.tsv`. import string, sys import h5py impor...
Make a tsv instead of a long string
Make a tsv instead of a long string
Python
apache-2.0
david4096/celldb
--- +++ @@ -29,6 +29,6 @@ counter_indptr_size = rowN fout = open("features.tsv",'w') - +fout.write("index\tfeature\tfeature_name\n") for i in range (0, len(genes)): - fout.write("{} {} {}".format(i, genes[i], gene_names[i])) + fout.write("{}\t{}\t{}\n".format(i, genes[i], gene_names[i]))
8d05eddbdc6005a649d848a1cfa68afe7bda7f47
filer/__init__.py
filer/__init__.py
#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.50' # pragma: nocover
#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.51' # pragma: nocover
Remove "cmp" occurences improve folder and file names listing
Remove "cmp" occurences improve folder and file names listing
Python
bsd-3-clause
pbs/django-filer,pbs/django-filer,pbs/django-filer,pbs/django-filer,pbs/django-filer
--- +++ @@ -1,3 +1,3 @@ #-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 -__version__ = '0.9pbs.50' # pragma: nocover +__version__ = '0.9pbs.51' # pragma: nocover
37d7656019d11b3b05d59f184d72e1dd6d4ccaf7
contones/srs.py
contones/srs.py
"""Spatial reference systems""" from osgeo import osr class BaseSpatialReference(osr.SpatialReference): """Base class for extending osr.SpatialReference.""" def __repr__(self): return self.wkt @property def srid(self): """Returns the EPSG ID as int if it exists.""" epsg_id = ...
"""Spatial reference systems""" __all__ = ['SpatialReference'] from osgeo import osr class BaseSpatialReference(osr.SpatialReference): """Base class for extending osr.SpatialReference.""" def __repr__(self): return self.wkt def __eq__(self, another): return bool(self.IsSame(another)) ...
Add equality methods to SpatialReference
Add equality methods to SpatialReference
Python
bsd-3-clause
bkg/greenwich
--- +++ @@ -1,4 +1,6 @@ """Spatial reference systems""" +__all__ = ['SpatialReference'] + from osgeo import osr @@ -7,6 +9,12 @@ def __repr__(self): return self.wkt + + def __eq__(self, another): + return bool(self.IsSame(another)) + + def __ne__(self, another): + return not ...
d52d26b45e20d0ae7b6b4fb5ffd3c29cdf7257ba
PCbuild8/rmpyc.py
PCbuild8/rmpyc.py
# Remove all the .pyc and .pyo files under ../Lib. import sys def deltree(root): import os from os.path import join npyc = npyo = 0 for root, dirs, files in os.walk(root): for name in files: delete = False if name.endswith('.pyc'): delete = True ...
# Remove all the .pyc and .pyo files under ../Lib. import sys def deltree(root): import os from os.path import join npyc = npyo = 0 for root, dirs, files in os.walk(root): for name in files: delete = False if name.endswith('.pyc'): delete = True ...
Use new print function (part of patch 1031)
Use new print function (part of patch 1031)
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -27,4 +27,4 @@ path = sys.argv[1] npyc, npyo = deltree(path) -print npyc, ".pyc deleted,", npyo, ".pyo deleted" +print(npyc, ".pyc deleted,", npyo, ".pyo deleted")
9a5b0f08dfc6fe74965e1576697697a71ece4934
dit/utils/tests/test_context.py
dit/utils/tests/test_context.py
from __future__ import unicode_literals from nose.tools import * import os import time from dit.utils import cd, named_tempfile, tempdir def test_cd(): with cd('/'): assert_equal(os.getcwd(), '/') def test_named_tempfile(): name = None with named_tempfile() as tempfile: name = tempfile.na...
from __future__ import unicode_literals from nose.tools import * import os import time from dit.utils import cd, named_tempfile, tempdir def test_cd(): with cd('/'): assert_equal(os.getcwd(), '/') def test_named_tempfile1(): name = None with named_tempfile() as tempfile: name = tempfile.n...
Add test to verify that named_tempfile() overrides the `delete` parameter.
Add test to verify that named_tempfile() overrides the `delete` parameter.
Python
bsd-3-clause
dit/dit,chebee7i/dit,dit/dit,dit/dit,chebee7i/dit,Autoplectic/dit,Autoplectic/dit,dit/dit,chebee7i/dit,Autoplectic/dit,Autoplectic/dit,chebee7i/dit,Autoplectic/dit,dit/dit
--- +++ @@ -9,7 +9,7 @@ with cd('/'): assert_equal(os.getcwd(), '/') -def test_named_tempfile(): +def test_named_tempfile1(): name = None with named_tempfile() as tempfile: name = tempfile.name @@ -19,6 +19,18 @@ assert_true(os.path.isfile(name)) assert_false(os.path.i...
366d7abd63d3f70ad206336a0278a0968b04b678
panoptes_aggregation/extractors/poly_line_text_extractor.py
panoptes_aggregation/extractors/poly_line_text_extractor.py
from collections import OrderedDict def classification_to_extract(classification): extract = OrderedDict([ ('points', OrderedDict([('x', []), ('y', [])])), ('text', []), ('frame', []) ]) annotation = classification['annotations'][0] for value in annotation['value']: tex...
from collections import OrderedDict def classification_to_extract(classification): extract = OrderedDict([ ('points', OrderedDict([('x', []), ('y', [])])), ('text', []), ('frame', []) ]) annotation = classification['annotations'][0] for value in annotation['value']: tex...
Add clarification comment to extractor
Add clarification comment to extractor Add a comment about the behavior of the extractor when the length of the `words` list does not match the lenght of the `points` list. The extract will only contain the *shorter* of the two lists and assume they match from the front.
Python
apache-2.0
CKrawczyk/python-reducers-for-caesar
--- +++ @@ -11,6 +11,9 @@ for value in annotation['value']: text = value['details'][0]['value'] words = text.split(' ') + # NOTE: if `words` and `points` are differnt lengths + # the extract will only contain the *shorter* of the + # two lists (assuming they match from the ...
94e70a0958f0db737ca82c5ea09528bf4e5e4fef
voteswap/wsgi.py
voteswap/wsgi.py
""" WSGI config for voteswap project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETT...
""" WSGI config for voteswap project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETT...
Add vendor dir to path
Add vendor dir to path
Python
mit
sbuss/voteswap,sbuss/voteswap,sbuss/voteswap,sbuss/voteswap
--- +++ @@ -14,3 +14,9 @@ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "voteswap.settings") application = get_wsgi_application() + +try: + from google.appengine.ext import vendor + vendor.add('lib') +except ImportError: + pass
1fde16891508179e5f3774d4624b9a0b48c39903
script/jsonify-book.py
script/jsonify-book.py
import sys from glob import glob from os.path import basename import json book_dir, out_dir = sys.argv[1:3] files = [basename(x).rstrip(".xhtml") for x in glob(f"{book_dir}/*.xhtml")] json_data = {} for path in files: with open(f"{book_dir}/{path}-metadata.json", "r") as meta_part: json_data = json.load...
import sys from glob import glob from os.path import basename import json book_dir, out_dir = sys.argv[1:3] files = [basename(x).rstrip(".xhtml") for x in glob(f"{book_dir}/*.xhtml")] json_data = {} for path in files: with open(f"{book_dir}/{path}.json", "r") as meta_part: json_data = json.load(meta_par...
Remove metadata from jsonify output name
Remove metadata from jsonify output name
Python
lgpl-2.1
Connexions/cnx-rulesets,Connexions/cnx-recipes,Connexions/cnx-recipes,Connexions/cnx-rulesets,Connexions/cnx-rulesets,Connexions/cnx-recipes,Connexions/cte,Connexions/cte,Connexions/cnx-recipes,Connexions/cnx-rulesets,Connexions/cnx-recipes
--- +++ @@ -10,12 +10,12 @@ json_data = {} for path in files: - with open(f"{book_dir}/{path}-metadata.json", "r") as meta_part: + with open(f"{book_dir}/{path}.json", "r") as meta_part: json_data = json.load(meta_part) with open(f"{book_dir}/{path}.xhtml", "r") as book_part: conten...
0c0190c9505197bd8e9671580bd6aa776bc8b04a
utils/get_message.py
utils/get_message.py
import amqp from contextlib import closing def __get_channel(connection): return connection.channel() def __get_message_from_queue(channel, queue): return channel.basic_get(queue=queue) def get_message(queue): """ Get the first message from a queue. The first message from a queue is retrieved. If t...
import amqp from contextlib import closing def get_message(queue): """ Get the first message from a queue. The first message from a queue is retrieved. If there is no such message, the function exits quietly. :param queue: The name of the queue from which to get the message. Usage:: >>> from ...
Revert "Revert "Remove redundant functions (one too many levels of abstraction)@""
Revert "Revert "Remove redundant functions (one too many levels of abstraction)@"" This reverts commit 34fda0b20a87b94d7413054bfcfc81dad0ecde19.
Python
mit
jdgillespie91/trackerSpend,jdgillespie91/trackerSpend
--- +++ @@ -1,12 +1,6 @@ import amqp from contextlib import closing - -def __get_channel(connection): - return connection.channel() - -def __get_message_from_queue(channel, queue): - return channel.basic_get(queue=queue) def get_message(queue): """ Get the first message from a queue. @@ -22,5 +16,5 ...
f6154cceaeb9d9be718df8f21153b09052bd597c
stix/ttp/victim_targeting.py
stix/ttp/victim_targeting.py
# Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. # external from cybox.core import Observables # internal import stix import stix.bindings.ttp as ttp_binding from stix.common import vocabs, VocabString from stix.common.identity import Identity, IdentityFactory fr...
# Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. # external from cybox.core import Observables # internal import stix import stix.bindings.ttp as ttp_binding from stix.common import vocabs from stix.common.identity import Identity, IdentityFactory from mixbox imp...
Add 'targeted_technical_details' TypedField to VictimTargeting
Add 'targeted_technical_details' TypedField to VictimTargeting
Python
bsd-3-clause
STIXProject/python-stix
--- +++ @@ -7,7 +7,7 @@ # internal import stix import stix.bindings.ttp as ttp_binding -from stix.common import vocabs, VocabString +from stix.common import vocabs from stix.common.identity import Identity, IdentityFactory from mixbox import fields @@ -21,6 +21,7 @@ targeted_systems = vocabs.VocabField(...
e9f3efcc1d9a3372e97e396160ea2ecbdee778c6
rfmodbuslib/__init__.py
rfmodbuslib/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2015 Legrand Group # # 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 # # Unl...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2015 Legrand Group # # 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 # # Unl...
Add a .__version__ attribute to package
Add a .__version__ attribute to package
Python
apache-2.0
Legrandgroup/robotframework-modbuslibrary
--- +++ @@ -19,3 +19,5 @@ __lib_version__ = '0.1' + __append_version__ __lib_name__ = 'rfmodbuslib' __lib_copyright__ = 'Copyright 2015 Legrand Group' + +__version__ = __lib_version__
25213d331b879a7203ccd99ccf34ad19661d1853
sublimelinter/modules/php.py
sublimelinter/modules/php.py
# -*- coding: utf-8 -*- # php.py - sublimelint package for checking php files import re from base_linter import BaseLinter CONFIG = { 'language': 'php', 'executable': 'php', 'lint_args': ('-l', '-d display_errors=On') } class Linter(BaseLinter): def parse_errors(self, view, errors, lines, errorUnde...
# -*- coding: utf-8 -*- # php.py - sublimelint package for checking php files import re from base_linter import BaseLinter CONFIG = { 'language': 'php', 'executable': 'php', 'lint_args': ('-l', '-d display_errors=On') } class Linter(BaseLinter): def parse_errors(self, view, errors, lines, errorUnde...
Remove "Parse error, " from error messages
Remove "Parse error, " from error messages
Python
mit
uschmidt83/SublimeLinter-for-ST2,benesch/sublime-linter,tangledhelix/SublimeLinter-for-ST2,tangledhelix/SublimeLinter-for-ST2,SublimeLinter/SublimeLinter-for-ST2,biodamasceno/SublimeLinter-for-ST2,SublimeLinter/SublimeLinter-for-ST2,uschmidt83/SublimeLinter-for-ST2,benesch/sublime-linter,biodamasceno/SublimeLinter-for-...
--- +++ @@ -15,7 +15,7 @@ class Linter(BaseLinter): def parse_errors(self, view, errors, lines, errorUnderlines, violationUnderlines, warningUnderlines, errorMessages, violationMessages, warningMessages): for line in errors.splitlines(): - match = re.match(r'^Parse error:\s*(?:syntax error,\...
388d8413f0df3cb6069cf393e033b3d23f4b63c7
features/environment.py
features/environment.py
from behave import * import server def before_all(context): context.app = server.app.test_client() server.initialize_mysql(test=True) server.initialize_index() context.server = server
from behave import * import server def before_all(context): context.app = server.app.test_client() server.initialize_mysql(test=True) context.server = server
Remove troublesome function from behave's environ.
Remove troublesome function from behave's environ.
Python
apache-2.0
nyu-delta-squad-s17/recommendation-service
--- +++ @@ -5,5 +5,4 @@ def before_all(context): context.app = server.app.test_client() server.initialize_mysql(test=True) - server.initialize_index() context.server = server
2f063f6dd9d10dabd967554bfcf7f6a63c979911
OpenSearchInNewTab.py
OpenSearchInNewTab.py
import sublime_plugin DEFAULT_NAME = 'Find Results' ALT_NAME = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): self.appl...
import sublime_plugin from threading import Timer DEFAULT_NAME = 'Find Results' ALT_NAME = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(...
Make plugin more stable by introducing async renaming to alternative name
Make plugin more stable by introducing async renaming to alternative name
Python
mit
everyonesdesign/OpenSearchInNewTab
--- +++ @@ -1,4 +1,5 @@ import sublime_plugin +from threading import Timer DEFAULT_NAME = 'Find Results' ALT_NAME = 'Find Results ' @@ -17,7 +18,7 @@ # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): - ...
e5f4627845a6874aa983d2d8ea02d5bea0fab8e2
meetings/osf_oauth2_adapter/provider.py
meetings/osf_oauth2_adapter/provider.py
from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word...
from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word...
Change username to osf uid
Change username to osf uid
Python
apache-2.0
jnayak1/osf-meetings,leodomingo/osf-meetings,jnayak1/osf-meetings,leodomingo/osf-meetings,jnayak1/osf-meetings,jnayak1/osf-meetings,leodomingo/osf-meetings,leodomingo/osf-meetings
--- +++ @@ -33,7 +33,7 @@ return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now - username=data.get('id'), + username=self.extract_uid(data), first_name=attributes.get('given_...
1473af1b50da6390e1b4475ae63d5a28f712e791
tests/test_frijoles.py
tests/test_frijoles.py
import unittest from frijoles import app class TamalesAPITestCase(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_basic(self): res = self.app.get('/api/v1/') self.assertEqual(res.status_code, 200)
import unittest from frijoles import app class FrijolesAPITestCase(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_basic(self): res = self.app.get('/api/v1/') self.assertEqual(res.status_code, 200)
Fix wrong test case name
Fix wrong test case name
Python
agpl-3.0
Antojitos/frijoles
--- +++ @@ -2,7 +2,7 @@ from frijoles import app -class TamalesAPITestCase(unittest.TestCase): +class FrijolesAPITestCase(unittest.TestCase): def setUp(self): self.app = app.test_client()
fbc5e2d52549452c2adbe58644358cf3c4eeb526
testsuite/test_util.py
testsuite/test_util.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest import pep8 class UtilTestCase(unittest.TestCase): def test_normalize_paths(self): cwd = os.getcwd() self.assertEquals(pep8.normalize_paths(''), []) self.assertEquals(pep8.normalize_paths(['foo']), ['foo']) s...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest import pep8 class UtilTestCase(unittest.TestCase): def test_normalize_paths(self): cwd = os.getcwd() self.assertEquals(pep8.normalize_paths(''), []) self.assertEquals(pep8.normalize_paths([]), []) self.assert...
Add a few more cases of "not value"
Add a few more cases of "not value"
Python
mit
ojengwa/pep8,pedros/pep8,asandyz/pep8,jayvdb/pep8,doismellburning/pep8,pandeesh/pep8,jayvdb/pep8,PyCQA/pep8,ABaldwinHunter/pep8,codeclimate/pep8,ABaldwinHunter/pep8-clone-classic,zevnux/pep8,MeteorAdminz/pep8
--- +++ @@ -11,9 +11,12 @@ cwd = os.getcwd() self.assertEquals(pep8.normalize_paths(''), []) + self.assertEquals(pep8.normalize_paths([]), []) + self.assertEquals(pep8.normalize_paths(None), []) self.assertEquals(pep8.normalize_paths(['foo']), ['foo']) self.assertEq...
03f74920a56afcbc4dbdb0370c3fab84a27bc299
openacademy/model/openacademy_course.py
openacademy/model/openacademy_course.py
from openerp import models, fields, api ''' This module is to create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name rec ...
from openerp import api, fields, models ''' This module is to create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name rec ...
Modify copy method into inherit
[REF] openacademy: Modify copy method into inherit
Python
apache-2.0
glizek/openacademy-project
--- +++ @@ -1,4 +1,4 @@ -from openerp import models, fields, api +from openerp import api, fields, models ''' This module is to create model of Course @@ -27,3 +27,19 @@ "The course title must be unique"), ] + @api.one # api.one send defaults params: cr, uid, id, context + def copy(self, ...
c775df0af114a332077771609d4b24a04bd6bfd2
bin/parsers/DeploysServiceLookup.py
bin/parsers/DeploysServiceLookup.py
if alert['resource'].startswith('R1'): alert['service'] = [ 'R1' ] elif alert['resource'].startswith('R2'): alert['service'] = [ 'R2' ] elif 'content-api' in alert['resource'].lower(): alert['service'] = [ 'ContentAPI' ] elif alert['resource'].startswith('frontend'): alert['service'] = [ 'Frontend' ] ...
if alert['resource'].startswith('R1'): alert['service'] = [ 'R1' ] elif alert['resource'].startswith('R2'): alert['service'] = [ 'R2' ] elif 'content-api' in alert['resource'].lower(): alert['service'] = [ 'ContentAPI' ] elif alert['resource'].startswith('frontend'): alert['service'] = [ 'Frontend' ] ...
Add email tag to fronted deploy failures
Add email tag to fronted deploy failures
Python
apache-2.0
skob/alerta,mrkeng/alerta,0312birdzhang/alerta,skob/alerta,mrkeng/alerta,0312birdzhang/alerta,skob/alerta,0312birdzhang/alerta,mrkeng/alerta,guardian/alerta,guardian/alerta,guardian/alerta,guardian/alerta,skob/alerta,mrkeng/alerta
--- +++ @@ -9,6 +9,7 @@ alert['service'] = [ 'Frontend' ] if alert['event'] == 'DeployFailed': alert['severity'] = 'CRITICAL' + alert['tags'].append('email:frontend') elif 'flexible' in alert['resource'].lower(): alert['service'] = [ 'FlexibleContent' ] elif alert['resource'].startswi...
b7bafa86cf6e2f568e99335fa6aeb6d8f3509170
dont_tread_on_memes/__init__.py
dont_tread_on_memes/__init__.py
#!python3 import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): ""...
#!python3 import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): ""...
Allow passing arguments through dont_me to tread_on
Allow passing arguments through dont_me to tread_on
Python
mit
controversial/dont-tread-on-memes
--- +++ @@ -25,6 +25,6 @@ return flag -def dont_me(phrase): +def dont_me(phrase, *args, **kwargs): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ - return tread_on("don't {} me".format(phrase)) + return tread_on("don't {} me".format(phrase), *args, **kwargs)
3ff4aef8d130cdcbf149328d93337fa984a9a94b
dont_tread_on_memes/__main__.py
dont_tread_on_memes/__main__.py
import dont_tread_on_memes import click @click.command() @click.option("--message", prompt="Don't _____ me: ", help=("The word or phrase to substitute for 'tread' in 'don't " "tread on me'")) def tread(message): dont_tread_on_memes.tread_on(message).show() if __name__ == "__mai...
import dont_tread_on_memes import click @click.command() @click.option("--message", prompt="Don't _____ me: ", help=("The word or phrase to substitute for 'tread' in 'don't " "tread on me'")) @click.option("--save", default=None, help="Where to save the image") def tread(message, sav...
Allow saving via --save CLI parameter
Allow saving via --save CLI parameter
Python
mit
controversial/dont-tread-on-memes
--- +++ @@ -6,8 +6,13 @@ @click.option("--message", prompt="Don't _____ me: ", help=("The word or phrase to substitute for 'tread' in 'don't " "tread on me'")) -def tread(message): - dont_tread_on_memes.tread_on(message).show() +@click.option("--save", default=None, help="Where...
4fbec4f4c0741edb6207d762cc92e48c6f249eec
dragonflow/common/extensions.py
dragonflow/common/extensions.py
# # 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 # ...
# # 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 # ...
Disable L3 agents scheduler extension in Tempest
Disable L3 agents scheduler extension in Tempest Change-Id: Ibc2d85bce9abb821e897693ebdade66d3b9199c3 Closes-Bug: #1707496
Python
apache-2.0
openstack/dragonflow,openstack/dragonflow,openstack/dragonflow
--- +++ @@ -13,6 +13,7 @@ # If you update this list, please also update # doc/source/features.rst. +# NOTE (dimak): This used only for tempest's enabled network API extensions SUPPORTED_API_EXTENSIONS = [ 'agent', 'quotas', @@ -22,7 +23,6 @@ 'security-group', 'external-net', 'router', - ...
97b6c8cb246e21d6bc2b0334cbf3a95588571c71
src/aimes/emgr/workloads/skeleton.py
src/aimes/emgr/workloads/skeleton.py
import sys from aimes.emgr.utils import * __author__ = "Matteo Turilli" __copyright__ = "Copyright 2015, The AIMES Project" __license__ = "MIT" # ----------------------------------------------------------------------------- def write_skeleton_conf(cfg, scale, cores, uniformity, fout): '''Write a skeleton configu...
import sys from aimes.emgr.utils import * __author__ = "Matteo Turilli" __copyright__ = "Copyright 2015, The AIMES Project" __license__ = "MIT" # ----------------------------------------------------------------------------- def write_skeleton_conf(cfg, scale, cores, uniformity, fout): '''Write a skeleton configu...
Use max duration when uniform time distribution
Use max duration when uniform time distribution
Python
mit
radical-cybertools/aimes.emgr
--- +++ @@ -29,8 +29,9 @@ if uniformity == 'uniform': substitutes['UNIFORMITY_DURATION'] = "%s %s" % \ - (uniformity, cfg['skeleton_task_duration']['avg']) + (uniformity, cfg['skeleton_task_duration']['max']) + # TODO: Calculate stdev and avg. elif uniformity == 'gauss'...
060c5f13886191777e2709c9119d480fe0983ced
TorGTK/pref_handle.py
TorGTK/pref_handle.py
import ConfigParser from gi.repository import Gtk from pref_mapping import * from var import * def read_config_if_exists(filename): if os.path.isfile(filename): # Init config parser and read config Config = ConfigParser.SafeConfigParser() Config.read(filename) section = "TorGTKprefs" # Loop through options...
import ConfigParser from gi.repository import Gtk from pref_mapping import * from var import * def read_config_if_exists(filename): if os.path.isfile(filename): # Init config parser and read config Config = ConfigParser.SafeConfigParser() Config.read(filename) section = "TorGTKprefs" # Loop through options...
Remove line for debugging which lists object type from elements of listbox
Remove line for debugging which lists object type from elements of listbox
Python
bsd-2-clause
neelchauhan/TorGTK,neelchauhan/TorNova
--- +++ @@ -14,7 +14,6 @@ options = Config.options(section) for option in options: value = Config.get(section, option) - print objs[pref_mappings[option]] objs[pref_mappings[option]].set_value(int(value)) def write_config(filename):
85a26420dda32d25a3c4b214e0156aaa558158e9
src/foremast/iam/construct_policy.py
src/foremast/iam/construct_policy.py
"""Construct an IAM Policy from templates. Examples: pipeline.json: { "services": { "dynamodb": [ "another_app" ] "lambda": true, "s3": true } } """ import json import logging from ..utils ...
"""Construct an IAM Policy from templates. Examples: pipeline.json: { "services": { "dynamodb": [ "another_app" ], "lambda": true, "s3": true } } """ import json import logging from ..utils...
Fix example of services for IAM Policies
docs: Fix example of services for IAM Policies See also: PSOBAT-1482
Python
apache-2.0
gogoair/foremast,gogoair/foremast
--- +++ @@ -7,7 +7,7 @@ "services": { "dynamodb": [ "another_app" - ] + ], "lambda": true, "s3": true }
a8e7f1161afa313e25e678a1a2c1cdc1bc443f25
src/core/urls.py
src/core/urls.py
__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView ...
__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView ...
Handle installs not using new settings engine
Handle installs not using new settings engine
Python
agpl-3.0
BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway
--- +++ @@ -21,13 +21,16 @@ url(r'', include('core.include_urls')), ] -if settings.DEBUG or settings.IN_TEST_RUNNER: - import debug_toolbar +try: + if settings.DEBUG or settings.IN_TEST_RUNNER: + import debug_toolbar - urlpatterns += [ - url(r'^media/(?P<path>.*)$', serve, {'document_...
5e1fc4fbb2f363fd2116d153e735ff3322001b3a
tests/trac/test-trac-0132.py
tests/trac/test-trac-0132.py
# -*- coding: utf-8 -*- import pyxb import unittest class TestTrac0132 (unittest.TestCase): message = u'bad character \u2620' def testDecode (self): e = pyxb.PyXBException(self.message) self.assertEqual(self.message, e.message) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- import sys import pyxb import unittest class TestTrac0132 (unittest.TestCase): message = u'bad character \u2620' def testDecode (self): e = pyxb.PyXBException(self.message) if sys.version[:2] > (2, 4): self.assertEqual(self.message, e.message) if __name__ =...
Revise test to support Python 2.4.
Revise test to support Python 2.4. In this version, base Exception didn't have a .message field. No wonder I had added it back in 2009, resulting in trac/132 which removed it.
Python
apache-2.0
balanced/PyXB,jonfoster/pyxb2,CantemoInternal/pyxb,jonfoster/pyxb1,pabigot/pyxb,jonfoster/pyxb2,balanced/PyXB,jonfoster/pyxb2,pabigot/pyxb,jonfoster/pyxb-upstream-mirror,CantemoInternal/pyxb,jonfoster/pyxb-upstream-mirror,jonfoster/pyxb1,balanced/PyXB,jonfoster/pyxb-upstream-mirror,CantemoInternal/pyxb
--- +++ @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- +import sys import pyxb import unittest @@ -7,7 +8,8 @@ message = u'bad character \u2620' def testDecode (self): e = pyxb.PyXBException(self.message) - self.assertEqual(self.message, e.message) + if sys.version[:2] > (2, 4): + ...