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 |
|---|---|---|---|---|---|---|---|---|---|---|
5d33de3868df4549621763db07267ef59fb94eb8 | dataset/models/tf/losses/core.py | dataset/models/tf/losses/core.py | """ Contains base tf losses """
import tensorflow as tf
def softmax_cross_entropy(labels, logits, *args, **kwargs):
""" Multi-class CE which takes plain or one-hot labels
Parameters
----------
labels : tf.Tensor
logits : tf.Tensor
args
other positional parameters from `tf.losses.sof... | """ Contains base tf losses """
import tensorflow as tf
def softmax_cross_entropy(labels, logits, *args, **kwargs):
""" Multi-class CE which takes plain or one-hot labels
Parameters
----------
labels : tf.Tensor
logits : tf.Tensor
args
other positional parameters from `tf.losses.sof... | Fix ohe type in ce | Fix ohe type in ce
| Python | apache-2.0 | analysiscenter/dataset | ---
+++
@@ -25,5 +25,5 @@
c = tf.cast(tf.equal(labels_shape, logits_shape), tf.int32)
e = tf.equal(tf.reduce_sum(c, axis=-1), logits_shape.shape[-1])
labels = tf.cond(e, lambda: tf.cast(labels, dtype=logits.dtype),
- lambda: tf.one_hot(labels, logits_shape[-1], dtype=logits.dtype))
... |
aef238386c71d52def424c8f47a103bd25f12e26 | server/proposal/migrations/0034_fix_updated.py | server/proposal/migrations/0034_fix_updated.py | import django.contrib.gis.db.models.fields
from django.db import migrations
from django.contrib.gis.db.models import Max
def fix_updated(apps, _):
Proposal = apps.get_model("proposal", "Proposal")
proposals = Proposal.objects.annotate(published=Max("documents__published"))
for proposal in proposals:
... | import django.contrib.gis.db.models.fields
from django.db import migrations
from django.contrib.gis.db.models import Max
def fix_updated(apps, _):
Proposal = apps.get_model("proposal", "Proposal")
proposals = Proposal.objects.annotate(published=Max("documents__published"))
for proposal in proposals:
... | Make fix_updated migration (sort of) reversible | Make fix_updated migration (sort of) reversible
| Python | mit | cityofsomerville/citydash,cityofsomerville/citydash,codeforboston/cornerwise,codeforboston/cornerwise,codeforboston/cornerwise,codeforboston/cornerwise,cityofsomerville/citydash,cityofsomerville/cornerwise,cityofsomerville/citydash,cityofsomerville/cornerwise,cityofsomerville/cornerwise,cityofsomerville/cornerwise | ---
+++
@@ -12,11 +12,15 @@
proposal.save()
+def do_nothing(apps, _):
+ pass
+
+
class Migration(migrations.Migration):
dependencies = [
('proposal', '0033_non_null_started'),
]
operations = [
- migrations.RunPython(fix_updated),
+ migrations.RunPython(fix_... |
6e526a173de970f2cc8f7cd62823a257786e348e | category/urls.py | category/urls.py | from django.conf.urls import patterns, url
from .views import CategoriesList, GalleryDetail, StoryDetail
urlpatterns = patterns('category.views',
url(r'^gallery/categories/(?P<slug>.+)/$', GalleryDetail.as_view(), name='gallery-detail'),
url(r'^stories/categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='... | from django.conf.urls import patterns, url
from .views import CategoriesList, GalleryDetail, StoryDetail
urlpatterns = patterns('category.views',
url(r'^categories/$', CategoriesList.as_view(), name='category-list'),
url(r'^categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='category-detail'),
url(r'... | Add the missing category-detail urlconf to not to break bookmarked users | Add the missing category-detail urlconf to not to break bookmarked users
| Python | bsd-3-clause | PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari | ---
+++
@@ -3,8 +3,10 @@
from .views import CategoriesList, GalleryDetail, StoryDetail
urlpatterns = patterns('category.views',
+ url(r'^categories/$', CategoriesList.as_view(), name='category-list'),
+ url(r'^categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='category-detail'),
+ url(r'^stories/ca... |
077ad3e5227c3ad9831a6c94c14cd640f7e933d9 | carusele/models.py | carusele/models.py | from django.db import models
class News (models.Model):
"""
News model represent detail description and
content of each carusele element.
"""
title = models.CharField(max_length=400)
description = models.TextField(default="")
content = models.TextField()
pubdate = models.DateTimeField(... | from django.core.urlresolvers import reverse
from django.db import models
class News (models.Model):
"""
News model represent detail description and
content of each carusele element.
"""
title = models.CharField(max_length=400)
description = models.TextField(default="")
content = models.Te... | Use reverse function for urls in carusele app | Use reverse function for urls in carusele app
| Python | apache-2.0 | SarFootball/backend,SarFootball/backend,SarFootball/backend | ---
+++
@@ -1,3 +1,4 @@
+from django.core.urlresolvers import reverse
from django.db import models
@@ -16,7 +17,7 @@
return unicode(self.title)
def get_absolute_url(self):
- return "/carusele/art/%i/" % self.id
+ return reverse("article", args=(self.id,))
class Element (models.... |
4aba708916984c61cc7f5fd205d66e8f64634589 | main/widgets.py | main/widgets.py | from django_filters.widgets import RangeWidget
class CustomRangeWidget(RangeWidget):
def __init__(self, widget, attrs=None):
attrs_start = {'placeholder': 'От', **(attrs or {})}
attrs_stop = {'placeholder': 'До', **(attrs or {})}
widgets = (widget(attrs_start), widget(attrs_stop))
... | from django_filters.widgets import RangeWidget
class CustomRangeWidget(RangeWidget):
def __init__(self, widget, attrs={}):
attrs_start = {'placeholder': 'От'}
attrs_start.update(attrs)
attrs_stop = {'placeholder': 'До'}
attrs_stop.update(attrs)
super(RangeWidget, self).__in... | Make compatible with python 3.4 | Make compatible with python 3.4
| Python | agpl-3.0 | Davidyuk/witcoin,Davidyuk/witcoin | ---
+++
@@ -2,11 +2,12 @@
class CustomRangeWidget(RangeWidget):
- def __init__(self, widget, attrs=None):
- attrs_start = {'placeholder': 'От', **(attrs or {})}
- attrs_stop = {'placeholder': 'До', **(attrs or {})}
- widgets = (widget(attrs_start), widget(attrs_stop))
- super(Range... |
94d66121368906b52fa8a9f214813b7b798c2b5b | lib/custom_data/settings_manager.py | lib/custom_data/settings_manager.py | """This module provides functions for saving to and loading data from
the settings XML file.
Attributes:
SETTINGS_PATH Filepath for the settings file.
"""
SETTINGS_PATH = 'settings.xml'
| """This module provides functions for saving to and loading data from
the settings XML file.
Attributes:
SETTINGS_PATH (String): The file path for the settings file.
SETTINGS_SCHEMA_PATH (String): The file path for the settings'
XML Schema.
"""
SETTINGS_PATH = 'settings.xml'
SETTINGS_SCHEMA_PATH = 'set... | Add constant for settings schema file path | Add constant for settings schema file path
| Python | unlicense | MarquisLP/Sidewalk-Champion | ---
+++
@@ -2,7 +2,9 @@
the settings XML file.
Attributes:
- SETTINGS_PATH Filepath for the settings file.
+ SETTINGS_PATH (String): The file path for the settings file.
+ SETTINGS_SCHEMA_PATH (String): The file path for the settings'
+ XML Schema.
"""
-
SETTINGS_PATH = 'settings.xml'
... |
60ea2738b39b38bdc1f25594a759aace0f520501 | web/manage.py | web/manage.py | from flask.ext.script import Manager
from app import get_app
from create_db import drop_all_tables, create_barebones_data, create_all_data, create_server
app = get_app('config.DockerConfiguration')
manager = Manager(app)
manager.command(drop_all_tables)
manager.command(create_barebones_data)
manager.command(create_... | from flask.ext.script import Manager
from app import get_app
from create_db import drop_all_tables, create_barebones_data, create_all_data, create_server
app = get_app('config.DockerConfiguration')
manager = Manager(app)
manager.command(drop_all_tables)
manager.command(create_barebones_data)
manager.command(create_... | Add utility function to dump flask env | Add utility function to dump flask env
| Python | mit | usgo/online-ratings,usgo/online-ratings,usgo/online-ratings,Kashomon/online-ratings,Kashomon/online-ratings,Kashomon/online-ratings | ---
+++
@@ -12,6 +12,10 @@
manager.command(create_all_data)
manager.command(create_server)
+@manager.command
+def config():
+ 'Print out all config values from the fully assembled flask app'
+ print('\n'.join('%s=%s' % item for item in sorted(app.config.items())))
if __name__ == '__main__':
manager.run... |
39946f9fa5127d240d7147d50b676ad083514e85 | campus02/urls.py | campus02/urls.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
url(r'^', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^web/', include('campus02.web.urls', namespace='we... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
url(r'^', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^web/', include('... | Add custom debug toolbar URL mount point. | Add custom debug toolbar URL mount point.
| Python | mit | fladi/django-campus02,fladi/django-campus02 | ---
+++
@@ -1,6 +1,7 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
+from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
@@ -11,3 +12,10 @@
url(r'^web/', include('campus02.web.urls', namespace='web')),
url(r'^', include('campus02.base.u... |
ce990bfb3c742c9f19f0af43a10aad8193fa084c | keystoneclient_kerberos/__init__.py | keystoneclient_kerberos/__init__.py | # -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... | # -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... | Use the package name when looking up version | Use the package name when looking up version
We need to give PBR the full package name when it looks up the version
from a pip installed package. keystoneclient_kerberos is the module
name, not the package name.
Change-Id: I638d0975d77db3767c3675dceb05466388abebc9
Closes-Bug: #1441918
| Python | apache-2.0 | cernops/python-keystoneclient-kerberos | ---
+++
@@ -17,7 +17,7 @@
from keystoneclient_kerberos import v3
__version__ = pbr.version.VersionInfo(
- 'keystoneclient_kerberos').version_string()
+ 'python-keystoneclient-kerberos').version_string()
V3Kerberos = v3.Kerberos
|
433d9b2c1c29f32a7d5289e84673308c96302d8d | controlers/access.py | controlers/access.py | '''Copyright(C): Leaf Johnson 2011
This file is part of makeclub.
makeclub is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later versi... | '''Copyright(C): Leaf Johnson 2011
This file is part of makeclub.
makeclub is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later versi... | FIX a bug, you fuck'in forgot to rename the new function | FIX a bug, you fuck'in forgot to rename the new function
| Python | agpl-3.0 | cardmaster/makeclub,cardmaster/makeclub,cardmaster/makeclub | ---
+++
@@ -31,11 +31,11 @@
"edit",
"delete",
"arrange",
- "finish"
+ "finish",
+ "newact"
]
actOperatoins = [
- "create",
"view",
"edit",
"join"
@@ -47,6 +47,6 @@
def hasClubPrivilige (user, club, operation):
return True
-def hasClubPrivilige (user, act, operation):
+def hasActPrivilige (user, a... |
addc1e83911f72282eca9603e2c483ba6ef5ef7c | packages/xsp.py | packages/xsp.py | GitHubTarballPackage('mono', 'xsp', '2.11', 'd3e2f80ff59ddff68e757a520655555e2fbf2695', configure = './autogen.sh --prefix="%{prefix}"')
| GitHubTarballPackage('mono', 'xsp', '3.0.11', '4587438369691b9b3e8415e1f113aa98b57d1fde', configure = './autogen.sh --prefix="%{prefix}"')
| Update to the latest XSP. | Update to the latest XSP.
| Python | mit | BansheeMediaPlayer/bockbuild,mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,mono/bockbuild | ---
+++
@@ -1 +1 @@
-GitHubTarballPackage('mono', 'xsp', '2.11', 'd3e2f80ff59ddff68e757a520655555e2fbf2695', configure = './autogen.sh --prefix="%{prefix}"')
+GitHubTarballPackage('mono', 'xsp', '3.0.11', '4587438369691b9b3e8415e1f113aa98b57d1fde', configure = './autogen.sh --prefix="%{prefix}"') |
d8b29fd094a7a2d74c74e32b05a810930655fb47 | src/modules/phython.py | src/modules/phython.py | import json
import runpy
import sys
def run():
args = sys.argv
if len(args) < 3:
raise Exception('Both module name and function name are required.')
module, function = args[1:3]
module = runpy.run_module(module)
if function not in module:
raise Exception(function + ' is not defin... | import json
import runpy
import sys
def run():
args = sys.argv
if len(args) < 3:
raise Exception('Both module name and function name are required.')
module, function = args[1:3]
module = runpy.run_module(module)
if function not in module:
raise Exception(function + ' is not defin... | Fix raw_input() error in python 3 | Fix raw_input() error in python 3
| Python | mit | marella/phython,marella/phython,marella/phython | ---
+++
@@ -17,7 +17,12 @@
call(module[function])
def call(function):
- arguments = raw_input().strip()
+ # raw_input() is removed in python 3
+ try:
+ input = raw_input
+ except NameError:
+ pass
+ arguments = input().strip()
arguments = json.loads(arguments)
output = f... |
bc1d19800d58291f4c4392d041a7913602fe8c7d | dallinger/jupyter.py | dallinger/jupyter.py | from ipywidgets import widgets
from jinja2 import Template
from traitlets import (
observe,
Unicode,
)
from dallinger.config import get_config
header_template = Template(u"""
<h2>{{ name }}</h2>
<div>Status: {{ status }}</div>
{% if app_id %}<div>App ID: {{ app_id }}</div>{% endif %}
""")
config_template = T... | from ipywidgets import widgets
from jinja2 import Template
from traitlets import (
observe,
Unicode,
)
from dallinger.config import get_config
header_template = Template(u"""
<h2>{{ name }}</h2>
<div>Status: {{ status }}</div>
{% if app_id %}<div>App ID: {{ app_id }}</div>{% endif %}
""")
config_template = T... | Fix sorting dict items in python 3 | Fix sorting dict items in python 3
| Python | mit | jcpeterson/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger | ---
+++
@@ -45,7 +45,7 @@
)
config = get_config()
if config.ready:
- config_items = config.as_dict().items()
+ config_items = list(config.as_dict().items())
config_items.sort()
config_tab = widgets.HTML(
config_template.render... |
745c9445e16f72dbc1791abef2b7f52eb5e1f093 | open_spiel/python/tests/referee_test.py | open_spiel/python/tests/referee_test.py | # Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | Increase timeouts for the python test. | Increase timeouts for the python test.
| Python | apache-2.0 | deepmind/open_spiel,deepmind/open_spiel,deepmind/open_spiel,deepmind/open_spiel,deepmind/open_spiel,deepmind/open_spiel | ---
+++
@@ -22,9 +22,12 @@
class RefereeTest(absltest.TestCase):
def test_playing_tournament(self):
base = os.path.dirname(__file__) + "/../../higc/bots"
- ref = pyspiel.Referee("kuhn_poker",
- [f"{base}/random_bot_py.sh",
- f"{base}/ran... |
e912c76ec60abf9a8263e65d8df8d466518f57b2 | pysswords/db.py | pysswords/db.py | from glob import glob
import os
import shutil
from .credential import Credential
from .crypt import create_gpg, load_gpg
class Database(object):
def __init__(self, path, gpg):
self.path = path
self.gpg = gpg
@classmethod
def create(cls, path, passphrase, gpg_bin="gpg"):
gpg = cr... | from glob import glob
import os
import shutil
from .credential import Credential
from .crypt import create_gpg, load_gpg
class Database(object):
def __init__(self, path, gpg):
self.path = path
self.gpg = gpg
@classmethod
def create(cls, path, passphrase, gpg_bin="gpg"):
gpg = cr... | Change GPG password encryption to AES256 | Change GPG password encryption to AES256
| Python | mit | scorphus/passpie,eiginn/passpie,marcwebbie/passpie,marcwebbie/pysswords,scorphus/passpie,eiginn/passpie,marcwebbie/passpie | ---
+++
@@ -34,7 +34,8 @@
def add(self, credential):
encrypted_password = self.gpg.encrypt(
credential.password,
- self.gpg_key
+ self.gpg_key,
+ cipher_algo="AES256"
)
credential.password = str(encrypted_password)
credential.save(... |
57d008222a531ec79957611dc077a67499426986 | CS480/milestone4/driver.py | CS480/milestone4/driver.py | #!/usr/bin/env python
from sys import *
from myreglexer import *
from getopt import *
from myparser import *
from tree import *
from semantic import *
contents = []
def main(argv):
try:
opts, args = getopt(argv, "h", ["help"])
except GetoptError:
usage()
sys.exit(1)
for opt, arg in opts:
if opt... | #!/usr/bin/env python
from sys import *
from myreglexer import *
from getopt import *
from myparser import *
from tree import *
from semantic import *
contents = []
def main(argv):
try:
opts, args = getopt(argv, "h", ["help"])
except GetoptError:
usage()
sys.exit(1)
for opt, arg in opts:
if opt... | Change the way semantic is called to allow for looping and handling | Change the way semantic is called to allow for looping and handling [SS]
| Python | apache-2.0 | stumped2/school,stumped2/school,stumped2/school,stumped2/school,stumped2/school,stumped2/school,stumped2/school,stumped2/school | ---
+++
@@ -29,7 +29,7 @@
#tree.traverse_pre()
temp = tree.build_stack_pre()
#print temp
- print semantic_check(temp)
+ semantic_check(temp)
temp = tree.build_stack_post()
for i in temp:
print i.data[1] |
98cbd5207bd25fb0fafd25f18870c771479255e1 | run-tests.py | run-tests.py | #!/usr/bin/env python3
import os
import subprocess
import sys
args = [
sys.executable or 'python', # Python interpreter to call for testing.
'-B', # Don't write .pyc files on import.
'-m', 'unittest', # Run the unittest module as a script.
'discover', # Use test discovery.
'-s', 'tests', # Sta... | #!/usr/bin/env python3
import os
import subprocess
import sys
args = [
sys.executable or 'python', # Python interpreter to call for testing.
'-B', # Don't write .pyc files on import.
'-W', 'default', # Enable default handling for all warnings.
'-m', 'unittest', # Run the unittest module as a script... | Enable default warnings while testing. | Enable default warnings while testing.
| Python | mit | shawnbrown/gpn,shawnbrown/gpn | ---
+++
@@ -7,6 +7,7 @@
args = [
sys.executable or 'python', # Python interpreter to call for testing.
'-B', # Don't write .pyc files on import.
+ '-W', 'default', # Enable default handling for all warnings.
'-m', 'unittest', # Run the unittest module as a script.
'discover', # Use test di... |
df155919eb81748231b5b7f834e0739d78a38471 | tests/CLI/modules/subnet_tests.py | tests/CLI/modules/subnet_tests.py | """
SoftLayer.tests.CLI.modules.subnet_tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:license: MIT, see LICENSE for more details.
"""
from SoftLayer import testing
import json
class SubnetTests(testing.TestCase):
def test_detail(self):
result = self.run_command(['subnet', 'detail', '1234'])... | """
SoftLayer.tests.CLI.modules.subnet_tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:license: MIT, see LICENSE for more details.
"""
from SoftLayer import testing
import json
class SubnetTests(testing.TestCase):
def test_detail(self):
result = self.run_command(['subnet', 'detail', '1234'])... | Fix style nit, line end for test file | Fix style nit, line end for test file
| Python | mit | allmightyspiff/softlayer-python,softlayer/softlayer-python,nanjj/softlayer-python,kyubifire/softlayer-python | |
d6e4aa32b7b79adc734dfc2b058509cedf771944 | munigeo/migrations/0004_building.py | munigeo/migrations/0004_building.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-11-10 08:46
from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('munigeo', '0003_... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-11-10 08:46
from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
from munigeo.utils import get_default_srid
DEFAULT_SRID = get_default_srid()
class Mig... | Fix building migration SRID logic | Fix building migration SRID logic
Hardcoding the SRID in the migration could result in a mismatch
between the model srid and the migration srid.
| Python | agpl-3.0 | City-of-Helsinki/munigeo | ---
+++
@@ -5,6 +5,9 @@
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
+
+from munigeo.utils import get_default_srid
+DEFAULT_SRID = get_default_srid()
class Migration(migrations.Migration):
@@ -19,7 +22,7 @@
fields=[
... |
35397c33f1b52f158c11941e17211eb699836003 | tests/integration/indexer-test.py | tests/integration/indexer-test.py | # -*- coding: utf-8 -*-
from nose import tools as nose
import unittest
from shiva.app import app
from shiva.indexer import Indexer
class IndexerTestCase(unittest.TestCase):
def test_main(self):
with app.app_context():
lola = Indexer(app.config)
nose.eq_(lola.run(), None)
| # -*- coding: utf-8 -*-
from nose import tools as nose
import unittest
from shiva.app import app, db
from shiva.indexer import Indexer
class IndexerTestCase(unittest.TestCase):
def setUp(self):
db.create_all()
def test_main(self):
with app.app_context():
app.config['MEDIA_DIRS']... | Fix to indexer integration tests | Fix to indexer integration tests
| Python | mit | tooxie/shiva-server,maurodelazeri/shiva-server,tooxie/shiva-server,maurodelazeri/shiva-server | ---
+++
@@ -2,13 +2,20 @@
from nose import tools as nose
import unittest
-from shiva.app import app
+from shiva.app import app, db
from shiva.indexer import Indexer
class IndexerTestCase(unittest.TestCase):
+ def setUp(self):
+ db.create_all()
+
def test_main(self):
with app.app_co... |
6421543ff423fc110cd660850f55f7097db5805d | contrib/performance/setbackend.py | contrib/performance/setbackend.py | ##
# Copyright (c) 2010 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | ##
# Copyright (c) 2010 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | Rewrite the config to disable the response cache, too. | Rewrite the config to disable the response cache, too.
git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6929 e27351fd-9f3e-4f54-a53b-843176b1656c
| Python | apache-2.0 | trevor/calendarserver,trevor/calendarserver,trevor/calendarserver | ---
+++
@@ -14,6 +14,12 @@
# limitations under the License.
##
+"""
+Generate a new calendar server configuration file based on an existing
+one, with a few values changed to satisfy requirements of the
+benchmarking tools.
+"""
+
import sys
from xml.etree import ElementTree
from xml.etree import ElementPath
@... |
0ef0f546c23754cd339adbc00cb3d90558af744c | examples/list_sysdig_captures.py | examples/list_sysdig_captures.py | #!/usr/bin/env python
#
# Print the list of sysdig captures.
#
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import SdcClient
#
# Parse arguments
#
if len(sys.argv) != 2:
print('usage: %s <sysdig-token>' % sys.argv[0])
print('You can... | #!/usr/bin/env python
#
# Print the list of sysdig captures.
#
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import SdcClient
#
# Parse arguments
#
if len(sys.argv) != 2:
print('usage: %s <sysdig-token>' % sys.argv[0])
print('You can... | Fix legacy use of action result | Fix legacy use of action result
| Python | mit | draios/python-sdc-client,draios/python-sdc-client | ---
+++
@@ -32,7 +32,7 @@
# Show the list of metrics
#
if ok:
- captures = res[1]['dumps']
+ captures = res['dumps']
else:
print(res)
sys.exit(1) |
73949126f9c50669da8687b9fae5b8c7db0a89f6 | coffee/deamon.py | coffee/deamon.py | #!/home/pi/coffee/venv/bin/python
import os
import sys
import time
from coffee.models import Status
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
DEBUG = 1
PIN = 14
def main():
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
status = Status()
def rc_time(RCpin):
reading = 0... | #!/home/pi/coffee/venv/bin/python
import os
import sys
import time
from coffee.models import Status
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
DEBUG = 1
# The GPIO pin the button is connected to
BUTTON_PIN = 7
# The GPIO pin the button's LED is connected to
LED_PIN = 4
def main():
import RP... | Write pi code to use button | Write pi code to use button
| Python | mit | webkom/coffee,webkom/coffee | ---
+++
@@ -10,32 +10,38 @@
DEBUG = 1
-PIN = 14
+
+# The GPIO pin the button is connected to
+BUTTON_PIN = 7
+# The GPIO pin the button's LED is connected to
+LED_PIN = 4
def main():
import RPi.GPIO as GPIO
- GPIO.setmode(GPIO.BCM)
status = Status()
- def rc_time(RCpin):
- reading... |
eb46bc61a05279d338c9e1062988f7db67f060fb | makesty.py | makesty.py | import re
# Input file created from http://astronautweb.co/snippet/font-awesome/
INPUT_FILE = 'htmlfontawesome.txt'
with open(INPUT_FILE) as r:
for line in r:
# Expects to find 'fa-NAME' ending with "
name = re.findall(r'fa-[^""]*', line)[0]
# Expects to find '\fSYMBOL' ending with "
symbol = re.fin... | import re
# Input file created from http://astronautweb.co/snippet/font-awesome/
INPUT_FILE = 'htmlfontawesome.txt'
OUTPUT_FILE = 'fontawesome.sty'
with open(INPUT_FILE) as r, open(OUTPUT_FILE, 'w') as w:
for line in r:
# Expects to find 'fa-NAME' ending with "
name = re.findall(r'fa-[^""]*', line)[0]
#... | Write output to .sty file. | Write output to .sty file.
| Python | mit | posquit0/latex-fontawesome | ---
+++
@@ -2,8 +2,9 @@
# Input file created from http://astronautweb.co/snippet/font-awesome/
INPUT_FILE = 'htmlfontawesome.txt'
+OUTPUT_FILE = 'fontawesome.sty'
-with open(INPUT_FILE) as r:
+with open(INPUT_FILE) as r, open(OUTPUT_FILE, 'w') as w:
for line in r:
# Expects to find 'fa-NAME' ending with... |
d1e2aacb7926a7e751cd27eb562b2c5d86f7e1e8 | opal/tests/test_core_test_runner.py | opal/tests/test_core_test_runner.py | """
Unittests fror opal.core.test_runner
"""
import ffs
from mock import MagicMock, patch
from opal.core.test import OpalTestCase
from opal.core import test_runner
class RunPyTestsTestCase(OpalTestCase):
@patch('subprocess.check_call')
def test_run_tests(self, check_call):
mock_args = MagicMock(name... | """
Unittests fror opal.core.test_runner
"""
import ffs
from mock import MagicMock, patch
from opal.core.test import OpalTestCase
from opal.core import test_runner
class RunPyTestsTestCase(OpalTestCase):
@patch('subprocess.check_call')
def test_run_tests(self, check_call):
mock_args = MagicMock(name... | Add test for opal test py -t | Add test for opal test py -t
| Python | agpl-3.0 | khchine5/opal,khchine5/opal,khchine5/opal | ---
+++
@@ -19,6 +19,17 @@
test_runner._run_py_tests(mock_args)
check_call.assert_called_once_with(['python', 'runtests.py'])
+ @patch('subprocess.check_call')
+ def test_run_tests_with_test_arg(self, check_call):
+ mock_args = MagicMock(name="args")
+ mock_args.userland_here =... |
267271f1d875e13b8a162976891bc8f3298fe8ba | stdnumfield/models.py | stdnumfield/models.py | # coding=utf-8
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils.itercompat import is_iterable
from six import string_types
from . import settings
from .forms import StdnumField
__all__ = [
'StdNumField',
]
class StdNumField(models.CharField):
"""Model f... | # coding=utf-8
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils.itercompat import is_iterable
from six import string_types
from . import settings
from .forms import StdnumField
__all__ = [
'StdNumField',
]
class StdNumField(models.CharField):
"""Model f... | Fix form field custom kwarg | Fix form field custom kwarg
| Python | unlicense | frnhr/django-stdnumfield,frnhr/django-stdnumfield,frnhr/django-stdnumfield | ---
+++
@@ -43,6 +43,9 @@
return 'CharField'
def formfield(self, **kwargs):
- defaults = {'form_class': StdnumField}
+ defaults = {
+ 'form_class': StdnumField,
+ 'formats': self.formats,
+ }
defaults.update(kwargs)
return super(StdNumField,... |
9637218c8b544c397bcd5d433de47cafbfad973d | octodns/source/base.py | octodns/source/base.py | #
#
#
from __future__ import absolute_import, division, print_function, \
unicode_literals
class BaseSource(object):
def __init__(self, id):
self.id = id
if not getattr(self, 'log', False):
raise NotImplementedError('Abstract base class, log property '
... | #
#
#
from __future__ import absolute_import, division, print_function, \
unicode_literals
class BaseSource(object):
def __init__(self, id):
self.id = id
if not getattr(self, 'log', False):
raise NotImplementedError('Abstract base class, log property '
... | Add lenient to abstract BaseSource signature | Add lenient to abstract BaseSource signature
| Python | mit | vanbroup/octodns,vanbroup/octodns,h-hwang/octodns,h-hwang/octodns | ---
+++
@@ -20,7 +20,7 @@
raise NotImplementedError('Abstract base class, SUPPORTS '
'property missing')
- def populate(self, zone, target=False):
+ def populate(self, zone, target=False, lenient=False):
'''
Loads all zones the provider kno... |
487acc33f8086a889193e5995424e7bfdbb208ce | django_project/frontend/tests/test_views.py | django_project/frontend/tests/test_views.py | # -*- coding: utf-8 -*-
from django.test import TestCase, Client
from django.core.urlresolvers import reverse
class TestViews(TestCase):
def setUp(self):
self.client = Client()
def test_home_view(self):
resp = self.client.get(reverse('home'))
self.assertEqual(resp.status_code, 200)
... | # -*- coding: utf-8 -*-
from django.test import TestCase, Client
from django.core.urlresolvers import reverse
from django.conf import settings
class TestViews(TestCase):
def setUp(self):
self.client = Client()
def test_home_view(self):
resp = self.client.get(reverse('home'))
self.ass... | Add missing tests for frontend views | Add missing tests for frontend views
| Python | bsd-2-clause | ismailsunni/healthsites,ismailsunni/healthsites,ismailsunni/healthsites,ismailsunni/healthsites | ---
+++
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from django.test import TestCase, Client
from django.core.urlresolvers import reverse
+from django.conf import settings
class TestViews(TestCase):
@@ -11,9 +12,49 @@
resp = self.client.get(reverse('home'))
self.assertEqual(resp.status_code, 2... |
db01eb72829db32c87a167c9b3529577a028ec54 | example_project/example_project/settings.py | example_project/example_project/settings.py | # Django settings for example_project project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'example_project.sqlite3',
}
}
SITE_ID = 1
SECRET_KEY = 'u%38dln@$1!7w#cxi4np504^sa3_skv5aekad)jy_u0v2mc+nr'
TEMPLATE_LOADERS = (
... | # Django settings for example_project project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'example_project.sqlite3',
}
}
SITE_ID = 1
SECRET_KEY = 'u%38dln@$1!7w#cxi4np504^sa3_skv5aekad)jy_u0v2mc+nr'
TEMPLATE_LOADERS = (
... | Append slash to urls in example project | Append slash to urls in example project
| Python | mit | yetty/django-embed-video,mpachas/django-embed-video,yetty/django-embed-video,jazzband/django-embed-video,jazzband/django-embed-video,mpachas/django-embed-video | ---
+++
@@ -19,6 +19,7 @@
'django.template.loaders.app_directories.Loader',
)
+APPEND_SLASH = True
ROOT_URLCONF = 'example_project.urls'
|
1c6392889a5393b9681d18aab5294c1f1927730a | __init__.py | __init__.py | _VERSION = 'CVS'
_TEMP_DIR = '.SloppyCell'
import logging
logging.basicConfig()
logger = logging.getLogger('__init__')
# Check for debugging option. I tried using optparse for this, but ran into
# issues with ipython and mpirun, both of which pollute sys.argv.
import sys
for arg in sys.argv:
if arg.startswith('--... | _VERSION = 'CVS'
import os
_TEMP_DIR = os.path.join(os.getcwd(), '.SloppyCell')
import logging
logging.basicConfig()
logger = logging.getLogger('__init__')
# Check for debugging option. I tried using optparse for this, but ran into
# issues with ipython and mpirun, both of which pollute sys.argv.
import sys
for arg i... | Handle temp directory with absolute path | Handle temp directory with absolute path
| Python | bsd-3-clause | GutenkunstLab/SloppyCell,GutenkunstLab/SloppyCell | ---
+++
@@ -1,5 +1,6 @@
_VERSION = 'CVS'
-_TEMP_DIR = '.SloppyCell'
+import os
+_TEMP_DIR = os.path.join(os.getcwd(), '.SloppyCell')
import logging
logging.basicConfig()
@@ -16,7 +17,6 @@
Utility.enable_debugging_msgs(words[1])
else:
Utility.enable_debugging_msgs(None)
-import ... |
d38fee106c00ed20b9a1ed3f38c057393576f6ea | tmaps/defaultconfig.py | tmaps/defaultconfig.py | import logging
import datetime
DEBUG = True
# Override this key with a secret one
SECRET_KEY = 'default_secret_key'
HASHIDS_SALT = 'default_secret_salt'
## Authentication
JWT_EXPIRATION_DELTA = datetime.timedelta(days=2)
JWT_NOT_BEFORE_DELTA = datetime.timedelta(seconds=0)
## Database
SQLALCHEMY_DATABASE_URI = None... | import logging
import datetime
DEBUG = False
# Override this key with a secret one
SECRET_KEY = 'default_secret_key'
HASHIDS_SALT = 'default_secret_salt'
## Authentication
JWT_EXPIRATION_DELTA = datetime.timedelta(days=2)
JWT_NOT_BEFORE_DELTA = datetime.timedelta(seconds=0)
## Database
SQLALCHEMY_DATABASE_URI = Non... | Remove spark settings from default config file | Remove spark settings from default config file
| Python | agpl-3.0 | TissueMAPS/TmServer | ---
+++
@@ -1,7 +1,7 @@
import logging
import datetime
-DEBUG = True
+DEBUG = False
# Override this key with a secret one
SECRET_KEY = 'default_secret_key' |
71d56354fb053c6cef3dc2c8960f78f588327114 | project/views.py | project/views.py | #! coding: utf-8
from django.shortcuts import render_to_response, render
from django.http import HttpResponseRedirect
from django.contrib.auth import login
from forms import LoginForm
def index(request):
return render_to_response('index.html', {})
def login_view(request):
if request.method == 'POST':
... | #! coding: utf-8
from django.shortcuts import render_to_response, render
from django.http import HttpResponseRedirect
from django.contrib.auth import login
from forms import LoginForm
def index(request):
return render_to_response('index.html', {})
def login_view(request):
if request.method == 'POST':
... | Store password in session after successful login. | Store password in session after successful login.
| Python | agpl-3.0 | InScience/DAMIS-old,InScience/DAMIS-old | ---
+++
@@ -15,6 +15,7 @@
if form.is_valid():
user = form.cleaned_data['user']
if user is not None and user.is_active:
+ request.session['password'] = form.cleaned_data['password']
login(request, user)
return HttpResponseRedirect('/')... |
9b55af4eb1d40517fce310b0751713dc8448f13f | main.py | main.py | import os
import logging
import gevent
from flask import Flask, render_template, url_for, redirect
from flask_sockets import Sockets
import io
app = Flask(__name__)
path = os.getcwd()
app.config['DEBUG'] = True
sockets = Sockets(app)
@app.route('/', methods=['GET', 'POST'])
def main():
return redirect(url_for('st... | import os
import logging
import gevent
from flask import Flask, render_template, url_for, redirect
from flask_sockets import Sockets
import io
import string
import random
app = Flask(__name__)
path = os.getcwd()
app.config['DEBUG'] = True
sockets = Sockets(app)
def rand_id(size=8):
return ''.join(random.SystemRan... | Add unique id for each wav file | Add unique id for each wav file
| Python | mit | j-salazar/mchacks15,j-salazar/mchacks15,j-salazar/mchacks15 | ---
+++
@@ -4,11 +4,16 @@
from flask import Flask, render_template, url_for, redirect
from flask_sockets import Sockets
import io
+import string
+import random
app = Flask(__name__)
path = os.getcwd()
app.config['DEBUG'] = True
sockets = Sockets(app)
+
+def rand_id(size=8):
+ return ''.join(random.SystemR... |
39cfea1b0528822720b88b890ae84fdf120826ff | bibliopixel/util/threads/compose_events.py | bibliopixel/util/threads/compose_events.py | import functools, threading
def compose_events(events, condition=all):
"""Compose a sequence of events into one event.
Arguments:
events: a sequence of objects looking like threading.Event
condition: a function taking a sequence of bools and returning a bool.
"""
events = list(event... | import functools, threading
def compose_events(events, condition=all):
"""Compose a sequence of events into one event.
Arguments:
events: a sequence of objects looking like threading.Event
condition: a function taking a sequence of bools and returning a bool.
"""
events = list(event... | Add an empty line for style | Add an empty line for style
| Python | mit | rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel | ---
+++
@@ -21,6 +21,7 @@
def wrapped():
f()
changed()
+
return wrapped
for e in events: |
c65a475c38a611cbf55f2dacbe22ccd50597c9ed | tests/test_database/test_sql/test_median.py | tests/test_database/test_sql/test_median.py | import unittest
from tkp.db import execute, rollback
class testMedian(unittest.TestCase):
def setUp(self):
try:
execute('drop table median_test')
except:
rollback()
execute('create table median_test (i int, f float)')
execute('insert into median_test values... | import unittest
import tkp
from tkp.db import execute, rollback, Database
from tkp.testutil import db_subs
from numpy import median
class testMedian(unittest.TestCase):
def setUp(self):
self.database = tkp.db.Database()
self.dataset = tkp.db.DataSet(database=self.database,
... | Use MonetDB friendly median query syntax in unit test. | Use MonetDB friendly median query syntax in unit test.
| Python | bsd-2-clause | transientskp/tkp,mkuiack/tkp,bartscheers/tkp,mkuiack/tkp,transientskp/tkp,bartscheers/tkp | ---
+++
@@ -1,24 +1,48 @@
import unittest
-from tkp.db import execute, rollback
-
+import tkp
+from tkp.db import execute, rollback, Database
+from tkp.testutil import db_subs
+from numpy import median
class testMedian(unittest.TestCase):
def setUp(self):
- try:
- execute('drop table median... |
0f5f5677ac2a1aa10067cbb509de28752fa106c0 | response.py | response.py | from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
def deconv(x, y, fs):
X = np.fft.fft(x)
Y = np.fft.fft(y)
H = Y / X
h = np.fft.ifft(H)
print("h =", h) # complex vector?
t = np.arange(len(x)) / fs
plt.plot(t, h.real)
plt.grid()
plt.title("impulse ... | """Response calculation."""
from __future__ import division
import numpy as np
def calculate(signal_excitation, signal_out):
"""Function returns impulse response."""
X = np.fft.fft(signal_excitation)
Y = np.fft.fft(signal_out)
H = Y / X
h = np.fft.ifft(H)
return h
| Change function content and pep257 | Change function content and pep257
| Python | mit | franzpl/sweep,spatialaudio/sweep | ---
+++
@@ -1,16 +1,12 @@
+"""Response calculation."""
from __future__ import division
import numpy as np
-import matplotlib.pyplot as plt
-def deconv(x, y, fs):
- X = np.fft.fft(x)
- Y = np.fft.fft(y)
+def calculate(signal_excitation, signal_out):
+ """Function returns impulse response."""
+ X = np... |
0ede19a4f2c9c6f01db0040d9d108eb0a0b2558c | py/kafka-tmdb.py | py/kafka-tmdb.py | import json
from get_tmdb import GetTMDB
from kafka import KafkaConsumer
try:
from GLOBALS import KAFKA_BROKER, TMDB_API
except ImportError:
print('Get it somewhere else')
class CollectTMDB(object):
def __init__(self, ):
self.tmdb = GetTMDB(TMDB_API)
self.consumer = KafkaConsumer(group_i... | import json
from get_tmdb import GetTMDB
from kafka import KafkaConsumer, KafkaProducer
try:
from GLOBALS import KAFKA_BROKER, TMDB_API
except ImportError:
print('Get it somewhere else')
class CollectTMDB(object):
def __init__(self, ):
self.tmdb = GetTMDB(TMDB_API)
self.producer = KafkaP... | Change KAFKA_BROKER parameter, added a send producer | Change KAFKA_BROKER parameter, added a send producer
| Python | mit | kinoreel/kino-gather | ---
+++
@@ -1,7 +1,7 @@
import json
from get_tmdb import GetTMDB
-from kafka import KafkaConsumer
+from kafka import KafkaConsumer, KafkaProducer
try:
from GLOBALS import KAFKA_BROKER, TMDB_API
@@ -12,9 +12,10 @@
def __init__(self, ):
self.tmdb = GetTMDB(TMDB_API)
+ self.producer = ... |
072d8fd3ccff957b427fca5e61b5a410a6762615 | pulldb/publishers.py | pulldb/publishers.py | # Copyright 2013 Russell Heilling
from google.appengine.ext import ndb
class Publisher(ndb.Model):
'''Publisher object in datastore.
Holds publisher data.
'''
identifier = ndb.IntegerProperty()
name = ndb.StringProperty()
image = ndb.StringProperty()
def fetch_or_store(identifier, publisher):
publishe... | # Copyright 2013 Russell Heilling
from google.appengine.ext import ndb
class Publisher(ndb.Model):
'''Publisher object in datastore.
Holds publisher data.
'''
identifier = ndb.IntegerProperty()
name = ndb.StringProperty()
image = ndb.StringProperty()
def fetch_or_store(identifier, publisher):
publishe... | Handle null image attribute on publisher | Handle null image attribute on publisher
| Python | mit | xchewtoyx/pulldb | ---
+++
@@ -14,7 +14,8 @@
def fetch_or_store(identifier, publisher):
publisher_key = Publisher.query(Publisher.identifier==identifier).get()
if not publisher_key:
- publisher_key = Publisher(identifier=publisher.id, name=publisher.name,
- image=publisher.image['tiny_url'])
+ ... |
4973656e6e569808fc9c7b50f52e67aae2c7b547 | billjobs/tests/tests_export_account_email.py | billjobs/tests/tests_export_account_email.py | from django.test import TestCase
from django.contrib.admin.sites import AdminSite
from billjobs.admin import UserAdmin
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.as... | from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def test_method_is_avaible(self):
... | Test export email return an HttpResponse | Test export email return an HttpResponse
| Python | mit | ioO/billjobs | ---
+++
@@ -1,5 +1,7 @@
from django.test import TestCase
+from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
+from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class EmailExportTestCase(TestCase):
@@ -17,3 +19,12 @@
""" Test method has a... |
a91a2d3468cb3bfc7fdc686327770365321ef102 | qa_app/challenges.py | qa_app/challenges.py | # Copyright 2016 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | # Copyright 2016 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | Implement demo 'exercises' api method. | Implement demo 'exercises' api method.
| Python | apache-2.0 | molecul/qa_app_flask,molecul/qa_app_flask,molecul/qa_app_flask | ---
+++
@@ -11,7 +11,9 @@
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
-from flask import Blueprint, render_template
+import requests
+
+from flask import Blueprint, render_template... |
5af61cae2ca438880357f88533cfa77ea161efac | corehq/ex-submodules/pillow_retry/admin.py | corehq/ex-submodules/pillow_retry/admin.py | from django.contrib import admin
from .models import PillowError
class PillowErrorAdmin(admin.ModelAdmin):
model = PillowError
list_display = [
'pillow',
'doc_id',
'error_type',
'date_created',
'date_last_attempt',
'date_next_attempt'
]
list_filter = ('... | from django.contrib import admin
from pillow_retry.models import PillowError
@admin.register(PillowError)
class PillowErrorAdmin(admin.ModelAdmin):
model = PillowError
list_display = [
'pillow',
'doc_id',
'error_type',
'date_created',
'date_last_attempt',
'dat... | Add delete action to PillowRetry | Add delete action to PillowRetry
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -1,7 +1,9 @@
from django.contrib import admin
-from .models import PillowError
+
+from pillow_retry.models import PillowError
+@admin.register(PillowError)
class PillowErrorAdmin(admin.ModelAdmin):
model = PillowError
@@ -14,6 +16,6 @@
'date_next_attempt'
]
list_filter = ('p... |
441e93cf96aa247a0cce36892e654de17ad44a8a | test/streamparse/cli/test_worker_uptime.py | test/streamparse/cli/test_worker_uptime.py | from __future__ import absolute_import, unicode_literals
import argparse
import unittest
from streamparse.cli.worker_uptime import subparser_hook
from nose.tools import ok_
class WorkerUptimeTestCase(unittest.TestCase):
def test_subparser_hook(self):
parser = argparse.ArgumentParser()
subparse... | from __future__ import absolute_import, unicode_literals
import argparse
import unittest
from streamparse.cli.worker_uptime import subparser_hook
from nose.tools import ok_
class WorkerUptimeTestCase(unittest.TestCase):
def test_subparser_hook(self):
parser = argparse.ArgumentParser()
subparse... | Fix unit test after worker-uptime changed to worker_uptime | Fix unit test after worker-uptime changed to worker_uptime
| Python | apache-2.0 | Parsely/streamparse,crohling/streamparse,petchat/streamparse,Parsely/streamparse,petchat/streamparse,hodgesds/streamparse,petchat/streamparse,codywilbourn/streamparse,phanib4u/streamparse,codywilbourn/streamparse,msmakhlouf/streamparse,msmakhlouf/streamparse,eric7j/streamparse,petchat/streamparse,crohling/streamparse,m... | ---
+++
@@ -16,7 +16,7 @@
subparser_hook(subparsers)
subcommands = parser._optionals._actions[1].choices.keys()
- ok_('worker-uptime' in subcommands)
+ ok_('worker_uptime' in subcommands)
if __name__ == '__main__': |
19d2dff39988309123ef97b4bb38a2eac6d18de1 | tests/integration/api/test_sc_test_jobs.py | tests/integration/api/test_sc_test_jobs.py | from tests.base import BaseTest
from tenable_io.api.models import ScTestJob
class TestScTestJobsApi(BaseTest):
def test_status(self, client, image):
jobs = client.sc_test_jobs_api.list()
assert len(jobs) > 0, u'At least one job exists.'
test_job = client.sc_test_jobs_api.status(jobs[0].j... | from tests.base import BaseTest
from tenable_io.api.models import ScTestJob
class TestScTestJobsApi(BaseTest):
def test_status(self, client, image):
jobs = client.sc_test_jobs_api.list()
assert len(jobs) > 0, u'At least one job exists.'
test_job = client.sc_test_jobs_api.status(jobs[0].j... | Fix for broken container security test | Fix for broken container security test
| Python | mit | tenable/Tenable.io-SDK-for-Python | ---
+++
@@ -16,7 +16,7 @@
assert isinstance(job, ScTestJob), u'The method returns type.'
def test_by_image_digest(self, client, image):
- job = client.sc_test_jobs_api.by_image(image['digest'])
+ job = client.sc_test_jobs_api.by_image_digest(image['digest'])
assert isinstance(jo... |
d7391bb7ef8d1cb2e900724f89f1753a7feb6fa7 | rsr/cmd.py | rsr/cmd.py | import os
import signal
import sys
from argparse import ArgumentParser
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('GtkSource', '3.0')
from gi.repository import Gio, GLib
from rsr import __version__
from rsr.app import Application
parser = ArgumentParser(prog='runsqlrun', description='Run SQL stat... | import os
import signal
import sys
from argparse import ArgumentParser
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('GtkSource', '3.0')
from gi.repository import Gio, GLib, Gtk
from rsr import __version__
from rsr.app import Application
parser = ArgumentParser(prog='runsqlrun', description='Run SQL... | Use dark theme if possible. | Use dark theme if possible.
| Python | mit | andialbrecht/runsqlrun | ---
+++
@@ -7,7 +7,7 @@
gi.require_version('Gtk', '3.0')
gi.require_version('GtkSource', '3.0')
-from gi.repository import Gio, GLib
+from gi.repository import Gio, GLib, Gtk
from rsr import __version__
from rsr.app import Application
@@ -31,5 +31,8 @@
resource = Gio.resource_load('data/runsqlrun.gresour... |
3b07818db48a5e3a205389051ccd9640e1079cc7 | tests/lib/__init__.py | tests/lib/__init__.py | from os.path import abspath, dirname, join
import sh
import psycopg2
import requests
PROJECT_FOLDER=dirname(dirname(abspath(__file__)))
DOCKER_FOLDER=join(PROJECT_FOLDER, 'docker')
def docker_compose(version, *args):
sh.docker_compose('-f', 'docker/{version}/docker-compose.yml'.format(version=version), *args)
d... | from os.path import abspath, dirname, join
import sh
import psycopg2
import requests
import time
PROJECT_FOLDER=dirname(dirname(abspath(__file__)))
DOCKER_FOLDER=join(PROJECT_FOLDER, 'docker')
def docker_compose(version, *args):
sh.docker_compose('-f', 'docker/{version}/docker-compose.yml'.format(version=version... | Make the lib pretty complete | Make the lib pretty complete
Should be able to replicate set up and tear down now
| Python | mit | matthewfranglen/postgres-elasticsearch-fdw | ---
+++
@@ -3,6 +3,7 @@
import sh
import psycopg2
import requests
+import time
PROJECT_FOLDER=dirname(dirname(abspath(__file__)))
DOCKER_FOLDER=join(PROJECT_FOLDER, 'docker')
@@ -10,14 +11,17 @@
def docker_compose(version, *args):
sh.docker_compose('-f', 'docker/{version}/docker-compose.yml'.format(versi... |
0b6cdcf91783e562d1da230e7658ba43b6ed5543 | tests/test_unicode.py | tests/test_unicode.py | # coding: utf-8
import logging
import os
import shutil
import sys
import tempfile
import unittest
import six
import fiona
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
class UnicodePathTest(unittest.TestCase):
def setUp(self):
tempdir = tempfile.mkdtemp()
self.dir = os.path.join(... | # coding: utf-8
import logging
import os
import shutil
import sys
import tempfile
import unittest
import six
import fiona
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
class UnicodePathTest(unittest.TestCase):
def setUp(self):
tempdir = tempfile.mkdtemp()
self.dir = os.path.join(... | Clean up parent temporary directory | TST: Clean up parent temporary directory
| Python | bsd-3-clause | johanvdw/Fiona,rbuffat/Fiona,Toblerity/Fiona,perrygeo/Fiona,rbuffat/Fiona,Toblerity/Fiona,perrygeo/Fiona | ---
+++
@@ -21,7 +21,7 @@
shutil.copytree('docs/data/', self.dir)
def tearDown(self):
- shutil.rmtree(self.dir)
+ shutil.rmtree(os.path.dirname(self.dir))
def test_unicode_path(self):
path = self.dir + '/test_uk.shp' |
25054586406024e082f9836884d5198ffa669f5b | models/ras_220_genes/build_ras_gene_network.py | models/ras_220_genes/build_ras_gene_network.py | from indra.tools.gene_network import GeneNetwork, grounding_filter
import csv
# STEP 0: Get gene list
gene_list = []
# Get gene list from ras_pathway_proteins.csv
with open('../../data/ras_pathway_proteins.csv') as f:
csvreader = csv.reader(f, delimiter='\t')
for row in csvreader:
gene_list.append(row[... | from indra.tools.gene_network import GeneNetwork, grounding_filter
import csv
import pickle
# STEP 0: Get gene list
gene_list = []
# Get gene list from ras_pathway_proteins.csv
with open('../../data/ras_pathway_proteins.csv') as f:
csvreader = csv.reader(f, delimiter='\t')
for row in csvreader:
gene_li... | Save the results of ras network | Save the results of ras network
| Python | bsd-2-clause | bgyori/indra,sorgerlab/belpy,johnbachman/indra,johnbachman/belpy,johnbachman/belpy,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,jmuhlich/indra,bgyori/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,sorgerlab/belpy,jmuhlich/indra,bgyori/indra,sorgerlab/indra,pvtodorov/indra,jmuhlich/indra,pv... | ---
+++
@@ -1,5 +1,6 @@
from indra.tools.gene_network import GeneNetwork, grounding_filter
import csv
+import pickle
# STEP 0: Get gene list
gene_list = []
@@ -13,4 +14,6 @@
stmts = gn.get_statements(filter=True)
grounded_stmts = grounding_filter(stmts)
results = gn.run_preassembly(grounded_stmts)
+with open... |
c98ab8807440e3cdbb98e11c53c7f246c35614fe | dedupe/convenience.py | dedupe/convenience.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
random_pairs = dedupe.core.randomPairs(len(data), sample_size)
... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPair... | Change dataSample to generate indices of random pair using list of values | Change dataSample to generate indices of random pair using list of values
| Python | mit | nmiranda/dedupe,01-/dedupe,neozhangthe1/dedupe,neozhangthe1/dedupe,nmiranda/dedupe,davidkunio/dedupe,dedupeio/dedupe,dedupeio/dedupe-examples,datamade/dedupe,tfmorris/dedupe,tfmorris/dedupe,davidkunio/dedupe,01-/dedupe,datamade/dedupe,pombredanne/dedupe,dedupeio/dedupe,pombredanne/dedupe | ---
+++
@@ -13,10 +13,10 @@
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
+ data_list = data.values()
+ random_pairs = dedupe.core.randomPairs(len(data_list), sample_size)
- random_pairs = dedupe.core.randomPairs(len(data), sample_size)
-
- retu... |
7733a84dc95d43070f476be42a3559b1a2a16ec0 | dataset/print.py | dataset/print.py | import json
with open('dataset_item.json') as dataset_file:
dataset = json.load(dataset_file)
for i in range(len(dataset)):
if 'Continual' == dataset[i]['frequency']:
print dataset[i]['name']
| import json
dataset = []
dataset_files = ['dataset_item.json']
for f in dataset_files:
with open(f) as file:
for line in file:
dataset.append(json.loads(file))
for i in range(len(dataset)):
if 'Continual' == dataset[i]['frequency']:
print dataset[i]['name']
| Update to line by line dataset JSON file parsing | Update to line by line dataset JSON file parsing
New format under Feed Exports
| Python | mit | MaxLikelihood/CODE | ---
+++
@@ -1,7 +1,12 @@
import json
-with open('dataset_item.json') as dataset_file:
- dataset = json.load(dataset_file)
+dataset = []
+dataset_files = ['dataset_item.json']
+
+for f in dataset_files:
+ with open(f) as file:
+ for line in file:
+ dataset.append(json.loads(file))
for i i... |
fe6891c949de75626396167a4aae78b276ed0223 | pkg_resources/tests/test_markers.py | pkg_resources/tests/test_markers.py | try:
import unitest.mock as mock
except ImportError:
import mock
from pkg_resources import evaluate_marker
@mock.patch('platform.python_version', return_value='2.7.10')
def test_ordering(python_version_mock):
assert evaluate_marker("python_full_version > '2.7.3'") is True
| try:
import unittest.mock as mock
except ImportError:
import mock
from pkg_resources import evaluate_marker
@mock.patch('platform.python_version', return_value='2.7.10')
def test_ordering(python_version_mock):
assert evaluate_marker("python_full_version > '2.7.3'") is True
| Fix typo, correcting failures on late Pythons when mock is not already installed. | Fix typo, correcting failures on late Pythons when mock is not already installed.
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -1,5 +1,5 @@
try:
- import unitest.mock as mock
+ import unittest.mock as mock
except ImportError:
import mock
|
2fd940a4c0eb047f2f5ac59fe04646e3e132e879 | api_client/python/setup.py | api_client/python/setup.py | #!/usr/bin/env python
# Copyright 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | #!/usr/bin/env python
# Copyright 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | Change version of API client | Change version of API client
| Python | apache-2.0 | google/timesketch,google/timesketch,google/timesketch,google/timesketch | ---
+++
@@ -20,8 +20,8 @@
setup(
name=u'timesketch-api-client',
- version=u'20170721',
- description=u'Timesketch',
+ version=u'20170815',
+ description=u'Timesketch API client',
license=u'Apache License, Version 2.0',
url=u'http://www.timesketch.org/',
maintainer=u'Timesketch devel... |
3de4665adae5f289fa896aa211ec32f72d956342 | testproject/testproject/urls.py | testproject/testproject/urls.py | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from testproject import views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'testproject.views.home', name='home'),
# url(r'^blog/', includ... | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from testproject import views
urlpatterns = [
# Examples:
# url(r'^$', 'testproject.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
... | Remove use of deprecated patterns function | Remove use of deprecated patterns function
| Python | mit | vittoriozamboni/django-groups-manager,vittoriozamboni/django-groups-manager | ---
+++
@@ -1,11 +1,11 @@
from django.conf import settings
-from django.conf.urls import patterns, include, url
+from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from testproject import views
-urlpatterns = patterns('',
+urlpatterns = [
... |
a75d14ec1792404eadf4b23570c7d198839c97d2 | day-02/solution.py | day-02/solution.py | from __future__ import print_function
import fileinput
from operator import mul
from functools import reduce
totalArea = 0
totalRibbon = 0
for line in fileinput.input():
parts = [int(i) for i in line.split('x')]
parts.sort()
sides = [parts[0] * parts[1], parts[0] * parts[2], parts[1] * parts[2]]
total... | from __future__ import print_function
import fileinput
from operator import mul
from functools import reduce
import itertools
totalArea = 0
totalRibbon = 0
for line in fileinput.input():
parts = [int(i) for i in line.split('x')]
parts.sort()
sides = [x * y for x, y in itertools.combinations(parts, 2)]
... | Use itertools for better readability. | Use itertools for better readability.
| Python | mit | bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adv... | ---
+++
@@ -2,6 +2,7 @@
import fileinput
from operator import mul
from functools import reduce
+import itertools
totalArea = 0
totalRibbon = 0
@@ -9,10 +10,9 @@
parts = [int(i) for i in line.split('x')]
parts.sort()
- sides = [parts[0] * parts[1], parts[0] * parts[2], parts[1] * parts[2]]
- t... |
68430e78313526a0b14b6d5abae810eb9c1ad53e | setup.py | setup.py | from setuptools import setup
import os
from appkit import __version__
data = list()
for d in os.walk('appkit/'):
if len(d[2]) > 0:
path_list = [str.join('/', os.path.join(d[0], x).split('/')[1:]) for x in d[2]]
data.extend(path_list)
requires = ['flask', 'pygobject',]
requires.append('beautifulso... | from setuptools import setup
import os
from appkit import __version__
data = list()
for d in os.walk('appkit/'):
if len(d[2]) > 0:
path_list = [str.join('/', os.path.join(d[0], x).split('/')[1:]) for x in d[2]]
data.extend(path_list)
requires = ['flask', 'pygobject',]
requires.append('beautifulso... | Fix package name to match PyPI | Fix package name to match PyPI
| Python | mit | nitipit/appkit | ---
+++
@@ -13,7 +13,7 @@
requires.append('beautifulsoup4') # v0_2_4 backward compatibility
setup(
- name='appkit',
+ name='AppKit',
version=__version__,
description='Desktop application framework based on Webkit' +
' HTML5, CSS3, Javascript and Python', |
c07bacb73eec4b963ec53c067f23385dad246fb6 | setup.py | setup.py |
from distutils.core import setup
setup(name='zencoder',
version='0.5.2',
description='Integration library for Zencoder',
author='Alex Schworer',
author_email='alex.schworer@gmail.com',
url='http://github.com/schworer/zencoder-py',
license="MIT License",
install_requires=['htt... |
from distutils.core import setup
setup(name='zencoder',
version='0.5.2',
description='Integration library for Zencoder',
author='Alex Schworer',
author_email='alex.schworer@gmail.com',
url='http://github.com/schworer/zencoder-py',
license="MIT License",
install_requires=['htt... | Add classifiers to zencoder-py package | Add classifiers to zencoder-py package
| Python | mit | zencoder/zencoder-py | ---
+++
@@ -9,6 +9,18 @@
url='http://github.com/schworer/zencoder-py',
license="MIT License",
install_requires=['httplib2'],
- packages=['zencoder']
+ packages=['zencoder'],
+ platforms='any',
+ classifiers=[
+ 'Development Status :: 4 - Beta',
+ 'Intended Au... |
2eea58a64c57c5a66c13220a66b92c4dc9f7fdb3 | setup.py | setup.py | import sys
from setuptools import setup, find_packages
py26_dependency = []
if sys.version_info.major == 2 and sys.version_info.minor < 7:
py26_dependency = ["argparse >= 1.2.1"]
setup(
name='dataset',
version='0.3.14',
description="Toolkit for Python-based data processing.",
long_description="",... | import sys
from setuptools import setup, find_packages
py26_dependency = []
if sys.version_info <= (2, 6):
py26_dependency = ["argparse >= 1.2.1"]
setup(
name='dataset',
version='0.3.14',
description="Toolkit for Python-based data processing.",
long_description="",
classifiers=[
"Deve... | Fix Python version detection for Python 2.6 | Fix Python version detection for Python 2.6 | Python | mit | reubano/dataset,vguzmanp/dataset,pudo/dataset,askebos/dataset,stefanw/dataset,twds/dataset,saimn/dataset | ---
+++
@@ -3,7 +3,7 @@
py26_dependency = []
-if sys.version_info.major == 2 and sys.version_info.minor < 7:
+if sys.version_info <= (2, 6):
py26_dependency = ["argparse >= 1.2.1"]
setup( |
dfca8ac68d69e533b954462094890faf0e723891 | autopoke.py | autopoke.py | #!/bin/env python
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from time import sleep
from getpass import getpass
if __name__ == '__main__':
driver = webdriver.phantomjs.webdriver.WebDriver()
driver.get('https://facebook.com')
driver.find_element_by_... | #!/bin/env python
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from time import sleep
from getpass import getpass
if __name__ == '__main__':
driver = webdriver.phantomjs.webdriver.WebDriver()
driver.get('https://facebook.com')
driver.find_element_by_... | Fix bug where page stops updating by forcing it to reload after a minute of no activity | Fix bug where page stops updating by forcing it to reload after a minute
of no activity
| Python | mit | matthewbentley/autopoke | ---
+++
@@ -15,14 +15,20 @@
assert "Forgot password?" not in driver.page_source
c = 0
+ c2 = 0
while True:
try:
for i in driver.find_elements_by_link_text("Poke Back"):
i.click()
c += 1
+ c2 = 0
print("Clicked ... |
7cb65a86a1b0fe8a739fb81fb8a66f3d205142cb | setup.py | setup.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from chandra_aca import __version__
from setuptools import setup
try:
from testr.setup_helper import cmdclass
except ImportError:
cmdclass = {}
setup(name='chandra_aca',
author='Jean Connelly, Tom Aldcroft',
description='Chandra Aspe... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from chandra_aca import __version__
from setuptools import setup
try:
from testr.setup_helper import cmdclass
except ImportError:
cmdclass = {}
setup(name='chandra_aca',
author='Jean Connelly, Tom Aldcroft',
description='Chandra Aspe... | Add missing package data for flickering | Add missing package data for flickering
| Python | bsd-2-clause | sot/chandra_aca,sot/chandra_aca | ---
+++
@@ -16,7 +16,8 @@
zip_safe=False,
packages=['chandra_aca', 'chandra_aca.tests'],
package_data={'chandra_aca.tests': ['data/*.txt', 'data/*.dat'],
- 'chandra_aca': ['data/*.dat', 'data/star_probs/*.fits.gz']},
+ 'chandra_aca': ['data/*.dat', 'data/*.fi... |
9668fdcfe67bea8d8c84dedd1e5f9e2646474e76 | setup.py | setup.py | from distutils.core import setup
with open('README.md') as f:
long_description = f.read()
setup(
name = 'dont_argue',
packages = ['dont_argue'],
version = '0.1.1',
description = 'Dead-simple command line argument parsing',
long_description=long_description,
author = 'Chris Penner',
aut... | from distutils.core import setup
with open('README.md') as f:
long_description = f.read()
setup(
name = 'dont_argue',
packages = ['dont_argue'],
version = '0.1.1',
description = 'Dead-simple command line argument parsing',
long_description=long_description,
author = 'Chris Penner',
aut... | Change release tagging convention to vX.Y.Z | Change release tagging convention to vX.Y.Z
| Python | mit | ChrisPenner/dont-argue | ---
+++
@@ -12,7 +12,7 @@
author = 'Chris Penner',
author_email = 'christopher.penner@gmail.com',
url = 'https://github.com/ChrisPenner/dont-argue',
- download_url = 'https://github.com/ChrisPenner/dont-argue/releases/tag/0.1.1',
+ download_url = 'https://github.com/ChrisPenner/dont-argue/releas... |
2af4061d0add17e54c7ded45e34177efdffbc7db | setup.py | setup.py | # -*- coding: utf-8 -*-
import sys
if sys.version_info[0] != 2:
sys.exit("Sorry, Python 3 is not supported yet")
from setuptools import setup, find_packages
install_requires = [
'pytz',
'requests',
'lxml',
'python-dateutil',
'parsedatetime',
'cached-property',
'click',
'enum34', ... | # -*- coding: utf-8 -*-
from pathlib import Path
from setuptools import setup, find_packages
install_requires = [
'pytz',
'requests',
'lxml',
'python-dateutil',
'parsedatetime',
'cached-property',
'click',
'enum34', # backported versions from Python3
'pathlib',
'configparser'... | Make the package installable with python3 | Make the package installable with python3
| Python | mit | pokerregion/poker | ---
+++
@@ -1,9 +1,5 @@
# -*- coding: utf-8 -*-
-
-import sys
-if sys.version_info[0] != 2:
- sys.exit("Sorry, Python 3 is not supported yet")
-
+from pathlib import Path
from setuptools import setup, find_packages
@@ -40,7 +36,7 @@
name='poker',
version='0.23.1',
description='Poker Framework'... |
27c6df9b0e936ce4fb173ec64230931ffe0719c7 | querylist/querylist.py | querylist/querylist.py | from betterdict import BetterDict
class QueryList(list):
def __init__(self, data=None, wrapper=BetterDict):
"""Create a QueryList from an iterable and a wrapper object."""
self._wrapper = wrapper
self.src_data = data
# Wrap our src_data with wrapper
converted_data = self._... | from betterdict import BetterDict
class QueryList(list):
def __init__(self, data=None, wrapper=BetterDict):
"""Create a QueryList from an iterable and a wrapper object."""
self._wrapper = wrapper
self.src_data = data
# Wrap our src_data with wrapper
converted_data = self._... | Add missing docs tring to QueryList._convert_iterable() | Add missing docs tring to QueryList._convert_iterable()
| Python | mit | zoidbergwill/querylist,thomasw/querylist | ---
+++
@@ -13,6 +13,10 @@
super(QueryList, self).__init__(converted_data)
def _convert_iterable(self, iterable):
+ """Converts elements returned by an iterable into instances of
+ self._wrapper
+
+ """
# Return original if _wrapper isn't callable
if not callable... |
3d9911a6a2d24631b21850da6fe8f04787465b9e | example-flask-python3.6-index/app/main.py | example-flask-python3.6-index/app/main.py | from flask import Flask, send_file
app = Flask(__name__)
@app.route("/hello")
def hello():
return "Hello World from Flask in a uWSGI Nginx Docker container with \
Python 3.6 (from the example template)"
@app.route("/")
def main():
return send_file('./static/index.html')
# Everything not declared before ... | import os
from flask import Flask, send_file
app = Flask(__name__)
@app.route("/hello")
def hello():
return "Hello World from Flask in a uWSGI Nginx Docker container with \
Python 3.6 (from the example template)"
@app.route("/")
def main():
return send_file('./static/index.html')
# Everything not de... | Fix not imported os and format code | Fix not imported os and format code
| Python | apache-2.0 | tiangolo/uwsgi-nginx-flask-docker,tiangolo/uwsgi-nginx-flask-docker,tiangolo/uwsgi-nginx-flask-docker | ---
+++
@@ -1,14 +1,19 @@
+import os
+
from flask import Flask, send_file
app = Flask(__name__)
+
@app.route("/hello")
def hello():
return "Hello World from Flask in a uWSGI Nginx Docker container with \
Python 3.6 (from the example template)"
+
@app.route("/")
def main():
return send_file('... |
31d0cd541980ef6bf15d3a29b68cc0cc994c28a4 | packs/st2cd/actions/kvstore.py | packs/st2cd/actions/kvstore.py | from st2actions.runners.pythonrunner import Action
from st2client.client import Client
from st2client.models.datastore import KeyValuePair
class KVPAction(Action):
def run(self, key, action, st2host='localhost', value=""):
st2_endpoints = {
'action': "http://%s:9101" % st2host,
'r... | from st2actions.runners.pythonrunner import Action
from st2client.client import Client
from st2client.models.datastore import KeyValuePair
class KVPAction(Action):
def run(self, key, action, st2host='localhost', value=""):
st2_endpoints = {
'action': "http://%s:9101" % st2host,
'r... | Fix create action for key value pair | Fix create action for key value pair
| Python | apache-2.0 | StackStorm/st2incubator,pinterb/st2incubator,pinterb/st2incubator,pinterb/st2incubator,StackStorm/st2incubator | ---
+++
@@ -25,16 +25,12 @@
return kvp.value
else:
- instance = KeyValuePair()
- instance.id = client.keys.get_by_name(key).name
+ instance = client.keys.get_by_name(key) or KeyValuePair()
+ instance.id = key
instance.name = key
... |
c2272f7d23645932b72617b1b20e5ddd86267ef0 | app/letter_branding/letter_branding_rest.py | app/letter_branding/letter_branding_rest.py | from flask import Blueprint
from app.errors import register_errors
email_branding_blueprint = Blueprint('letter_branding', __name__, url_prefix='letter-branding')
register_errors(email_branding_blueprint) | from flask import Blueprint
from app.errors import register_errors
email_branding_blueprint = Blueprint('letter_branding', __name__, url_prefix='letter-branding')
register_errors(email_branding_blueprint)
| Fix mock in unit test. Not sure why it passed locally with previous mock. | Fix mock in unit test. Not sure why it passed locally with previous mock.
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | |
a0ff3446a177d11268c49b37c03f0d495341fe81 | banana/maya/extensions/OpenMaya/__init__.py | banana/maya/extensions/OpenMaya/__init__.py | """
banana.maya.extensions.OpenMaya
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
OpenMaya extensions.
:copyright: Copyright 2014 by Christopher Crouzet.
:license: MIT, see LICENSE for details.
"""
__all__ = [
'iterators',
'MDagPath',
'MFileIO',
'MFnDagNode',
'MFnDependencyNode',
... | """
banana.maya.extensions.OpenMaya
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
OpenMaya extensions.
:copyright: Copyright 2014 by Christopher Crouzet.
:license: MIT, see LICENSE for details.
"""
__all__ = [
'iterators',
'MDagPath',
'MFileIO',
'MFnDagNode',
'MFnDependencyNode',
... | Add the missing `MGlobal` module to the `__all__` attribute. | Add the missing `MGlobal` module to the `__all__` attribute.
| Python | mit | christophercrouzet/bana,christophercrouzet/banana.maya | ---
+++
@@ -15,5 +15,6 @@
'MFnDagNode',
'MFnDependencyNode',
'MFnTransform',
+ 'MGlobal',
'MObject'
] |
5868f46a05ef19862ea81b4e402851a3e40ceeff | events/serializers.py | events/serializers.py | from .models import Event, EventActivity
from employees.serializers import LocationSerializer
from rest_framework import serializers
class EventSerializer(serializers.ModelSerializer):
location = LocationSerializer()
class Meta(object):
model = Event
depth = 1
fields = ("pk", "name", ... | from .models import Event, EventActivity
from employees.serializers import LocationSerializer
from rest_framework import serializers
class EventSerializer(serializers.ModelSerializer):
location = LocationSerializer()
class Meta(object):
model = Event
depth = 1
fields = ("pk", "name", ... | Remove is_upcoming field from Event response and Add explicit fields to EventActivity serializer | Remove is_upcoming field from Event response and Add explicit fields to EventActivity serializer
| Python | apache-2.0 | belatrix/BackendAllStars | ---
+++
@@ -9,7 +9,7 @@
class Meta(object):
model = Event
depth = 1
- fields = ("pk", "name", "image", "datetime", "address", "description", "is_active", "is_upcoming", "location")
+ fields = ("pk", "name", "image", "datetime", "address", "description", "is_active", "location")
... |
f9f41ec4f27ba5fd19ca82d4c04b13bed6627d23 | app/PRESUBMIT.py | app/PRESUBMIT.py | #!/usr/bin/python
# Copyright (c) 2009 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.
"""Makes sure that the app/ code is cpplint clean."""
INCLUDE_CPP_FILES_ONLY = (
r'.*\.cc$', r'.*\.h$'
)
EXCLUDE = (
# Autogener... | #!/usr/bin/python
# Copyright (c) 2009 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.
"""Makes sure that the app/ code is cpplint clean."""
INCLUDE_CPP_FILES_ONLY = (
r'.*\.cc$', r'.*\.h$'
)
EXCLUDE = (
# Autogener... | Make all changes to app/ run on all trybot platforms, not just the big three. Anyone who's changing a header here may break the chromeos build. | Make all changes to app/ run on all trybot platforms, not just the big three.
Anyone who's changing a header here may break the chromeos build.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/2838027
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@51000 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | rogerwang/chromium,Fireblend/chromium-crosswalk,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,dushu1203/chromium.src,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,Fireblend/chromium-crosswalk,zc... | ---
+++
@@ -23,3 +23,6 @@
results.extend(input_api.canned_checks.CheckChangeLintsClean(
input_api, output_api, sources))
return results
+
+def GetPreferredTrySlaves():
+ return ['win', 'linux', 'linux_view', 'linux_chromeos', 'mac'] |
a55f816072503241bd1ff4e953de12a7b48af4ac | backend/unimeet/helpers.py | backend/unimeet/helpers.py | from .models import School, User
import re
import string
import random
def get_school_list():
schools = School.objects.all()
school_list = []
for s in schools:
school = {}
school['id'] = s.id
school['name'] = s.name
school['site'] = s.site
school['university'] = s.u... | from .models import School, User
import re
import string
import random
from mail import send_mail
def get_school_list():
schools = School.objects.all()
school_list = []
for s in schools:
school = {}
school['id'] = s.id
school['name'] = s.name
school['site'] = s.site
... | Use send_mail in signup helper function | Use send_mail in signup helper function
| Python | mit | dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet | ---
+++
@@ -2,6 +2,7 @@
import re
import string
import random
+from mail import send_mail
def get_school_list():
@@ -32,5 +33,4 @@
user_obj = User.objects.create_user(email=email, school=school, password=password, token=token)
user_obj.interestedInSchools.set(School.objects.all().values_list('id', f... |
4b1b5d0b71100fea17f127683a58533ef0e06fe9 | bintools/splitter.py | bintools/splitter.py | import os
# Splits a file using the dsplit mechanism
def dsplit(fromfile, todir, chunksize = 1024):
if not os.path.exists(todir): # caller handles errors
os.mkdir(todir) # make dir, read/write parts
original_file = os.path.basename(fromfile)
filesize = o... | import os
# Splits a file using the dsplit mechanism
def dsplit(fromfile, todir = os.getcwd(), offset = 0, limit = None, chunksize = 1024):
if not os.path.exists(todir): # caller handles errors
os.mkdir(todir) # make dir, read/write parts
original_file = os.... | Refactor functions & add params | Refactor functions & add params
| Python | apache-2.0 | FernandoDoming/offset_finder | ---
+++
@@ -1,7 +1,7 @@
import os
# Splits a file using the dsplit mechanism
-def dsplit(fromfile, todir, chunksize = 1024):
+def dsplit(fromfile, todir = os.getcwd(), offset = 0, limit = None, chunksize = 1024):
if not os.path.exists(todir): # caller handles errors
os.mkdir(todir) ... |
fab9ff4d5d0f04f4ebfe86ed407b16ea73110a04 | apps/package/templatetags/package_tags.py | apps/package/templatetags/package_tags.py | from datetime import timedelta
from datetime import datetime
from django import template
from github2.client import Github
from package.models import Package, Commit
register = template.Library()
github = Github()
@register.filter
def commits_over_52(package):
current = datetime.now()
weeks = []
comm... | from datetime import datetime, timedelta
from django import template
from package.models import Commit
register = template.Library()
@register.filter
def commits_over_52(package):
current = datetime.now()
weeks = []
commits = Commit.objects.filter(package=package).values_list('commit_date', flat=True)
... | Clean up some imports in the package app's template_tags.py file. | Clean up some imports in the package app's template_tags.py file.
| Python | mit | QLGu/djangopackages,pydanny/djangopackages,cartwheelweb/packaginator,nanuxbe/djangopackages,cartwheelweb/packaginator,audreyr/opencomparison,QLGu/djangopackages,nanuxbe/djangopackages,pydanny/djangopackages,miketheman/opencomparison,pydanny/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages,miketheman/opencompar... | ---
+++
@@ -1,15 +1,10 @@
-from datetime import timedelta
-from datetime import datetime
+from datetime import datetime, timedelta
from django import template
-from github2.client import Github
-
-from package.models import Package, Commit
+from package.models import Commit
register = template.Library()
-
-gi... |
d3a24fae87005b7f5c47657851b4341726494383 | atest/resources/atest_variables.py | atest/resources/atest_variables.py | from os.path import abspath, dirname, join, normpath
import locale
import os
import subprocess
import robot
__all__ = ['ROBOTPATH', 'ROBOT_VERSION', 'DATADIR', 'SYSTEM_ENCODING',
'CONSOLE_ENCODING']
ROBOTPATH = dirname(abspath(robot.__file__))
ROBOT_VERSION = robot.version.get_version()
DATADIR = normpa... | from os.path import abspath, dirname, join, normpath
import locale
import os
import subprocess
import robot
__all__ = ['ROBOTPATH', 'ROBOT_VERSION', 'DATADIR', 'SYSTEM_ENCODING',
'CONSOLE_ENCODING']
ROBOTPATH = dirname(abspath(robot.__file__))
ROBOT_VERSION = robot.version.get_version()
DATADIR = normpa... | Fix getting Windows system encoding on non-ASCII envs | atests: Fix getting Windows system encoding on non-ASCII envs
| Python | apache-2.0 | HelioGuilherme66/robotframework,robotframework/robotframework,HelioGuilherme66/robotframework,robotframework/robotframework,HelioGuilherme66/robotframework,robotframework/robotframework | ---
+++
@@ -17,7 +17,8 @@
SYSTEM_ENCODING = locale.getpreferredencoding(False)
# Python 3.6+ uses UTF-8 internally on Windows. We want real console encoding.
if os.name == 'nt':
- output = subprocess.check_output('chcp', shell=True, encoding='ASCII')
+ output = subprocess.check_output('chcp', shell=True, enc... |
f21796d28ebf9328b68c6321d691b221457bafa6 | jenkins/scripts/pypi-extract-universal.py | jenkins/scripts/pypi-extract-universal.py | #!/usr/bin/python
#
# 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
#... | #!/usr/bin/python
#
# 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
#... | Fix universal extraction in non-universal wheel | Fix universal extraction in non-universal wheel
The pypi-extract-universal.py would raise ConfigParser.NoOptionError
when inspecting a setup.cfg with a wheel section but no universal
option. Guard against this by actually testing whether the option is
there rather than merely whether the section exists.
Change-Id: I7... | Python | apache-2.0 | Tesora/tesora-project-config,coolsvap/project-config,noorul/os-project-config,Tesora/tesora-project-config,dongwenjuan/project-config,dongwenjuan/project-config,openstack-infra/project-config,openstack-infra/project-config,anbangr/osci-project-config,coolsvap/project-config,anbangr/osci-project-config,noorul/os-project... | ---
+++
@@ -20,7 +20,7 @@
setup_cfg = ConfigParser.SafeConfigParser()
setup_cfg.read("setup.cfg")
-if setup_cfg.has_section("wheel"):
+if setup_cfg.has_option("wheel", "universal"):
universal = setup_cfg.getboolean("wheel", "universal")
if universal:
print("py2.py3") |
757df7c04d862feb9067ae52c83875fc2e3aedf8 | cla_backend/apps/cla_provider/admin/base.py | cla_backend/apps/cla_provider/admin/base.py | from django.contrib import admin
from core.admin.modeladmin import OneToOneUserAdmin
from ..models import Provider, ProviderAllocation, Staff, OutOfHoursRota
from .forms import StaffAdminForm
class StaffAdmin(OneToOneUserAdmin):
model = Staff
form = StaffAdminForm
actions = None
list_display = (
... | from django.contrib import admin
from core.admin.modeladmin import OneToOneUserAdmin
from ..models import Provider, ProviderAllocation, Staff, OutOfHoursRota
from .forms import StaffAdminForm
class StaffAdmin(OneToOneUserAdmin):
model = Staff
form = StaffAdminForm
actions = None
list_display = (
... | Disable ProviderAllocation admin page, still accessible from Provider Inlines | Disable ProviderAllocation admin page, still accessible from Provider Inlines
| Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | ---
+++
@@ -44,6 +44,5 @@
admin.site.register(Provider, ProviderAdmin)
-admin.site.register(ProviderAllocation)
admin.site.register(OutOfHoursRota)
admin.site.register(Staff, StaffAdmin) |
f5d2cc8406b16fe2f0d4f640109dbb9a1ceba8d8 | purchase_discount/models/purchase_order.py | purchase_discount/models/purchase_order.py | # -*- coding: utf-8 -*-
# © 2004-2009 Tiny SPRL (<http://tiny.be>).
# © 2015 Pedro M. Baeza
# © 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import api, fields, models
import openerp.addons.decimal_precision as dp
class PurchaseOrderLine(models.Mo... | # -*- coding: utf-8 -*-
# © 2004-2009 Tiny SPRL (<http://tiny.be>).
# © 2015 Pedro M. Baeza
# © 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import api, fields, models
import openerp.addons.decimal_precision as dp
class PurchaseOrderLine(models.Mo... | Fix issue with multiple lines | Fix issue with multiple lines
| Python | agpl-3.0 | OCA/purchase-workflow,OCA/purchase-workflow | ---
+++
@@ -20,7 +20,7 @@
super(PurchaseOrderLine, self)._compute_amount()
# restore prices
for line in self:
- if self.discount:
+ if line.discount:
line.price_unit = prices[line.id]
discount = fields.Float( |
b8bf868d6ae7dbeb695dac36d5f72231d429d180 | clone-vm.py | clone-vm.py | #!/usr/bin/env python
import os
import sys
# Set arguments values
if len(sys.argv) == 1:
print "Usage: clone-vm.py [new-vm-name]"
exit(1)
else:
new_vm_name = sys.argv[1]
vms_home_dir = os.getenv('HOME') + '/Documents/Virtual\ Machines.localized/'
vms_home_dir_not_escaped = os.getenv('HOME') + '/Documents/Vi... | #!/usr/bin/env python
import os, sys
# Set arguments values
if len(sys.argv) == 1:
print "Usage: clone-vm.py [new-vm-name]"
exit(1)
else:
new_vm_name = sys.argv[1]
vms_path_dir = os.getenv('HOME') + '/Documents/Virtual Machines.localized/'
vm_source_vmx = vms_home_dir + 'base-centos-64.vmwarevm/base-centos... | Delete escped variable, replaced with single quotes | Delete escped variable, replaced with single quotes
| Python | apache-2.0 | slariviere/py-vmrum,slariviere/py-vmrum | ---
+++
@@ -1,7 +1,6 @@
#!/usr/bin/env python
-import os
-import sys
+import os, sys
# Set arguments values
if len(sys.argv) == 1:
@@ -10,19 +9,17 @@
else:
new_vm_name = sys.argv[1]
-vms_home_dir = os.getenv('HOME') + '/Documents/Virtual\ Machines.localized/'
-vms_home_dir_not_escaped = os.getenv('HOME'... |
f2a0c0c7329087421f6d3c237d2bb5f9633d180c | linear_math_tests/test_alignedobjectarray.py | linear_math_tests/test_alignedobjectarray.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
linear_math_tests.test_alignedobjectarray
"""
from __future__ import unicode_literals, print_function, absolute_import
import unittest
import math
import bullet
class ClassTestName(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
linear_math_tests.test_alignedobjectarray
"""
from __future__ import unicode_literals, print_function, absolute_import
import unittest
import math
import bullet
class ClassTestName(unittest.TestCase):
def setUp(self):
self.a = bullet.btVector3Array()
... | Add some basic tests for assignment. Note that slicing is not supported | Add some basic tests for assignment. Note that slicing is not supported
| Python | mit | Klumhru/boost-python-bullet,Klumhru/boost-python-bullet,Klumhru/boost-python-bullet | ---
+++
@@ -13,7 +13,23 @@
class ClassTestName(unittest.TestCase):
def setUp(self):
- pass
+ self.a = bullet.btVector3Array()
+ for i in range(10):
+ self.a.append(bullet.btVector3(i, i+1, i+2))
+ self.b = bullet.btVector3Array()
+ for i in range(10, 20):
+ ... |
941da2b1453cda2b981c5891fcc5d58c04df4544 | eve_api/tasks.py | eve_api/tasks.py | from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
acc = import_eve_account(api_key, api_userid, force_cache=force_cach... | import logging
from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
l = logging.getLogger('import_apikey')
l.info("Im... | Add some logging to the EVE API task | Add some logging to the EVE API task
| Python | bsd-3-clause | nikdoof/test-auth | ---
+++
@@ -1,3 +1,4 @@
+import logging
from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
@@ -5,6 +6,8 @@
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
+ l = logging.getLogger('import_apikey')
+ ... |
698a3fe81a15b40b95836426f9292365f9f57c9c | cartoframes/core/cartodataframe.py | cartoframes/core/cartodataframe.py | from geopandas import GeoDataFrame
from ..utils.geom_utils import generate_index, generate_geometry
class CartoDataFrame(GeoDataFrame):
def __init__(self, *args, **kwargs):
index_column = kwargs.pop('index_column', None)
geom_column = kwargs.pop('geom_column', None)
lnglat_column = kwarg... | from geopandas import GeoDataFrame
from ..utils.geom_utils import generate_index, generate_geometry
class CartoDataFrame(GeoDataFrame):
def __init__(self, *args, **kwargs):
index_column = kwargs.pop('index_column', None)
geom_column = kwargs.pop('geom_column', None)
lnglat_column = kwarg... | Add a wrapper for from_file/from_features methods | Add a wrapper for from_file/from_features methods
| Python | bsd-3-clause | CartoDB/cartoframes,CartoDB/cartoframes | ---
+++
@@ -23,6 +23,16 @@
from ..io.carto import read_carto
return read_carto(*args, **kwargs)
+ @classmethod
+ def from_file(cls, filename, **kwargs):
+ gdf = GeoDataFrame.from_file(filename, **kwargs)
+ return cls(gdf)
+
+ @classmethod
+ def from_features(cls, features... |
9028bbd2f624196d6b28eaf7fcd3dccbcfca5f14 | py/oldfart/handler.py | py/oldfart/handler.py | import http.server
import os
import oldfart.make
__all__ = ['make_http_request_handler_class']
# The idea here is to modify the request handling by intercepting the
# `send_head` call which is combines the common bits of GET and HEAD commands
# and, more importantly, is the first method in the request handling pro... | import http.server
import os
import oldfart.make
__all__ = ['make_http_request_handler_class']
# The idea here is to modify the request handling by intercepting the
# `send_head` call which is combines the common bits of GET and HEAD commands
# and, more importantly, is the first method in the request handling pro... | Improve logging of build failure | Improve logging of build failure
| Python | bsd-3-clause | mjhanninen/oldfart,mjhanninen/oldfart,mjhanninen/oldfart | ---
+++
@@ -22,8 +22,9 @@
if not os.path.isdir(path):
retval, output = self.maker.make(target)
if retval == oldfart.make.FAILURE:
- self.log_error('Building resource failed:\n%s', output)
- self.send_error(500, 'Could not generate resource')
+ self.log_error('Bu... |
8f11aa020d5e539653120d5e895ea6f7b09392ce | cea/interfaces/dashboard/api/dashboard.py | cea/interfaces/dashboard/api/dashboard.py | from flask_restplus import Namespace, Resource, fields, abort
import cea.config
import cea.plots.cache
api = Namespace('Dashboard', description='Dashboard plots')
LAYOUTS = ['row', 'grid', 'map']
CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]}
for c... | from flask_restplus import Namespace, Resource, fields, abort
import cea.config
import cea.plots.cache
api = Namespace('Dashboard', description='Dashboard plots')
LAYOUTS = ['row', 'grid', 'map']
CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]}
for c... | Allow 'scenario-name' to be null if it does not exist | Allow 'scenario-name' to be null if it does not exist
| Python | mit | architecture-building-systems/CEAforArcGIS,architecture-building-systems/CEAforArcGIS | ---
+++
@@ -22,4 +22,6 @@
dashboards = cea.plots.read_dashboards(config, plot_cache)
return [{'name': d.name, 'description': d.description, 'layout': d.layout if d.layout in LAYOUTS else 'row',
- 'plots': [{'title': plot.title, 'scenario': plot.parameters['scenario-name']} for plo... |
cf57bc6d564fdaf2af71f9eb8114b2487ae94867 | meinberlin/config/settings/dev.py | meinberlin/config/settings/dev.py | from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
for template_engine in TEMPLATES:
template_engine['OPTIONS']['debug'] = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qid$h1o8&wh#p(j)lifis*5-rf@lbiy8%^3l4x%@b$z(tli@ab'
tr... | from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
for template_engine in TEMPLATES:
template_engine['OPTIONS']['debug'] = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qid$h1o8&wh#p(j)lifis*5-rf@lbiy8%^3l4x%@b$z(tli@ab'
# F... | Disable django debug toolbar until wagtail 1.12 is released | Disable django debug toolbar until wagtail 1.12 is released
see https://github.com/jazzband/django-debug-toolbar/issues/950 for
reference
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin | ---
+++
@@ -9,16 +9,17 @@
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qid$h1o8&wh#p(j)lifis*5-rf@lbiy8%^3l4x%@b$z(tli@ab'
-
-try:
- import debug_toolbar
-except ImportError:
- pass
-else:
- INSTALLED_APPS += ('debug_toolbar',)
- MIDDLEWARE += ('debug_toolbar.middle... |
c79714249a0278b49a19a6a219328c4a74453c2d | cme/modules/MachineAccountQuota.py | cme/modules/MachineAccountQuota.py | from impacket.ldap import ldapasn1 as ldapasn1_impacket
class CMEModule:
'''
Module by Shutdown and Podalirius
Initial module:
https://github.com/ShutdownRepo/CrackMapExec-MachineAccountQuota
Authors:
Shutdown: @_nwodtuhs
Podalirius: @podalirius_
'''
def option... | from impacket.ldap import ldapasn1 as ldapasn1_impacket
class CMEModule:
'''
Module by Shutdown and Podalirius
Initial module:
https://github.com/ShutdownRepo/CrackMapExec-MachineAccountQuota
Authors:
Shutdown: @_nwodtuhs
Podalirius: @podalirius_
'''
def option... | Remove error message when using MAQ module | Remove error message when using MAQ module
| Python | bsd-2-clause | byt3bl33d3r/CrackMapExec | ---
+++
@@ -22,13 +22,10 @@
opsec_safe = True
multiple_hosts = False
- def on_login(self, context, connection):
+ def on_login(self, context, connection):
result = []
context.log.info('Getting the MachineAccountQuota')
searchFilter = '(objectClass=*)'
attribu... |
7ed9b5dc23867381c34a77f31ccf4da5effbb0b0 | tracpro/orgs_ext/migrations/0002_auto_20150724_1609.py | tracpro/orgs_ext/migrations/0002_auto_20150724_1609.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from django.conf import settings
from django.db import models, migrations
def add_available_languages(apps, schema_editor):
"""Set default available_languages to all languages defined for this project."""
all_languages = [l[0] for l... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from django.conf import settings
from django.db import models, migrations
def add_available_languages(apps, schema_editor):
"""Set default available_languages to all languages defined for this project."""
all_languages = [l[0] for l... | Handle if org.config is None | Handle if org.config is None
| Python | bsd-3-clause | xkmato/tracpro,rapidpro/tracpro,xkmato/tracpro,rapidpro/tracpro,xkmato/tracpro,xkmato/tracpro,rapidpro/tracpro | ---
+++
@@ -12,7 +12,7 @@
all_languages = [l[0] for l in settings.LANGUAGES]
for org in apps.get_model('orgs', 'Org').objects.all():
updated = False
- config = json.loads(org.config)
+ config = json.loads(org.config) if org.config else {}
if not config.get('available_language... |
505a88eaa461eb99d67b36692869b6d4025a054f | gapipy/models/address.py | gapipy/models/address.py | from .base import BaseModel
class Address(BaseModel):
_as_is_fields = ['city', 'latitude', 'longitude', 'postal_zip', 'street']
_resource_fields = [('country', 'Country')]
def __repr__(self):
return '<{0}: {1}, {2}>'.format(
self.__class__.__name__, self.city, self.country.name)
| from .base import BaseModel
class Address(BaseModel):
_as_is_fields = ['city', 'latitude', 'longitude', 'postal_zip', 'street']
_resource_fields = [
('state', 'State'),
('country', 'Country')
]
def __repr__(self):
return '<{0}: {1}, {2}>'.format(
self.__class__.__n... | Add State to Address model definition. | Add State to Address model definition.
| Python | mit | gadventures/gapipy | ---
+++
@@ -3,7 +3,10 @@
class Address(BaseModel):
_as_is_fields = ['city', 'latitude', 'longitude', 'postal_zip', 'street']
- _resource_fields = [('country', 'Country')]
+ _resource_fields = [
+ ('state', 'State'),
+ ('country', 'Country')
+ ]
def __repr__(self):
return... |
481f4444e063d5559d396a5a26154b9ebde27248 | formspree/app.py | formspree/app.py | import json
import stripe
import flask
from flask import g
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager, current_user
from flask_redis import Redis
import settings
DB = SQLAlchemy()
redis_store = Redis()
stripe.api_key = settings.STRIPE_SECRET_KEY
import routes
from users.mode... | import json
import stripe
import os
import flask
from flask import g
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager, current_user
from flask.ext.cdn import CDN
from formspree import log
from flask_redis import Redis
import settings
DB = SQLAlchemy()
redis_store = Redis()
stripe.a... | Allow for static contents served over CDN | Allow for static contents served over CDN
| Python | agpl-3.0 | asm-products/formspree,asm-products/formspree,asm-products/formspree,asm-products/formspree | ---
+++
@@ -1,16 +1,20 @@
import json
import stripe
+import os
import flask
from flask import g
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager, current_user
+from flask.ext.cdn import CDN
+from formspree import log
from flask_redis import Redis
import settings
DB = S... |
fbadf23356b40c36378cef8f3a9c8b382bce9e32 | comics/core/admin.py | comics/core/admin.py | from django.contrib import admin
from comics.core import models
class ComicAdmin(admin.ModelAdmin):
list_display = ('slug', 'name', 'language', 'url', 'rights')
prepopulated_fields = {
'slug': ('name',)
}
class ReleaseAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'comic', 'pub_dat... | from django.contrib import admin
from comics.core import models
class ComicAdmin(admin.ModelAdmin):
list_display = ('slug', 'name', 'language', 'url', 'rights', 'start_date',
'end_date', 'active')
prepopulated_fields = {
'slug': ('name',)
}
class ReleaseAdmin(admin.ModelAdmin):
list... | Include start date, end date, and active flag in comics list | Include start date, end date, and active flag in comics list
| Python | agpl-3.0 | jodal/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,datagutten/comics,jodal/comics,datagutten/comics | ---
+++
@@ -4,7 +4,8 @@
class ComicAdmin(admin.ModelAdmin):
- list_display = ('slug', 'name', 'language', 'url', 'rights')
+ list_display = ('slug', 'name', 'language', 'url', 'rights', 'start_date',
+ 'end_date', 'active')
prepopulated_fields = {
'slug': ('name',)
} |
f2f078a866c0185a6194b3ebc8b0e7090b8adeca | src/wirecloud/core/catalogue_manager.py | src/wirecloud/core/catalogue_manager.py | # -*- coding: utf-8 -*-
# Copyright 2012 Universidad Politécnica de Madrid
# This file is part of Wirecloud.
# Wirecloud is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#... | # -*- coding: utf-8 -*-
# Copyright 2012 Universidad Politécnica de Madrid
# This file is part of Wirecloud.
# Wirecloud is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#... | Fix workspace publish on the local catalogue | Fix workspace publish on the local catalogue
| Python | agpl-3.0 | rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud | ---
+++
@@ -32,5 +32,5 @@
template = TemplateParser(build_template_from_workspace(publish_options, published_workspace.workspace, user))
resource = add_resource_from_template(published_workspace.get_template_url(request), template, user)
- resource.publish = True
+ resource.public = ... |
da729057ac482f4c03d4512a615ee86c9901bba9 | glitch/config.py | glitch/config.py | # Basic config for stuff that can be easily changed, but which is git-managed.
# See also apikeys_sample.py for the configs which are _not_ git-managed.
#server_domain = "http://www.infiniteglitch.net"
server_domain = "http://50.116.55.59"
http_port = 8888 # Port for the main web site, in debug mode
renderer_port = 81... | # Basic config for stuff that can be easily changed, but which is git-managed.
# See also apikeys_sample.py for the configs which are _not_ git-managed.
#server_domain = "http://www.infiniteglitch.net"
server_domain = "http://50.116.55.59"
http_port = 8888 # Port for the main web site, in debug mode
renderer_port = 88... | Revert to port 8889, as it appears that unicorn sets port 81. | Revert to port 8889, as it appears that unicorn sets port 81.
| Python | artistic-2.0 | MikeiLL/appension,MikeiLL/appension,MikeiLL/appension,MikeiLL/appension | ---
+++
@@ -4,7 +4,7 @@
server_domain = "http://50.116.55.59"
http_port = 8888 # Port for the main web site, in debug mode
-renderer_port = 81 # Port for the renderer (/all.mp3 and friends)
+renderer_port = 8889 # Port for the renderer (/all.mp3 and friends)
# Track limits in seconds
max_track_length = 400 |
80a28d495bc57c6866800d037cfc389050166319 | tracpro/profiles/tests/factories.py | tracpro/profiles/tests/factories.py | import factory
import factory.django
import factory.fuzzy
from tracpro.test.factory_utils import FuzzyEmail
__all__ = ['User']
class User(factory.django.DjangoModelFactory):
username = factory.fuzzy.FuzzyText()
email = FuzzyEmail()
class Meta:
model = "auth.User"
@factory.post_generation
... | import factory
import factory.django
import factory.fuzzy
from tracpro.test.factory_utils import FuzzyEmail
__all__ = ['User']
class User(factory.django.DjangoModelFactory):
username = factory.fuzzy.FuzzyText()
email = FuzzyEmail()
class Meta:
model = "auth.User"
@factory.post_generation
... | Use username as password default | Use username as password default
For compatibility with TracProTest.login()
| Python | bsd-3-clause | xkmato/tracpro,rapidpro/tracpro,rapidpro/tracpro,xkmato/tracpro,xkmato/tracpro,rapidpro/tracpro,xkmato/tracpro | ---
+++
@@ -17,7 +17,7 @@
@factory.post_generation
def password(self, create, extracted, **kwargs):
- password = extracted or "password"
+ password = extracted or self.username
self.set_password(password)
if create:
self.save() |
d43f87c18807853fde0a0e79828b5a8e7ab036fc | assess_isoform_quantification/set_isoform_frequencies.py | assess_isoform_quantification/set_isoform_frequencies.py | #!/usr/bin/python
"""Usage:
set_isoform_frequencies [{help}] [{version}] {pro_file}
{help_short} {help} Show this message.
{version_short} {version} Show version.
{pro_file} Flux simulator gene expression profile file.
"""
from docopt import docopt
from options import validate_file_... | #!/usr/bin/python
"""Usage:
set_isoform_frequencies [{help}] [{version}] {pro_file}
{help_short} {help} Show this message.
{version_short} {version} Show version.
{pro_file} Flux simulator gene expression profile file.
"""
from docopt import docopt
from options import validate_file_... | Read in Flux Simulator expression profile with pandas. | Read in Flux Simulator expression profile with pandas.
| Python | mit | lweasel/piquant,COMBINE-lab/piquant,lweasel/piquant | ---
+++
@@ -10,6 +10,7 @@
from docopt import docopt
from options import validate_file_option
+from pandas import read_csv
from schema import SchemaError
HELP_SHORT = "-h"
@@ -17,6 +18,25 @@
VERSION_SHORT = "-v"
VERSION = "--version"
PRO_FILE = "<pro-file>"
+
+LOCUS_COL = 'loc'
+TRANSCRIPT_ID_COL = 't_id'
+... |
156c049cc3965f969ee252dc5859cf0713bcbe27 | grip/__init__.py | grip/__init__.py | """\
Grip
----
Render local readme files before sending off to Github.
:copyright: (c) 2012 by Joe Esposito.
:license: MIT, see LICENSE for more details.
"""
__version__ = '1.2.0'
from . import command
from .server import default_filenames, serve
from .renderer import render_content, render_page
| """\
Grip
----
Render local readme files before sending off to Github.
:copyright: (c) 2012 by Joe Esposito.
:license: MIT, see LICENSE for more details.
"""
__version__ = '1.2.0'
from . import command
from .renderer import render_content, render_page
from .server import default_filenames, create_app, serve
from .... | Add create_app and export to API. | Add create_app and export to API.
| Python | mit | jbarreras/grip,jbarreras/grip,joeyespo/grip,mgoddard-pivotal/grip,ssundarraj/grip,ssundarraj/grip,mgoddard-pivotal/grip,joeyespo/grip | ---
+++
@@ -12,5 +12,6 @@
from . import command
-from .server import default_filenames, serve
from .renderer import render_content, render_page
+from .server import default_filenames, create_app, serve
+from .exporter import export |
d49d7dc7943e25be8497a7cbed059aa04fe76e7d | nefi2_main/nefi2/model/algorithms/_alg.py | nefi2_main/nefi2/model/algorithms/_alg.py | # -*- coding: utf-8 -*-
"""
This class represents an interface of an image processing algorithm.
The class abstracts algorithm interface from user so he can fully focus on his
algorithm implementation.
"""
__author__ = "p.shkadzko@gmail.com"
class Algorithm:
def __init__(self):
"""
Algorithm cla... | # -*- coding: utf-8 -*-
"""
This class represents an interface of an image processing algorithm.
The class abstracts algorithm interface from user so he can fully focus on his
algorithm implementation.
"""
__author__ = "p.shkadzko@gmail.com"
class Algorithm:
def __init__(self):
"""
Algorithm cla... | Change modfied variable to true | Change modfied variable to true
| Python | bsd-2-clause | LumPenPacK/NetworkExtractionFromImages,LumPenPacK/NetworkExtractionFromImages,LumPenPacK/NetworkExtractionFromImages,LumPenPacK/NetworkExtractionFromImages,LumPenPacK/NetworkExtractionFromImages | ---
+++
@@ -17,7 +17,7 @@
self.modified -- True if Algorithm settings were modified
self.belongs -- A step name to which current algorithm belongs
"""
- self.modified = False
+ self.modified = True
# for debugging only
print '> Algorithm: I am "%s" ... |
0ddad675169952f861f164d7ce311c83dccd51e0 | invoice/admin.py | invoice/admin.py | from django.contrib import admin
from django.conf.urls.defaults import patterns
from invoice.models import Invoice, InvoiceItem
from invoice.views import pdf_view
from invoice.forms import InvoiceAdminForm
class InvoiceItemInline(admin.TabularInline):
model = InvoiceItem
class InvoiceAdmin(admin.ModelAdmin):
... | from django.contrib import admin
from django.conf.urls.defaults import patterns
from invoice.models import Invoice, InvoiceItem
from invoice.views import pdf_view
from invoice.forms import InvoiceAdminForm
class InvoiceItemInline(admin.TabularInline):
model = InvoiceItem
class InvoiceAdmin(admin.ModelAdmin):
... | Add paid_date to invoice list. | Add paid_date to invoice list.
| Python | bsd-3-clause | simonluijk/django-invoice,Chris7/django-invoice,Chris7/django-invoice | ---
+++
@@ -26,6 +26,7 @@
'user',
'invoice_date',
'due_date',
+ 'paid_date',
'status',
'total_amount',
) |
09c2e6fff38e5c47391c0f8e948089e3efd26337 | serfnode/handler/file_utils.py | serfnode/handler/file_utils.py | import os
from tempfile import mkstemp
import time
class atomic_write(object):
"""Perform an atomic write to a file.
Use as::
with atomic_write('/my_file') as f:
f.write('foo')
"""
def __init__(self, filepath):
"""
:type filepath: str
"""
self.fi... | import os
from tempfile import mkstemp
import time
class atomic_write(object):
"""Perform an atomic write to a file.
Use as::
with atomic_write('/my_file') as f:
f.write('foo')
"""
def __init__(self, filepath):
"""
:type filepath: str
"""
self.fi... | Allow waiting for multiple files | Allow waiting for multiple files | Python | mit | waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode | ---
+++
@@ -33,8 +33,8 @@
os.rename(self.temp, self.filepath)
-def wait_for_file(filepath, sleep_interval=0.1):
- """Wait for the existence of a file.
+def wait_for_files(*filepath, sleep_interval=0.1):
+ """Wait for the existence of files.
Warning: use ``atomic_write`` to write the file... |
eb61e5c989cda3f5e021150f91561a88ba6db73e | setuptools/tests/py26compat.py | setuptools/tests/py26compat.py | import sys
import unittest
import tarfile
try:
# provide skipIf for Python 2.4-2.6
skipIf = unittest.skipIf
except AttributeError:
def skipIf(condition, reason):
def skipper(func):
def skip(*args, **kwargs):
return
if condition:
return skip
return func
return skipper
def _tarfile_open_ex(*args... | import sys
import unittest
import tarfile
import contextlib
try:
# provide skipIf for Python 2.4-2.6
skipIf = unittest.skipIf
except AttributeError:
def skipIf(condition, reason):
def skipper(func):
def skip(*args, **kwargs):
return
if condition:
return skip
return func
return skipper
def _tar... | Use contextlib.closing on tarfile compat shim | Use contextlib.closing on tarfile compat shim
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -1,6 +1,7 @@
import sys
import unittest
import tarfile
+import contextlib
try:
# provide skipIf for Python 2.4-2.6
@@ -19,9 +20,6 @@
"""
Extend result as a context manager.
"""
- res = tarfile.open(*args, **kwargs)
- res.__exit__ = lambda exc_type, exc_value, traceback: res.close()
- res.__en... |
29b3ea81fad91b9cdba150a74aeeb43b40dc0d67 | numba/cuda/tests/cudadrv/test_profiler.py | numba/cuda/tests/cudadrv/test_profiler.py | import unittest
from numba.cuda.testing import ContextResettingTestCase
from numba import cuda
from numba.cuda.testing import skip_on_cudasim
@skip_on_cudasim('CUDA Profiler unsupported in the simulator')
class TestProfiler(ContextResettingTestCase):
def test_profiling(self):
with cuda.profiling():
... | import unittest
from numba.cuda.testing import ContextResettingTestCase
from numba import cuda
from numba.cuda.testing import skip_on_cudasim, xfail_with_cuda_python
@skip_on_cudasim('CUDA Profiler unsupported in the simulator')
@xfail_with_cuda_python
class TestProfiler(ContextResettingTestCase):
def test_profil... | Revert "Re-enable profiler with CUDA Python" | Revert "Re-enable profiler with CUDA Python"
This reverts commit 0a7a8d891b946ad7328ac83854b18935f3cf23d6.
The Conda packages for the NVIDIA bindings do not support this API -
only the Github source version supports it, the profiler tests must be
disabled.
| Python | bsd-2-clause | IntelLabs/numba,numba/numba,seibert/numba,IntelLabs/numba,cpcloud/numba,cpcloud/numba,IntelLabs/numba,numba/numba,cpcloud/numba,numba/numba,seibert/numba,seibert/numba,cpcloud/numba,numba/numba,IntelLabs/numba,seibert/numba,cpcloud/numba,IntelLabs/numba,seibert/numba,numba/numba | ---
+++
@@ -1,10 +1,11 @@
import unittest
from numba.cuda.testing import ContextResettingTestCase
from numba import cuda
-from numba.cuda.testing import skip_on_cudasim
+from numba.cuda.testing import skip_on_cudasim, xfail_with_cuda_python
@skip_on_cudasim('CUDA Profiler unsupported in the simulator')
+@xfai... |
4c6c7067c05026b0e40020b0be58de83aa79e4f5 | entrypoint.py | entrypoint.py | import bcrypt
import sys
if len(sys.argv) < 2:
print('Error: please provide a password.', file=sys.stderr)
sys.exit(2)
password = sys.argv[1]
strength = None
if len(sys.argv) > 2:
strength = int(sys.argv[2])
if strength:
salt = bcrypt.gensalt(rounds=strength)
else:
salt = bcrypt.gensalt()
password ... | import bcrypt
import sys
if len(sys.argv) < 2:
print('Error: please provide a password.', file=sys.stderr)
sys.exit(2)
password = sys.argv[1]
strength = None
if len(sys.argv) > 2:
strength = int(sys.argv[2])
if strength:
salt = bcrypt.gensalt(rounds=strength)
else:
salt = bcrypt.gensalt()
password ... | Remove newline character from stdout. | Remove newline character from stdout.
| Python | apache-2.0 | JohnStarich/docker-bcrypt | ---
+++
@@ -14,5 +14,6 @@
salt = bcrypt.gensalt()
password = password.encode('utf-8')
bhash = bcrypt.hashpw(password, salt)
-print(bhash.decode('utf-8'))
+print(bhash.decode('utf-8'), end='', flush=True)
+print(file=sys.stderr)
|
f10d2b0aa6da7347435ad1036c0e53e67c89d362 | dougrain.py | dougrain.py | #!/usr/bin/python
import urlparse
import curie
import link
class Document(object):
def expand_curie(self, link):
return self.curie.expand(link)
@classmethod
def from_object(cls, o, relative_to_url=None, parent_curie=None):
if isinstance(o, list):
return map(lambda x: cls.from_... | #!/usr/bin/python
import urlparse
import curie
import link
class Document(object):
def __init__(self, o, relative_to_url, parent_curie=None):
self.attrs = o
self.__dict__.update(o)
self.links = {}
for key, value in o.get("_links", {}).iteritems():
self.links[key] = link... | Move some construction to __init__. | Refactor: Move some construction to __init__. | Python | mit | wharris/dougrain | ---
+++
@@ -4,6 +4,33 @@
import link
class Document(object):
+ def __init__(self, o, relative_to_url, parent_curie=None):
+ self.attrs = o
+ self.__dict__.update(o)
+ self.links = {}
+
+ for key, value in o.get("_links", {}).iteritems():
+ self.links[key] = link.Link.from... |
410c47921da205c1628cdff771f3385546edd503 | src/engine/SCons/Platform/darwin.py | src/engine/SCons/Platform/darwin.py | """engine.SCons.Platform.darwin
Platform-specific initialization for Mac OS X systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004 Steven Knight
#
# Permi... | """engine.SCons.Platform.darwin
Platform-specific initialization for Mac OS X systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of char... | Fix __COPYRIGHT__ and __REVISION__ in new Darwin module. | Fix __COPYRIGHT__ and __REVISION__ in new Darwin module.
| Python | mit | Distrotech/scons,Distrotech/scons,Distrotech/scons,Distrotech/scons,Distrotech/scons | ---
+++
@@ -8,7 +8,7 @@
"""
#
-# Copyright (c) 2001, 2002, 2003, 2004 Steven Knight
+# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -30,6 +30,8 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN... |
f664b85c3bc68612d19ae0fc762ca314f6517b00 | src/constants.py | src/constants.py | #!/usr/bin/env python
TRAJECTORY = 'linear'
CONTROLLER = 'euler'
# control constants
K_X = 0.90
K_Y = 0.90
K_THETA = 0.90
# PID control constants
K_P_V = 0.2
K_I_V = 1.905
K_D_V = 0.00
K_P_W = 0.45
K_I_W = 1.25
K_D_W = 0.000
if TRAJECTORY == 'linear':
SIMULATION_TIME_IN_SECONDS = 60.0
MAX_V = 0.075
MAX... | #!/usr/bin/env python
TRAJECTORY = 'linear'
CONTROLLER = 'euler'
# control constants
K_X = 0.90
K_Y = 0.90
K_THETA = 0.90
# PID control constants
K_P_V = 0.2
K_I_V = 1.905
K_D_V = 0.00
K_P_W = 0.45
K_I_W = 1.25
K_D_W = 0.000
SIMULATION_TIME_IN_SECONDS = 0.0
if TRAJECTORY == 'linear':
SIMULATION_TIME_IN_SECONDS ... | Add default value for simulation time | Add default value for simulation time
| Python | mit | bit0001/trajectory_tracking,bit0001/trajectory_tracking | ---
+++
@@ -16,7 +16,7 @@
K_I_W = 1.25
K_D_W = 0.000
-
+SIMULATION_TIME_IN_SECONDS = 0.0
if TRAJECTORY == 'linear':
SIMULATION_TIME_IN_SECONDS = 60.0
MAX_V = 0.075 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.