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
|
---|---|---|---|---|---|---|---|---|---|---|
2a4b02fe84542f3f44fa4e6913f86ed3a4771d43 | issue_tracker/core/models.py | issue_tracker/core/models.py | from django.db import models
from django.contrib.auth.models import User
class Project(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
version = models.CharField(max_length=15, null=True)
release_date = models.DateField(null=True)
class Issue(models.Model):
project = models.ForeignKey(Project)
status_choices = (
("0", "OPEN"),
("1", "IN PROGRESS"),
("2", "FINISHED"),
("3", "CLOSED"),
("4", "CANCELED"),
)
status = models.CharField(max_length=10, choices=status_choices)
level_choices = (
("0", "LOW"),
("1", "MEDIUM"),
("2", "HIGH"),
("3", "CRITICAL"),
("4", "BLOCKER"),
)
level = models.CharField(max_length=10, choices=level_choices)
title = models.CharField(max_length=50, null=True)
description = models.CharField(max_length=50, null=True)
date_created = models.DateField(auto_now_add=True)
date_completed = models.DateField(null=True)
# TODO implement these
# time_estimate
# percentage_completed
class Comments(models.Model):
issue = models.ForeignKey(Issue)
comment = models.CharField(max_length=500)
user = models.ForeignKey(User,null=True, blank=True)
| from django.db import models
from django.contrib.auth.models import User
class Project(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
version = models.CharField(max_length=15, null=True)
release_date = models.DateField(null=True)
class Issue(models.Model):
project = models.ForeignKey(Project)
status_choices = (
("0", "OPEN"),
("1", "IN PROGRESS"),
("2", "FINISHED"),
("3", "CLOSED"),
("4", "CANCELED"),
)
status = models.CharField(max_length=10, choices=status_choices)
level_choices = (
("0", "LOW"),
("1", "MEDIUM"),
("2", "HIGH"),
("3", "CRITICAL"),
("4", "BLOCKER"),
)
level = models.CharField(max_length=10, choices=level_choices)
title = models.CharField(max_length=50, null=True)
description = models.CharField(max_length=50, null=True)
date_created = models.DateField(auto_now_add=True)
date_completed = models.DateField(null=True)
# TODO implement these
# time_estimate
# percentage_completed
class Comments(models.Model):
issue = models.ForeignKey(Issue)
comment = models.TextField(max_length=500)
date_created = models.DateTimeField(null=False, auto_now_add=True)
user = models.ForeignKey(User,null=True, blank=True)
| Change comment from a charfield to a textfield, and add a date_created field; which is not working correctly. | Change comment from a charfield to a textfield, and add a date_created field; which is not working correctly.
| Python | mit | hfrequency/django-issue-tracker | ---
+++
@@ -35,6 +35,7 @@
class Comments(models.Model):
issue = models.ForeignKey(Issue)
- comment = models.CharField(max_length=500)
+ comment = models.TextField(max_length=500)
+ date_created = models.DateTimeField(null=False, auto_now_add=True)
user = models.ForeignKey(User,null=True, blank=True)
|
4485b65722645d6c9617b5ff4aea6d62ee8a9adf | bumblebee_status/modules/contrib/optman.py | bumblebee_status/modules/contrib/optman.py | """Displays currently active gpu by optimus-manager
Requires the following packages:
* optimus-manager
"""
import subprocess
import core.module
import core.widget
class Module(core.module.Module):
def __init__(self, config, theme):
super().__init__(config, theme, core.widget.Widget(self.output))
self.__gpumode = ""
def output(self, _):
return "GPU: {}".format(self.__gpumode)
def update(self):
cmd = ["optimus-manager", "--print-mode"]
output = (
subprocess.Popen(cmd, stdout=subprocess.PIPE)
.communicate()[0]
.decode("utf-8")
.lower()
)
if "intel" in output:
self.__gpumode = "Intel"
elif "nvidia" in output:
self.__gpumode = "Nvidia"
elif "amd" in output:
self.__gpumode = "AMD"
| """Displays currently active gpu by optimus-manager
Requires the following packages:
* optimus-manager
"""
import core.module
import core.widget
import util.cli
class Module(core.module.Module):
def __init__(self, config, theme):
super().__init__(config, theme, core.widget.Widget(self.output))
self.__gpumode = ""
def output(self, _):
return "GPU: {}".format(self.__gpumode)
def update(self):
cmd = "optimus-manager --print-mode"
output = util.cli.execute(cmd).strip()
if "intel" in output:
self.__gpumode = "Intel"
elif "nvidia" in output:
self.__gpumode = "Nvidia"
elif "amd" in output:
self.__gpumode = "AMD"
| Use the existing util.cli module | Use the existing util.cli module | Python | mit | tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status | ---
+++
@@ -5,11 +5,10 @@
"""
-import subprocess
-
import core.module
import core.widget
+import util.cli
class Module(core.module.Module):
def __init__(self, config, theme):
@@ -20,13 +19,8 @@
return "GPU: {}".format(self.__gpumode)
def update(self):
- cmd = ["optimus-manager", "--print-mode"]
- output = (
- subprocess.Popen(cmd, stdout=subprocess.PIPE)
- .communicate()[0]
- .decode("utf-8")
- .lower()
- )
+ cmd = "optimus-manager --print-mode"
+ output = util.cli.execute(cmd).strip()
if "intel" in output:
self.__gpumode = "Intel" |
7ad0e624e4bccab39b56152e9d4c6d5fba8dc528 | dudebot/__init__.py | dudebot/__init__.py | from core import BotAI
from core import Connector
from decorators import message_must_begin_with
from decorators import message_must_begin_with_attr
from decorators import message_must_begin_with_nickname
| Allow modules that use dudebot to just import dudebot... | Allow modules that use dudebot to just import dudebot...
| Python | bsd-2-clause | sujaymansingh/dudebot | ---
+++
@@ -0,0 +1,6 @@
+from core import BotAI
+from core import Connector
+
+from decorators import message_must_begin_with
+from decorators import message_must_begin_with_attr
+from decorators import message_must_begin_with_nickname |
|
710d94f0b08b3d51fbcfda13050dc21e3d53f2e7 | yunity/resources/tests/integration/test_chat__add_invalid_user_to_chat_fails/request.py | yunity/resources/tests/integration/test_chat__add_invalid_user_to_chat_fails/request.py | from .initial_data import request_user, chatid
request = {
"endpoint": "/api/chats/{}/participants".format(chatid),
"method": "post",
"user": request_user,
"body": {
"users": [666666]
}
}
| from .initial_data import request_user, chatid
request = {
"endpoint": "/api/chats/{}/participants".format(chatid),
"method": "post",
"user": request_user,
"body": {
"users": [666666, 22]
}
}
| Fix testcase for better coverage | Fix testcase for better coverage
| Python | agpl-3.0 | yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend | ---
+++
@@ -5,6 +5,6 @@
"method": "post",
"user": request_user,
"body": {
- "users": [666666]
+ "users": [666666, 22]
}
} |
3307bfb7075a527dc7805da2ff735f461f5fc02f | employees/models.py | employees/models.py | from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Role(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Category(models.Model):
name = models.CharField(max_length=100)
weight = models.PositiveSmallIntegerField(default=1)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "categories"
ordering = ['weight']
class Employee(AbstractUser):
role = models.ForeignKey(Role, null=True, blank=True)
skype_id = models.CharField(max_length=200, null=True, blank=True)
last_month_score = models.PositiveIntegerField(default=0)
current_month_score = models.PositiveIntegerField(default=0)
level = models.PositiveIntegerField(default=0)
total_score = models.PositiveIntegerField(default=0)
avatar = models.ImageField(upload_to='avatar', null=True, blank=True)
categories = models.ManyToManyField(Category)
| from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Role(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Category(models.Model):
name = models.CharField(max_length=100)
weight = models.PositiveSmallIntegerField(default=1)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "categories"
ordering = ['weight']
class Employee(AbstractUser):
role = models.ForeignKey(Role, null=True, blank=True)
skype_id = models.CharField(max_length=200, null=True, blank=True)
last_month_score = models.PositiveIntegerField(default=0)
current_month_score = models.PositiveIntegerField(default=0)
level = models.PositiveIntegerField(default=0)
total_score = models.PositiveIntegerField(default=0)
avatar = models.ImageField(upload_to='avatar', null=True, blank=True)
categories = models.ManyToManyField(Category, blank=True)
| Change categories field to non required. | Change categories field to non required.
| Python | mit | neosergio/allstars | ---
+++
@@ -34,4 +34,4 @@
level = models.PositiveIntegerField(default=0)
total_score = models.PositiveIntegerField(default=0)
avatar = models.ImageField(upload_to='avatar', null=True, blank=True)
- categories = models.ManyToManyField(Category)
+ categories = models.ManyToManyField(Category, blank=True) |
b8bc10e151f12e2bfe2c03765a410a04325a3233 | satchmo/product/templatetags/satchmo_product.py | satchmo/product/templatetags/satchmo_product.py | from django import template
from django.conf import settings
from django.core import urlresolvers
from django.template import Context, Template
from django.utils.translation import get_language, ugettext_lazy as _
from satchmo.configuration import config_value
from satchmo.product.models import Category
from satchmo.shop.templatetags import get_filter_args
register = template.Library()
def is_producttype(product, ptype):
"""Returns True if product is ptype"""
if ptype in product.get_subtypes():
return "true"
else:
return ""
register.filter('is_producttype', is_producttype)
def product_images(product, args=""):
args, kwargs = get_filter_args(args,
keywords=('include_main', 'maximum'),
boolargs=('include_main'),
intargs=('maximum'),
stripquotes=True)
q = product.productimage_set
if kwargs.get('include_main', True):
q = q.all()
else:
main = product.main_image
q = q.exclude(id = main.id)
maximum = kwargs.get('maximum', -1)
if maximum>-1:
q = list(q)[:maximum]
return q
register.filter('product_images', product_images)
def smart_attr(product, key):
"""Run the smart_attr function on the spec'd product
"""
return product.smart_attr(key)
register.filter('smart_attr', smart_attr)
| from django import template
from django.conf import settings
from django.core import urlresolvers
from django.template import Context, Template
from django.utils.translation import get_language, ugettext_lazy as _
from satchmo.configuration import config_value
from satchmo.product.models import Category
from satchmo.shop.templatetags import get_filter_args
register = template.Library()
def is_producttype(product, ptype):
"""Returns True if product is ptype"""
if ptype in product.get_subtypes():
return True
else:
return False
register.filter('is_producttype', is_producttype)
def product_images(product, args=""):
args, kwargs = get_filter_args(args,
keywords=('include_main', 'maximum'),
boolargs=('include_main'),
intargs=('maximum'),
stripquotes=True)
q = product.productimage_set
if kwargs.get('include_main', True):
q = q.all()
else:
main = product.main_image
q = q.exclude(id = main.id)
maximum = kwargs.get('maximum', -1)
if maximum>-1:
q = list(q)[:maximum]
return q
register.filter('product_images', product_images)
def smart_attr(product, key):
"""Run the smart_attr function on the spec'd product
"""
return product.smart_attr(key)
register.filter('smart_attr', smart_attr)
| Change the is_producttype template tag to return a boolean rather than a string. | Change the is_producttype template tag to return a boolean rather than a string.
--HG--
extra : convert_revision : svn%3Aa38d40e9-c014-0410-b785-c606c0c8e7de/satchmo/trunk%401200
| Python | bsd-3-clause | Ryati/satchmo,ringemup/satchmo,Ryati/satchmo,dokterbob/satchmo,twidi/satchmo,twidi/satchmo,dokterbob/satchmo,ringemup/satchmo | ---
+++
@@ -12,15 +12,15 @@
def is_producttype(product, ptype):
"""Returns True if product is ptype"""
if ptype in product.get_subtypes():
- return "true"
+ return True
else:
- return ""
+ return False
register.filter('is_producttype', is_producttype)
def product_images(product, args=""):
- args, kwargs = get_filter_args(args,
- keywords=('include_main', 'maximum'),
+ args, kwargs = get_filter_args(args,
+ keywords=('include_main', 'maximum'),
boolargs=('include_main'),
intargs=('maximum'),
stripquotes=True)
@@ -31,11 +31,11 @@
else:
main = product.main_image
q = q.exclude(id = main.id)
-
+
maximum = kwargs.get('maximum', -1)
if maximum>-1:
q = list(q)[:maximum]
-
+
return q
register.filter('product_images', product_images)
@@ -44,5 +44,5 @@
"""Run the smart_attr function on the spec'd product
"""
return product.smart_attr(key)
-
+
register.filter('smart_attr', smart_attr) |
b4247769fcaa67d09e0f38d1283cf4f28ddc350e | cookiecutter/extensions.py | cookiecutter/extensions.py | # -*- coding: utf-8 -*-
"""Jinja2 extensions."""
import json
from jinja2.ext import Extension
class JsonifyExtension(Extension):
"""Jinja2 extension to convert a python object to json."""
def __init__(self, environment):
"""Initilize extension with given environment."""
super(JsonifyExtension, self).__init__(environment)
def jsonify(obj):
return json.dumps(obj, sort_keys=True, indent=4)
environment.filters['jsonify'] = jsonify
| # -*- coding: utf-8 -*-
"""Jinja2 extensions."""
import json
from jinja2.ext import Extension
class JsonifyExtension(Extension):
"""Jinja2 extension to convert a Python object to JSON."""
def __init__(self, environment):
"""Initialize the extension with the given environment."""
super(JsonifyExtension, self).__init__(environment)
def jsonify(obj):
return json.dumps(obj, sort_keys=True, indent=4)
environment.filters['jsonify'] = jsonify
| Fix typo and improve grammar in doc string | Fix typo and improve grammar in doc string
| Python | bsd-3-clause | michaeljoseph/cookiecutter,dajose/cookiecutter,audreyr/cookiecutter,hackebrot/cookiecutter,audreyr/cookiecutter,hackebrot/cookiecutter,luzfcb/cookiecutter,pjbull/cookiecutter,dajose/cookiecutter,pjbull/cookiecutter,luzfcb/cookiecutter,michaeljoseph/cookiecutter | ---
+++
@@ -8,10 +8,10 @@
class JsonifyExtension(Extension):
- """Jinja2 extension to convert a python object to json."""
+ """Jinja2 extension to convert a Python object to JSON."""
def __init__(self, environment):
- """Initilize extension with given environment."""
+ """Initialize the extension with the given environment."""
super(JsonifyExtension, self).__init__(environment)
def jsonify(obj): |
42ec5ed6d56fcc59c99d175e1c9280d00cd3bef1 | tests/test_published_results.py | tests/test_published_results.py |
""" To test if the new code produces the same precision values on the published results."""
from __future__ import division, print_function
import pytest
import numpy as np
import eniric.Qcalculator as Q
import eniric.IOmodule as IO
from bin.prec_1 import calc_prec1
# For python2.X compatibility
file_error_to_catch = getattr(__builtins__, 'FileNotFoundError', IOError)
path = "data/Published_Results/resampled/"
@pytest.mark.xfail(raises=file_error_to_catch) # Data file may not exist
def test_presicion_1():
""" New precision 1 test that works."""
published_results = {1: 3.8, 5: 9.1, 10: 20.7}
path = "data/resampled/"
for vsini in [1, 5, 10]:
# name = "Spectrum_M0-PHOENIX-ACES_Yband_vsini{0}.0_R100k_res3.txt".format(vsini)
__, p1 = calc_prec1("M0", "Y", vsini, "100k", 3, resampled_dir=path)
assert np.round(p1, 1).value == published_results[vsini]
|
""" To test if the new code produces the same precision values on the published results."""
from __future__ import division, print_function
import pytest
import numpy as np
import eniric.Qcalculator as Q
import eniric.IOmodule as IO
from bin.prec_1 import calc_prec1
# For python2.X compatibility
file_error_to_catch = getattr(__builtins__, 'FileNotFoundError', IOError)
path = "data/Published_Results/resampled/"
@pytest.mark.xfail(raises=file_error_to_catch) # Data file may not exist
def test_presicion_1():
""" New precision 1 test that works."""
published_results = {1: 3.8, 5: 9.1, 10: 20.7}
path = "data/resampled/"
for vsini in [1, 5, 10]:
# name = "Spectrum_M0-PHOENIX-ACES_Yband_vsini{0}.0_R100k_res3.txt".format(vsini)
__, p1 = calc_prec1("M0", "Y", vsini, "100k", 3, resampled_dir=path)
# assert np.round(p1, 1).value == published_results[vsini]
assert np.round(100 * p1, 1).value == published_results[vsini] # With incorect normalization
| Add known offset for known bad calibration. | Add known offset for known bad calibration.
Former-commit-id: afa3d6a66e32bbcc2b20f00f7e63fba5cb45882e [formerly 0470ca22b8a24205d2eb1c66caee912c990da0b3] [formerly c23210f4056c27e61708da2f2440bce3eda151a8 [formerly 5c0a6b9c0fefd2b88b9382d4a6ed98d9eac626df]]
Former-commit-id: 8bfdaa1f7940b26aee05f20e801616f4a8d1d55d [formerly 1c85db5b2b87b73dfb28a1db171ff79a69e3a24a]
Former-commit-id: d02a26b263c5c59776a35fc130e5c96b7ac30f5d | Python | mit | jason-neal/eniric,jason-neal/eniric | ---
+++
@@ -24,4 +24,5 @@
# name = "Spectrum_M0-PHOENIX-ACES_Yband_vsini{0}.0_R100k_res3.txt".format(vsini)
__, p1 = calc_prec1("M0", "Y", vsini, "100k", 3, resampled_dir=path)
- assert np.round(p1, 1).value == published_results[vsini]
+ # assert np.round(p1, 1).value == published_results[vsini]
+ assert np.round(100 * p1, 1).value == published_results[vsini] # With incorect normalization |
f3df3b2b8e1167e953457a85f2297d28b6a39729 | examples/Micro.Blog/microblog.py | examples/Micro.Blog/microblog.py | from getpass import getpass
from bessie import BaseClient
import config
class MicroBlogApi(BaseClient):
endpoints = config.available_endpoints
separator = '/'
base_url='https://micro.blog'
def __init__(self, path='', token=''):
self.token = token
super(self.__class__, self).__init__(path, token=token)
# override method from BaseClient to inject Authorization header
def _prepare_request(self):
super(self.__class__, self)._prepare_request()
self.request.headers['Authorization'] = 'Token {}'.format(self.token)
if __name__ == '__main__':
token = getpass('Token... ')
mba = MicroBlogApi(token=token)
# GET - https://micro.blog/posts/all
posts = mba.posts.all.get()
print(posts.status_code, posts.reason)
print(posts.json())
| from getpass import getpass
from bessie import BaseClient
import config
class MicroBlogApi(BaseClient):
endpoints = config.available_endpoints
separator = '/'
base_url='https://micro.blog'
def __init__(self, path='', path_params=None, token=''):
self.token = token
super(self.__class__, self).__init__(path, path_params, token=token)
# override method from BaseClient to inject Authorization header
def _prepare_request(self):
super(self.__class__, self)._prepare_request()
self.request.headers['Authorization'] = 'Token {}'.format(self.token)
if __name__ == '__main__':
token = getpass('Token... ')
mba = MicroBlogApi(token=token)
# GET - https://micro.blog/posts/all
posts = mba.posts.all.get()
print(posts.status_code, posts.reason)
print(posts.json())
| Include path_params in override constructor | Include path_params in override constructor
| Python | mit | andymitchhank/bessie | ---
+++
@@ -10,9 +10,9 @@
separator = '/'
base_url='https://micro.blog'
- def __init__(self, path='', token=''):
+ def __init__(self, path='', path_params=None, token=''):
self.token = token
- super(self.__class__, self).__init__(path, token=token)
+ super(self.__class__, self).__init__(path, path_params, token=token)
# override method from BaseClient to inject Authorization header
def _prepare_request(self): |
c9980756dcee82cc570208e73ec1a2112aea0155 | tvtk/tests/test_scene.py | tvtk/tests/test_scene.py | """ Tests for the garbage collection of Scene objects.
"""
# Authors: Deepak Surti, Ioannis Tziakos
# Copyright (c) 2015, Enthought, Inc.
# License: BSD Style.
import unittest
import weakref
import gc
from traits.etsconfig.api import ETSConfig
from tvtk.pyface.scene import Scene
from tvtk.tests.common import restore_gc_state
class TestScene(unittest.TestCase):
@unittest.skipIf(
ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)')
def test_scene_garbage_collected(self):
# given
scene_collected = []
scene_weakref = None
def scene_collected_callback(weakref):
scene_collected.append(True)
def do():
scene = Scene()
reference = weakref.ref(scene, scene_collected_callback)
scene.close()
return reference
# when
with restore_gc_state():
gc.disable()
scene_weakref = do()
# The Scene should have been collected.
self.assertTrue(scene_collected[0])
if __name__ == "__main__":
unittest.main()
| """ Tests for the garbage collection of Scene objects.
"""
# Authors: Deepak Surti, Ioannis Tziakos
# Copyright (c) 2015, Enthought, Inc.
# License: BSD Style.
import unittest
import weakref
import gc
from traits.etsconfig.api import ETSConfig
from tvtk.pyface.scene import Scene
from tvtk.tests.common import restore_gc_state
class TestScene(unittest.TestCase):
@unittest.skipIf(
ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)')
def test_scene_garbage_collected(self):
# given
scene_collected = []
scene_weakref = None
def scene_collected_callback(weakref):
scene_collected.append(True)
def do():
scene = Scene()
reference = weakref.ref(scene, scene_collected_callback)
scene.close()
return reference
# when
with restore_gc_state():
gc.disable()
scene_weakref = do()
# The Scene should have been collected.
self.assertTrue(scene_collected[0])
self.assertIsNone(scene_weakref())
if __name__ == "__main__":
unittest.main()
| Add weakref assertion in test case | Add weakref assertion in test case
| Python | bsd-3-clause | alexandreleroux/mayavi,dmsurti/mayavi,dmsurti/mayavi,alexandreleroux/mayavi,liulion/mayavi,liulion/mayavi | ---
+++
@@ -40,6 +40,7 @@
# The Scene should have been collected.
self.assertTrue(scene_collected[0])
+ self.assertIsNone(scene_weakref())
if __name__ == "__main__": |
74b2883c3371304e8f5ea95b0454fb006d85ba3d | mapentity/urls.py | mapentity/urls.py | from django.conf import settings
from django.conf.urls import patterns, url
from . import app_settings
from .views import (map_screenshot, convert, history_delete,
serve_secure_media, JSSettings)
_MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '')[1:]
urlpatterns = patterns(
'',
url(r'^%s(?P<path>.*?)$' % _MEDIA_URL, serve_secure_media),
url(r'^map_screenshot/$', map_screenshot, name='map_screenshot'),
url(r'^convert/$', convert, name='convert'),
url(r'^history/delete/$', history_delete, name='history_delete'),
# See default value in app_settings.JS_SETTINGS.
# Will be overriden, most probably.
url(r'^api/settings.json$', JSSettings.as_view(), name='js_settings'),
)
| from django.conf import settings
from django.conf.urls import patterns, url
from . import app_settings
from .views import (map_screenshot, convert, history_delete,
serve_secure_media, JSSettings)
_MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '')
if _MEDIA_URL.startswith('/'):
_MEDIA_URL = _MEDIA_URL[1:]
if _MEDIA_URL.endswith('/'):
_MEDIA_URL = _MEDIA_URL[:-1]
urlpatterns = patterns(
'',
url(r'^%s(?P<path>.*?)$' % _MEDIA_URL, serve_secure_media),
url(r'^map_screenshot/$', map_screenshot, name='map_screenshot'),
url(r'^convert/$', convert, name='convert'),
url(r'^history/delete/$', history_delete, name='history_delete'),
# See default value in app_settings.JS_SETTINGS.
# Will be overriden, most probably.
url(r'^api/settings.json$', JSSettings.as_view(), name='js_settings'),
)
| Remove leading and trailing slash of MEDIA_URL | Remove leading and trailing slash of MEDIA_URL
Conflicts:
mapentity/static/mapentity/Leaflet.label
| Python | bsd-3-clause | Anaethelion/django-mapentity,Anaethelion/django-mapentity,makinacorpus/django-mapentity,makinacorpus/django-mapentity,Anaethelion/django-mapentity,makinacorpus/django-mapentity | ---
+++
@@ -6,7 +6,11 @@
serve_secure_media, JSSettings)
-_MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '')[1:]
+_MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '')
+if _MEDIA_URL.startswith('/'):
+ _MEDIA_URL = _MEDIA_URL[1:]
+if _MEDIA_URL.endswith('/'):
+ _MEDIA_URL = _MEDIA_URL[:-1]
urlpatterns = patterns( |
6953b831c3c48a3512a86ca9e7e92edbf7a62f08 | tests/integration/test_sqs.py | tests/integration/test_sqs.py | import os
from asyncaws import SQS
from tornado.testing import AsyncTestCase, gen_test
aws_key_id = os.environ['AWS_ACCESS_KEY_ID']
aws_key_secret = os.environ['AWS_SECRET_ACCESS_KEY']
aws_region = os.environ['AWS_REGION']
class TestSQS(AsyncTestCase):
sqs = SQS(aws_key_id, aws_key_secret, aws_region, async=False)
@gen_test(timeout=60)
def test_create_queue(self):
queue_url = self.sqs.create_queue(
"test-queue", {"MessageRetentionPeriod": 60})
self.assertIsInstance(queue_url, str)
self.assertTrue(queue_url.startswith('http'))
get_attr_result = self.sqs.get_queue_attributes(
queue_url, ['MessageRetentionPeriod'])
self.assertIsInstance(get_attr_result, dict)
self.assertEqual(get_attr_result['MessageRetentionPeriod'], '60')
add_perm_result = self.sqs.add_permission(
queue_url, ['637085312181'], ["SendMessage"], "test-permission-id")
self.assertIsInstance(add_perm_result, str)
delete_result = self.sqs.delete_queue(queue_url)
self.assertIsInstance(delete_result, str)
| import os
from asyncaws import SQS
from tornado.testing import AsyncTestCase, gen_test
from random import randint
aws_key_id = os.environ['AWS_ACCESS_KEY_ID']
aws_key_secret = os.environ['AWS_SECRET_ACCESS_KEY']
aws_region = os.environ['AWS_REGION']
aws_test_account_id = "637085312181"
class TestSQS(AsyncTestCase):
@classmethod
def setUpClass(cls):
cls.sqs = SQS(aws_key_id, aws_key_secret, aws_region, async=False)
cls.queue_name = "test-queue-%s" % randint(1000, 9999)
cls.queue_url = cls.sqs.create_queue(
cls.queue_name, {"MessageRetentionPeriod": 60})
@classmethod
def tearDownClass(cls):
cls.sqs.delete_queue(cls.queue_url)
@gen_test
def test_queue_actions(self):
self.assertTrue(self.queue_url.startswith('http'))
get_attr_result = self.sqs.get_queue_attributes(
self.queue_url, ['MessageRetentionPeriod'])
self.assertIsInstance(get_attr_result, dict)
self.assertEqual(get_attr_result['MessageRetentionPeriod'], '60')
add_perm_result = self.sqs.add_permission(
self.queue_url, [aws_test_account_id], ["SendMessage"], "test-permission-id")
self.assertIsInstance(add_perm_result, str)
| Add correct setUp/tearDown methods for integration sqs test | Add correct setUp/tearDown methods for integration sqs test
| Python | mit | MA3STR0/AsyncAWS | ---
+++
@@ -1,27 +1,34 @@
import os
from asyncaws import SQS
from tornado.testing import AsyncTestCase, gen_test
+from random import randint
aws_key_id = os.environ['AWS_ACCESS_KEY_ID']
aws_key_secret = os.environ['AWS_SECRET_ACCESS_KEY']
aws_region = os.environ['AWS_REGION']
+aws_test_account_id = "637085312181"
class TestSQS(AsyncTestCase):
- sqs = SQS(aws_key_id, aws_key_secret, aws_region, async=False)
- @gen_test(timeout=60)
- def test_create_queue(self):
- queue_url = self.sqs.create_queue(
- "test-queue", {"MessageRetentionPeriod": 60})
- self.assertIsInstance(queue_url, str)
- self.assertTrue(queue_url.startswith('http'))
+ @classmethod
+ def setUpClass(cls):
+ cls.sqs = SQS(aws_key_id, aws_key_secret, aws_region, async=False)
+ cls.queue_name = "test-queue-%s" % randint(1000, 9999)
+ cls.queue_url = cls.sqs.create_queue(
+ cls.queue_name, {"MessageRetentionPeriod": 60})
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.sqs.delete_queue(cls.queue_url)
+
+ @gen_test
+ def test_queue_actions(self):
+ self.assertTrue(self.queue_url.startswith('http'))
get_attr_result = self.sqs.get_queue_attributes(
- queue_url, ['MessageRetentionPeriod'])
+ self.queue_url, ['MessageRetentionPeriod'])
self.assertIsInstance(get_attr_result, dict)
self.assertEqual(get_attr_result['MessageRetentionPeriod'], '60')
add_perm_result = self.sqs.add_permission(
- queue_url, ['637085312181'], ["SendMessage"], "test-permission-id")
+ self.queue_url, [aws_test_account_id], ["SendMessage"], "test-permission-id")
self.assertIsInstance(add_perm_result, str)
- delete_result = self.sqs.delete_queue(queue_url)
- self.assertIsInstance(delete_result, str) |
180e574471d449cfb3500c720741b36008917ec0 | example_project/urls.py | example_project/urls.py | import re
import sys
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Admin section
from django.contrib import admin
admin.autodiscover()
urlpatterns = staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# If we're running test, then we need to serve static files even though DEBUG
# is false to prevent lots of 404s. So do what staticfiles_urlpatterns would do.
if 'test' in sys.argv:
static_url = re.escape(settings.STATIC_URL.lstrip('/'))
urlpatterns += patterns('',
url(r'^%s(?P<path>.*)$' % static_url, 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
url('^(?P<path>favicon\.ico)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
)
urlpatterns += patterns('',
url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
url(r'^', include('speeches.urls', app_name='speeches', namespace='speeches')),
)
| import re
import sys
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Admin section
from django.contrib import admin
admin.autodiscover()
urlpatterns = staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# If we're running test, then we need to serve static files even though DEBUG
# is false to prevent lots of 404s. So do what staticfiles_urlpatterns would do.
if 'test' in sys.argv:
static_url = re.escape(settings.STATIC_URL.lstrip('/'))
urlpatterns += patterns('',
url(r'^%s(?P<path>.*)$' % static_url, 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
url('^(?P<path>favicon\.ico)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
)
urlpatterns += patterns('',
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^admin/', include(admin.site.urls)),
url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
url(r'^', include('speeches.urls', app_name='speeches', namespace='speeches')),
)
| Include admin in example project. | Include admin in example project.
| Python | agpl-3.0 | opencorato/sayit,opencorato/sayit,opencorato/sayit,opencorato/sayit | ---
+++
@@ -27,6 +27,8 @@
)
urlpatterns += patterns('',
+ (r'^admin/doc/', include('django.contrib.admindocs.urls')),
+ (r'^admin/', include(admin.site.urls)),
url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout'), |
7dd17cc10f7e0857ab3017177d6c4abeb115ff07 | south/models.py | south/models.py | from django.db import models
from south.db import DEFAULT_DB_ALIAS
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
@classmethod
def for_migration(cls, migration, database):
try:
# Switch on multi-db-ness
if database != DEFAULT_DB_ALIAS:
# Django 1.2
objects = cls.objects.using(database)
else:
# Django <= 1.1
objects = cls.objects
return objects.get(
app_name=migration.app_label(),
migration=migration.name(),
)
except cls.DoesNotExist:
return cls(
app_name=migration.app_label(),
migration=migration.name(),
)
def get_migrations(self):
from south.migration.base import Migrations
return Migrations(self.app_name)
def get_migration(self):
return self.get_migrations().migration(self.migration)
def __str__(self):
return "<%s: %s>" % (self.app_name, self.migration)
| from django.db import models
from south.db import DEFAULT_DB_ALIAS
# If we detect Django 1.7 or higher, then exit
# Placed here so it's guaranteed to be imported on Django start
import django
if django.VERSION[0] > 1 or (django.VERSION[0] == 1 and django.VERSION[1] > 6):
raise RuntimeError("South does not support Django 1.7 or higher. Please use native Django migrations.")
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
@classmethod
def for_migration(cls, migration, database):
try:
# Switch on multi-db-ness
if database != DEFAULT_DB_ALIAS:
# Django 1.2
objects = cls.objects.using(database)
else:
# Django <= 1.1
objects = cls.objects
return objects.get(
app_name=migration.app_label(),
migration=migration.name(),
)
except cls.DoesNotExist:
return cls(
app_name=migration.app_label(),
migration=migration.name(),
)
def get_migrations(self):
from south.migration.base import Migrations
return Migrations(self.app_name)
def get_migration(self):
return self.get_migrations().migration(self.migration)
def __str__(self):
return "<%s: %s>" % (self.app_name, self.migration)
| Add explicit version check for Django 1.7 or above | Add explicit version check for Django 1.7 or above
| Python | apache-2.0 | smartfile/django-south,smartfile/django-south | ---
+++
@@ -1,5 +1,11 @@
from django.db import models
from south.db import DEFAULT_DB_ALIAS
+
+# If we detect Django 1.7 or higher, then exit
+# Placed here so it's guaranteed to be imported on Django start
+import django
+if django.VERSION[0] > 1 or (django.VERSION[0] == 1 and django.VERSION[1] > 6):
+ raise RuntimeError("South does not support Django 1.7 or higher. Please use native Django migrations.")
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255) |
b4cd58a9c5c27fb32b4f13cfc2d41206bb6b86a1 | lib/presenter.py | lib/presenter.py | import os
import tempfile
from subprocess import call
class SlidePresenter(object):
def __init__(self):
pass
def present(self, slides):
for sno, slide in enumerate(slides):
with open(os.path.join(tempfile.gettempdir(), str(sno)+".md"), 'w') as f:
f.write(slide)
class VimPresenter(SlidePresenter):
def __init__(self, vim_rc_generator, vim_args=[]):
super(VimPresenter, self).__init__()
self.vim_args = vim_args
self.vim_rc_generator = vim_rc_generator
def withRC(self):
temp_rc = self.vim_rc_generator.generateFile()
self.vim_args += ['-u', temp_rc]
return self
def _get_command(self, num_slides):
self.withRC()
return ['vim'] + self.vim_args + [os.path.join(tempfile.gettempdir(), str(num)+".md") for num in xrange(num_slides)]
def present(self, slides):
super(VimPresenter, self).present(slides)
call(self._get_command(len(slides)))
class VimRCGenerator(object):
def __init__(self):
self.rc_string = "set nonu"
def generateFile(self):
temp_vimrc = os.path.join(tempfile.gettempdir(), 'rand.vimrc')
with open(temp_vimrc, 'w') as f:
f.write(self.rc_string)
return temp_vimrc
| import os
import tempfile
from subprocess import call
class SlidePresenter(object):
def __init__(self):
pass
def present(self, slides):
for sno, slide in enumerate(slides):
with open(os.path.join(tempfile.gettempdir(), str(sno)+".md"), 'w') as f:
f.write(slide)
class VimPresenter(SlidePresenter):
def __init__(self, vim_rc_generator, vim_args=[]):
super(VimPresenter, self).__init__()
self.vim_args = vim_args
self.vim_rc_generator = vim_rc_generator
def withRC(self):
temp_rc = self.vim_rc_generator.generateFile()
self.vim_args += ['-u', temp_rc]
return self
def _get_command(self, num_slides):
self.withRC()
return ['vim'] + self.vim_args + [os.path.join(tempfile.gettempdir(), str(num)+".md") for num in range(num_slides)]
def present(self, slides):
super(VimPresenter, self).present(slides)
call(self._get_command(len(slides)))
class VimRCGenerator(object):
def __init__(self):
self.rc_string = "set nonu"
def generateFile(self):
temp_vimrc = os.path.join(tempfile.gettempdir(), 'rand.vimrc')
with open(temp_vimrc, 'w') as f:
f.write(self.rc_string)
return temp_vimrc
| Use range instead of xrange | Use range instead of xrange
| Python | mit | gabber12/slides.vim | ---
+++
@@ -28,7 +28,7 @@
def _get_command(self, num_slides):
self.withRC()
- return ['vim'] + self.vim_args + [os.path.join(tempfile.gettempdir(), str(num)+".md") for num in xrange(num_slides)]
+ return ['vim'] + self.vim_args + [os.path.join(tempfile.gettempdir(), str(num)+".md") for num in range(num_slides)]
def present(self, slides):
super(VimPresenter, self).present(slides) |
fe85f1f135d2a7831afee6c8ab0bad394beb8aba | src/ais.py | src/ais.py | class MonsterAI(object):
def __init__(self, level):
self.owner = None
self.level = level
def take_turn(self):
self.owner.log.log_begin_turn(self.owner.oid)
self._take_turn()
def _take_turn(self):
raise NotImplementedError('Subclass this before usage please.')
class TestMonster(MonsterAI):
def _take_turn(self):
enemies = self.level.get_objects_outside_faction(self.owner.faction)
if len(enemies) > 0:
distances = {self.owner.distance_to(e): e for e in enemies}
closest_distance = min(distances)
closest_enemy = distances[closest_distance]
if closest_distance <= 1.5:
self.owner.fighter.attack(closest_enemy)
else:
self.owner.move_towards(closest_enemy.x, closest_enemy.y, self.level)
| from src.constants import *
class MonsterAI(object):
def __init__(self, level):
self.owner = None
self.level = level
def take_turn(self):
self.owner.log.log_begin_turn(self.owner.oid)
self._take_turn()
def _take_turn(self):
raise NotImplementedError('Subclass this before usage please.')
class TestMonster(MonsterAI):
def _take_turn(self):
enemies = self.level.get_objects_outside_faction(self.owner.faction)
if len(enemies) > 0:
# Identify the closest enemy
distances = {self.owner.distance_to(e): e for e in enemies}
closest_distance = min(distances)
closest_enemy = distances[closest_distance]
# Inspect inventory for usable items
if self.owner.inventory is not None:
usable = self.owner.inventory.get_usable_items()
throwing_items = [i for i in usable if i.item.can_use(self.owner, closest_enemy, self.level)]
else:
throwing_items = []
# Attack if adjacent
if closest_distance <= 1.5:
self.owner.fighter.attack(closest_enemy)
# Throw if you have a throwing item
if len(throwing_items) > 0:
throwing_items[0].item.use(self.owner, closest_enemy, self.level)
else:
self.owner.move_towards(closest_enemy.x, closest_enemy.y, self.level)
| Add throwing item usage to test AI | Add throwing item usage to test AI
Unforutnately the item isn't evicted from the inventory on usage,
so the guy with the throwing item can kill everybody, but it's
working - he does throw it!
| Python | mit | MoyTW/RL_Arena_Experiment | ---
+++
@@ -1,3 +1,6 @@
+from src.constants import *
+
+
class MonsterAI(object):
def __init__(self, level):
self.owner = None
@@ -13,12 +16,27 @@
class TestMonster(MonsterAI):
def _take_turn(self):
+
enemies = self.level.get_objects_outside_faction(self.owner.faction)
+
if len(enemies) > 0:
+ # Identify the closest enemy
distances = {self.owner.distance_to(e): e for e in enemies}
closest_distance = min(distances)
closest_enemy = distances[closest_distance]
+
+ # Inspect inventory for usable items
+ if self.owner.inventory is not None:
+ usable = self.owner.inventory.get_usable_items()
+ throwing_items = [i for i in usable if i.item.can_use(self.owner, closest_enemy, self.level)]
+ else:
+ throwing_items = []
+
+ # Attack if adjacent
if closest_distance <= 1.5:
self.owner.fighter.attack(closest_enemy)
+ # Throw if you have a throwing item
+ if len(throwing_items) > 0:
+ throwing_items[0].item.use(self.owner, closest_enemy, self.level)
else:
self.owner.move_towards(closest_enemy.x, closest_enemy.y, self.level) |
3db0d12163d839c00965338c4f8efe29a85b3de7 | journal.py | journal.py | # -*- coding: utf-8 -*-
from flask import Flask
import os
import psycopg2
from contextlib import closing
DB_SCHEMA = """
DROP TABLE IF EXISTS entries;
CREATE TABLE entries (
id serial PRIMARY KEY,
title VARCHAR (127) NOT NULL,
text TEXT NOT NULL,
created TIMESTAMP NOT NULL
)
"""
app = Flask(__name__)
app.config['DATABASE'] = os.environ.get(
'DATABASE_URL', 'dbname=learning_journal user=miked, lfritts'
)
def connect_db():
"""Return a connection to the configured database"""
return psycopg2.connect(app.config['DATABASE'])
def init_db():
"""Initialize the database using DB_SCHEMA
WARNING: executing this function will drop existing tables.
"""
with closing(connect_db()) as db:
db.cursor().execute(DB_SCHEMA)
db.commit()
@app.route('/')
def hello():
return u'Hello world!'
if __name__ == '__main__':
app.run(debug=True)
| # -*- coding: utf-8 -*-
from flask import Flask
import os
import psycopg2
from contextlib import closing
DB_SCHEMA = """
DROP TABLE IF EXISTS entries;
CREATE TABLE entries (
id serial PRIMARY KEY,
title VARCHAR (127) NOT NULL,
text TEXT NOT NULL,
created TIMESTAMP NOT NULL
)
"""
app = Flask(__name__)
app.config['DATABASE'] = os.environ.get(
'DATABASE_URL', 'dbname=learning_journal'
)
def connect_db():
"""Return a connection to the configured database"""
return psycopg2.connect(app.config['DATABASE'])
def init_db():
"""Initialize the database using DB_SCHEMA
WARNING: executing this function will drop existing tables.
"""
with closing(connect_db()) as db:
db.cursor().execute(DB_SCHEMA)
db.commit()
@app.route('/')
def hello():
return u'Hello world!'
if __name__ == '__main__':
app.run(debug=True)
| Remove user from db connection string | Remove user from db connection string
| Python | mit | lfritts/learning_journal,lfritts/learning_journal | ---
+++
@@ -16,7 +16,7 @@
app = Flask(__name__)
app.config['DATABASE'] = os.environ.get(
- 'DATABASE_URL', 'dbname=learning_journal user=miked, lfritts'
+ 'DATABASE_URL', 'dbname=learning_journal'
)
|
fe78335e4f469e22f9a1de7a1e5ddd52021a7f0f | linesep.py | linesep.py | STARTER = -1
SEPARATOR = 0
TERMINATOR = 1
def readlines(fp, sep, mode=TERMINATOR, retain=True, size=512):
if mode < 0:
return _readlines_start(fp, sep, retain, size)
elif mode == 0:
return _readlines_sep(fp, sep, size)
else:
return _readlines_term(fp, sep, retain, size)
def _readlines_start(fp, sep, retain=True, size=512):
# Omits empty leading entry
entries = _readlines_sep(fp, sep, size=size)
e = next(entries)
if e:
yield e
for e in entries:
if retain:
e = sep + e
yield e
def _readlines_sep(fp, sep, size=512):
buff = ''
for chunk in iter(lambda: fp.read(size), ''):
buff += chunk
lines = buff.split(sep)
buff = lines.pop()
for l in lines:
yield l
yield buff
def _readlines_term(fp, sep, retain=True, size=512):
# Omits empty trailing entry
buff = ''
for chunk in iter(lambda: fp.read(size), ''):
buff += chunk
lines = buff.split(sep)
buff = lines.pop()
for l in lines:
if retain:
l += sep
yield l
if buff:
yield buff
| def read_begun(fp, sep, retain=True, size=512):
# Omits empty leading entry
entries = read_separated(fp, sep, size=size)
e = next(entries)
if e:
yield e
for e in entries:
if retain:
e = sep + e
yield e
def read_separated(fp, sep, size=512):
buff = ''
for chunk in iter(lambda: fp.read(size), ''):
buff += chunk
lines = buff.split(sep)
buff = lines.pop()
for l in lines:
yield l
yield buff
def read_terminated(fp, sep, retain=True, size=512):
# Omits empty trailing entry
buff = ''
for chunk in iter(lambda: fp.read(size), ''):
buff += chunk
lines = buff.split(sep)
buff = lines.pop()
for l in lines:
if retain:
l += sep
yield l
if buff:
yield buff
| Use three public functions instead of one | Use three public functions instead of one
| Python | mit | jwodder/linesep | ---
+++
@@ -1,18 +1,6 @@
-STARTER = -1
-SEPARATOR = 0
-TERMINATOR = 1
-
-def readlines(fp, sep, mode=TERMINATOR, retain=True, size=512):
- if mode < 0:
- return _readlines_start(fp, sep, retain, size)
- elif mode == 0:
- return _readlines_sep(fp, sep, size)
- else:
- return _readlines_term(fp, sep, retain, size)
-
-def _readlines_start(fp, sep, retain=True, size=512):
+def read_begun(fp, sep, retain=True, size=512):
# Omits empty leading entry
- entries = _readlines_sep(fp, sep, size=size)
+ entries = read_separated(fp, sep, size=size)
e = next(entries)
if e:
yield e
@@ -21,7 +9,7 @@
e = sep + e
yield e
-def _readlines_sep(fp, sep, size=512):
+def read_separated(fp, sep, size=512):
buff = ''
for chunk in iter(lambda: fp.read(size), ''):
buff += chunk
@@ -31,7 +19,7 @@
yield l
yield buff
-def _readlines_term(fp, sep, retain=True, size=512):
+def read_terminated(fp, sep, retain=True, size=512):
# Omits empty trailing entry
buff = ''
for chunk in iter(lambda: fp.read(size), ''): |
93650252e195b036698ded99d271d6249f0bd80f | project/scripts/dates.py | project/scripts/dates.py | # For now I am assuming the investment date will be returned from the db
# as a string yyyy-mm-dd, representing the day the trend was purchased in UTC time
#!/usr/bin/env python3
from datetime import datetime, timedelta
import pytz
def get_start_times(date):
"""
date: an epoch integer representing the date that the investment was purchased
returns the integers (year, month, day)
"""
datetime_object = datetime.utcfromtimestamp(date)
return datetime_object.year, datetime_object.month, datetime_object.day
def get_end_times():
"""
returns the end dates to query pytrends for as integers (year, month, day)
"""
datetime = get_current_date() - timedelta(days = 1) #get yesterday's date
return datetime.year, datetime.month, datetime.day
def get_current_date():
"""
returns the current date in UTC as a datetime object
"""
utc = pytz.utc
date = datetime.now(tz=utc)
return date
def date_to_epoch(date):
"""
converts date object back into epoch
"""
return date.timestamp()
| # For now I am assuming the investment date will be returned from the db
# as a string yyyy-mm-dd, representing the day the trend was purchased in UTC time
#!/usr/bin/env python3
from datetime import datetime, timedelta
import pytz
def get_start_times(date):
"""
date: an epoch integer representing the date that the investment was purchased
returns the integers (year, month, day)
"""
datetime_object = datetime.utcfromtimestamp(date)
return datetime_object.year, datetime_object.month, datetime_object.day
def get_end_times():
"""
returns the end dates to query pytrends for as integers (year, month, day)
"""
datetime = get_current_date() - timedelta(days = 1) #get yesterday's date
return datetime.year, datetime.month, datetime.day
def get_current_date():
"""
returns the current date in UTC as a datetime object
"""
utc = pytz.utc
date = datetime.now(tz=utc)
return date
def date_to_epoch(date):
"""
converts date object back into epoch
"""
return int(date.timestamp())
| Make sure epoch return type is int | Make sure epoch return type is int
| Python | apache-2.0 | googleinterns/sgonks,googleinterns/sgonks,googleinterns/sgonks,googleinterns/sgonks | ---
+++
@@ -37,4 +37,4 @@
"""
converts date object back into epoch
"""
- return date.timestamp()
+ return int(date.timestamp()) |
e9ae6b7f92ee0a4585adc11e695cc15cbe425e23 | morepath/app.py | morepath/app.py | from .interfaces import IRoot, IApp
from .publish import publish
from .request import Request
from .traject import Traject
from comparch import ClassRegistry, Lookup, ChainClassLookup
known_apps = {}
class App(IApp, ClassRegistry):
def __init__(self, name='', parent=None):
super(App, self).__init__()
self.name = name
self.root_model = None
self.root_obj = None
self.child_apps = {}
self.parent = parent
self.traject = Traject()
if self.parent is not None:
parent.add_child(self)
def add_child(self, app):
self.child_apps[app.name] = app
self.traject.register(app.name, lambda: app, conflicting=True)
def class_lookup(self):
if self.parent is None:
return ChainClassLookup(self, global_app)
return ChainClassLookup(self, self.parent.class_lookup())
def __call__(self, environ, start_response):
# XXX do caching lookup where?
lookup = Lookup(self.class_lookup())
request = Request(environ)
request.lookup = lookup
response = publish(request, self, lookup)
return response(environ, start_response)
global_app = App()
# XXX this shouldn't be here but be the root of the global app
class Root(IRoot):
pass
root = Root()
| from .interfaces import IRoot, IApp
from .publish import publish
from .request import Request
from .traject import Traject
from comparch import ClassRegistry, Lookup, ChainClassLookup
known_apps = {}
class App(IApp, ClassRegistry):
def __init__(self, name='', parent=None):
super(App, self).__init__()
self.name = name
self.root_model = None
self.root_obj = None
self.child_apps = {}
self.parent = parent
self.traject = Traject()
if self.parent is not None:
parent.add_child(self)
def add_child(self, app):
self.child_apps[app.name] = app
self.traject.register(app.name, lambda: app, conflicting=True)
def class_lookup(self):
if self.parent is None:
return ChainClassLookup(self, global_app)
return ChainClassLookup(self, self.parent.class_lookup())
def __call__(self, environ, start_response):
# XXX do caching lookup where?
lookup = Lookup(self.class_lookup())
request = Request(environ)
request.lookup = lookup
response = publish(request, self, lookup)
return response(environ, start_response)
global_app = App()
| Remove root that wasn't used. | Remove root that wasn't used.
| Python | bsd-3-clause | faassen/morepath,morepath/morepath,taschini/morepath | ---
+++
@@ -36,8 +36,3 @@
return response(environ, start_response)
global_app = App()
-
-# XXX this shouldn't be here but be the root of the global app
-class Root(IRoot):
- pass
-root = Root() |
a7938ed9ec814fa9cf53272ceb65e84d11d50dc1 | moto/s3/urls.py | moto/s3/urls.py | from __future__ import unicode_literals
from moto.compat import OrderedDict
from .responses import S3ResponseInstance
url_bases = [
"https?://s3(.*).amazonaws.com",
"https?://(?P<bucket_name>[a-zA-Z0-9\-_.]*)\.?s3(.*).amazonaws.com"
]
url_paths = OrderedDict([
# subdomain bucket
('{0}/$', S3ResponseInstance.bucket_response),
# subdomain key of path-based bucket
('{0}/(?P<key_or_bucket_name>.+)', S3ResponseInstance.ambiguous_response),
# path-based bucket + key
('{0}/(?P<bucket_name_path>[a-zA-Z0-9\-_./]+)/(?P<key_name>.+)', S3ResponseInstance.key_response),
])
| from __future__ import unicode_literals
from .responses import S3ResponseInstance
url_bases = [
"https?://s3(.*).amazonaws.com",
"https?://(?P<bucket_name>[a-zA-Z0-9\-_.]*)\.?s3(.*).amazonaws.com"
]
url_paths = {
# subdomain bucket
'{0}/$': S3ResponseInstance.bucket_response,
# subdomain key of path-based bucket
'{0}/(?P<key_or_bucket_name>[^/]+)/?$': S3ResponseInstance.ambiguous_response,
# path-based bucket + key
'{0}/(?P<bucket_name_path>[a-zA-Z0-9\-_./]+)/(?P<key_name>.+)': S3ResponseInstance.key_response,
}
| Fix s3 url regex to ensure path-based bucket and key does not catch. | Fix s3 url regex to ensure path-based bucket and key does not catch.
| Python | apache-2.0 | william-richard/moto,kefo/moto,botify-labs/moto,2rs2ts/moto,dbfr3qs/moto,im-auld/moto,william-richard/moto,william-richard/moto,Affirm/moto,kefo/moto,botify-labs/moto,Brett55/moto,ZuluPro/moto,ZuluPro/moto,okomestudio/moto,spulec/moto,whummer/moto,william-richard/moto,kefo/moto,kefo/moto,ZuluPro/moto,dbfr3qs/moto,heddle317/moto,Brett55/moto,whummer/moto,mrucci/moto,gjtempleton/moto,rocky4570/moto,spulec/moto,whummer/moto,tootedom/moto,Brett55/moto,heddle317/moto,gjtempleton/moto,IlyaSukhanov/moto,botify-labs/moto,2rs2ts/moto,spulec/moto,william-richard/moto,okomestudio/moto,ZuluPro/moto,okomestudio/moto,whummer/moto,gjtempleton/moto,Affirm/moto,rocky4570/moto,silveregg/moto,2rs2ts/moto,spulec/moto,botify-labs/moto,okomestudio/moto,dbfr3qs/moto,heddle317/moto,whummer/moto,rocky4570/moto,Affirm/moto,dbfr3qs/moto,Brett55/moto,Brett55/moto,dbfr3qs/moto,spulec/moto,2rs2ts/moto,gjtempleton/moto,botify-labs/moto,botify-labs/moto,spulec/moto,whummer/moto,kefo/moto,Brett55/moto,Affirm/moto,braintreeps/moto,ZuluPro/moto,heddle317/moto,gjtempleton/moto,Affirm/moto,rocky4570/moto,okomestudio/moto,rocky4570/moto,Affirm/moto,heddle317/moto,2rs2ts/moto,dbfr3qs/moto,rocky4570/moto,ZuluPro/moto,william-richard/moto,riccardomc/moto,okomestudio/moto | ---
+++
@@ -1,6 +1,5 @@
from __future__ import unicode_literals
-from moto.compat import OrderedDict
from .responses import S3ResponseInstance
url_bases = [
@@ -8,13 +7,13 @@
"https?://(?P<bucket_name>[a-zA-Z0-9\-_.]*)\.?s3(.*).amazonaws.com"
]
-url_paths = OrderedDict([
+url_paths = {
# subdomain bucket
- ('{0}/$', S3ResponseInstance.bucket_response),
+ '{0}/$': S3ResponseInstance.bucket_response,
# subdomain key of path-based bucket
- ('{0}/(?P<key_or_bucket_name>.+)', S3ResponseInstance.ambiguous_response),
+ '{0}/(?P<key_or_bucket_name>[^/]+)/?$': S3ResponseInstance.ambiguous_response,
# path-based bucket + key
- ('{0}/(?P<bucket_name_path>[a-zA-Z0-9\-_./]+)/(?P<key_name>.+)', S3ResponseInstance.key_response),
-])
+ '{0}/(?P<bucket_name_path>[a-zA-Z0-9\-_./]+)/(?P<key_name>.+)': S3ResponseInstance.key_response,
+} |
429c2548835aef1cb1655229ee11f42ccf189bd1 | shopping_list.py | shopping_list.py | shopping_list = []
def show_help():
print("What should we pick up at the store?")
print("Enter DONE to stop. Enter HELP for this help. Enter SHOW to see your current list.")
| shopping_list = []
def show_help():
print("What should we pick up at the store?")
print("Enter DONE to stop. Enter HELP for this help. Enter SHOW to see your current list.")
def add_to_list(item):
shopping_list.append(item)
print("Added! List has {} items.".format(len(shopping_list)))
| Add an item to the shopping list. | Add an item to the shopping list.
| Python | mit | adityatrivedi/shopping-list | ---
+++
@@ -4,3 +4,8 @@
print("What should we pick up at the store?")
print("Enter DONE to stop. Enter HELP for this help. Enter SHOW to see your current list.")
+def add_to_list(item):
+ shopping_list.append(item)
+ print("Added! List has {} items.".format(len(shopping_list)))
+
+ |
39ce4e74a6b7115a35260fa2722ace1792cb1780 | python/count_triplets.py | python/count_triplets.py | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
def countTriplets(arr, r):
potential_triplets_with_middle = Counter()
potential_triplets_with_end = Counter()
total_triplets = 0
for num in arr:
# num completed potential_triplets_with_end[num] triplets
if potential_triplets_with_end[num]:
total_triplets += potential_triplets_with_end[num]
# num can be the middle number in potential_triplets_with_middle[num] triplets
if potential_triplets_with_middle[num]:
potential_triplets_with_end[num * r] += potential_triplets_with_middle[num]
# num can be the begining of a triplet
potential_triplets_with_middle[num * r] += 1
print("num", num, " middle", potential_triplets_with_middle, " end", potential_triplets_with_end, " total", total_triplets)
return total_triplets
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nr = input().rstrip().split()
n = int(nr[0])
r = int(nr[1])
arr = list(map(int, input().rstrip().split()))
ans = countTriplets(arr, r)
fptr.write(str(ans) + '\n')
fptr.close()
| #!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
def countTriplets(arr, r):
potential_triplets_with_middle = Counter()
potential_triplets_with_end = Counter()
total_triplets = 0
for num in arr:
# num completed potential_triplets_with_end[num] triplets
if potential_triplets_with_end[num]:
total_triplets += potential_triplets_with_end[num]
# num can be the middle number in
# potential_triplets_with_middle[num] triplets
if potential_triplets_with_middle[num]:
potential_triplets_with_end[num * r] += \
potential_triplets_with_middle[num]
# num can be the begining of a triplet
potential_triplets_with_middle[num * r] += 1
return total_triplets
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nr = input().rstrip().split()
n = int(nr[0])
r = int(nr[1])
arr = list(map(int, input().rstrip().split()))
ans = countTriplets(arr, r)
fptr.write(str(ans) + '\n')
fptr.close()
| Remove debug output and pycodestyle | Remove debug output and pycodestyle
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank | ---
+++
@@ -6,6 +6,7 @@
import re
import sys
from collections import Counter
+
def countTriplets(arr, r):
potential_triplets_with_middle = Counter()
@@ -16,13 +17,14 @@
if potential_triplets_with_end[num]:
total_triplets += potential_triplets_with_end[num]
- # num can be the middle number in potential_triplets_with_middle[num] triplets
+ # num can be the middle number in
+ # potential_triplets_with_middle[num] triplets
if potential_triplets_with_middle[num]:
- potential_triplets_with_end[num * r] += potential_triplets_with_middle[num]
+ potential_triplets_with_end[num * r] += \
+ potential_triplets_with_middle[num]
# num can be the begining of a triplet
potential_triplets_with_middle[num * r] += 1
- print("num", num, " middle", potential_triplets_with_middle, " end", potential_triplets_with_end, " total", total_triplets)
return total_triplets
|
5dd78f614e5882bc2a3fcae24117a26ee34371ac | register-result.py | register-result.py | #!/usr/bin/env python
import json
import socket
import sys
if len(sys.argv) < 4:
print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>")
sys.exit(128)
check_client = sys.argv[1]
check_name = sys.argv[2]
check_output = sys.argv[3]
check_status = int(sys.argv[4])
check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000
# Our result dict
result = dict()
result['source'] = check_client
result['name'] = check_name
result['output'] = check_output
result['status'] = check_status
result['ttl'] = check_ttl
# TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 3030)
sock.connect(server_address)
print (json.dumps(result))
socket.sendall(json.dumps(result))
| #!/usr/bin/env python
import json
import socket
import sys
if len(sys.argv) < 4:
print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>")
sys.exit(128)
check_client = sys.argv[1]
check_name = sys.argv[2]
check_output = sys.argv[3]
check_status = int(sys.argv[4])
check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000
# Our result dict
result = dict()
result['source'] = check_client
result['name'] = check_name
result['output'] = check_output
result['status'] = check_status
result['ttl'] = check_ttl
# TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 3030)
sock.connect(server_address)
sock.sendall(json.dumps(result))
print (json.dumps(result))
| Fix mistake with socket constructor | Fix mistake with socket constructor
| Python | mit | panubo/docker-monitor,panubo/docker-monitor,panubo/docker-monitor | ---
+++
@@ -26,5 +26,5 @@
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 3030)
sock.connect(server_address)
+sock.sendall(json.dumps(result))
print (json.dumps(result))
-socket.sendall(json.dumps(result)) |
7124d56b3edd85c64dcc7f3ff0fa172102fe8358 | devtools/travis-ci/update_versions_json.py | devtools/travis-ci/update_versions_json.py | import json
try:
# Only works in Python 3.5
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from yank import version
if not version.release:
print("This is not a release.")
exit(0)
URL = 'http://www.getyank.org'
try:
data = urlopen(URL + '/versions.json').read().decode()
versions = json.loads(data)
except:
# Initial population
versions = [
{'version': "0.14.1",
'display': "0.14.1",
'url': "{base}/{version}".format(base=URL, version="0.14.1"),
'latest': False
}
]
# Debug lines
# import pdb
# sd = urlopen('http://mdtraj.org' + '/versions.json').read().decode()
# sv = json.loads(sd)
# Sort the list so the versions are in the right order online
versions = sorted(versions, key=lambda k: k['version'])
# new release so all the others are now old
for i in range(len(versions)):
versions[i]['latest'] = False
versions.append({
'version': version.version,
'display': version.short_version,
'url': "{base}/{version}".format(base=URL, version=version.version),
'latest': True,
})
with open("docs/_deploy/versions.json", 'w') as versionf:
json.dump(versions, versionf, indent=2)
| import json
try:
# Only works in Python 3.5
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from yank import version
#if not version.release:
# print("This is not a release.")
# exit(0)
URL = 'http://www.getyank.org'
try:
data = urlopen(URL + '/versions.json').read().decode()
versions = json.loads(data)
except:
# Initial population
versions = [
{'version': "0.14.1",
'display': "0.14.1",
'url': "{base}/{version}".format(base=URL, version="0.14.1"),
'latest': False
}
]
# Debug lines
# import pdb
# sd = urlopen('http://mdtraj.org' + '/versions.json').read().decode()
# sv = json.loads(sd)
# Sort the list so the versions are in the right order online
versions = sorted(versions, key=lambda k: k['version'])
# new release so all the others are now old
for i in range(len(versions)):
versions[i]['latest'] = False
versions.append({
'version': version.version,
'display': version.short_version,
'url': "{base}/{version}".format(base=URL, version=version.version),
'latest': True,
})
with open("docs/_deploy/versions.json", 'w') as versionf:
json.dump(versions, versionf, indent=2)
| Disable the check for the initial versions push | Disable the check for the initial versions push
| Python | mit | andrrizzi/yank,andrrizzi/yank,choderalab/yank,andrrizzi/yank,choderalab/yank | ---
+++
@@ -7,9 +7,9 @@
from urllib2 import urlopen
from yank import version
-if not version.release:
- print("This is not a release.")
- exit(0)
+#if not version.release:
+# print("This is not a release.")
+# exit(0)
URL = 'http://www.getyank.org'
try: |
5e57dce84ffe7be7e699af1e2be953d5a65d8435 | tests/test_module.py | tests/test_module.py | #!/usr/bin/env python
#
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
# Copyright (c) 2008-2014 California Institute of Technology.
# License: 3-clause BSD. The full license text is available at:
# - http://trac.mystic.cacr.caltech.edu/project/pathos/browser/dill/LICENSE
import sys
import dill
import test_mixins as module
module.a = 1234
pik_mod = dill.dumps(module)
module.a = 0
# remove module
del sys.modules[module.__name__]
del module
module = dill.loads(pik_mod)
assert module.a == 1234
assert module.double_add(1, 2, 3) == 2 * module.fx
| #!/usr/bin/env python
#
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
# Copyright (c) 2008-2014 California Institute of Technology.
# License: 3-clause BSD. The full license text is available at:
# - http://trac.mystic.cacr.caltech.edu/project/pathos/browser/dill/LICENSE
import sys
import dill
import test_mixins as module
cached = (module.__cached__ if hasattr(module, "__cached__")
else module.__file__ + "c")
module.a = 1234
pik_mod = dill.dumps(module)
module.a = 0
# remove module
del sys.modules[module.__name__]
del module
module = dill.loads(pik_mod)
assert hasattr(module, "a") and module.a == 1234
assert module.double_add(1, 2, 3) == 2 * module.fx
# clean up
import os
os.remove(cached)
if os.path.exists("__pycache__") and not os.listdir("__pycache__"):
os.removedirs("__pycache__")
| Add code to clean up | Add code to clean up
| Python | bsd-3-clause | wxiang7/dill,mindw/dill | ---
+++
@@ -8,6 +8,9 @@
import sys
import dill
import test_mixins as module
+
+cached = (module.__cached__ if hasattr(module, "__cached__")
+ else module.__file__ + "c")
module.a = 1234
@@ -20,5 +23,11 @@
del module
module = dill.loads(pik_mod)
-assert module.a == 1234
+assert hasattr(module, "a") and module.a == 1234
assert module.double_add(1, 2, 3) == 2 * module.fx
+
+# clean up
+import os
+os.remove(cached)
+if os.path.exists("__pycache__") and not os.listdir("__pycache__"):
+ os.removedirs("__pycache__") |
66a6223ca2c512f3f39ecb4867547a440611713b | nisl/__init__.py | nisl/__init__.py | """
Machine Learning module for NeuroImaging in python
==================================================
See http://nisl.github.com for complete documentation.
"""
#from . import check_build
#from .base import clone
try:
from numpy.testing import nosetester
class NoseTester(nosetester.NoseTester):
""" Subclass numpy's NoseTester to add doctests by default
"""
def test(self, label='fast', verbose=1, extra_argv=['--exe'],
doctests=True, coverage=False):
"""Run the full test suite
Examples
--------
This will run the test suite and stop at the first failing
example
>>> from nisl import test
>>> test(extra_argv=['--exe', '-sx']) #doctest: +SKIP
"""
return super(NoseTester, self).test(label=label, verbose=verbose,
extra_argv=extra_argv,
doctests=doctests, coverage=coverage)
test = NoseTester().test
del nosetester
except:
pass
__all__ = ['datasets']
__version__ = '2010'
| """
Machine Learning module for NeuroImaging in python
==================================================
See http://nisl.github.com for complete documentation.
"""
try:
import numpy
except ImportError:
print 'Numpy could not be found, please install it properly to use nisl.'
try:
import scipy
except ImportError:
print 'Scipy could not be found, please install it properly to use nisl.'
try:
import sklearn
except ImportError:
print 'Sklearn could not be found, please install it properly to use nisl.'
try:
from numpy.testing import nosetester
class NoseTester(nosetester.NoseTester):
""" Subclass numpy's NoseTester to add doctests by default
"""
def test(self, label='fast', verbose=1, extra_argv=['--exe'],
doctests=True, coverage=False):
"""Run the full test suite
Examples
--------
This will run the test suite and stop at the first failing
example
>>> from nisl import test
>>> test(extra_argv=['--exe', '-sx']) #doctest: +SKIP
"""
return super(NoseTester, self).test(label=label, verbose=verbose,
extra_argv=extra_argv,
doctests=doctests, coverage=coverage)
test = NoseTester().test
del nosetester
except:
pass
__all__ = ['datasets']
__version__ = '2010'
| Add an error message when trying to load nisl without having Numpy, Scipy and Sklearn installed. | Add an error message when trying to load nisl without having Numpy, Scipy and Sklearn installed.
| Python | bsd-3-clause | abenicho/isvr | ---
+++
@@ -5,8 +5,21 @@
See http://nisl.github.com for complete documentation.
"""
-#from . import check_build
-#from .base import clone
+try:
+ import numpy
+except ImportError:
+ print 'Numpy could not be found, please install it properly to use nisl.'
+
+
+try:
+ import scipy
+except ImportError:
+ print 'Scipy could not be found, please install it properly to use nisl.'
+
+try:
+ import sklearn
+except ImportError:
+ print 'Sklearn could not be found, please install it properly to use nisl.'
try: |
5a74ebe16cc46b93c5d6a7cb4880e74a7ea69442 | chainerx/_cuda.py | chainerx/_cuda.py | import chainerx
from chainerx import _pybind_cuda
try:
import cupy
_cupy_available = True
except Exception:
_cupy_available = False
_chainerx_allocator = None
def cupy_share_allocator(owner=chainerx._global_context):
# Replace CuPy's allocator with ChainerX's if ChainerX is available with
# the CUDA backend. This is needed in order to share the GPU memory
# without having both modules using separate memory pools.
# TODO(imanishi): Make sure this allocator works when the global
# default context is changed by the user. It currently will not
# since the allocator is only configured here once.
try:
owner.get_backend('cuda')
except chainerx.BackendError:
raise RuntimeError(
'Cannot share allocator with CuPy without the CUDA backend.')
if not _cupy_available:
raise RuntimeError(
'Cannot share allocator with CuPy since CuPy is not available.')
param = _pybind_cuda.get_backend_ptr()
malloc_func, free_func = _pybind_cuda.get_backend_malloc_free_ptrs()
global _chainerx_allocator
_chainerx_allocator = cupy.cuda.memory.CFunctionAllocator(
param, malloc_func, free_func, owner)
cupy.cuda.set_allocator(_chainerx_allocator.malloc)
| import chainerx
try:
import cupy
_cupy_available = True
except Exception:
_cupy_available = False
_chainerx_allocator = None
def cupy_share_allocator(owner=chainerx._global_context):
# Replace CuPy's allocator with ChainerX's if ChainerX is available with
# the CUDA backend. This is needed in order to share the GPU memory
# without having both modules using separate memory pools.
# TODO(imanishi): Make sure this allocator works when the global
# default context is changed by the user. It currently will not
# since the allocator is only configured here once.
try:
owner.get_backend('cuda')
except chainerx.BackendError:
raise RuntimeError(
'Cannot share allocator with CuPy without the CUDA backend.')
if not _cupy_available:
raise RuntimeError(
'Cannot share allocator with CuPy since CuPy is not available.')
param = chainerx._pybind_cuda.get_backend_ptr()
malloc_func, free_func = (
chainerx._pybind_cuda.get_backend_malloc_free_ptrs())
global _chainerx_allocator
_chainerx_allocator = cupy.cuda.memory.CFunctionAllocator(
param, malloc_func, free_func, owner)
cupy.cuda.set_allocator(_chainerx_allocator.malloc)
| Fix import error when CUDA is not available | Fix import error when CUDA is not available
| Python | mit | okuta/chainer,keisuke-umezawa/chainer,wkentaro/chainer,chainer/chainer,hvy/chainer,wkentaro/chainer,hvy/chainer,keisuke-umezawa/chainer,chainer/chainer,wkentaro/chainer,keisuke-umezawa/chainer,chainer/chainer,tkerola/chainer,keisuke-umezawa/chainer,pfnet/chainer,okuta/chainer,wkentaro/chainer,niboshi/chainer,niboshi/chainer,hvy/chainer,niboshi/chainer,okuta/chainer,okuta/chainer,hvy/chainer,chainer/chainer,niboshi/chainer | ---
+++
@@ -1,5 +1,4 @@
import chainerx
-from chainerx import _pybind_cuda
try:
import cupy
@@ -29,8 +28,9 @@
raise RuntimeError(
'Cannot share allocator with CuPy since CuPy is not available.')
- param = _pybind_cuda.get_backend_ptr()
- malloc_func, free_func = _pybind_cuda.get_backend_malloc_free_ptrs()
+ param = chainerx._pybind_cuda.get_backend_ptr()
+ malloc_func, free_func = (
+ chainerx._pybind_cuda.get_backend_malloc_free_ptrs())
global _chainerx_allocator
_chainerx_allocator = cupy.cuda.memory.CFunctionAllocator( |
910e1a1762dac1d62c8a6749286c436d6c2b28d9 | UM/Operations/RemoveSceneNodeOperation.py | UM/Operations/RemoveSceneNodeOperation.py | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.Selection import Selection
from UM.Application import Application
## An operation that removes a SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
## Initialises the RemoveSceneNodeOperation.
#
# \param node The node to remove.
def __init__(self, node):
super().__init__()
self._node = node
self._parent = node.getParent()
## Undoes the operation, putting the node back in the scene.
def undo(self):
self._node.setParent(self._parent) # Hanging it back under its original parent puts it back in the scene.
## Redo the operation, removing the node again.
def redo(self):
self._node.setParent(None)
# Hack to ensure that the _onchanged is triggered correctly.
# We can't do it the right way as most remove changes don't need to trigger
# a reslice (eg; removing hull nodes don't need to trigger reslice).
try:
Application.getInstance().getBackend().forceSlice()
except:
pass
if Selection.isSelected(self._node): # Also remove the selection.
Selection.remove(self._node)
| # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.Selection import Selection
from UM.Application import Application
## An operation that removes a SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
## Initialises the RemoveSceneNodeOperation.
#
# \param node The node to remove.
def __init__(self, node):
super().__init__()
self._node = node
self._parent = node.getParent()
## Undoes the operation, putting the node back in the scene.
def undo(self):
self._node.setParent(self._parent) # Hanging it back under its original parent puts it back in the scene.
## Redo the operation, removing the node again.
def redo(self):
old_parent = self._parent
self._node.setParent(None)
if old_parent and old_parent.callDecoration("isGroup"):
old_parent.callDecoration("recomputeConvexHull")
# Hack to ensure that the _onchanged is triggered correctly.
# We can't do it the right way as most remove changes don't need to trigger
# a reslice (eg; removing hull nodes don't need to trigger reslice).
try:
Application.getInstance().getBackend().forceSlice()
except:
pass
if Selection.isSelected(self._node): # Also remove the selection.
Selection.remove(self._node)
| Update convex hull of the group when removing a node from the group | Update convex hull of the group when removing a node from the group
CURA-2573
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -23,8 +23,11 @@
## Redo the operation, removing the node again.
def redo(self):
+ old_parent = self._parent
self._node.setParent(None)
+ if old_parent and old_parent.callDecoration("isGroup"):
+ old_parent.callDecoration("recomputeConvexHull")
# Hack to ensure that the _onchanged is triggered correctly.
# We can't do it the right way as most remove changes don't need to trigger |
a17f711a6e055a9de4674e4c35570a2c6d6f0335 | ttysend.py | ttysend.py | from __future__ import print_function
import sys
import os
import fcntl
import termios
import argparse
class RootRequired(Exception):
"""Our standard exception."""
pass
def send(data, tty):
"""Send each char of data to tty."""
if(os.getuid() != 0):
raise RootRequired('Only root can send input to other TTYs.')
for c in data:
fcntl.ioctl(tty, termios.TIOCSTI, c)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('tty', type=argparse.FileType('w'),
help='display a square of a given number')
group = parser.add_mutually_exclusive_group()
group.add_argument('-n', action='store_true',
help='Do not print the trailing newline character.')
group.add_argument('--stdin', action='store_true',
help='Read input from stdin.')
args, data = parser.parse_known_args()
# Prepare data
if args.stdin:
data = sys.stdin.read()
else:
data = ' '.join(data)
# Send data
try:
send(data, args.tty)
except RootRequired, e:
sys.exit(print('ERROR:', e, file=sys.stderr))
# Handle trailing newline
if data[-1][-1] != '\n' and not args.n:
send('\n', args.tty)
| #!/usr/bin/env python
from __future__ import print_function
import sys
import os
import fcntl
import termios
import argparse
class RootRequired(Exception):
"""Our standard exception."""
pass
def send(data, tty):
if len(data):
# Handle trailing newline
if data[-1][-1] != '\n':
data += '\n'
send_raw(data, tty)
def send_raw(data, tty):
"""Send each char of data to tty."""
if(os.getuid() != 0):
raise RootRequired('Only root can send input to other TTYs.')
for c in data:
fcntl.ioctl(tty, termios.TIOCSTI, c)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('tty', type=argparse.FileType('w'),
help='display a square of a given number')
group = parser.add_mutually_exclusive_group()
group.add_argument('-n', action='store_true',
help='Do not force a trailing newline character.')
group.add_argument('--stdin', action='store_true',
help='Read input from stdin.')
args, data = parser.parse_known_args()
# Prepare data
if args.stdin:
data = sys.stdin.read()
else:
data = ' '.join(data)
# Send data
try:
if args.n:
send_raw(data, args.tty)
else:
send(data, args.tty)
except RootRequired, e:
sys.exit(print('ERROR:', e, file=sys.stderr))
| Move newline handling to a function. | Move newline handling to a function.
Allows library users to choose to force trailing newlines.
| Python | mit | RichardBronosky/ttysend | ---
+++
@@ -1,3 +1,4 @@
+#!/usr/bin/env python
from __future__ import print_function
import sys
import os
@@ -14,6 +15,13 @@
def send(data, tty):
+ if len(data):
+ # Handle trailing newline
+ if data[-1][-1] != '\n':
+ data += '\n'
+ send_raw(data, tty)
+
+def send_raw(data, tty):
"""Send each char of data to tty."""
if(os.getuid() != 0):
raise RootRequired('Only root can send input to other TTYs.')
@@ -26,7 +34,7 @@
help='display a square of a given number')
group = parser.add_mutually_exclusive_group()
group.add_argument('-n', action='store_true',
- help='Do not print the trailing newline character.')
+ help='Do not force a trailing newline character.')
group.add_argument('--stdin', action='store_true',
help='Read input from stdin.')
args, data = parser.parse_known_args()
@@ -39,10 +47,9 @@
# Send data
try:
- send(data, args.tty)
+ if args.n:
+ send_raw(data, args.tty)
+ else:
+ send(data, args.tty)
except RootRequired, e:
sys.exit(print('ERROR:', e, file=sys.stderr))
-
- # Handle trailing newline
- if data[-1][-1] != '\n' and not args.n:
- send('\n', args.tty) |
782c1b8379d38f99de413398919aa797af0df645 | plot_s_curve.py | plot_s_curve.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from numpy import array, log
import sys
x = []
y = []
infile = open(sys.argv[1])
for line in infile:
data = line.replace('\n','').split()
print(data)
try :
x.append(float(data[0]))
y.append(float(data[1]))
except ValueError:
pass
#x = array(x)
#y = array(y)
figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
#plt.plot(log(x),log(y))
plt.plot(x,y,"o")
plt.ylabel('$\log T$')
plt.xlabel('$\log \Sigma$')
plt.grid()
plt.show()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from numpy import array, log
import sys
import os
import matplotlib.animation as animation
fig = plt.figure()
inpath = sys.argv[1]
if os.path.isfile(inpath):
print('Visiting {}'.format(inpath))
filenames = [inpath]
else:
_filenames = os.listdir(inpath)
_filenames.sort()
filesnames = [inpath + '/' + fname for fname in _filesnames if '_tot.dat' in fname]
print('Visiting all files of {}'.format(inpath))
axline, = plt.plot(0, 0, 'o')
def draw_once(filename):
x = []
y = []
if not 'tot.dat' in filename:
return ([0], [0])
else:
print('Visiting {}'.format(filename))
outfile = filename.replace('.dat', '.png')
for line in open(filename):
data = line.replace('\n', '').split()
try :
print (data)
xData = float(data[0])
yData = float(data[1])
x.append(xData)
y.append(yData)
except ValueError:
pass
axline.set_xdata(x)
axline.set_ydata(y)
return axline,
def init():
print('Initialisation')
plt.ylabel('$\log T$')
plt.xlabel('$\log \Sigma$')
plt.xlim(1.8, 4)
plt.ylim(6, 8)
plt.grid()
if len(filenames) > 1:
ani = animation.FuncAnimation(fig, draw_once, filenames, init_func=init, interval=10)
else:
init()
draw_once(filenames[0])
plt.show()
# x, y = draw_once(filenames[2])
# plt.plot(x, y, 'o')
| Use animation if dirname is provided | Use animation if dirname is provided
| Python | mit | M2-AAIS/BAD | ---
+++
@@ -4,31 +4,65 @@
import matplotlib.pyplot as plt
from numpy import array, log
import sys
+import os
-x = []
+import matplotlib.animation as animation
-y = []
+fig = plt.figure()
-infile = open(sys.argv[1])
+inpath = sys.argv[1]
-for line in infile:
- data = line.replace('\n','').split()
- print(data)
- try :
- x.append(float(data[0]))
- y.append(float(data[1]))
- except ValueError:
- pass
+if os.path.isfile(inpath):
+ print('Visiting {}'.format(inpath))
+ filenames = [inpath]
+else:
+ _filenames = os.listdir(inpath)
+ _filenames.sort()
+ filesnames = [inpath + '/' + fname for fname in _filesnames if '_tot.dat' in fname]
+
+ print('Visiting all files of {}'.format(inpath))
-#x = array(x)
-#y = array(y)
+axline, = plt.plot(0, 0, 'o')
-figManager = plt.get_current_fig_manager()
-figManager.window.showMaximized()
-#plt.plot(log(x),log(y))
-plt.plot(x,y,"o")
+def draw_once(filename):
+ x = []
+ y = []
+ if not 'tot.dat' in filename:
+ return ([0], [0])
+ else:
+ print('Visiting {}'.format(filename))
+ outfile = filename.replace('.dat', '.png')
+
+ for line in open(filename):
+ data = line.replace('\n', '').split()
+ try :
+ print (data)
+ xData = float(data[0])
+ yData = float(data[1])
+ x.append(xData)
+ y.append(yData)
+ except ValueError:
+ pass
-plt.ylabel('$\log T$')
-plt.xlabel('$\log \Sigma$')
-plt.grid()
-plt.show()
+ axline.set_xdata(x)
+ axline.set_ydata(y)
+
+ return axline,
+
+def init():
+ print('Initialisation')
+ plt.ylabel('$\log T$')
+ plt.xlabel('$\log \Sigma$')
+ plt.xlim(1.8, 4)
+ plt.ylim(6, 8)
+ plt.grid()
+
+if len(filenames) > 1:
+ ani = animation.FuncAnimation(fig, draw_once, filenames, init_func=init, interval=10)
+else:
+ init()
+ draw_once(filenames[0])
+ plt.show()
+# x, y = draw_once(filenames[2])
+# plt.plot(x, y, 'o')
+ |
c5ef0d8333bb427c588aa65ee6f081742c31c41e | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='snippets',
version='0.0.dev',
license='ISC',
description='Code snippets repository generator',
url='https://github.com/trilan/snippets',
author='Mike Yumatov',
author_email='[email protected]',
packages=find_packages(),
classifiers=[
'Development Status :: 1 - Planning',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
],
)
| from setuptools import setup, find_packages
setup(
name='snippets',
version='0.0.dev',
license='ISC',
description='Code snippets repository generator',
url='https://github.com/trilan/snippets',
author='Mike Yumatov',
author_email='[email protected]',
packages=find_packages(),
install_requires=[
'Pygments',
],
classifiers=[
'Development Status :: 1 - Planning',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
],
)
| Add Pygments as installation requirement | Add Pygments as installation requirement
| Python | isc | trilan/snippets,trilan/snippets | ---
+++
@@ -10,6 +10,9 @@
author='Mike Yumatov',
author_email='[email protected]',
packages=find_packages(),
+ install_requires=[
+ 'Pygments',
+ ],
classifiers=[
'Development Status :: 1 - Planning',
'Environment :: Console', |
56572fd9e38274074c8476f25dd47ee0799271ea | setup.py | setup.py | from distutils.core import setup
setup(name='pv_atmos',
version='1.1',
description='Utilities for scientific visualization with ParaView',
long_description='This package is described in a peer-reviewed open access article, which can be found at http://dx.doi.org/10.5334/jors.al'.
author='Martin Jucker',
url='https://github.com/mjucker/pv_atmos',
package_dir={'pv_atmos': ''},
packages=['pv_atmos'],
) | from distutils.core import setup
setup(name='pv_atmos',
version='1.1.1',
description='Utilities for scientific visualization with ParaView',
long_description='This package is described in a peer-reviewed open access article, which can be found at http://dx.doi.org/10.5334/jors.al'.
author='Martin Jucker',
url='https://github.com/mjucker/pv_atmos',
package_dir={'pv_atmos': ''},
packages=['pv_atmos'],
)
| Update to appropriate version number | Update to appropriate version number | Python | mit | mjucker/pv_atmos | ---
+++
@@ -1,6 +1,6 @@
from distutils.core import setup
setup(name='pv_atmos',
- version='1.1',
+ version='1.1.1',
description='Utilities for scientific visualization with ParaView',
long_description='This package is described in a peer-reviewed open access article, which can be found at http://dx.doi.org/10.5334/jors.al'.
author='Martin Jucker', |
e61b7b91157f0d198c90cb3652f6656bd6c44cba | setup.py | setup.py | """Setup script to generate an stand-alone executable.
Author-email: "Dietmar Winkler" <[email protected]>
License: See UNLICENSE file
Usage: Run the build process by running the command 'python setup.py build'
If everything works well you should find a subdirectory in the build
subdirectory that contains the files needed to run the script
without Python
"""
from setuptools import setup, find_packages
CLASSIFIERS = """
Environment :: Console
Intended Audience :: Developers
Operating System :: OS Independent
Programming Language :: Python :: 2
""".strip().splitlines()
META = {
'name': 'ttws',
'url': 'https://github.com/dietmarw/trimtrailingwhitespaces',
'version': '0.3',
'description': 'WSGI middleware to handle HTTP responses using exceptions',
'description': 'Script to remove trailing whitespaces from textfiles.',
'classifiers': CLASSIFIERS,
'license': 'UNLICENSE',
'author': 'Dietmar Winkler',
'author_email': 'http://claimid/dietmarw',
'packages': find_packages(exclude=['test']),
'entry_points': {
'console_scripts': 'ttws = ttws.cli:main'
},
'platforms': 'Posix; MacOS X; Windows',
'include_package_data': False,
'zip_safe': False,
'install_requires': ['pyparsing'],
'extras_require': {
'testing': ['pytest']
}
}
if __name__ == '__main__':
setup(**META)
| """Setup script to generate an stand-alone executable.
Author-email: "Dietmar Winkler" <[email protected]>
License: See UNLICENSE file
Usage: Run the build process by running the command 'python setup.py build'
If everything works well you should find a subdirectory in the build
subdirectory that contains the files needed to run the script
without Python
"""
from setuptools import setup, find_packages
CLASSIFIERS = """
Environment :: Console
Intended Audience :: Developers
Operating System :: OS Independent
Programming Language :: Python :: 2
""".strip().splitlines()
META = {
'name': 'ttws',
'url': 'https://github.com/dietmarw/trimtrailingwhitespaces',
'version': '0.3',
'description': 'Script to remove trailing whitespaces from textfiles.',
'classifiers': CLASSIFIERS,
'license': 'UNLICENSE',
'author': 'Dietmar Winkler',
'author_email': 'http://claimid/dietmarw',
'packages': find_packages(exclude=['test']),
'entry_points': {
'console_scripts': 'ttws = ttws.cli:main'
},
'platforms': 'Posix; MacOS X; Windows',
'include_package_data': False,
'zip_safe': False,
'install_requires': ['pyparsing'],
'extras_require': {
'testing': ['pytest']
}
}
if __name__ == '__main__':
setup(**META)
| Remove string from a copy and paste fail. | Remove string from a copy and paste fail.
| Python | unlicense | dietmarw/trimtrailingwhitespaces | ---
+++
@@ -25,7 +25,6 @@
'name': 'ttws',
'url': 'https://github.com/dietmarw/trimtrailingwhitespaces',
'version': '0.3',
- 'description': 'WSGI middleware to handle HTTP responses using exceptions',
'description': 'Script to remove trailing whitespaces from textfiles.',
'classifiers': CLASSIFIERS,
'license': 'UNLICENSE', |
7886e2a7b55ad03e125f7e69a78574c2044b518b | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup
setup(
name='py-vkontakte',
version='2016.8',
packages=['vk'],
url='https://github.com/sgaynetdinov/py-vkontakte',
license='MIT License',
author='Sergey Gaynetdinov',
author_email='[email protected]',
description='Python API wrapper around vk.com API',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2.7'
],
install_requires=[
'requests',
],
)
| #!/usr/bin/env python
from setuptools import setup
setup(
name='py-vkontakte',
version='2016.10',
packages=['vk'],
url='https://github.com/sgaynetdinov/py-vkontakte',
license='MIT License',
author='Sergey Gaynetdinov',
author_email='[email protected]',
description='Python API wrapper around vk.com API',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2.7'
],
install_requires=[
'requests',
],
)
| Change version `2016.8` => `2016.10` | Change version `2016.8` => `2016.10`
| Python | mit | sgaynetdinov/py-vkontakte | ---
+++
@@ -3,7 +3,7 @@
setup(
name='py-vkontakte',
- version='2016.8',
+ version='2016.10',
packages=['vk'],
url='https://github.com/sgaynetdinov/py-vkontakte',
license='MIT License', |
02d3f0f0b7c27f04289f8fd488973fdf17c8f42f | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import xml4h
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name=xml4h.__title__,
version=xml4h.__version__,
description='XML for Humans in Python',
long_description=open('README.rst').read(),
author='James Murty',
author_email='[email protected]',
url='https://github.com/jmurty/xml4h',
packages=[
'xml4h',
'xml4h.impls',
],
package_dir={'xml4h': 'xml4h'},
package_data={'': ['README.rst', 'LICENSE']},
include_package_data=True,
install_requires=[
'six',
],
license=open('LICENSE').read(),
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Text Processing :: Markup :: XML',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
# 'Programming Language :: Python :: 3.0',
# 'Programming Language :: Python :: 3.1',
# 'Programming Language :: Python :: 3.2',
],
test_suite='tests',
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import xml4h
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name=xml4h.__title__,
version=xml4h.__version__,
description='XML for Humans in Python',
long_description=open('README.rst').read(),
author='James Murty',
author_email='[email protected]',
url='https://github.com/jmurty/xml4h',
packages=[
'xml4h',
'xml4h.impls',
],
package_dir={'xml4h': 'xml4h'},
package_data={'': ['README.rst', 'LICENSE']},
include_package_data=True,
install_requires=[
'six',
],
license=open('LICENSE').read(),
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Text Processing :: Markup :: XML',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
test_suite='tests',
)
| Update Python version classifiers to supported versions | Update Python version classifiers to supported versions
| Python | mit | jmurty/xml4h | ---
+++
@@ -36,9 +36,9 @@
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
- # 'Programming Language :: Python :: 3.0',
- # 'Programming Language :: Python :: 3.1',
- # 'Programming Language :: Python :: 3.2',
+ 'Programming Language :: Python :: 3.6',
+ 'Programming Language :: Python :: 3.7',
+ 'Programming Language :: Python :: 3.8',
],
test_suite='tests',
) |
cb965a2dc227c9c498a8c95f48bb5ce24a6db66c | setup.py | setup.py | from distutils.core import setup
desc = (
'An interface to the Pluggable Authentication Modules (PAM) library'
'on linux, written in pure python (using ctypes)'
)
setup(name='python3-simplepam', version='0.1.4',
description=desc,
py_modules=['simplepam'],
author='Leon Weber <[email protected]>, Chris AtLee <[email protected]>',
author_email='[email protected]',
url='https://github.com/leonnnn/python3-simplepam',
license='MIT'
)
| from distutils.core import setup
desc = (
'An interface to the Pluggable Authentication Modules (PAM) library '
'on linux, written in pure python (using ctypes)'
)
setup(name='python3-simplepam', version='0.1.4',
description=desc,
py_modules=['simplepam'],
author='Leon Weber <[email protected]>, Chris AtLee <[email protected]>',
author_email='[email protected]',
url='https://github.com/leonnnn/python3-simplepam',
license='MIT'
)
| Add missing space in description | Add missing space in description
| Python | mit | leonnnn/python3-simplepam | ---
+++
@@ -1,7 +1,7 @@
from distutils.core import setup
desc = (
- 'An interface to the Pluggable Authentication Modules (PAM) library'
+ 'An interface to the Pluggable Authentication Modules (PAM) library '
'on linux, written in pure python (using ctypes)'
)
|
38d30c5589dfbdae92198a404d58400ec3c2ed4b | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name="echidna",
version="0.0.1-dev",
url='http://github.com/praekelt/echidna',
license='BSD',
description='A scalable pub-sub WebSocket service.',
long_description=open('README.rst', 'r').read(),
author='Praekelt Foundation',
author_email='[email protected]',
packages=find_packages(),
install_requires=[
'Twisted',
'cyclone',
'txzookeeper',
'redis',
'zope.dottedname',
],
tests_require=[
'ws4py',
'requests',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Cyclone',
'Framework :: Twisted',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Communications',
'Topic :: Internet',
'Topic :: System :: Networking',
]
)
| from setuptools import setup, find_packages
setup(
name="echidna",
version="0.0.1-dev",
url='http://github.com/praekelt/echidna',
license='BSD',
description='A scalable pub-sub WebSocket service.',
long_description=open('README.rst', 'r').read(),
author='Praekelt Foundation',
author_email='[email protected]',
packages=find_packages(),
install_requires=[
'Twisted',
'cyclone',
'txzookeeper',
'redis',
'zope.dottedname',
'ws4py',
],
tests_require=[
'ws4py',
'requests',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Cyclone',
'Framework :: Twisted',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Communications',
'Topic :: Internet',
'Topic :: System :: Networking',
]
)
| Add ws4py to normal requirements in an attempt to get Travis to install it | Add ws4py to normal requirements in an attempt to get Travis to install it
| Python | bsd-3-clause | praekelt/echidna,praekelt/echidna,praekelt/echidna,praekelt/echidna | ---
+++
@@ -17,6 +17,7 @@
'txzookeeper',
'redis',
'zope.dottedname',
+ 'ws4py',
],
tests_require=[
'ws4py', |
4a810640a3ccdaaa975b9d1b807ff7365282e5b9 | django_website/settings/docs.py | django_website/settings/docs.py | from django_website.settings.www import *
PREPEND_WWW = False
APPEND_SLASH = True
INSTALLED_APPS = ['django_website.docs']
TEMPLATE_CONTEXT_PROCESSORS += ["django.core.context_processors.request"]
ROOT_URLCONF = 'django_website.urls.docs'
CACHE_MIDDLEWARE_KEY_PREFIX = 'djangodocs'
# Where to store the build Sphinx docs.
if PRODUCTION:
DOCS_BUILD_ROOT = BASE.parent.child('docbuilds')
else:
DOCS_BUILD_ROOT = '/tmp/djangodocs'
| from django_website.settings.www import *
PREPEND_WWW = False
APPEND_SLASH = True
INSTALLED_APPS = ['django_website.docs']
TEMPLATE_CONTEXT_PROCESSORS += ["django.core.context_processors.request"]
ROOT_URLCONF = 'django_website.urls.docs'
CACHE_MIDDLEWARE_KEY_PREFIX = 'djangodocs'
# Where to store the build Sphinx docs.
if PRODUCTION:
DOCS_BUILD_ROOT = BASE.ancestor(2).child('docbuilds')
else:
DOCS_BUILD_ROOT = '/tmp/djangodocs'
| Fix the docbuilds path location. | Fix the docbuilds path location.
| Python | bsd-3-clause | relekang/djangoproject.com,gnarf/djangoproject.com,relekang/djangoproject.com,django/djangoproject.com,django/djangoproject.com,khkaminska/djangoproject.com,nanuxbe/django,khkaminska/djangoproject.com,nanuxbe/django,vxvinh1511/djangoproject.com,django/djangoproject.com,django/djangoproject.com,vxvinh1511/djangoproject.com,rmoorman/djangoproject.com,nanuxbe/django,django/djangoproject.com,khkaminska/djangoproject.com,django/djangoproject.com,hassanabidpk/djangoproject.com,hassanabidpk/djangoproject.com,khkaminska/djangoproject.com,rmoorman/djangoproject.com,xavierdutreilh/djangoproject.com,alawnchen/djangoproject.com,vxvinh1511/djangoproject.com,xavierdutreilh/djangoproject.com,alawnchen/djangoproject.com,rmoorman/djangoproject.com,alawnchen/djangoproject.com,hassanabidpk/djangoproject.com,gnarf/djangoproject.com,alawnchen/djangoproject.com,relekang/djangoproject.com,relekang/djangoproject.com,nanuxbe/django,hassanabidpk/djangoproject.com,vxvinh1511/djangoproject.com,rmoorman/djangoproject.com,xavierdutreilh/djangoproject.com,gnarf/djangoproject.com,gnarf/djangoproject.com,xavierdutreilh/djangoproject.com | ---
+++
@@ -9,6 +9,6 @@
# Where to store the build Sphinx docs.
if PRODUCTION:
- DOCS_BUILD_ROOT = BASE.parent.child('docbuilds')
+ DOCS_BUILD_ROOT = BASE.ancestor(2).child('docbuilds')
else:
DOCS_BUILD_ROOT = '/tmp/djangodocs' |
f39c6ff64478f4b20f5eaa26ec060275cdc81813 | setup.py | setup.py | from setuptools import setup, find_packages
import codecs
import os
import re
root_dir = os.path.abspath(os.path.dirname(__file__))
PACKAGE = 'hackernews_scraper'
def get_version(package_name):
version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$")
package_components = package_name.split('.')
init_path = os.path.join(root_dir, *(package_components + ['__init__.py']))
with codecs.open(init_path, 'r', 'utf-8') as f:
for line in f:
match = version_re.match(line[:-1])
if match:
return match.groups()[0]
return '0.1.0'
setup(name=PACKAGE
description='Python library for retrieving comments and stories from HackerNews',
packages=find_packages(),
version=get_version(PACKAGE),
install_requires=['requests'],
url='https://github.com/NiGhTTraX/hackernews-scraper',
license='MIT',
platforms='any',
tests_require=['nose', 'factory_boy', 'httpretty'],
)
| from setuptools import setup, find_packages
import codecs
import os
import re
root_dir = os.path.abspath(os.path.dirname(__file__))
PACKAGE = 'hackernews_scraper'
def get_version(package_name):
version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$")
package_components = package_name.split('.')
init_path = os.path.join(root_dir, *(package_components + ['__init__.py']))
with codecs.open(init_path, 'r', 'utf-8') as f:
for line in f:
match = version_re.match(line[:-1])
if match:
return match.groups()[0]
raise Exception("No package version found!")
setup(name=PACKAGE
description='Python library for retrieving comments and stories from HackerNews',
packages=find_packages(),
version=get_version(PACKAGE),
install_requires=['requests'],
url='https://github.com/NiGhTTraX/hackernews-scraper',
license='MIT',
platforms='any',
tests_require=['nose', 'factory_boy', 'httpretty'],
)
| Raise exception if version does not exist | Raise exception if version does not exist
| Python | bsd-2-clause | NiGhTTraX/hackernews-scraper | ---
+++
@@ -16,7 +16,7 @@
match = version_re.match(line[:-1])
if match:
return match.groups()[0]
- return '0.1.0'
+ raise Exception("No package version found!")
setup(name=PACKAGE
description='Python library for retrieving comments and stories from HackerNews', |
a0e795cb0bed84ae6161f5e64290910f2ffe8ee6 | setup.py | setup.py | #!/usr/bin/env python
import collections
from setuptools import setup
from pip.req import parse_requirements
dependency_links = []
install_requires = []
ReqOpts = collections.namedtuple('ReqOpts', ['skip_requirements_regex', 'default_vcs'])
opts = ReqOpts(None, 'git')
for ir in parse_requirements("requirements.txt", options=opts):
if ir is not None:
if ir.url is not None:
dependency_links.append(str(ir.url))
if ir.req is not None:
install_requires.append(str(ir.req))
setup(
name='vertica-python',
version='0.1',
description='A native Python client for the Vertica database.',
author='Justin Berka',
author_email='[email protected]',
url='https://github.com/uber/vertica-python/',
keywords="database vertica",
packages=['vertica_python'],
license="MIT",
install_requires=install_requires,
dependency_links=dependency_links,
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Database",
"Topic :: Database :: Database Engines/Servers",
"Operating System :: OS Independent"
]
)
| #!/usr/bin/env python
import collections
from setuptools import setup
from pip.req import parse_requirements
dependency_links = []
install_requires = []
ReqOpts = collections.namedtuple('ReqOpts', ['skip_requirements_regex', 'default_vcs'])
opts = ReqOpts(None, 'git')
for ir in parse_requirements("requirements.txt", options=opts):
if ir is not None:
if ir.url is not None:
dependency_links.append(str(ir.url))
if ir.req is not None:
install_requires.append(str(ir.req))
setup(
name='vertica-python',
version='0.1',
description='A native Python client for the Vertica database.',
author='Justin Berka',
author_email='[email protected]',
url='https://github.com/uber/vertica-python/',
keywords="database vertica",
packages=['vertica_python'],
package_data={
'': ['*.txt', '*.md'],
},
license="MIT",
install_requires=install_requires,
dependency_links=dependency_links,
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Database",
"Topic :: Database :: Database Engines/Servers",
"Operating System :: OS Independent"
]
)
| Add .md and .txt files to package | Add .md and .txt files to package
| Python | apache-2.0 | uber/vertica-python,twneale/vertica-python,brokendata/vertica-python,natthew/vertica-python,dennisobrien/vertica-python | ---
+++
@@ -27,6 +27,9 @@
url='https://github.com/uber/vertica-python/',
keywords="database vertica",
packages=['vertica_python'],
+ package_data={
+ '': ['*.txt', '*.md'],
+ },
license="MIT",
install_requires=install_requires,
dependency_links=dependency_links, |
c3bb736962d77d1fdd0207ba2ee487c1177451c7 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
with open('README.rst') as file:
long_description = file.read()
classifiers = [
'Programming Language :: Python :: 3',
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved',
'Intended Audience :: Developers',
'Natural Language :: French',
'Operating System :: OS Independent',
'Topic :: Utilities',
]
setup(name='PyEventEmitter',
version='1.0.2',
description='Simple python events library',
long_description=long_description,
author='Etienne Tissieres',
author_email='[email protected]',
url='https://github.com/etissieres/PyEventEmitter',
packages=['event_emitter'],
license='MIT',
classifiers=classifiers)
| #!/usr/bin/env python
from distutils.core import setup
with open('README.rst') as file:
long_description = file.read()
classifiers = [
'Programming Language :: Python :: 3',
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved',
'Intended Audience :: Developers',
'Natural Language :: French',
'Operating System :: OS Independent',
'Topic :: Utilities',
]
setup(name='PyEventEmitter',
version='1.0.3',
description='Simple python events library',
long_description=long_description,
author='Etienne Tissieres',
author_email='[email protected]',
url='https://github.com/etissieres/PyEventEmitter',
packages=['event_emitter'],
license='MIT',
classifiers=classifiers)
| Upgrade version to publish a release without tests | Upgrade version to publish a release without tests
| Python | mit | etissieres/PyEventEmitter | ---
+++
@@ -16,7 +16,7 @@
]
setup(name='PyEventEmitter',
- version='1.0.2',
+ version='1.0.3',
description='Simple python events library',
long_description=long_description,
author='Etienne Tissieres', |
1372c00a0668cc6a39953264d23f012391afe768 | python/helpers/pycharm/_jb_unittest_runner.py | python/helpers/pycharm/_jb_unittest_runner.py | # coding=utf-8
import os
from unittest import main
from _jb_runner_tools import jb_start_tests, jb_doc_args
from teamcity import unittestpy
if __name__ == '__main__':
path, targets, additional_args = jb_start_tests()
args = ["python -m unittest"]
if path:
discovery_args = ["discover", "-s"]
# Unittest does not support script directly, but it can use "discover" to find all tests in some folder
# filtering by script
assert os.path.exists(path), "{0}: No such file or directory".format(path)
if os.path.isfile(path):
discovery_args += [os.path.dirname(path), "-p", os.path.basename(path)]
else:
discovery_args.append(path)
additional_args = discovery_args + additional_args
else:
additional_args += targets
args += additional_args
jb_doc_args("unittests", args)
main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner())
| # coding=utf-8
import os
from unittest import main
from _jb_runner_tools import jb_start_tests, jb_doc_args
from teamcity import unittestpy
if __name__ == '__main__':
path, targets, additional_args = jb_start_tests()
args = ["python -m unittest"]
if path:
discovery_args = ["discover", "-s"]
# Unittest does not support script directly, but it can use "discover" to find all tests in some folder
# filtering by script
assert os.path.exists(path), "{0}: No such file or directory".format(path)
if os.path.isfile(path):
discovery_args += [os.path.dirname(path), "-p", os.path.basename(path)]
else:
discovery_args.append(path)
additional_args = discovery_args + additional_args
elif targets:
additional_args += targets
args += additional_args
jb_doc_args("unittests", args)
main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner())
| Check variable before accessing it | PY-22460: Check variable before accessing it
| Python | apache-2.0 | mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,signed/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,signed/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,FHannes/intellij-community,da1z/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,allotria/intellij-community,allotria/intellij-community,signed/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,signed/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,allotria/intellij-community,ibinti/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,semonte/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,signed/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,apixandru/intellij-community,apixandru/intellij-community,semonte/intellij-community,signed/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,semonte/intellij-community,asedunov/intellij-community,signed/intellij-community,ibinti/intellij-community,xfournet/intellij-community,da1z/intellij-community,vvv1559/intellij-community,semonte/intellij-community,da1z/intellij-community,semonte/intellij-community,ibinti/intellij-community,FHannes/intellij-community,FHannes/intellij-community,signed/intellij-community,ibinti/intellij-community,ibinti/intellij-community,da1z/intellij-community,allotria/intellij-community,apixandru/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,FHannes/intellij-community,da1z/intellij-community,da1z/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,xfournet/intellij-community,xfournet/intellij-community,asedunov/intellij-community,semonte/intellij-community,FHannes/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,signed/intellij-community,vvv1559/intellij-community,allotria/intellij-community,asedunov/intellij-community,apixandru/intellij-community,signed/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,semonte/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,da1z/intellij-community,allotria/intellij-community,da1z/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,da1z/intellij-community,asedunov/intellij-community,FHannes/intellij-community,FHannes/intellij-community,xfournet/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,allotria/intellij-community,signed/intellij-community,vvv1559/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,FHannes/intellij-community,semonte/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,FHannes/intellij-community,semonte/intellij-community,da1z/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community | ---
+++
@@ -19,7 +19,7 @@
else:
discovery_args.append(path)
additional_args = discovery_args + additional_args
- else:
+ elif targets:
additional_args += targets
args += additional_args
jb_doc_args("unittests", args) |
d486505f270125a4b5c7f460f4f39a9c1eab9a1f | setup.py | setup.py | from setuptools import setup
setup(
name='tephi',
version='0.2.0-alpha',
url='https://github.com/SciTools/tephi',
author='Bill Little',
author_email='[email protected]',
packages=['tephi', 'tephi.tests'],
package_dir={'': 'lib'},
package_data={'tephi': ['etc/test_data/*.txt'] + ['etc/test_results/*.pkl']},
classifiers=['License :: OSI Approved :: '
'GNU Lesser General Public License v3 (LGPLv3)'],
description='Tephigram plotting in Python',
long_description=open('README.rst').read(),
test_suite='tephi.tests',
)
| from setuptools import setup
setup(
name='tephi',
version='0.2.0-alpha',
url='https://github.com/SciTools/tephi',
author='Bill Little',
author_email='[email protected]',
packages=['tephi', 'tephi.tests'],
package_dir={'': 'lib'},
package_data={'tephi': ['etc/test_data/*.txt'] + ['etc/test_results/*.pkl']},
classifiers=['License :: OSI Approved :: '
'GNU Lesser General Public License v3 (LGPLv3)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',],
description='Tephigram plotting in Python',
long_description=open('README.rst').read(),
test_suite='tephi.tests',
)
| Add Python 2 and 3 PyPI classifiers. | Add Python 2 and 3 PyPI classifiers.
| Python | bsd-3-clause | SciTools/tephi | ---
+++
@@ -11,7 +11,13 @@
package_dir={'': 'lib'},
package_data={'tephi': ['etc/test_data/*.txt'] + ['etc/test_results/*.pkl']},
classifiers=['License :: OSI Approved :: '
- 'GNU Lesser General Public License v3 (LGPLv3)'],
+ 'GNU Lesser General Public License v3 (LGPLv3)',
+ 'Programming Language :: Python',
+ 'Programming Language :: Python :: 2',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.3',
+ 'Programming Language :: Python :: 3.4',],
description='Tephigram plotting in Python',
long_description=open('README.rst').read(),
test_suite='tephi.tests', |
3053219149f7dac7ab073fc24488116b1b280b77 | money_rounding.py | money_rounding.py | def get_price_without_vat(price_to_show, vat_percent):
raise NotImplementedError()
def get_price_without_vat_from_other_valuta(conversion_rate, origin_price,
origin_vat, other_vat):
raise NotImplementedError()
| def show_pretty_price(value):
raise NotImplementedError()
| Use function described in readme | Use function described in readme | Python | mit | coolshop-com/coolshop-application-assignment | ---
+++
@@ -1,7 +1,2 @@
-def get_price_without_vat(price_to_show, vat_percent):
+def show_pretty_price(value):
raise NotImplementedError()
-
-
-def get_price_without_vat_from_other_valuta(conversion_rate, origin_price,
- origin_vat, other_vat):
- raise NotImplementedError() |
ea7200bc9774f69562b37f177ad18ca606998dfa | perfrunner/utils/debug.py | perfrunner/utils/debug.py | import glob
import shutil
from optparse import OptionParser
from perfrunner.helpers.remote import RemoteHelper
from perfrunner.settings import ClusterSpec
def get_options():
usage = '%prog -c cluster'
parser = OptionParser(usage)
parser.add_option('-c', dest='cluster_spec_fname',
help='path to the cluster specification file',
metavar='cluster.spec')
options, args = parser.parse_args()
if not options.cluster_spec_fname:
parser.error('Please specify a cluster specification')
return options, args
def main():
options, args = get_options()
cluster_spec = ClusterSpec()
cluster_spec.parse(options.cluster_spec_fname, args)
remote = RemoteHelper(cluster_spec, test_config=None, verbose=False)
remote.collect_info()
for hostname in cluster_spec.yield_hostnames():
for fname in glob.glob('{}/*.zip'.format(hostname)):
shutil.move(fname, '{}.zip'.format(hostname))
if __name__ == '__main__':
main()
| import glob
import os.path
import shutil
from optparse import OptionParser
from perfrunner.helpers.remote import RemoteHelper
from perfrunner.settings import ClusterSpec
def get_options():
usage = '%prog -c cluster'
parser = OptionParser(usage)
parser.add_option('-c', dest='cluster_spec_fname',
help='path to the cluster specification file',
metavar='cluster.spec')
options, args = parser.parse_args()
if not options.cluster_spec_fname:
parser.error('Please specify a cluster specification')
return options, args
def main():
options, args = get_options()
cluster_spec = ClusterSpec()
cluster_spec.parse(options.cluster_spec_fname, args)
remote = RemoteHelper(cluster_spec, test_config=None, verbose=False)
remote.collect_info()
for hostname in cluster_spec.yield_hostnames():
for fname in glob.glob('{}/*.zip'.format(hostname)):
shutil.move(fname, '{}.zip'.format(hostname))
if cluster_spec.backup is not None:
logs = os.path.join(cluster_spec.backup, 'logs')
if os.path.exists(logs):
shutil.make_archive('tools', 'zip', logs)
if __name__ == '__main__':
main()
| Archive logs from the tools | Archive logs from the tools
Change-Id: I184473d20cc2763fbc97c993bfcab36b80d1c864
Reviewed-on: http://review.couchbase.org/76571
Tested-by: Build Bot <[email protected]>
Reviewed-by: Pavel Paulau <[email protected]>
| Python | apache-2.0 | couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner | ---
+++
@@ -1,4 +1,5 @@
import glob
+import os.path
import shutil
from optparse import OptionParser
@@ -35,6 +36,11 @@
for fname in glob.glob('{}/*.zip'.format(hostname)):
shutil.move(fname, '{}.zip'.format(hostname))
+ if cluster_spec.backup is not None:
+ logs = os.path.join(cluster_spec.backup, 'logs')
+ if os.path.exists(logs):
+ shutil.make_archive('tools', 'zip', logs)
+
if __name__ == '__main__':
main() |
22e82e3fb6949efe862216feafaedb2da9b19c62 | filehandler.py | filehandler.py | import csv
import sys
import urllib
from scheduleitem import ScheduleItem
from team import Team
def read(uri):
"""Open a File or a Web URL"""
if uri.startswith('http://') or uri.startswith('https://'):
return open_url(uri)
else:
return open_file(uri)
def open_url(url):
"""Return the games file data as an array"""
try:
with urllib.request.urlopen(url) as response:
return response.read()
except urllib.HTTPError as e:
msg = "Could Not Open URL {}.\nThe Code is: {} "
print(msg.format(url, e.code))
sys.exit(1)
except urllib.URLError as e:
msg = "Could Not Open URL {}.\nThe Reason is: {} "
print(msg.format(url.url, e.reason))
sys.exit(1)
def open_file(uri):
"""Return the games file data as an array"""
try:
with open(uri, 'r') as f:
return f.read()
except IOError:
msg = "Could not open file: `{}`"
print(msg.format(uri))
sys.exit(1)
def load_schedules(games_file):
with open(games_file, 'r') as f:
return [ScheduleItem.from_str(line) for line in f.readlines()]
def load_teams_data(data_file):
with open(data_file, 'r') as csv_file:
reader = csv.reader(csv_file)
# Skip the header row
next(reader)
return [Team(row[0], row[2], row[3]) for row in reader]
| import csv
import sys
import urllib.error
import urllib.request
from scheduleitem import ScheduleItem
from team import Team
def read(uri):
"""Open a File or a Web URL"""
if uri.startswith('http://') or uri.startswith('https://'):
return open_url(uri)
else:
return open_local_file(uri)
def open_url(url):
"""Return the game file data."""
with urllib.request.urlopen(url) as response:
if response.status != 200:
msg = 'Status {}. Could Not Open URL {}. Reason: {}'
raise urllib.error.HTTPError(
msg.format(response.status, url, response.msg)
)
encoding = sys.getdefaultencoding()
return [line.decode(encoding) for line in response.readlines()]
def open_local_file(uri):
"""Return the games file data as an array"""
with open(uri, 'r') as f:
return f.readlines()
def load_schedules(uri):
data = read(uri)
return [ScheduleItem.from_str(line) for line in data]
def load_teams_data(data_file):
with open(data_file, 'r') as csv_file:
reader = csv.reader(csv_file)
next(reader) # Skip the header row
return [Team(row[0], row[2], row[3]) for row in reader]
| Update file handlers to use Python3 urllib | Update file handlers to use Python3 urllib
| Python | mit | brianjbuck/robie | ---
+++
@@ -1,6 +1,8 @@
import csv
import sys
-import urllib
+import urllib.error
+import urllib.request
+
from scheduleitem import ScheduleItem
from team import Team
@@ -11,43 +13,34 @@
if uri.startswith('http://') or uri.startswith('https://'):
return open_url(uri)
else:
- return open_file(uri)
+ return open_local_file(uri)
def open_url(url):
- """Return the games file data as an array"""
- try:
- with urllib.request.urlopen(url) as response:
- return response.read()
- except urllib.HTTPError as e:
- msg = "Could Not Open URL {}.\nThe Code is: {} "
- print(msg.format(url, e.code))
- sys.exit(1)
- except urllib.URLError as e:
- msg = "Could Not Open URL {}.\nThe Reason is: {} "
- print(msg.format(url.url, e.reason))
- sys.exit(1)
+ """Return the game file data."""
+ with urllib.request.urlopen(url) as response:
+ if response.status != 200:
+ msg = 'Status {}. Could Not Open URL {}. Reason: {}'
+ raise urllib.error.HTTPError(
+ msg.format(response.status, url, response.msg)
+ )
+ encoding = sys.getdefaultencoding()
+ return [line.decode(encoding) for line in response.readlines()]
-def open_file(uri):
+def open_local_file(uri):
"""Return the games file data as an array"""
- try:
- with open(uri, 'r') as f:
- return f.read()
- except IOError:
- msg = "Could not open file: `{}`"
- print(msg.format(uri))
- sys.exit(1)
+ with open(uri, 'r') as f:
+ return f.readlines()
-def load_schedules(games_file):
- with open(games_file, 'r') as f:
- return [ScheduleItem.from_str(line) for line in f.readlines()]
+def load_schedules(uri):
+ data = read(uri)
+ return [ScheduleItem.from_str(line) for line in data]
def load_teams_data(data_file):
with open(data_file, 'r') as csv_file:
reader = csv.reader(csv_file)
- # Skip the header row
- next(reader)
+ next(reader) # Skip the header row
return [Team(row[0], row[2], row[3]) for row in reader] |
650682c3643912c53e643d7b1074f1a6c4a1556b | setup.py | setup.py | from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='django-cra-helper',
version='1.0.2',
description='The missing piece of the Django + React puzzle',
long_description=long_description,
long_description_content_type="text/markdown",
url='https://github.com/MasterKale/django-cra-helper',
author='Matthew Miller',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
],
keywords='django react create-react-app integrate',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
install_requires=[
'bleach>=2'
],
)
| from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='django-cra-helper',
version='1.1.0',
description='The missing piece of the Django + React puzzle',
long_description=long_description,
long_description_content_type="text/markdown",
url='https://github.com/MasterKale/django-cra-helper',
author='Matthew Miller',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
],
keywords='django react create-react-app integrate',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
install_requires=[
'bleach>=2'
],
)
| Update package version to v1.1.0 | Update package version to v1.1.0
| Python | mit | MasterKale/django-cra-helper | ---
+++
@@ -10,7 +10,7 @@
setup(
name='django-cra-helper',
- version='1.0.2',
+ version='1.1.0',
description='The missing piece of the Django + React puzzle',
long_description=long_description,
long_description_content_type="text/markdown", |
c1dcdb3c8856fbfd449524f66f5fc819eb1a19bc | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
'SQLAlchemy',
'python-dateutil',
'python-magic',
'elasticsearch',
]
test_requirements = [
'coverage',
]
setup(
name='esis',
version='0.1.0',
description="Elastic Search Index & Search",
long_description=readme + '\n\n' + history,
author="Javier Collado",
author_email='[email protected]',
url='https://github.com/jcollado/esis',
packages=[
'esis',
],
package_dir={'esis':
'esis'},
include_package_data=True,
install_requires=requirements,
license="MIT",
zip_safe=False,
keywords='elastic search index sqlite',
entry_points={
'console_scripts': [
'esis = esis.cli:main',
]
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
],
test_suite='tests',
tests_require=test_requirements
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
'SQLAlchemy',
'python-dateutil',
'python-magic',
'elasticsearch',
]
test_requirements = [
'coverage',
]
setup(
name='esis',
version='0.1.0',
description="Elastic Search Index & Search",
long_description=readme + '\n\n' + history,
author="Javier Collado",
author_email='[email protected]',
url='https://github.com/jcollado/esis',
packages=[
'esis',
],
package_dir={'esis':
'esis'},
include_package_data=True,
install_requires=requirements,
license="MIT",
zip_safe=False,
keywords='elastic search index sqlite',
entry_points={
'console_scripts': [
'esis = esis.cli:main',
]
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
],
test_suite='tests',
tests_require=test_requirements
)
| Move development status to alpha | Move development status to alpha
| Python | mit | jcollado/esis | ---
+++
@@ -49,7 +49,7 @@
]
},
classifiers=[
- 'Development Status :: 2 - Pre-Alpha',
+ 'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English', |
7b4b2fcbcb9a95c07f09b71305afa0c5ce95fe99 | tenant_schemas/routers.py | tenant_schemas/routers.py | from django.conf import settings
class TenantSyncRouter(object):
"""
A router to control which applications will be synced,
depending if we are syncing the shared apps or the tenant apps.
"""
def allow_syncdb(self, db, model):
# the imports below need to be done here else django <1.5 goes crazy
# https://code.djangoproject.com/ticket/20704
from django.db import connection
from tenant_schemas.utils import get_public_schema_name, app_labels
if connection.schema_name == get_public_schema_name():
if model._meta.app_label not in app_labels(settings.SHARED_APPS):
return False
else:
if model._meta.app_label not in app_labels(settings.TENANT_APPS):
return False
return None
| from django.conf import settings
class TenantSyncRouter(object):
"""
A router to control which applications will be synced,
depending if we are syncing the shared apps or the tenant apps.
"""
def allow_migrate(self, db, model):
# the imports below need to be done here else django <1.5 goes crazy
# https://code.djangoproject.com/ticket/20704
from django.db import connection
from tenant_schemas.utils import get_public_schema_name, app_labels
if connection.schema_name == get_public_schema_name():
if model._meta.app_label not in app_labels(settings.SHARED_APPS):
return False
else:
if model._meta.app_label not in app_labels(settings.TENANT_APPS):
return False
return None
def allow_syncdb(self, db, model):
# allow_syncdb was changed to allow_migrate in django 1.7
return self.allow_migrate(db, model)
| Add database router allow_migrate() for Django 1.7 | Add database router allow_migrate() for Django 1.7
| Python | mit | goodtune/django-tenant-schemas,Mobytes/django-tenant-schemas,kajarenc/django-tenant-schemas,honur/django-tenant-schemas,mcanaves/django-tenant-schemas,ArtProcessors/django-tenant-schemas,goodtune/django-tenant-schemas,ArtProcessors/django-tenant-schemas,bernardopires/django-tenant-schemas,bernardopires/django-tenant-schemas,pombredanne/django-tenant-schemas | ---
+++
@@ -7,7 +7,7 @@
depending if we are syncing the shared apps or the tenant apps.
"""
- def allow_syncdb(self, db, model):
+ def allow_migrate(self, db, model):
# the imports below need to be done here else django <1.5 goes crazy
# https://code.djangoproject.com/ticket/20704
from django.db import connection
@@ -21,3 +21,7 @@
return False
return None
+
+ def allow_syncdb(self, db, model):
+ # allow_syncdb was changed to allow_migrate in django 1.7
+ return self.allow_migrate(db, model) |
1c11d8e2169a90efcd16340c46114cf978e2343f | setup.py | setup.py | #!/usr/bin/env python
import sys
try:
from setuptools import setup, Extension
except ImportError:
from distutils.core import setup, Extension
uinput = Extension('libuinput',
sources = ['src/uinput.c'])
deps = ['libusb1', 'psutil']
if sys.version_info < (3,4):
deps.append('enum34')
setup(name='python-steamcontroller',
version='1.1',
description='Steam Controller userland driver',
author='Stany MARCEL',
author_email='[email protected]',
url='https://github.com/ynsta/steamcontroller',
package_dir={'steamcontroller': 'src'},
packages=['steamcontroller'],
scripts=['scripts/sc-dump.py',
'scripts/sc-xbox.py',
'scripts/sc-desktop.py',
'scripts/sc-test-cmsg.py',
'scripts/sc-gyro-plot.py',
'scripts/vdf2json.py',
'scripts/json2vdf.py'],
license='MIT',
platforms=['Linux'],
install_requires=deps,
ext_modules=[uinput, ])
| #!/usr/bin/env python
import sys
try:
from setuptools import setup, Extension
except ImportError:
from distutils.core import setup, Extension
uinput = Extension('libuinput',
sources = ['src/uinput.c'])
deps = ['libusb1', 'psutil']
if sys.version_info < (3,4):
deps.append('enum34')
setup(name='python-steamcontroller',
version='1.1',
description='Steam Controller userland driver',
author='Stany MARCEL',
author_email='[email protected]',
url='https://github.com/ynsta/steamcontroller',
package_dir={'steamcontroller': 'src'},
packages=['steamcontroller'],
scripts=['scripts/sc-dump.py',
'scripts/sc-xbox.py',
'scripts/sc-desktop.py',
'scripts/sc-mixed.py',
'scripts/sc-test-cmsg.py',
'scripts/sc-gyro-plot.py',
'scripts/vdf2json.py',
'scripts/json2vdf.py'],
license='MIT',
platforms=['Linux'],
install_requires=deps,
ext_modules=[uinput, ])
| Add sc-mixed.py in installed scripts | Add sc-mixed.py in installed scripts
Signed-off-by: Stany MARCEL <[email protected]>
| Python | mit | ynsta/steamcontroller,ynsta/steamcontroller | ---
+++
@@ -24,6 +24,7 @@
scripts=['scripts/sc-dump.py',
'scripts/sc-xbox.py',
'scripts/sc-desktop.py',
+ 'scripts/sc-mixed.py',
'scripts/sc-test-cmsg.py',
'scripts/sc-gyro-plot.py',
'scripts/vdf2json.py', |
b3acf639f310019d042bbe24e653a6f79c240858 | setup.py | setup.py | from distutils.core import Extension, setup
from Cython.Build import cythonize
try:
from Cython.Distutils import build_ext
except ImportError:
use_cython = False
else:
use_cython = True
if use_cython:
extensions = [
Extension('mathix.vector', ['mathix/vector.pyx']),
]
cmdclass = {
'build_ext': build_ext
}
else:
extensions = [
Extension('mathix.vector', ['mathix/vector.c']),
]
cmdclass = {}
setup(
name='mathix',
author='Peith Vergil',
version='0.1',
cmdclass=cmdclass,
packages=[
'mathix',
],
keywords='useless simple math library',
description='A useless simple math library.',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Cython',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
ext_modules=cythonize(extensions)
)
| from distutils.core import Extension, setup
try:
from Cython.Distutils import build_ext
except ImportError:
use_cython = False
else:
use_cython = True
if use_cython:
extensions = [
Extension('mathix.vector', ['mathix/vector.pyx']),
]
cmdclass = {
'build_ext': build_ext
}
else:
extensions = [
Extension('mathix.vector', ['mathix/vector.c']),
]
cmdclass = {}
setup(
name='mathix',
author='Peith Vergil',
version='0.1',
cmdclass=cmdclass,
packages=[
'mathix',
],
keywords='useless simple math library',
description='A useless simple math library.',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Cython',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
ext_modules=extensions
)
| Remove the importing of the "cythonize" function. | Remove the importing of the "cythonize" function.
| Python | mit | PeithVergil/cython-example | ---
+++
@@ -1,6 +1,4 @@
from distutils.core import Extension, setup
-
-from Cython.Build import cythonize
try:
from Cython.Distutils import build_ext
@@ -53,5 +51,5 @@
'Programming Language :: Python :: 3.5',
],
- ext_modules=cythonize(extensions)
+ ext_modules=extensions
) |
f8cbb96f2d5040d060799f62b642e8bb80060d07 | setup.py | setup.py | #!/usr/bin/env python
#coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()
from aero.__version__ import __version__, __title__, __authors__, __email__, __license__, __url__, __download_url__
from setuptools import setup
setup(
name = __title__,
author = __authors__,
author_email = __email__,
version = __version__,
license = __license__,
url = __url__,
download_url = __download_url__,
packages = ['aero', 'aero.adapters'],
package_data ={'aero': ['assets/*.ascii']},
description = [descr for descr in open('README.txt').read().splitlines() if descr.strip() and '===' not in descr][1],
long_description=open('README.txt').read(),
scripts = ["aero/aero"],
)
| #!/usr/bin/env python
#coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()
from aero.__version__ import __version__, __title__, __authors__, __email__, __license__, __url__, __download_url__
from setuptools import setup
setup(
name = __title__,
author = __authors__,
author_email = __email__,
version = __version__,
license = __license__,
url = __url__,
download_url = __download_url__,
packages = ['aero', 'aero.adapters'],
package_data ={'aero': ['assets/*.ascii']},
description = [descr for descr in open('README.txt').read().splitlines() if descr.strip() and '===' not in descr][1],
long_description=open('README.txt').read(),
install_requires = ["argparse","Beaker","PyYAML"],
scripts = ["aero/aero"],
)
| Add project dependencies to install | Add project dependencies to install
| Python | bsd-3-clause | Aeronautics/aero | ---
+++
@@ -18,6 +18,7 @@
package_data ={'aero': ['assets/*.ascii']},
description = [descr for descr in open('README.txt').read().splitlines() if descr.strip() and '===' not in descr][1],
long_description=open('README.txt').read(),
+ install_requires = ["argparse","Beaker","PyYAML"],
scripts = ["aero/aero"],
) |
507ac62597b30ccfa58841ccf26207b67baa8eac | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='django-lightweight-queue',
url="https://chris-lamb.co.uk/projects/django-lightweight-queue",
version='2.0.1',
description="Lightweight & modular queue and cron system for Django",
author="Chris Lamb",
author_email='[email protected]',
license="BSD",
packages=find_packages(),
)
| from setuptools import setup, find_packages
setup(
name='django-lightweight-queue',
url="https://chris-lamb.co.uk/projects/django-lightweight-queue",
version='2.0.1',
description="Lightweight & modular queue and cron system for Django",
author="Chris Lamb",
author_email='[email protected]',
license="BSD",
packages=find_packages(),
install_requires=(
'Django>=1.8',
),
)
| Update Django requirement to latest LTS | Update Django requirement to latest LTS
| Python | bsd-3-clause | lamby/django-lightweight-queue | ---
+++
@@ -12,4 +12,8 @@
license="BSD",
packages=find_packages(),
+
+ install_requires=(
+ 'Django>=1.8',
+ ),
) |
f8fcdb461f414f3c29263edd7e5c9906d76435a1 | setup.py | setup.py | from setuptools import setup
setup(
name='pytest-flakes',
description='pytest plugin to check source code with pyflakes',
long_description=open("README.rst").read(),
license="MIT license",
version='1.0.1',
author='Florian Schulze, Holger Krekel and Ronny Pfannschmidt',
author_email='[email protected]',
url='https://github.com/fschulze/pytest-flakes',
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Pytest',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
],
py_modules=['pytest_flakes'],
entry_points={'pytest11': ['flakes = pytest_flakes']},
install_requires=['pytest-cache', 'pytest>=2.3.dev14', 'pyflakes'])
| from setuptools import setup
setup(
name='pytest-flakes',
description='pytest plugin to check source code with pyflakes',
long_description=open("README.rst").read(),
license="MIT license",
version='1.0.1',
author='Florian Schulze, Holger Krekel and Ronny Pfannschmidt',
author_email='[email protected]',
url='https://github.com/fschulze/pytest-flakes',
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Pytest',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
],
py_modules=['pytest_flakes'],
entry_points={'pytest11': ['flakes = pytest_flakes']},
install_requires=['pytest-cache', 'pytest>=2.3.dev14', 'pyflakes'])
| Use correct MIT license classifier. | Use correct MIT license classifier.
`LICENSE` contains the MIT/Expat license but `setup.py` uses the LGPLv3
classifier. I assume the later is an oversight.
| Python | mit | fschulze/pytest-flakes | ---
+++
@@ -13,7 +13,7 @@
'Development Status :: 4 - Beta',
'Framework :: Pytest',
'Intended Audience :: Developers',
- 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
+ 'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7', |
787ee9390fbf2ace59d2f8544b735feb6c895dda | setup.py | setup.py | import os
from setuptools import setup
PACKAGE_VERSION = '0.3'
def version():
if os.getenv('TRAVIS'):
return os.getenv('TRAVIS_BUILD_NUMBER')
else:
import odintools
return odintools.version(PACKAGE_VERSION, os.environ.get('BUILD_NUMBER'))
setup(
name='osaapi',
version_getter=version,
author='apsliteteam, oznu',
author_email='[email protected]',
packages=['osaapi'],
url='https://aps.odin.com',
license='Apache License',
description='A python client for the Odin Service Automation (OSA) and billing APIs.',
long_description=open('README.md').read(),
setup_requires=['odintools'],
odintools=True,
)
| import os
from setuptools import setup
PACKAGE_VERSION = '0.3'
def version():
import odintools
b = os.getenv('TRAVIS_BUILD_NUMBER') if os.getenv('TRAVIS') else os.environ.get('BUILD_NUMBER')
return odintools.version(PACKAGE_VERSION, b)
setup(
name='osaapi',
version_getter=version,
author='apsliteteam, oznu',
author_email='[email protected]',
packages=['osaapi'],
url='https://aps.odin.com',
license='Apache License',
description='A python client for the Odin Service Automation (OSA) and billing APIs.',
long_description=open('README.md').read(),
setup_requires=['odintools'],
odintools=True,
)
| Fix issue with version setter | Fix issue with version setter
| Python | apache-2.0 | odin-public/osaAPI | ---
+++
@@ -6,12 +6,9 @@
def version():
- if os.getenv('TRAVIS'):
- return os.getenv('TRAVIS_BUILD_NUMBER')
- else:
- import odintools
-
- return odintools.version(PACKAGE_VERSION, os.environ.get('BUILD_NUMBER'))
+ import odintools
+ b = os.getenv('TRAVIS_BUILD_NUMBER') if os.getenv('TRAVIS') else os.environ.get('BUILD_NUMBER')
+ return odintools.version(PACKAGE_VERSION, b)
setup( |
df97966941f2ffe924f98b329b136edf069eb6ca | setup.py | setup.py | #!/usr/bin/env python
"""Django/PostgreSQL implementation of the Meteor DDP service."""
import os.path
from setuptools import setup, find_packages
setup(
name='django-ddp',
version='0.2.0',
description=__doc__,
long_description=open('README.rst').read(),
author='Tyson Clugg',
author_email='[email protected]',
url='https://github.com/commoncode/django-ddp',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Django>=1.7',
'psycopg2>=2.5.4',
'gevent>=1.0',
'gevent-websocket>=0.9',
'meteor-ejson>=1.0',
'psycogreen>=1.0',
'django-dbarray>=0.2',
],
classifiers=[
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Topic :: Internet :: WWW/HTTP",
],
)
| #!/usr/bin/env python
"""Django/PostgreSQL implementation of the Meteor DDP service."""
import os.path
from setuptools import setup, find_packages
setup(
name='django-ddp',
version='0.2.1',
description=__doc__,
long_description=open('README.rst').read(),
author='Tyson Clugg',
author_email='[email protected]',
url='https://github.com/commoncode/django-ddp',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Django>=1.7',
'psycopg2>=2.5.4',
'gevent>=1.0',
'gevent-websocket>=0.9',
'meteor-ejson>=1.0',
'psycogreen>=1.0',
'django-dbarray>=0.2',
],
classifiers=[
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Topic :: Internet :: WWW/HTTP",
],
)
| Bump version number in preparation for next release. | Bump version number in preparation for next release.
| Python | mit | django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,PythonicNinja/django-ddp,commoncode/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,PythonicNinja/django-ddp,PythonicNinja/django-ddp | ---
+++
@@ -5,7 +5,7 @@
setup(
name='django-ddp',
- version='0.2.0',
+ version='0.2.1',
description=__doc__,
long_description=open('README.rst').read(),
author='Tyson Clugg', |
d63d391d5b9ee221c0cd67e030895f4598430f08 | onetime/models.py | onetime/models.py | from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
class Key(models.Model):
user = models.ForeignKey(User)
key = models.CharField(max_length=40)
created = models.DateTimeField(auto_now_add=True)
usage_left = models.IntegerField(null=True, default=1)
expires = models.DateTimeField(null=True)
next = models.CharField(null=True, max_length=200)
def __unicode__(self):
return '%s (%s)' % (self.key, self.user.username)
def is_valid(self):
if self.usage_left is not None and self.usage_left <= 0:
return False
if self.expires is not None and self.expires < datetime.now():
return False
return True
def update_usage(self):
if self.usage_left is not None:
self.usage_left -= 1
self.save()
| from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
class Key(models.Model):
user = models.ForeignKey(User)
key = models.CharField(max_length=40)
created = models.DateTimeField(auto_now_add=True)
usage_left = models.IntegerField(null=True, default=1)
expires = models.DateTimeField(null=True)
next = models.CharField(null=True, max_length=200)
def __unicode__(self):
return '%s (%s)' % (self.key, self.user.username)
def is_valid(self):
if self.usage_left is not None and self.usage_left <= 0:
return False
if self.expires is not None and self.expires < datetime.now():
return False
return True
def update_usage(self):
if self.usage_left is not None and self.usage_left > 0:
self.usage_left -= 1
self.save()
| Update key usage when the usage_left counter is still greater than zero. | Update key usage when the usage_left counter is still greater than zero.
| Python | bsd-3-clause | uploadcare/django-loginurl,vanschelven/cmsplugin-journal,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,fajran/django-loginurl,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website | ---
+++
@@ -22,7 +22,7 @@
return True
def update_usage(self):
- if self.usage_left is not None:
+ if self.usage_left is not None and self.usage_left > 0:
self.usage_left -= 1
self.save()
|
c8a0f4f439c2123c9b7f9b081f91d75b1f9a8a13 | dmoj/checkers/linecount.py | dmoj/checkers/linecount.py | from re import split as resplit
from typing import Callable, Union
from dmoj.result import CheckerResult
from dmoj.utils.unicode import utf8bytes
verdict = u"\u2717\u2713"
def check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True,
match: Callable[[bytes, bytes], bool] = lambda p, j: p.strip() == j.strip(),
**kwargs) -> Union[CheckerResult, bool]:
process_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(process_output))))
judge_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(judge_output))))
if len(process_lines) > len(judge_lines):
return False
if not judge_lines:
return True
if isinstance(match, str):
match = eval(match)
cases = [verdict[0]] * len(judge_lines)
count = 0
for i, (process_line, judge_line) in enumerate(zip(process_lines, judge_lines)):
if match(process_line, judge_line):
cases[i] = verdict[1]
count += 1
return CheckerResult(count == len(judge_lines), point_value * (1.0 * count / len(judge_lines)),
''.join(cases) if feedback else "")
check.run_on_error = True # type: ignore
| from re import split as resplit
from typing import Callable, Union
from dmoj.result import CheckerResult
from dmoj.utils.unicode import utf8bytes
verdict = u"\u2717\u2713"
def check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True,
**kwargs) -> Union[CheckerResult, bool]:
process_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(process_output))))
judge_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(judge_output))))
if len(process_lines) > len(judge_lines):
return False
if not judge_lines:
return True
cases = [verdict[0]] * len(judge_lines)
count = 0
for i, (process_line, judge_line) in enumerate(zip(process_lines, judge_lines)):
if process_line.strip() == judge_line.strip():
cases[i] = verdict[1]
count += 1
return CheckerResult(count == len(judge_lines), point_value * (1.0 * count / len(judge_lines)),
''.join(cases) if feedback else "")
check.run_on_error = True # type: ignore
| Remove the match param to fix RCE. | Remove the match param to fix RCE. | Python | agpl-3.0 | DMOJ/judge,DMOJ/judge,DMOJ/judge | ---
+++
@@ -8,7 +8,6 @@
def check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True,
- match: Callable[[bytes, bytes], bool] = lambda p, j: p.strip() == j.strip(),
**kwargs) -> Union[CheckerResult, bool]:
process_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(process_output))))
judge_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(judge_output))))
@@ -19,14 +18,11 @@
if not judge_lines:
return True
- if isinstance(match, str):
- match = eval(match)
-
cases = [verdict[0]] * len(judge_lines)
count = 0
for i, (process_line, judge_line) in enumerate(zip(process_lines, judge_lines)):
- if match(process_line, judge_line):
+ if process_line.strip() == judge_line.strip():
cases[i] = verdict[1]
count += 1
|
18b62174d8fd48691a78f23b0a9f806eb7eb01f7 | indra/tests/test_tas.py | indra/tests/test_tas.py | from nose.plugins.attrib import attr
from indra.sources.tas import process_from_web
@attr('slow')
def test_processor():
tp = process_from_web(affinity_class_limit=10)
assert tp
assert tp.statements
num_stmts = len(tp.statements)
# This is the total number of statements about human genes
assert num_stmts == 1130277, num_stmts
assert all(len(s.evidence) >= 1 for s in tp.statements), \
'Some statements lack any evidence'
| from nose.plugins.attrib import attr
from indra.sources.tas import process_from_web
@attr('slow')
def test_processor():
tp = process_from_web(affinity_class_limit=10)
assert tp
assert tp.statements
num_stmts = len(tp.statements)
# This is the total number of statements about human genes
assert num_stmts == 1128585, num_stmts
assert all(len(s.evidence) >= 1 for s in tp.statements), \
'Some statements lack any evidence'
| Update test again after better aggregation | Update test again after better aggregation
| Python | bsd-2-clause | johnbachman/indra,bgyori/indra,johnbachman/belpy,sorgerlab/indra,sorgerlab/indra,johnbachman/belpy,sorgerlab/belpy,bgyori/indra,sorgerlab/belpy,johnbachman/indra,bgyori/indra,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,johnbachman/belpy | ---
+++
@@ -9,6 +9,6 @@
assert tp.statements
num_stmts = len(tp.statements)
# This is the total number of statements about human genes
- assert num_stmts == 1130277, num_stmts
+ assert num_stmts == 1128585, num_stmts
assert all(len(s.evidence) >= 1 for s in tp.statements), \
'Some statements lack any evidence' |
973641c7d68f4b1505541a06ec46901b412ab56b | tests/test_constraints.py | tests/test_constraints.py | import unittest
import numpy as np
from constraints import (generate_constraints_function,
generate_constraint_gradients_function, )
from robot_arm import RobotArm
class TestConstraintFunctions(unittest.TestCase):
def setUp(self):
self.lengths = (3, 2, 2,)
self.destinations = (
(5, 4, 6, 4, 5),
(0, 2, 0.5, -2, -1),
)
self.theta = (np.pi, np.pi / 2, 0,)
self.thetas = np.ones((3 * 5,))
self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta)
self.constraints_func = generate_constraints_function(self.robot_arm)
self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm)
def test_constraints_func_return_type(self):
constraints = self.constraints_func(self.thetas)
self.assertEqual(constraints.shape, (2 * 5,))
def test_constraint_gradients_func_return_type(self):
constraint_gradients = self.constraint_gradients_func(self.thetas)
self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5))
# print(np.array2string(constraint_gradients, max_line_width=np.inf))
| import unittest
import numpy as np
from constraints import (generate_constraints_function,
generate_constraint_gradients_function, )
from robot_arm import RobotArm
class TestConstraintFunctions(unittest.TestCase):
def setUp(self):
self.lengths = (3, 2, 2,)
self.destinations = (
(5, 4, 6, 4, 5),
(0, 2, 0.5, -2, -1),
)
self.theta = (np.pi, np.pi / 2, 0,)
self.thetas = np.ones((3 * 5,))
self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta)
self.constraints_func = generate_constraints_function(self.robot_arm)
self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm)
def test_constraints_func_return_type(self):
constraints = self.constraints_func(self.thetas)
self.assertEqual(constraints.shape, (2 * 5,))
def test_constraint_gradients_func_return_type(self):
constraint_gradients = self.constraint_gradients_func(self.thetas)
self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5))
# print(np.array2string(constraint_gradients, max_line_width=np.inf))
def test_licq(self):
constraint_gradients = self.constraint_gradients_func(self.thetas)
rank = np.linalg.matrix_rank(constraint_gradients)
self.assertEqual(rank, 2 * 5)
| Test LICQ condition of constraint gradient | Test LICQ condition of constraint gradient
| Python | mit | JakobGM/robotarm-optimization | ---
+++
@@ -28,3 +28,8 @@
constraint_gradients = self.constraint_gradients_func(self.thetas)
self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5))
# print(np.array2string(constraint_gradients, max_line_width=np.inf))
+
+ def test_licq(self):
+ constraint_gradients = self.constraint_gradients_func(self.thetas)
+ rank = np.linalg.matrix_rank(constraint_gradients)
+ self.assertEqual(rank, 2 * 5) |
c8c9c42f14c742c6fcb180b7a3cc1bab1655ac46 | projections/simpleexpr.py | projections/simpleexpr.py |
import numpy as np
import numpy.ma as ma
import projections.r2py.reval as reval
import projections.r2py.rparser as rparser
class SimpleExpr():
def __init__(self, name, expr):
self.name = name
self.tree = reval.make_inputs(rparser.parse(expr))
lokals = {}
exec(reval.to_py(self.tree, name), lokals)
self.func = lokals[name + '_st']
@property
def syms(self):
return reval.find_inputs(self.tree)
def eval(self, df):
try:
res = self.func(df)
except KeyError as e:
print("Error: input '%s' not defined" % e)
raise e
if not isinstance(res, np.ndarray):
res = ma.masked_array(np.full(tuple(df.values())[0].shape, res,
dtype=np.float32))
return res
|
import numpy as np
import numpy.ma as ma
import projections.r2py.reval as reval
import projections.r2py.rparser as rparser
class SimpleExpr():
def __init__(self, name, expr):
self.name = name
self.tree = reval.make_inputs(rparser.parse(expr))
lokals = {}
exec(reval.to_py(self.tree, name), lokals)
self.func = lokals[name + '_st']
@property
def syms(self):
return reval.find_inputs(self.tree)
def eval(self, df):
try:
res = self.func(df)
except KeyError as e:
print("Error: input '%s' not defined" % e)
raise e
if not isinstance(res, np.ndarray):
arrays = filter(lambda v: isinstance(v, np.ndarray), df.values())
res = ma.masked_array(np.full(tuple(arrays)[0].shape, res,
dtype=np.float32))
return res
| Improve determination of array shape for constant expressions | Improve determination of array shape for constant expressions
When Evaluating a constant expression, I only used to look at the first
column in the df dictionary. But that could also be a constant or
expression. So look instead at all columns and find the first numpy
array.
| Python | apache-2.0 | ricardog/raster-project,ricardog/raster-project,ricardog/raster-project,ricardog/raster-project,ricardog/raster-project | ---
+++
@@ -24,6 +24,7 @@
print("Error: input '%s' not defined" % e)
raise e
if not isinstance(res, np.ndarray):
- res = ma.masked_array(np.full(tuple(df.values())[0].shape, res,
+ arrays = filter(lambda v: isinstance(v, np.ndarray), df.values())
+ res = ma.masked_array(np.full(tuple(arrays)[0].shape, res,
dtype=np.float32))
return res |
632180274abe4cf91f65cf0e84f817dc7124e293 | zerver/migrations/0108_fix_default_string_id.py | zerver/migrations/0108_fix_default_string_id.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-24 02:39
from __future__ import unicode_literals
from django.db import migrations
def fix_realm_string_ids(apps, schema_editor):
# type: (StateApps, DatabaseSchemaEditor) -> None
Realm = apps.get_model('zerver', 'Realm')
if Realm.objects.count() != 2:
return
zulip_realm = Realm.objects.get(string_id="zulip")
try:
user_realm = Realm.objects.exclude(id=zulip_realm.id)[0]
except Realm.DoesNotExist:
return
user_realm.string_id = ""
user_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0107_multiuseinvite'),
]
operations = [
migrations.RunPython(fix_realm_string_ids,
reverse_code=migrations.RunPython.noop),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-24 02:39
from __future__ import unicode_literals
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def fix_realm_string_ids(apps, schema_editor):
# type: (StateApps, DatabaseSchemaEditor) -> None
Realm = apps.get_model('zerver', 'Realm')
if Realm.objects.count() != 2:
return
zulip_realm = Realm.objects.get(string_id="zulip")
try:
user_realm = Realm.objects.exclude(id=zulip_realm.id)[0]
except Realm.DoesNotExist:
return
user_realm.string_id = ""
user_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0107_multiuseinvite'),
]
operations = [
migrations.RunPython(fix_realm_string_ids,
reverse_code=migrations.RunPython.noop),
]
| Add imports needed for new migration. | mypy: Add imports needed for new migration.
| Python | apache-2.0 | eeshangarg/zulip,Galexrt/zulip,shubhamdhama/zulip,punchagan/zulip,Galexrt/zulip,tommyip/zulip,brainwane/zulip,tommyip/zulip,zulip/zulip,brainwane/zulip,punchagan/zulip,eeshangarg/zulip,rht/zulip,timabbott/zulip,rht/zulip,zulip/zulip,andersk/zulip,synicalsyntax/zulip,brainwane/zulip,rht/zulip,eeshangarg/zulip,rishig/zulip,andersk/zulip,timabbott/zulip,amanharitsh123/zulip,synicalsyntax/zulip,timabbott/zulip,rht/zulip,jackrzhang/zulip,rishig/zulip,mahim97/zulip,Galexrt/zulip,kou/zulip,brockwhittaker/zulip,kou/zulip,eeshangarg/zulip,andersk/zulip,dhcrzf/zulip,hackerkid/zulip,brockwhittaker/zulip,verma-varsha/zulip,showell/zulip,brainwane/zulip,kou/zulip,shubhamdhama/zulip,tommyip/zulip,andersk/zulip,brainwane/zulip,eeshangarg/zulip,hackerkid/zulip,brainwane/zulip,eeshangarg/zulip,zulip/zulip,andersk/zulip,brainwane/zulip,verma-varsha/zulip,jackrzhang/zulip,timabbott/zulip,zulip/zulip,synicalsyntax/zulip,timabbott/zulip,rht/zulip,synicalsyntax/zulip,Galexrt/zulip,zulip/zulip,dhcrzf/zulip,rht/zulip,showell/zulip,rishig/zulip,synicalsyntax/zulip,mahim97/zulip,kou/zulip,mahim97/zulip,verma-varsha/zulip,showell/zulip,Galexrt/zulip,Galexrt/zulip,jackrzhang/zulip,eeshangarg/zulip,synicalsyntax/zulip,hackerkid/zulip,punchagan/zulip,tommyip/zulip,shubhamdhama/zulip,jackrzhang/zulip,amanharitsh123/zulip,tommyip/zulip,jackrzhang/zulip,amanharitsh123/zulip,jackrzhang/zulip,dhcrzf/zulip,rishig/zulip,dhcrzf/zulip,dhcrzf/zulip,mahim97/zulip,shubhamdhama/zulip,shubhamdhama/zulip,rishig/zulip,kou/zulip,hackerkid/zulip,mahim97/zulip,zulip/zulip,tommyip/zulip,kou/zulip,showell/zulip,shubhamdhama/zulip,punchagan/zulip,rishig/zulip,brockwhittaker/zulip,punchagan/zulip,andersk/zulip,synicalsyntax/zulip,amanharitsh123/zulip,dhcrzf/zulip,kou/zulip,rht/zulip,brockwhittaker/zulip,zulip/zulip,rishig/zulip,verma-varsha/zulip,punchagan/zulip,hackerkid/zulip,showell/zulip,brockwhittaker/zulip,hackerkid/zulip,amanharitsh123/zulip,mahim97/zulip,showell/zulip,Galexrt/zulip,hackerkid/zulip,shubhamdhama/zulip,verma-varsha/zulip,amanharitsh123/zulip,brockwhittaker/zulip,timabbott/zulip,verma-varsha/zulip,showell/zulip,punchagan/zulip,tommyip/zulip,jackrzhang/zulip,andersk/zulip,timabbott/zulip,dhcrzf/zulip | ---
+++
@@ -3,6 +3,8 @@
from __future__ import unicode_literals
from django.db import migrations
+from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
+from django.db.migrations.state import StateApps
def fix_realm_string_ids(apps, schema_editor):
# type: (StateApps, DatabaseSchemaEditor) -> None |
91ef89371f7ba99346ba982a3fdb7fc2105a9840 | superdesk/users/__init__.py | superdesk/users/__init__.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from .users import RolesResource, UsersResource
from .services import DBUsersService, RolesService, is_admin # noqa
import superdesk
def init_app(app):
endpoint_name = 'users'
service = DBUsersService(endpoint_name, backend=superdesk.get_backend())
UsersResource(endpoint_name, app=app, service=service)
endpoint_name = 'roles'
service = RolesService(endpoint_name, backend=superdesk.get_backend())
RolesResource(endpoint_name, app=app, service=service)
superdesk.privilege(name='users', label='User Management', description='User can manage users.')
superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.')
# Registering with intrinsic privileges because: A user should be allowed to update their own profile.
superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])
| # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from .users import RolesResource, UsersResource
from .services import UsersService, DBUsersService, RolesService, is_admin # noqa
import superdesk
def init_app(app):
endpoint_name = 'users'
service = DBUsersService(endpoint_name, backend=superdesk.get_backend())
UsersResource(endpoint_name, app=app, service=service)
endpoint_name = 'roles'
service = RolesService(endpoint_name, backend=superdesk.get_backend())
RolesResource(endpoint_name, app=app, service=service)
superdesk.privilege(name='users', label='User Management', description='User can manage users.')
superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.')
# Registering with intrinsic privileges because: A user should be allowed to update their own profile.
superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])
| Make UsersResource reusable for LDAP | Make UsersResource reusable for LDAP
| Python | agpl-3.0 | ioanpocol/superdesk-core,plamut/superdesk-core,akintolga/superdesk-core,ancafarcas/superdesk-core,ancafarcas/superdesk-core,nistormihai/superdesk-core,superdesk/superdesk-core,sivakuna-aap/superdesk-core,superdesk/superdesk-core,mdhaman/superdesk-core,petrjasek/superdesk-core,mdhaman/superdesk-core,mugurrus/superdesk-core,mugurrus/superdesk-core,mdhaman/superdesk-core,superdesk/superdesk-core,ioanpocol/superdesk-core,sivakuna-aap/superdesk-core,marwoodandrew/superdesk-core,plamut/superdesk-core,superdesk/superdesk-core,petrjasek/superdesk-core,ioanpocol/superdesk-core,marwoodandrew/superdesk-core,hlmnrmr/superdesk-core,akintolga/superdesk-core,nistormihai/superdesk-core,hlmnrmr/superdesk-core,mugurrus/superdesk-core,petrjasek/superdesk-core,petrjasek/superdesk-core | ---
+++
@@ -9,7 +9,7 @@
# at https://www.sourcefabric.org/superdesk/license
from .users import RolesResource, UsersResource
-from .services import DBUsersService, RolesService, is_admin # noqa
+from .services import UsersService, DBUsersService, RolesService, is_admin # noqa
import superdesk
|
05e19922a5a0f7268ce1a34e25e5deb8e9a2f5d3 | sfmtools.py | sfmtools.py | """ Utility functions for PhotoScan processing """
import os, sys
import PhotoScan
def align_and_clean_photos(chunk):
ncameras = len(chunk.cameras)
for frame in chunk.frames:
frame.matchPhotos()
chunk.alignCameras()
for camera in chunk.cameras:
if camera.transform is None:
chunk.remove(camera)
naligned = len(chunk.cameras)
print('%d/%d cameras aligned' % (naligned, ncameras))
def export_dems(resolution, formatstring, pathname)
if not os.path.isdir(pathname):
os.mkdir(pathname)
nchunks = len(PhotoScan.app.document.chunks)
nexported = nchunks
for chunk in PhotoScan.app.document.chunks:
filename = ''.join([pathname, chunk.label.split(' '), '.', formatstring])
exported = chunk.exportDem(filename, format=formatstring, dx=resolution, dy=resolution)
if not exported:
print('Export failed:', chunk.label)
nexported -= 1
print('%d/%d DEMs exported' % (nexported, nchunks))
| """ Utility functions for PhotoScan processing """
import os, sys
import PhotoScan
def align_and_clean_photos(chunk):
ncameras = len(chunk.cameras)
for frame in chunk.frames:
frame.matchPhotos()
chunk.alignCameras()
for camera in chunk.cameras:
if camera.transform is None:
chunk.remove(camera)
naligned = len(chunk.cameras)
print('%d/%d cameras aligned' % (naligned, ncameras))
def export_dems(resolution, formatstring, pathname)
if not os.path.isdir(pathname):
os.mkdir(pathname)
if pathname[-1:] is not '/':
pathname = ''.join(pathname, '/')
nchunks = len(PhotoScan.app.document.chunks)
nexported = nchunks
for chunk in PhotoScan.app.document.chunks:
filename = ''.join([pathname, chunk.label.split(' '), '.', formatstring])
exported = chunk.exportDem(filename, format=formatstring, dx=resolution, dy=resolution)
if not exported:
print('Export failed:', chunk.label)
nexported -= 1
print('%d/%d DEMs exported' % (nexported, nchunks))
| Check for trailing slash in path | Check for trailing slash in path | Python | mit | rmsare/sfmtools | ---
+++
@@ -19,6 +19,8 @@
def export_dems(resolution, formatstring, pathname)
if not os.path.isdir(pathname):
os.mkdir(pathname)
+ if pathname[-1:] is not '/':
+ pathname = ''.join(pathname, '/')
nchunks = len(PhotoScan.app.document.chunks)
nexported = nchunks |
33328f7d6c3fbab4a7ae968103828ac40463543b | __main__.py | __main__.py | #!/usr/bin/env python
# MAKE IT UNICODE OK
import sys
reload( sys )
sys.setdefaultencoding( 'utf-8' )
import os, sys
import Bot
import logging
if __name__ == '__main__':
logging.basicConfig( level = logging.DEBUG, format = '[%(asctime)s] %(levelname)s: %(message)s' )
logging.getLogger().addHandler( logging.FileHandler( 'ircbot.log' ) )
logging.info( "Welcome to botje" )
fork = True
if len( sys.argv ) > 1:
if sys.argv[1] == '-nofork':
fork = False
if fork:
try:
pid = os.fork()
if pid > 0:
logging.info( 'Forked into PID {0}'.format( pid ) )
sys.exit(0)
sys.stdout = open( '/tmp/ircbot.log', 'w' )
except OSError as error:
logging.error( 'Unable to fork. Error: {0} ({1})'.format( error.errno, error.strerror ) )
sys.exit(1)
botje = Bot.Bot()
while True:
try:
botje.start()
except Bot.BotReloadException:
logging.info( 'Force reloading Bot class' )
botje = None
reload(Bot)
botje = Bot.Bot()
logging.info( 'Botje died, restarting in 5...' )
import time
time.sleep( 5 )
| #!/usr/bin/env python
# MAKE IT UNICODE OK
import sys
reload( sys )
sys.setdefaultencoding( 'utf-8' )
import os, sys
import Bot
import logging
if __name__ == '__main__':
logging.basicConfig( filename = 'ircbot.log', level = logging.DEBUG, format = '[%(asctime)s] %(levelname)s: %(message)s' )
logging.info( "Welcome to botje" )
fork = True
if len( sys.argv ) > 1:
if sys.argv[1] == '-nofork':
fork = False
if fork:
try:
pid = os.fork()
if pid > 0:
logging.info( 'Forked into PID {0}'.format( pid ) )
sys.exit(0)
sys.stdout = open( '/tmp/ircbot.log', 'w' )
except OSError as error:
logging.error( 'Unable to fork. Error: {0} ({1})'.format( error.errno, error.strerror ) )
sys.exit(1)
botje = Bot.Bot()
while True:
try:
botje.start()
except Bot.BotReloadException:
logging.info( 'Force reloading Bot class' )
botje = None
reload(Bot)
botje = Bot.Bot()
logging.info( 'Botje died, restarting in 5...' )
import time
time.sleep( 5 )
| Set default logger to file | Set default logger to file
| Python | mit | jawsper/modularirc | ---
+++
@@ -10,8 +10,7 @@
import logging
if __name__ == '__main__':
- logging.basicConfig( level = logging.DEBUG, format = '[%(asctime)s] %(levelname)s: %(message)s' )
- logging.getLogger().addHandler( logging.FileHandler( 'ircbot.log' ) )
+ logging.basicConfig( filename = 'ircbot.log', level = logging.DEBUG, format = '[%(asctime)s] %(levelname)s: %(message)s' )
logging.info( "Welcome to botje" )
fork = True
if len( sys.argv ) > 1: |
0bd84e74a30806f1e317288aa5dee87b4c669790 | shcol/config.py | shcol/config.py | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke
# Released under the Simplified BSD license
# (see LICENSE file for details).
"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read during initialization of the `shcol`-package.
"""
import logging
import os
import sys
ENCODING = 'utf-8'
ERROR_STREAM = sys.stderr
INPUT_STREAM = sys.stdin
LINE_WIDTH = None
LINESEP = '\n'
LOGGER = logging.getLogger('shol')
MAKE_UNIQUE = False
ON_WINDOWS = 'windows' in os.getenv('os', '').lower()
PY_VERSION = sys.version_info[:2]
SORT_ITEMS = False
SPACING = 2
STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else ''))
TERMINAL_STREAM = sys.stdout
UNICODE_TYPE = type(u'')
| # -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke
# Released under the Simplified BSD license
# (see LICENSE file for details).
"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read during initialization of the `shcol`-package.
"""
import logging
import os
import sys
ERROR_STREAM = sys.stderr
INPUT_STREAM = sys.stdin
LINE_WIDTH = None
LINESEP = '\n'
LOGGER = logging.getLogger('shol')
MAKE_UNIQUE = False
ON_WINDOWS = 'windows' in os.getenv('os', '').lower()
PY_VERSION = sys.version_info[:2]
SORT_ITEMS = False
SPACING = 2
STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else ''))
TERMINAL_STREAM = sys.stdout
UNICODE_TYPE = type(u'')
ENCODING = TERMINAL_STREAM.encoding or 'utf-8'
| Use output stream's encoding (if any). Blindly using UTF-8 would break output on Windows terminals. | Use output stream's encoding (if any).
Blindly using UTF-8 would break output on Windows terminals.
| Python | bsd-2-clause | seblin/shcol | ---
+++
@@ -13,7 +13,6 @@
import os
import sys
-ENCODING = 'utf-8'
ERROR_STREAM = sys.stderr
INPUT_STREAM = sys.stdin
LINE_WIDTH = None
@@ -27,3 +26,5 @@
STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else ''))
TERMINAL_STREAM = sys.stdout
UNICODE_TYPE = type(u'')
+
+ENCODING = TERMINAL_STREAM.encoding or 'utf-8' |
49a275a268fba520252ee864c39934699c053d13 | csunplugged/resources/views/barcode_checksum_poster.py | csunplugged/resources/views/barcode_checksum_poster.py | """Module for generating Barcode Checksum Poster resource."""
from PIL import Image
from utils.retrieve_query_parameter import retrieve_query_parameter
def resource_image(request, resource):
"""Create a image for Barcode Checksum Poster resource.
Args:
request: HTTP request object (QueryDict).
resource: Object of resource data (Resource).
Returns:
A list of Pillow image objects.
"""
# Retrieve parameters
parameter_options = valid_options()
barcode_length = retrieve_query_parameter(request, "barcode_length", parameter_options["barcode_length"])
image_path = "static/img/resources/barcode-checksum-poster/{}-digits.png"
image = Image.open(image_path.format(barcode_length))
return image
def subtitle(request, resource):
"""Return the subtitle string of the resource.
Used after the resource name in the filename, and
also on the resource image.
Args:
request: HTTP request object (QueryDict).
resource: Object of resource data (Resource).
Returns:
Text for subtitle (str).
"""
barcode_length = retrieve_query_parameter(request, "barcode_length")
paper_size = retrieve_query_parameter(request, "paper_size")
return "{} digits - {}".format(barcode_length, paper_size)
def valid_options():
"""Provide dictionary of all valid parameters.
This excludes the header text parameter.
Returns:
All valid options (dict).
"""
return {
"barcode_length": ["12", "13"],
"paper_size": ["a4", "letter"],
}
| """Module for generating Barcode Checksum Poster resource."""
from PIL import Image
from utils.retrieve_query_parameter import retrieve_query_parameter
def resource(request, resource):
"""Create a image for Barcode Checksum Poster resource.
Args:
request: HTTP request object (QueryDict).
resource: Object of resource data (Resource).
Returns:
A dictionary for the resource page.
"""
# Retrieve parameters
parameter_options = valid_options()
barcode_length = retrieve_query_parameter(request, "barcode_length", parameter_options["barcode_length"])
image_path = "static/img/resources/barcode-checksum-poster/{}-digits.png"
image = Image.open(image_path.format(barcode_length))
return {"type": "image", "data": image}
def subtitle(request, resource):
"""Return the subtitle string of the resource.
Used after the resource name in the filename, and
also on the resource image.
Args:
request: HTTP request object (QueryDict).
resource: Object of resource data (Resource).
Returns:
Text for subtitle (str).
"""
barcode_length = retrieve_query_parameter(request, "barcode_length")
paper_size = retrieve_query_parameter(request, "paper_size")
return "{} digits - {}".format(barcode_length, paper_size)
def valid_options():
"""Provide dictionary of all valid parameters.
This excludes the header text parameter.
Returns:
All valid options (dict).
"""
return {
"barcode_length": ["12", "13"],
"paper_size": ["a4", "letter"],
}
| Update barcode resource to new resource specification | Update barcode resource to new resource specification
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | ---
+++
@@ -4,7 +4,7 @@
from utils.retrieve_query_parameter import retrieve_query_parameter
-def resource_image(request, resource):
+def resource(request, resource):
"""Create a image for Barcode Checksum Poster resource.
Args:
@@ -12,7 +12,7 @@
resource: Object of resource data (Resource).
Returns:
- A list of Pillow image objects.
+ A dictionary for the resource page.
"""
# Retrieve parameters
parameter_options = valid_options()
@@ -20,7 +20,7 @@
image_path = "static/img/resources/barcode-checksum-poster/{}-digits.png"
image = Image.open(image_path.format(barcode_length))
- return image
+ return {"type": "image", "data": image}
def subtitle(request, resource): |
ee74fa5705fbf276e092b778f5bead9ffcd04b5e | django_fixmystreet/fixmystreet/tests/__init__.py | django_fixmystreet/fixmystreet/tests/__init__.py | import shutil
import os
from django.core.files.storage import default_storage
from django.test import TestCase
class SampleFilesTestCase(TestCase):
fixtures = ['sample']
@classmethod
def setUpClass(cls):
default_storage.location = 'media' # force using source media folder to avoid real data erasing
# @classmethod
# def setUpClass(cls):
# shutil.copytree('media', 'media-tmp')
# default_storage.location = 'media-tmp'
#
# @classmethod
# def tearDownClass(self):
# shutil.rmtree('media-tmp')
def _fixture_setup(self):
if os.path.exists('media/photos'):
shutil.rmtree('media/photos')
shutil.copytree('media/photos-sample', 'media/photos')
super(SampleFilesTestCase, self)._fixture_setup()
def tearDown(self):
shutil.rmtree('media-tmp/photos')
from django_fixmystreet.fixmystreet.tests.views import *
from django_fixmystreet.fixmystreet.tests.reports import *
from django_fixmystreet.fixmystreet.tests.users import *
from django_fixmystreet.fixmystreet.tests.organisation_entity import *
from django_fixmystreet.fixmystreet.tests.mail import *
# from django_fixmystreet.fixmystreet.tests.api import *
| import shutil
import os
from django.core.files.storage import default_storage
from django.test import TestCase
class SampleFilesTestCase(TestCase):
fixtures = ['sample']
@classmethod
def setUpClass(cls):
default_storage.location = 'media' # force using source media folder to avoid real data erasing
# @classmethod
# def setUpClass(cls):
# shutil.copytree('media', 'media-tmp')
# default_storage.location = 'media-tmp'
#
# @classmethod
# def tearDownClass(self):
# shutil.rmtree('media-tmp')
def _fixture_setup(self):
if os.path.exists('media/photos'):
shutil.rmtree('media/photos')
shutil.copytree('media/photos-sample', 'media/photos')
super(SampleFilesTestCase, self)._fixture_setup()
def tearDown(self):
shutil.rmtree('media/photos')
from django_fixmystreet.fixmystreet.tests.views import *
from django_fixmystreet.fixmystreet.tests.reports import *
from django_fixmystreet.fixmystreet.tests.users import *
from django_fixmystreet.fixmystreet.tests.organisation_entity import *
from django_fixmystreet.fixmystreet.tests.mail import *
# from django_fixmystreet.fixmystreet.tests.api import *
| Fix unit test fixtures files | Fix unit test fixtures files
| Python | agpl-3.0 | IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet | ---
+++
@@ -26,7 +26,7 @@
super(SampleFilesTestCase, self)._fixture_setup()
def tearDown(self):
- shutil.rmtree('media-tmp/photos')
+ shutil.rmtree('media/photos')
from django_fixmystreet.fixmystreet.tests.views import *
from django_fixmystreet.fixmystreet.tests.reports import * |
12f3bb8c82b97496c79948d323f7076b6618293a | saleor/graphql/scalars.py | saleor/graphql/scalars.py | from graphene.types import Scalar
from graphql.language import ast
class AttributesFilterScalar(Scalar):
@staticmethod
def coerce_filter(value):
if isinstance(value, tuple) and len(value) == 2:
return ":".join(value)
serialize = coerce_filter
parse_value = coerce_filter
@staticmethod
def parse_literal(node):
if isinstance(node, ast.StringValue):
splitted = node.value.split(":")
if len(splitted) == 2:
return tuple(splitted)
| from graphene.types import Scalar
from graphql.language import ast
class AttributesFilterScalar(Scalar):
@staticmethod
def parse_literal(node):
if isinstance(node, ast.StringValue):
splitted = node.value.split(":")
if len(splitted) == 2:
return tuple(splitted)
@staticmethod
def parse_value(value):
if isinstance(value, basestring):
splitted = value.split(":")
if len(splitted) == 2:
return tuple(splitted)
@staticmethod
def serialize(value):
if isinstance(value, tuple) and len(value) == 2:
return ":".join(value)
| Fix parsing attributes filter values in GraphQL API | Fix parsing attributes filter values in GraphQL API
| Python | bsd-3-clause | KenMutemi/saleor,KenMutemi/saleor,jreigel/saleor,itbabu/saleor,maferelo/saleor,maferelo/saleor,jreigel/saleor,jreigel/saleor,HyperManTT/ECommerceSaleor,mociepka/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,car3oon/saleor,itbabu/saleor,UITools/saleor,HyperManTT/ECommerceSaleor,car3oon/saleor,car3oon/saleor,UITools/saleor,HyperManTT/ECommerceSaleor,tfroehlich82/saleor,itbabu/saleor,tfroehlich82/saleor,tfroehlich82/saleor,KenMutemi/saleor,mociepka/saleor,UITools/saleor,mociepka/saleor | ---
+++
@@ -5,16 +5,20 @@
class AttributesFilterScalar(Scalar):
@staticmethod
- def coerce_filter(value):
- if isinstance(value, tuple) and len(value) == 2:
- return ":".join(value)
-
- serialize = coerce_filter
- parse_value = coerce_filter
-
- @staticmethod
def parse_literal(node):
if isinstance(node, ast.StringValue):
splitted = node.value.split(":")
if len(splitted) == 2:
return tuple(splitted)
+
+ @staticmethod
+ def parse_value(value):
+ if isinstance(value, basestring):
+ splitted = value.split(":")
+ if len(splitted) == 2:
+ return tuple(splitted)
+
+ @staticmethod
+ def serialize(value):
+ if isinstance(value, tuple) and len(value) == 2:
+ return ":".join(value) |
5b8ff4276fbe92d5ccd5fa63fecccc5ff7d571a9 | quokka/core/tests/test_models.py | quokka/core/tests/test_models.py | # coding: utf-8
from . import BaseTestCase
from ..models import Channel
class TestCoreModels(BaseTestCase):
def setUp(self):
# Create method was not returning the created object with
# the create() method
self.channel, new = Channel.objects.get_or_create(
title=u'Monkey Island',
description=u'The coolest pirate history ever',
)
def tearDown(self):
self.channel.delete()
def test_channel_fields(self):
self.assertEqual(self.channel.title, u'Monkey Island')
self.assertEqual(self.channel.slug, u'monkey-island')
self.assertEqual(self.channel.description,
u'The coolest pirate history ever')
| # coding: utf-8
from . import BaseTestCase
from ..models import Channel
class TestChannel(BaseTestCase):
def setUp(self):
# Create method was not returning the created object with
# the create() method
self.parent, new = Channel.objects.get_or_create(
title=u'Father',
)
self.channel, new = Channel.objects.get_or_create(
title=u'Monkey Island',
description=u'The coolest pirate history ever',
parent=self.parent,
tags=['tag1', 'tag2'],
)
def tearDown(self):
self.channel.delete()
def test_channel_fields(self):
self.assertEqual(self.channel.title, u'Monkey Island')
self.assertEqual(self.channel.slug, u'monkey-island')
self.assertEqual(self.channel.long_slug, u'father/monkey-island')
self.assertEqual(self.channel.mpath, u',father,monkey-island,')
self.assertEqual(self.channel.description,
u'The coolest pirate history ever')
self.assertEqual(self.channel.tags, ['tag1', 'tag2'])
self.assertEqual(self.channel.parent, self.parent)
self.assertEqual(unicode(self.channel), u'father/monkey-island')
def test_get_ancestors(self):
self.assertEqual(list(self.channel.get_ancestors()), [self.channel,
self.parent])
def test_get_ancestors_slug(self):
self.assertEqual(self.channel.get_ancestors_slugs(),
[u'father/monkey-island', u'father'])
def test_get_children(self):
self.assertEqual(list(self.parent.get_children()), [self.channel])
def test_get_descendants(self):
self.assertEqual(list(self.parent.get_descendants()),
[self.parent, self.channel])
def test_absolute_urls(self):
self.assertEqual(self.channel.get_absolute_url(),
'/father/monkey-island/')
self.assertEqual(self.parent.get_absolute_url(),
'/father/')
def test_get_canonical_url(self):
self.assertEqual(self.channel.get_canonical_url(),
'/father/monkey-island/')
self.assertEqual(self.parent.get_canonical_url(),
'/father/')
| Add more core tests / Rename test | Add more core tests / Rename test
| Python | mit | romulocollopy/quokka,felipevolpone/quokka,lnick/quokka,ChengChiongWah/quokka,felipevolpone/quokka,wushuyi/quokka,wushuyi/quokka,cbeloni/quokka,felipevolpone/quokka,CoolCloud/quokka,ChengChiongWah/quokka,lnick/quokka,romulocollopy/quokka,Ckai1991/quokka,cbeloni/quokka,CoolCloud/quokka,alexandre/quokka,felipevolpone/quokka,fdumpling/quokka,fdumpling/quokka,romulocollopy/quokka,CoolCloud/quokka,maurobaraldi/quokka,maurobaraldi/quokka,romulocollopy/quokka,Ckai1991/quokka,fdumpling/quokka,cbeloni/quokka,ChengChiongWah/quokka,lnick/quokka,ChengChiongWah/quokka,Ckai1991/quokka,wushuyi/quokka,lnick/quokka,fdumpling/quokka,CoolCloud/quokka,alexandre/quokka,Ckai1991/quokka,maurobaraldi/quokka,maurobaraldi/quokka,wushuyi/quokka,cbeloni/quokka | ---
+++
@@ -4,13 +4,18 @@
from ..models import Channel
-class TestCoreModels(BaseTestCase):
+class TestChannel(BaseTestCase):
def setUp(self):
# Create method was not returning the created object with
# the create() method
+ self.parent, new = Channel.objects.get_or_create(
+ title=u'Father',
+ )
self.channel, new = Channel.objects.get_or_create(
title=u'Monkey Island',
description=u'The coolest pirate history ever',
+ parent=self.parent,
+ tags=['tag1', 'tag2'],
)
def tearDown(self):
@@ -19,5 +24,37 @@
def test_channel_fields(self):
self.assertEqual(self.channel.title, u'Monkey Island')
self.assertEqual(self.channel.slug, u'monkey-island')
+ self.assertEqual(self.channel.long_slug, u'father/monkey-island')
+ self.assertEqual(self.channel.mpath, u',father,monkey-island,')
self.assertEqual(self.channel.description,
u'The coolest pirate history ever')
+ self.assertEqual(self.channel.tags, ['tag1', 'tag2'])
+ self.assertEqual(self.channel.parent, self.parent)
+ self.assertEqual(unicode(self.channel), u'father/monkey-island')
+
+ def test_get_ancestors(self):
+ self.assertEqual(list(self.channel.get_ancestors()), [self.channel,
+ self.parent])
+
+ def test_get_ancestors_slug(self):
+ self.assertEqual(self.channel.get_ancestors_slugs(),
+ [u'father/monkey-island', u'father'])
+
+ def test_get_children(self):
+ self.assertEqual(list(self.parent.get_children()), [self.channel])
+
+ def test_get_descendants(self):
+ self.assertEqual(list(self.parent.get_descendants()),
+ [self.parent, self.channel])
+
+ def test_absolute_urls(self):
+ self.assertEqual(self.channel.get_absolute_url(),
+ '/father/monkey-island/')
+ self.assertEqual(self.parent.get_absolute_url(),
+ '/father/')
+
+ def test_get_canonical_url(self):
+ self.assertEqual(self.channel.get_canonical_url(),
+ '/father/monkey-island/')
+ self.assertEqual(self.parent.get_canonical_url(),
+ '/father/') |
3037562643bc1ddaf081a6fa9c757aed4101bb53 | robots/urls.py | robots/urls.py | try:
from django.conf.urls import patterns, url
except ImportError:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns(
'robots.views',
url(r'^$', 'rules_list', name='robots_rule_list'),
)
| from django.conf.urls import url
from robots.views import rules_list
urlpatterns = [
url(r'^$', rules_list, name='robots_rule_list'),
]
| Fix warnings about URLconf in Django 1.9 | Fix warnings about URLconf in Django 1.9
* django.conf.urls.patterns will be removed in Django 1.10
* Passing a dotted path and not a view function will be deprecated in
Django 1.10
| Python | bsd-3-clause | jezdez/django-robots,jezdez/django-robots,jscott1971/django-robots,jscott1971/django-robots,jazzband/django-robots,jazzband/django-robots | ---
+++
@@ -1,9 +1,8 @@
-try:
- from django.conf.urls import patterns, url
-except ImportError:
- from django.conf.urls.defaults import patterns, url
+from django.conf.urls import url
-urlpatterns = patterns(
- 'robots.views',
- url(r'^$', 'rules_list', name='robots_rule_list'),
-)
+from robots.views import rules_list
+
+
+urlpatterns = [
+ url(r'^$', rules_list, name='robots_rule_list'),
+] |
76243416f36a932c16bee93cc753de3d71168f0b | manager/__init__.py | manager/__init__.py | import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
from flask.ext.login import LoginManager
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
db= SQLAlchemy(app)
login = LoginManager()
login.init_app(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower_components')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootswatch/sandstone/bootstrap.css',
'css/ignition.css',
output='css_all.css'
)
)
from manager.views import core
| import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
from flask.ext.login import LoginManager
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
db= SQLAlchemy(app)
login = LoginManager()
login.init_app(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower_components')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootswatch/sandstone/bootstrap.css',
'css/ignition.css',
output='css_all.css'
)
)
from manager.views import core
from manager.models import users | Add user table to module init | Add user table to module init
| Python | mit | hreeder/ignition,hreeder/ignition,hreeder/ignition | ---
+++
@@ -40,3 +40,4 @@
)
from manager.views import core
+from manager.models import users |
aba5ae9736b064fd1e3541de3ef36371d92fc875 | RandoAmisSecours/admin.py | RandoAmisSecours/admin.py | # -*- coding: utf-8 -*-
# vim: set ts=4
# Copyright 2013 Rémi Duraffort
# This file is part of RandoAmisSecours.
#
# RandoAmisSecours is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# RandoAmisSecours is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with RandoAmisSecours. If not, see <http://www.gnu.org/licenses/>
from django.contrib import admin
from models import *
admin.site.register(FriendRequest)
admin.site.register(Outing)
admin.site.register(Profile)
| # -*- coding: utf-8 -*-
# vim: set ts=4
# Copyright 2013 Rémi Duraffort
# This file is part of RandoAmisSecours.
#
# RandoAmisSecours is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# RandoAmisSecours is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with RandoAmisSecours. If not, see <http://www.gnu.org/licenses/>
from django.contrib import admin
from RandoAmisSecours.models import *
admin.site.register(FriendRequest)
admin.site.register(Outing)
admin.site.register(Profile)
| Fix import when using python3.3 | Fix import when using python3.3
| Python | agpl-3.0 | ivoire/RandoAmisSecours,ivoire/RandoAmisSecours | ---
+++
@@ -18,7 +18,7 @@
# along with RandoAmisSecours. If not, see <http://www.gnu.org/licenses/>
from django.contrib import admin
-from models import *
+from RandoAmisSecours.models import *
admin.site.register(FriendRequest)
admin.site.register(Outing) |
b3ef748df9eca585ae3fc77da666ba5ce93bc428 | lala/plugins/fortune.py | lala/plugins/fortune.py | import logging
from functools import partial
from lala.util import command, msg
from twisted.internet.utils import getProcessOutput
@command
def fortune(user, channel, text):
"""Show a random, hopefully interesting, adage"""
_call_fortune(user, channel)
@command
def ofortune(user, channel, text):
"""Show a random, hopefully interesting, offensive adage"""
_call_fortune(user, channel, ["-o"])
def _call_fortune(user, channel, args=[]):
"""Call the ``fortune`` executable with ``args`` (a sequence of strings).
"""
callback = partial(_send_output_to_channel, user, channel)
errback = partial(_send_error_to_channel, user, channel)
deferred = getProcessOutput("fortune", args)
deferred.addCallback(callback)
deferred.addErrback(errback)
deferred.addErrback(logging.error)
def _send_output_to_channel(user, channel, text):
msg(channel, "%s: %s" %(user, text.replace("\n","")))
def _send_error_to_channel(user, channel, exception):
msg(channel, "%s: Sorry, no fortune for you today! Details are in the log." % user)
return exception
| import logging
from functools import partial
from lala.util import command, msg
from twisted.internet.utils import getProcessOutput
@command
def fortune(user, channel, text):
"""Show a random, hopefully interesting, adage"""
_call_fortune(user, channel)
@command
def ofortune(user, channel, text):
"""Show a random, hopefully interesting, offensive adage"""
_call_fortune(user, channel, ["-o"])
def _call_fortune(user, channel, args=[]):
"""Call the ``fortune`` executable with ``args`` (a sequence of strings).
"""
callback = partial(_send_output_to_channel, user, channel)
errback = partial(_send_error_to_channel, user, channel)
deferred = getProcessOutput("fortune", args)
deferred.addCallback(callback)
deferred.addErrback(errback)
deferred.addErrback(logging.error)
def _send_output_to_channel(user, channel, text):
msg(channel, "%s: %s" %(user, text.replace("\n"," ")))
def _send_error_to_channel(user, channel, exception):
msg(channel, "%s: Sorry, no fortune for you today! Details are in the log." % user)
return exception
| Replace newlines with spaces for readability | Replace newlines with spaces for readability
| Python | mit | mineo/lala,mineo/lala | ---
+++
@@ -25,7 +25,7 @@
deferred.addErrback(logging.error)
def _send_output_to_channel(user, channel, text):
- msg(channel, "%s: %s" %(user, text.replace("\n","")))
+ msg(channel, "%s: %s" %(user, text.replace("\n"," ")))
def _send_error_to_channel(user, channel, exception):
msg(channel, "%s: Sorry, no fortune for you today! Details are in the log." % user) |
b9e1b34348444c4c51c8fd30ff7882552e21939b | temba/msgs/migrations/0094_auto_20170501_1641.py | temba/msgs/migrations/0094_auto_20170501_1641.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-01 16:41
from __future__ import unicode_literals
from django.db import migrations, models
import temba.utils.models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0093_populate_translatables'),
]
operations = [
migrations.RemoveField(
model_name='broadcast',
name='language_dict',
),
migrations.RemoveField(
model_name='broadcast',
name='media_dict',
),
migrations.RemoveField(
model_name='broadcast',
name='text',
),
migrations.AlterField(
model_name='broadcast',
name='base_language',
field=models.CharField(help_text='The language used to send this to contacts without a language',
max_length=4),
),
migrations.AlterField(
model_name='broadcast',
name='translations',
field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text',
max_length=640, verbose_name='Translations'),
),
migrations.RenameField(
model_name='broadcast',
old_name='translations',
new_name='text',
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-01 16:41
from __future__ import unicode_literals
from django.db import migrations, models
import temba.utils.models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0093_populate_translatables'),
]
operations = [
migrations.AlterField(
model_name='broadcast',
name='base_language',
field=models.CharField(help_text='The language used to send this to contacts without a language',
max_length=4),
),
migrations.AlterField(
model_name='broadcast',
name='translations',
field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text',
max_length=640, verbose_name='Translations'),
),
migrations.RemoveField(
model_name='broadcast',
name='language_dict',
),
migrations.RemoveField(
model_name='broadcast',
name='media_dict',
),
migrations.RemoveField(
model_name='broadcast',
name='text',
),
migrations.RenameField(
model_name='broadcast',
old_name='translations',
new_name='text',
),
]
| Change order of operations within migration so breaking schema changes come last | Change order of operations within migration so breaking schema changes come last
| Python | agpl-3.0 | pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro | ---
+++
@@ -13,6 +13,18 @@
]
operations = [
+ migrations.AlterField(
+ model_name='broadcast',
+ name='base_language',
+ field=models.CharField(help_text='The language used to send this to contacts without a language',
+ max_length=4),
+ ),
+ migrations.AlterField(
+ model_name='broadcast',
+ name='translations',
+ field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text',
+ max_length=640, verbose_name='Translations'),
+ ),
migrations.RemoveField(
model_name='broadcast',
name='language_dict',
@@ -25,18 +37,6 @@
model_name='broadcast',
name='text',
),
- migrations.AlterField(
- model_name='broadcast',
- name='base_language',
- field=models.CharField(help_text='The language used to send this to contacts without a language',
- max_length=4),
- ),
- migrations.AlterField(
- model_name='broadcast',
- name='translations',
- field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text',
- max_length=640, verbose_name='Translations'),
- ),
migrations.RenameField(
model_name='broadcast',
old_name='translations', |
3c9da01bee3d157e344f3ad317b777b3977b2e4d | account_invoice_start_end_dates/models/account_move.py | account_invoice_start_end_dates/models/account_move.py | # Copyright 2019 Akretion France <https://akretion.com/>
# @author: Alexis de Lattre <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, models
from odoo.exceptions import UserError
class AccountMove(models.Model):
_inherit = "account.move"
def action_post(self):
for move in self:
for line in move.line_ids:
if line.product_id and line.product_id.must_have_dates:
if not line.start_date or not line.end_date:
raise UserError(
_(
"Missing Start Date and End Date for invoice "
"line with Product '%s' which has the "
"property 'Must Have Start and End Dates'."
)
% (line.product_id.display_name)
)
return super(AccountMove, self).action_post()
| # Copyright 2019 Akretion France <https://akretion.com/>
# @author: Alexis de Lattre <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, models
from odoo.exceptions import UserError
class AccountMove(models.Model):
_inherit = "account.move"
def action_post(self):
for move in self:
for line in move.line_ids:
if line.product_id and line.product_id.must_have_dates:
if not line.start_date or not line.end_date:
raise UserError(
_(
"Missing Start Date and End Date for invoice "
"line with Product '%s' which has the "
"property 'Must Have Start and End Dates'."
)
% (line.product_id.display_name)
)
return super().action_post()
| Use super() instead of super(classname, self) | Use super() instead of super(classname, self)
| Python | agpl-3.0 | OCA/account-closing,OCA/account-closing | ---
+++
@@ -22,4 +22,4 @@
)
% (line.product_id.display_name)
)
- return super(AccountMove, self).action_post()
+ return super().action_post() |
d0919465239399f1ab6d65bbd8c42b1b9657ddb6 | scripts/utils.py | scripts/utils.py | #!/usr/bin/env python3
# Touhou Community Reliant Automatic Patcher
# Scripts
#
# ----
#
"""Utility functions shared among all the scripts."""
from collections import OrderedDict
import json
import os
json_load_params = {
'object_pairs_hook': OrderedDict
}
def patch_files_filter(files):
"""Filters all file names that can not be among the content of a patch."""
for i in files:
if i != 'files.js':
yield i
json_dump_params = {
'ensure_ascii': False,
'indent': '\t',
'separators': (',', ': '),
'sort_keys': True
}
# Default parameters for JSON input and output
def json_load(fn):
with open(fn, 'r', encoding='utf-8') as file:
return json.load(file, **json_load_params)
def json_store(fn, obj, dirs=['']):
"""Saves the JSON object [obj] to [fn], creating all necessary
directories in the process. If [dirs] is given, the function is
executed for every root directory in the array."""
for i in dirs:
full_fn = os.path.join(i, fn)
os.makedirs(os.path.dirname(full_fn), exist_ok=True)
with open(full_fn, 'w', encoding='utf-8') as file:
json.dump(obj, file, **json_dump_params)
file.write('\n')
| #!/usr/bin/env python3
# Touhou Community Reliant Automatic Patcher
# Scripts
#
# ----
#
"""Utility functions shared among all the scripts."""
from collections import OrderedDict
import json
import os
json_load_params = {
'object_pairs_hook': OrderedDict
}
def patch_files_filter(files):
"""Filters all file names that can not be among the content of a patch."""
for i in files:
if i != 'files.js':
yield i
json_dump_params = {
'ensure_ascii': False,
'indent': '\t',
'separators': (',', ': '),
'sort_keys': True
}
# Default parameters for JSON input and output
def json_load(fn, json_kwargs=json_load_params):
with open(fn, 'r', encoding='utf-8') as file:
return json.load(file, **json_kwargs)
def json_store(fn, obj, dirs=[''], json_kwargs=json_dump_params):
"""Saves the JSON object [obj] to [fn], creating all necessary
directories in the process. If [dirs] is given, the function is
executed for every root directory in the array."""
for i in dirs:
full_fn = os.path.join(i, fn)
os.makedirs(os.path.dirname(full_fn), exist_ok=True)
with open(full_fn, 'w', encoding='utf-8') as file:
json.dump(obj, file, **json_kwargs)
file.write('\n')
| Allow to override the JSON loading and dumping parameters. | scripts: Allow to override the JSON loading and dumping parameters.
| Python | unlicense | VBChunguk/thcrap,thpatch/thcrap,VBChunguk/thcrap,thpatch/thcrap,thpatch/thcrap,thpatch/thcrap,thpatch/thcrap,VBChunguk/thcrap | ---
+++
@@ -30,12 +30,12 @@
}
# Default parameters for JSON input and output
-def json_load(fn):
+def json_load(fn, json_kwargs=json_load_params):
with open(fn, 'r', encoding='utf-8') as file:
- return json.load(file, **json_load_params)
+ return json.load(file, **json_kwargs)
-def json_store(fn, obj, dirs=['']):
+def json_store(fn, obj, dirs=[''], json_kwargs=json_dump_params):
"""Saves the JSON object [obj] to [fn], creating all necessary
directories in the process. If [dirs] is given, the function is
executed for every root directory in the array."""
@@ -43,5 +43,5 @@
full_fn = os.path.join(i, fn)
os.makedirs(os.path.dirname(full_fn), exist_ok=True)
with open(full_fn, 'w', encoding='utf-8') as file:
- json.dump(obj, file, **json_dump_params)
+ json.dump(obj, file, **json_kwargs)
file.write('\n') |
b0254fd4090c0d17f60a87f3fe5fe28c0382310e | scripts/v0to1.py | scripts/v0to1.py | #!/usr/bin/env python
import sys
import h5py
infiles = sys.argv[1:]
for infile in infiles:
with h5py.File(infile, 'a') as h5:
print(infile)
if 'format-version' in h5.attrs and h5.attrs['format-version'] < 1:
if 'matrix' in h5 and not 'pixels' in h5:
print('renaming matrix --> pixels')
h5['pixels'] = h5['matrix']
if 'scaffolds' in h5 and not 'chroms' in h5:
print('renaming scaffolds --> chroms')
h5['chroms'] = h5['scaffolds']
h5.attrs['format-version'] = 1
| #!/usr/bin/env python
import sys
import h5py
infiles = sys.argv[1:]
for infile in infiles:
with h5py.File(infile, 'a') as h5:
print(infile)
if 'format-version' in h5.attrs and h5.attrs['format-version'] < 1:
if 'matrix' in h5 and not 'pixels' in h5:
print('renaming matrix --> pixels')
h5['pixels'] = h5['matrix']
del h5['matrix']
if 'scaffolds' in h5 and not 'chroms' in h5:
print('renaming scaffolds --> chroms')
h5['chroms'] = h5['scaffolds']
del h5['scaffolds']
h5.attrs['format-version'] = 1
| Drop old names from v0 | Drop old names from v0
| Python | bsd-3-clause | mirnylab/cooler | ---
+++
@@ -12,10 +12,12 @@
if 'matrix' in h5 and not 'pixels' in h5:
print('renaming matrix --> pixels')
h5['pixels'] = h5['matrix']
+ del h5['matrix']
if 'scaffolds' in h5 and not 'chroms' in h5:
print('renaming scaffolds --> chroms')
h5['chroms'] = h5['scaffolds']
+ del h5['scaffolds']
h5.attrs['format-version'] = 1
|
de82b44979f3e3b1c7e73594cd2138d00add4e47 | test-console.py | test-console.py | import logging
logging.basicConfig(level=logging.DEBUG)
import mdk_tracing
import time
import quark
tracer = mdk_tracing.Tracer.withURLsAndToken("ws://localhost:52690/ws", None, None)
# tracer = mdk_tracing.Tracer.withURLsAndToken("wss://tracing-develop.datawire.io/ws", None, None)
def goodHandler(result):
# logging.info("Good!")
for record in result:
logging.info(record.toString())
def badHandler(result):
logging.info("Failure: %s" % result.toString())
def formatLogRecord(record):
return("%.3f %s %s" % (record.timestamp, record.record.level, record.record.text))
def poller(hrm=None):
# logging.info("POLLING")
tracer.poll() \
.andEither(goodHandler, badHandler) \
.andFinally(lambda x: quark.IO.schedule(1)) \
.andFinally(poller)
poller()
| import logging
logging.basicConfig(level=logging.DEBUG)
import mdk_tracing
import time
import quark
# tracer = mdk_tracing.Tracer.withURLsAndToken("ws://localhost:52690/ws", None, None)
tracer = mdk_tracing.Tracer.withURLsAndToken("wss://tracing-develop.datawire.io/ws", None, None)
def goodHandler(result):
# logging.info("Good!")
for record in result:
logging.info(record.toString())
def badHandler(result):
logging.info("Failure: %s" % result.toString())
def formatLogRecord(record):
return("%.3f %s %s" % (record.timestamp, record.record.level, record.record.text))
def poller(hrm=None):
# logging.info("POLLING")
tracer.poll() \
.andEither(goodHandler, badHandler) \
.andFinally(lambda x: quark.IO.schedule(1)) \
.andFinally(poller)
poller()
| Switch console to use tracing-develop | Switch console to use tracing-develop
| Python | apache-2.0 | datawire/mdk,datawire/mdk,datawire/mdk,datawire/mdk | ---
+++
@@ -6,8 +6,8 @@
import quark
-tracer = mdk_tracing.Tracer.withURLsAndToken("ws://localhost:52690/ws", None, None)
-# tracer = mdk_tracing.Tracer.withURLsAndToken("wss://tracing-develop.datawire.io/ws", None, None)
+# tracer = mdk_tracing.Tracer.withURLsAndToken("ws://localhost:52690/ws", None, None)
+tracer = mdk_tracing.Tracer.withURLsAndToken("wss://tracing-develop.datawire.io/ws", None, None)
def goodHandler(result):
# logging.info("Good!") |
43350965e171e6a3bfd89af3dd192ab5c9281b3a | vumi/blinkenlights/tests/test_message20110818.py | vumi/blinkenlights/tests/test_message20110818.py | from twisted.trial.unittest import TestCase
import vumi.blinkenlights.message20110818 as message
import time
class TestMessage(TestCase):
def test_to_dict(self):
now = time.time()
datapoint = ("vumi.w1.a_metric", now, 1.5)
msg = message.MetricMessage()
msg.append(datapoint)
self.assertEqual(msg.to_dict(), {
'datapoints': [datapoint],
})
def test_from_dict(self):
now = time.time()
datapoint = ("vumi.w1.a_metric", now, 1.5)
msgdict = {"datapoints": [datapoint]}
msg = message.MetricMessage.from_dict(msgdict)
self.assertEqual(msg._datapoints, [datapoint])
| from twisted.trial.unittest import TestCase
import vumi.blinkenlights.message20110818 as message
import time
class TestMessage(TestCase):
def test_to_dict(self):
now = time.time()
datapoint = ("vumi.w1.a_metric", now, 1.5)
msg = message.MetricMessage()
msg.append(datapoint)
self.assertEqual(msg.to_dict(), {
'datapoints': [datapoint],
})
def test_from_dict(self):
now = time.time()
datapoint = ("vumi.w1.a_metric", now, 1.5)
msgdict = {"datapoints": [datapoint]}
msg = message.MetricMessage.from_dict(msgdict)
self.assertEqual(msg._datapoints, [datapoint])
def test_extend(self):
now = time.time()
datapoint = ("vumi.w1.a_metric", now, 1.5)
msg = message.MetricMessage()
msg.extend([datapoint, datapoint, datapoint])
self.assertEqual(msg._datapoints, [
datapoint, datapoint, datapoint])
| Add test for extend method. | Add test for extend method.
| Python | bsd-3-clause | TouK/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,TouK/vumi,harrissoerja/vumi,TouK/vumi,harrissoerja/vumi,harrissoerja/vumi | ---
+++
@@ -20,3 +20,11 @@
msgdict = {"datapoints": [datapoint]}
msg = message.MetricMessage.from_dict(msgdict)
self.assertEqual(msg._datapoints, [datapoint])
+
+ def test_extend(self):
+ now = time.time()
+ datapoint = ("vumi.w1.a_metric", now, 1.5)
+ msg = message.MetricMessage()
+ msg.extend([datapoint, datapoint, datapoint])
+ self.assertEqual(msg._datapoints, [
+ datapoint, datapoint, datapoint]) |
f5198851aebb000a6107b3f9ce34825da200abff | src/foremast/utils/get_template.py | src/foremast/utils/get_template.py | """Render Jinja2 template."""
import logging
import os
import jinja2
LOG = logging.getLogger(__name__)
def get_template(template_file='', **kwargs):
"""Get the Jinja2 template and renders with dict _kwargs_.
Args:
kwargs: Keywords to use for rendering the Jinja2 template.
Returns:
String of rendered JSON template.
"""
here = os.path.dirname(os.path.realpath(__file__))
templatedir = '{0}/../templates/'.format(here)
LOG.debug('Template directory: %s', templatedir)
LOG.debug('Template file: %s', template_file)
jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader(templatedir))
template = jinjaenv.get_template(template_file)
for k,v in kwargs.items():
LOG.debug('%s => %s', k,v)
rendered_json = template.render(**kwargs)
LOG.debug('Rendered JSON:\n%s', rendered_json)
return rendered_json
| """Render Jinja2 template."""
import logging
import os
import jinja2
LOG = logging.getLogger(__name__)
def get_template(template_file='', **kwargs):
"""Get the Jinja2 template and renders with dict _kwargs_.
Args:
kwargs: Keywords to use for rendering the Jinja2 template.
Returns:
String of rendered JSON template.
"""
here = os.path.dirname(os.path.realpath(__file__))
templatedir = '{0}/../templates/'.format(here)
LOG.debug('Template directory: %s', templatedir)
LOG.debug('Template file: %s', template_file)
jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader(templatedir))
template = jinjaenv.get_template(template_file)
for key, value in kwargs.items():
LOG.debug('%s => %s', key, value)
rendered_json = template.render(**kwargs)
LOG.debug('Rendered JSON:\n%s', rendered_json)
return rendered_json
| Use more descriptive variable names | style: Use more descriptive variable names
See also: PSOBAT-1197
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast | ---
+++
@@ -23,8 +23,8 @@
jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader(templatedir))
template = jinjaenv.get_template(template_file)
- for k,v in kwargs.items():
- LOG.debug('%s => %s', k,v)
+ for key, value in kwargs.items():
+ LOG.debug('%s => %s', key, value)
rendered_json = template.render(**kwargs)
LOG.debug('Rendered JSON:\n%s', rendered_json) |
159d09e18dc3b10b7ba3c104a2761f300d50ff28 | organizer/models.py | organizer/models.py | from django.db import models
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Tag(models.Model):
name = models.CharField(
max_length=31, unique=True)
slug = models.SlugField(
max_length=31,
unique=True,
help_text='A label for URL config.')
class Startup(models.Model):
name = models.CharField(max_length=31)
slug = models.SlugField()
description = models.TextField()
founded_date = models.DateField()
contact = models.EmailField()
website = models.URLField()
tags = models.ManyToManyField(Tag)
class NewsLink(models.Model):
title = models.CharField(max_length=63)
pub_date = models.DateField()
link = models.URLField()
startup = models.ForeignKey(Startup)
| from django.db import models
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Tag(models.Model):
name = models.CharField(
max_length=31, unique=True)
slug = models.SlugField(
max_length=31,
unique=True,
help_text='A label for URL config.')
class Startup(models.Model):
name = models.CharField(max_length=31)
slug = models.SlugField()
description = models.TextField()
founded_date = models.DateField()
contact = models.EmailField()
website = models.URLField()
tags = models.ManyToManyField(Tag)
class NewsLink(models.Model):
title = models.CharField(max_length=63)
pub_date = models.DateField('date published')
link = models.URLField(max_length=255)
startup = models.ForeignKey(Startup)
| Add options to NewsLink model fields. | Ch03: Add options to NewsLink model fields. [skip ci]
Field options allow us to easily customize behavior of a field.
Verbose name documentation:
https://docs.djangoproject.com/en/1.8/ref/models/fields/#verbose-name
https://docs.djangoproject.com/en/1.8/topics/db/models/#verbose-field-names
The max_length field option is defined in CharField and inherited by all
CharField subclasses (but is typically optional in these subclasses,
unlike CharField itself).
The 255 character limit of the URLField is based on RFC 3986.
https://tools.ietf.org/html/rfc3986
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 | ---
+++
@@ -26,6 +26,6 @@
class NewsLink(models.Model):
title = models.CharField(max_length=63)
- pub_date = models.DateField()
- link = models.URLField()
+ pub_date = models.DateField('date published')
+ link = models.URLField(max_length=255)
startup = models.ForeignKey(Startup) |
761fbb68f72ff8f425ad40670ea908b4959d3292 | specchio/main.py | specchio/main.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import time
from watchdog.observers import Observer
from specchio.handlers import SpecchioEventHandler
from specchio.utils import init_logger, logger
def main():
"""Main function for specchio
Example: specchio test/ user@host:test/
:return: None
"""
if len(sys.argv) == 3:
src_path = sys.argv[1].strip()
dst_ssh, dst_path = sys.argv[2].strip().split(":")
event_handler = SpecchioEventHandler(
src_path=src_path, dst_ssh=dst_path, dst_path=dst_path
)
init_logger()
logger.info("Initialize Specchio")
observer = Observer()
observer.schedule(event_handler, src_path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
else:
print """Specchio is a tool that can help you rsync your file,
it use `.gitignore` in git to discern which file is ignored.
Usage: specchio src/ user@host:dst"""
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import time
from watchdog.observers import Observer
from specchio.handlers import SpecchioEventHandler
from specchio.utils import init_logger, logger
def main():
"""Main function for specchio
Example: specchio test/ user@host:test/
:return: None
"""
if len(sys.argv) == 3:
src_path = sys.argv[1].strip()
dst_ssh, dst_path = sys.argv[2].strip().split(":")
event_handler = SpecchioEventHandler(
src_path=src_path, dst_ssh=dst_path, dst_path=dst_path
)
init_logger()
logger.info("Initialize Specchio")
observer = Observer()
observer.schedule(event_handler, src_path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
else:
print """Usage: specchio src/ user@host:dst/"""
| Fix the output when there is wrong usage | Fix the output when there is wrong usage
| Python | mit | brickgao/specchio | ---
+++
@@ -35,7 +35,4 @@
observer.stop()
observer.join()
else:
- print """Specchio is a tool that can help you rsync your file,
-it use `.gitignore` in git to discern which file is ignored.
-
-Usage: specchio src/ user@host:dst"""
+ print """Usage: specchio src/ user@host:dst/""" |
e910c9f3ee3fec868f2a6dfb7b7d337440cbb768 | virtool/logs.py | virtool/logs.py | import logging.handlers
import coloredlogs
def configure(verbose=False):
logging_level = logging.INFO if verbose else logging.DEBUG
logging.captureWarnings(True)
log_format = "%(asctime)-20s %(module)-11s %(levelname)-8s %(message)s"
coloredlogs.install(
level=logging_level,
fmt=log_format
)
logger = logging.getLogger("virtool")
handler = logging.handlers.RotatingFileHandler("virtool.log", maxBytes=1000000, backupCount=5)
handler.setFormatter(logging.Formatter(log_format))
logger.addHandler(handler)
return logger
| import logging.handlers
import coloredlogs
def configure(verbose=False):
logging_level = logging.INFO if verbose else logging.DEBUG
logging.captureWarnings(True)
log_format = "%(asctime)-20s %(module)-11s %(levelname)-8s %(message)s"
coloredlogs.install(
level=logging_level,
fmt=log_format
)
logger = logging.getLogger()
handler = logging.handlers.RotatingFileHandler("virtool.log", maxBytes=1000000, backupCount=5)
handler.setFormatter(logging.Formatter(log_format))
logger.addHandler(handler)
return logger
| Write all log lines to log files | Write all log lines to log files
Only the virtool logger was being written before. | Python | mit | igboyes/virtool,virtool/virtool,virtool/virtool,igboyes/virtool | ---
+++
@@ -15,7 +15,7 @@
fmt=log_format
)
- logger = logging.getLogger("virtool")
+ logger = logging.getLogger()
handler = logging.handlers.RotatingFileHandler("virtool.log", maxBytes=1000000, backupCount=5)
handler.setFormatter(logging.Formatter(log_format)) |
0ddbea23c8703576e260fa5b57474930393e7d1a | base/components/merchandise/media/views.py | base/components/merchandise/media/views.py | from django.views.generic import DetailView
from .models import Videodisc
class VideodiscDetailView(DetailView):
model = Videodisc
template_name = 'merchandise/media/videodisc_detail.html'
| Create a small detail view for videodiscs. | Create a small detail view for videodiscs.
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web | ---
+++
@@ -0,0 +1,8 @@
+from django.views.generic import DetailView
+
+from .models import Videodisc
+
+
+class VideodiscDetailView(DetailView):
+ model = Videodisc
+ template_name = 'merchandise/media/videodisc_detail.html' |
|
5d188a71ae43ec8858f985dddbb0ff970cd18e73 | feder/domains/apps.py | feder/domains/apps.py | from django.apps import AppConfig
class DomainsConfig(AppConfig):
name = "domains"
| from django.apps import AppConfig
class DomainsConfig(AppConfig):
name = "feder.domains"
| Fix DomainsConfig.name to fix rtfd build | Fix DomainsConfig.name to fix rtfd build
| Python | mit | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder | ---
+++
@@ -2,4 +2,4 @@
class DomainsConfig(AppConfig):
- name = "domains"
+ name = "feder.domains" |
f6e8907b0e742b47425de140cc7b308c3815ffce | dequorum/forms.py | dequorum/forms.py |
from django import forms
from django.forms import widgets
from . import models
class ThreadCreateForm(forms.ModelForm):
class Meta:
model = models.Thread
fields = ['title']
class MessageCreateForm(forms.ModelForm):
class Meta:
model = models.Message
fields = ['body']
class TagFilterForm(forms.Form):
tag = forms.ModelMultipleChoiceField(
queryset=models.Tag.objects.all(),
required=True,
widget=widgets.CheckboxSelectMultiple
) |
from django import forms
from django.forms import widgets
from . import models
class ThreadCreateForm(forms.ModelForm):
class Meta:
model = models.Thread
fields = ['title']
class MessageCreateForm(forms.ModelForm):
class Meta:
model = models.Message
fields = ['body']
class TagFilterForm(forms.Form):
tag = forms.ModelMultipleChoiceField(
queryset=models.Tag.objects.all(),
required=False,
widget=widgets.CheckboxSelectMultiple
)
| Mark tags as not required in filter form | Mark tags as not required in filter form
| Python | mit | funkybob/django-dequorum,funkybob/django-dequorum,funkybob/django-dequorum | ---
+++
@@ -22,6 +22,6 @@
class TagFilterForm(forms.Form):
tag = forms.ModelMultipleChoiceField(
queryset=models.Tag.objects.all(),
- required=True,
+ required=False,
widget=widgets.CheckboxSelectMultiple
) |
58734468f027ddff31bfa7dc685f4af177e8dbb1 | t5x/__init__.py | t5x/__init__.py | # Copyright 2021 The T5X Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Import API modules."""
import t5x.adafactor
import t5x.checkpoints
import t5x.decoding
import t5x.gin_utils
import t5x.models
import t5x.multihost_utils
import t5x.partitioning
import t5x.state_utils
import t5x.train_state
import t5x.trainer
import t5x.utils
# Version number.
from t5x.version import __version__
# TODO(adarob): Move clients to t5x.checkpointing and rename
# checkpoints.py to checkpointing.py
checkpointing = t5x.checkpoints
| # Copyright 2021 The T5X Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Import API modules."""
import t5x.adafactor
import t5x.checkpoints
import t5x.decoding
import t5x.gin_utils
import t5x.losses
import t5x.models
import t5x.multihost_utils
import t5x.partitioning
import t5x.state_utils
import t5x.train_state
import t5x.trainer
import t5x.utils
# Version number.
from t5x.version import __version__
# TODO(adarob): Move clients to t5x.checkpointing and rename
# checkpoints.py to checkpointing.py
checkpointing = t5x.checkpoints
| Add t5x.losses to public API. | Add t5x.losses to public API.
PiperOrigin-RevId: 417631806
| Python | apache-2.0 | google-research/t5x | ---
+++
@@ -18,6 +18,7 @@
import t5x.checkpoints
import t5x.decoding
import t5x.gin_utils
+import t5x.losses
import t5x.models
import t5x.multihost_utils
import t5x.partitioning |
34960807eac1818a8167ff015e941c42be8827da | checkenv.py | checkenv.py | from colorama import Fore
from pkgutil import iter_modules
def check_import(packagename):
"""
Checks that a package is present. Returns true if it is available, and
false if not available.
"""
if packagename in (name for _, name, _ in iter_modules()):
return True
else:
return False
packages = ['missingno', 'pytest', 'pytest_cov', 'tinydb', 'yaml',
'pandas_summary', 'environment_kernels', 'hypothesis']
try:
for pkg in packages:
assert check_import(pkg)
print(Fore.GREEN + 'All packages found; environment checks passed.')
except AssertionError:
print(Fore.RED + f"{pkg} cannot be found. Please pip or conda install.")
| from colorama import Fore, Style
from pkgutil import iter_modules
def check_import(packagename):
"""
Checks that a package is present. Returns true if it is available, and
false if not available.
"""
if packagename in (name for _, name, _ in iter_modules()):
return True
else:
return False
packages = ['missingno', 'pytest', 'pytest_cov', 'tinydb', 'yaml',
'pandas_summary', 'environment_kernels', 'hypothesis']
try:
for pkg in packages:
assert check_import(pkg)
print(Fore.GREEN + 'All packages found; environment checks passed.')
except AssertionError:
print(Fore.RED + f"{pkg} cannot be found. Please pip or conda install.")
Style.RESET_ALL
| Reset colors at the end | Reset colors at the end
| Python | mit | ericmjl/data-testing-tutorial,ericmjl/data-testing-tutorial | ---
+++
@@ -1,4 +1,4 @@
-from colorama import Fore
+from colorama import Fore, Style
from pkgutil import iter_modules
@@ -22,3 +22,5 @@
print(Fore.GREEN + 'All packages found; environment checks passed.')
except AssertionError:
print(Fore.RED + f"{pkg} cannot be found. Please pip or conda install.")
+
+Style.RESET_ALL |
dfa752590c944fc07253c01c3d99b640a46dae1d | jinja2_time/jinja2_time.py | jinja2_time/jinja2_time.py | # -*- coding: utf-8 -*-
import arrow
from jinja2 import nodes
from jinja2.ext import Extension
class TimeExtension(Extension):
tags = set(['now'])
def __init__(self, environment):
super(TimeExtension, self).__init__(environment)
# add the defaults to the environment
environment.extend(
datetime_format='%Y-%m-%d',
)
def _now(self, timezone, datetime_format):
datetime_format = datetime_format or self.environment.datetime_format
return arrow.now(timezone).strftime(datetime_format)
def parse(self, parser):
lineno = next(parser.stream).lineno
args = [parser.parse_expression()]
if parser.stream.skip_if('comma'):
args.append(parser.parse_expression())
else:
args.append(nodes.Const(None))
call = self.call_method('_now', args, lineno=lineno)
return nodes.Output([call], lineno=lineno)
| # -*- coding: utf-8 -*-
import arrow
from jinja2 import nodes
from jinja2.ext import Extension
class TimeExtension(Extension):
tags = set(['now'])
def __init__(self, environment):
super(TimeExtension, self).__init__(environment)
# add the defaults to the environment
environment.extend(datetime_format='%Y-%m-%d')
def _datetime(self, timezone, operator, offset, datetime_format):
d = arrow.now(timezone)
# Parse replace kwargs from offset and include operator
replace_params = {}
for param in offset.split(','):
interval, value = param.split('=')
replace_params[interval] = float(operator + value)
d = d.replace(**replace_params)
if datetime_format is None:
datetime_format = self.environment.datetime_format
return d.strftime(datetime_format)
def _now(self, timezone, datetime_format):
if datetime_format is None:
datetime_format = self.environment.datetime_format
return arrow.now(timezone).strftime(datetime_format)
def parse(self, parser):
lineno = next(parser.stream).lineno
node = parser.parse_expression()
if parser.stream.skip_if('comma'):
datetime_format = parser.parse_expression()
else:
datetime_format = nodes.Const(None)
if isinstance(node, nodes.Add):
call_method = self.call_method(
'_datetime',
[node.left, nodes.Const('+'), node.right, datetime_format],
lineno=lineno,
)
elif isinstance(node, nodes.Sub):
call_method = self.call_method(
'_datetime',
[node.left, nodes.Const('-'), node.right, datetime_format],
lineno=lineno,
)
else:
call_method = self.call_method(
'_now',
[node, datetime_format],
lineno=lineno,
)
return nodes.Output([call_method], lineno=lineno)
| Implement parser method for optional offset | Implement parser method for optional offset
| Python | mit | hackebrot/jinja2-time | ---
+++
@@ -13,24 +13,53 @@
super(TimeExtension, self).__init__(environment)
# add the defaults to the environment
- environment.extend(
- datetime_format='%Y-%m-%d',
- )
+ environment.extend(datetime_format='%Y-%m-%d')
+
+ def _datetime(self, timezone, operator, offset, datetime_format):
+ d = arrow.now(timezone)
+
+ # Parse replace kwargs from offset and include operator
+ replace_params = {}
+ for param in offset.split(','):
+ interval, value = param.split('=')
+ replace_params[interval] = float(operator + value)
+ d = d.replace(**replace_params)
+
+ if datetime_format is None:
+ datetime_format = self.environment.datetime_format
+ return d.strftime(datetime_format)
def _now(self, timezone, datetime_format):
- datetime_format = datetime_format or self.environment.datetime_format
+ if datetime_format is None:
+ datetime_format = self.environment.datetime_format
return arrow.now(timezone).strftime(datetime_format)
def parse(self, parser):
lineno = next(parser.stream).lineno
- args = [parser.parse_expression()]
+ node = parser.parse_expression()
if parser.stream.skip_if('comma'):
- args.append(parser.parse_expression())
+ datetime_format = parser.parse_expression()
else:
- args.append(nodes.Const(None))
+ datetime_format = nodes.Const(None)
- call = self.call_method('_now', args, lineno=lineno)
-
- return nodes.Output([call], lineno=lineno)
+ if isinstance(node, nodes.Add):
+ call_method = self.call_method(
+ '_datetime',
+ [node.left, nodes.Const('+'), node.right, datetime_format],
+ lineno=lineno,
+ )
+ elif isinstance(node, nodes.Sub):
+ call_method = self.call_method(
+ '_datetime',
+ [node.left, nodes.Const('-'), node.right, datetime_format],
+ lineno=lineno,
+ )
+ else:
+ call_method = self.call_method(
+ '_now',
+ [node, datetime_format],
+ lineno=lineno,
+ )
+ return nodes.Output([call_method], lineno=lineno) |
5b3d69d2c9338ab0c50fd9ea8cf3c01adf0c1de3 | breakpad.py | breakpad.py | # 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.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
import sys
def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'):
print 'Do you want to send a crash report [y/N]? ',
if sys.stdin.read(1).lower() == 'y':
try:
params = {
'args': sys.argv,
'stack': stack,
'user': getpass.getuser(),
}
request = urllib.urlopen(url, urllib.urlencode(params))
print request.read()
request.close()
except IOError:
print('There was a failure while trying to send the stack trace. Too bad.')
@atexit.register
def CheckForException():
if 'test' in sys.modules['__main__'].__file__:
# Probably a unit test.
return
last_tb = getattr(sys, 'last_traceback', None)
if last_tb:
SendStack(''.join(traceback.format_tb(last_tb)))
| # 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.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
import sys
def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'):
print 'Do you want to send a crash report [y/N]? ',
if sys.stdin.read(1).lower() == 'y':
try:
params = {
'args': sys.argv,
'stack': stack,
'user': getpass.getuser(),
}
request = urllib.urlopen(url, urllib.urlencode(params))
print request.read()
request.close()
except IOError:
print('There was a failure while trying to send the stack trace. Too bad.')
#@atexit.register
def CheckForException():
if 'test' in sys.modules['__main__'].__file__:
# Probably a unit test.
return
last_tb = getattr(sys, 'last_traceback', None)
if last_tb:
SendStack(''.join(traceback.format_tb(last_tb)))
| Disable braekpad automatic registration while we figure out stuff | Disable braekpad automatic registration while we figure out stuff
Review URL: http://codereview.chromium.org/462022
git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@33686 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | xuyuhan/depot_tools,npe9/depot_tools,SuYiling/chrome_depot_tools,Neozaru/depot_tools,npe9/depot_tools,Midrya/chromium,michalliu/chromium-depot_tools,kaiix/depot_tools,disigma/depot_tools,Chilledheart/depot_tools,fracting/depot_tools,airtimemedia/depot_tools,Midrya/chromium,duongbaoduy/gtools,coreos/depot_tools,duongbaoduy/gtools,liaorubei/depot_tools,coreos/depot_tools,duanwujie/depot_tools,duanwujie/depot_tools,jankeromnes/depot_tools,SuYiling/chrome_depot_tools,primiano/depot_tools,jankeromnes/depot_tools,smikes/depot_tools,G-P-S/depot_tools,G-P-S/depot_tools,HackFisher/depot_tools,fanjunwei/depot_tools,Phonebooth/depot_tools,azunite/chrome_build,Phonebooth/depot_tools,cpanelli/-git-clone-https-chromium.googlesource.com-chromium-tools-depot_tools,Neozaru/depot_tools,HackFisher/depot_tools,Neozaru/depot_tools,jankeromnes/depot_tools,jankeromnes/depot_tools,cybertk/depot_tools,airtimemedia/depot_tools,coreos/depot_tools,CoherentLabs/depot_tools,xuyuhan/depot_tools,kaiix/depot_tools,primiano/depot_tools,cybertk/depot_tools,azunite/chrome_build,fanjunwei/depot_tools,airtimemedia/depot_tools,xuyuhan/depot_tools,fracting/depot_tools,yetu/repotools,jankeromnes/depot_tools,cybertk/depot_tools,ajohnson23/depot_tools,sarvex/depot-tools,primiano/depot_tools,kromain/chromium-tools,jankeromnes/depot_tools,eatbyte/depot_tools,gcodetogit/depot_tools,eatbyte/depot_tools,fracting/depot_tools,michalliu/chromium-depot_tools,SuYiling/chrome_depot_tools,cpanelli/-git-clone-https-chromium.googlesource.com-chromium-tools-depot_tools,coreos/depot_tools,withtone/depot_tools,mlufei/depot_tools,azureplus/chromium_depot_tools,duanwujie/depot_tools,cybertk/depot_tools,sarvex/depot-tools,hsharsha/depot_tools,coreos/depot_tools,cpanelli/-git-clone-https-chromium.googlesource.com-chromium-tools-depot_tools,Chilledheart/depot_tools,ajohnson23/depot_tools,chinmaygarde/depot_tools,smikes/depot_tools,kromain/chromium-tools,smikes/depot_tools,duongbaoduy/gtools,Neozaru/depot_tools,aleonliao/depot_tools,smikes/depot_tools,kaiix/depot_tools,xuyuhan/depot_tools,hsharsha/depot_tools,yetu/repotools,liaorubei/depot_tools,withtone/depot_tools,cybertk/depot_tools,coreos/depot_tools,npe9/depot_tools,azureplus/chromium_depot_tools,chinmaygarde/depot_tools,Chilledheart/depot_tools,yetu/repotools,michalliu/chromium-depot_tools,aleonliao/depot_tools,airtimemedia/depot_tools,liaorubei/depot_tools,sarvex/depot-tools,eatbyte/depot_tools,eatbyte/depot_tools,disigma/depot_tools,Phonebooth/depot_tools,npe9/depot_tools,azureplus/chromium_depot_tools,Neozaru/depot_tools,fanjunwei/depot_tools,azunite/chrome_build,chinmaygarde/depot_tools,Midrya/chromium,kromain/chromium-tools,disigma/depot_tools,G-P-S/depot_tools,G-P-S/depot_tools,mlufei/depot_tools,CoherentLabs/depot_tools,kromain/chromium-tools,gcodetogit/depot_tools,jankeromnes/depot_tools,Chilledheart/depot_tools,sarvex/depot-tools,HackFisher/depot_tools,gcodetogit/depot_tools,withtone/depot_tools,aleonliao/depot_tools,hsharsha/depot_tools,mlufei/depot_tools,Chilledheart/depot_tools,smikes/depot_tools,liaorubei/depot_tools,ajohnson23/depot_tools,Phonebooth/depot_tools,fanjunwei/depot_tools,michalliu/chromium-depot_tools,HackFisher/depot_tools | ---
+++
@@ -29,7 +29,7 @@
print('There was a failure while trying to send the stack trace. Too bad.')
[email protected]
+#@atexit.register
def CheckForException():
if 'test' in sys.modules['__main__'].__file__:
# Probably a unit test. |
d68f28581cd3c3f57f7c41adbd65676887a51136 | opps/channels/tests/test_forms.py | opps/channels/tests/test_forms.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
from opps.channels.models import Channel
from opps.channels.forms import ChannelAdminForm
class ChannelFormTest(TestCase):
def setUp(self):
User = get_user_model()
self.user = User.objects.create(username=u'test', password='test')
self.site = Site.objects.filter(name=u'example.com').get()
self.parent = Channel.objects.create(name=u'Home', slug=u'home',
description=u'home page',
site=self.site, user=self.user)
def test_init(self):
"""
Test successful init without data
"""
form = ChannelAdminForm(instance=self.parent)
self.assertTrue(isinstance(form.instance, Channel))
self.assertEqual(form.instance.pk, self.parent.pk)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
from opps.channels.models import Channel
from opps.channels.forms import ChannelAdminForm
class ChannelFormTest(TestCase):
def setUp(self):
User = get_user_model()
self.user = User.objects.create(username=u'test', password='test')
self.site = Site.objects.filter(name=u'example.com').get()
self.parent = Channel.objects.create(name=u'Home', slug=u'home',
description=u'home page',
site=self.site, user=self.user)
def test_init(self):
"""
Test successful init without data
"""
form = ChannelAdminForm(instance=self.parent)
self.assertTrue(isinstance(form.instance, Channel))
self.assertEqual(form.instance.pk, self.parent.pk)
self.assertEqual(int(form.fields['slug'].widget.attrs['maxlength']), 150)
def test_readonly_slug(self):
"""
Check readonly field slug
"""
form = ChannelAdminForm(instance=self.parent)
self.assertTrue(form.fields['slug'].widget.attrs['readonly'])
form_2 = ChannelAdminForm()
self.assertNotIn('readonly', form_2.fields['slug'].widget.attrs)
| Add test check readonly field slug of channel | Add test check readonly field slug of channel
| Python | mit | jeanmask/opps,opps/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,williamroot/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,opps/opps,jeanmask/opps,opps/opps | ---
+++
@@ -26,4 +26,14 @@
form = ChannelAdminForm(instance=self.parent)
self.assertTrue(isinstance(form.instance, Channel))
self.assertEqual(form.instance.pk, self.parent.pk)
+ self.assertEqual(int(form.fields['slug'].widget.attrs['maxlength']), 150)
+ def test_readonly_slug(self):
+ """
+ Check readonly field slug
+ """
+ form = ChannelAdminForm(instance=self.parent)
+ self.assertTrue(form.fields['slug'].widget.attrs['readonly'])
+
+ form_2 = ChannelAdminForm()
+ self.assertNotIn('readonly', form_2.fields['slug'].widget.attrs) |
b97115679929dfe4f69618f756850617f265048f | service/pixelated/config/site.py | service/pixelated/config/site.py | from twisted.web.server import Site, Request
class AddCSPHeaderRequest(Request):
CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'"
def process(self):
self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES)
self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES)
self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES)
self.setHeader('X-Frame-Options', 'SAMEORIGIN')
self.setHeader('X-XSS-Protection', '1; mode=block')
self.setHeader('X-Content-Type-Options', 'nosniff')
if self.isSecure():
self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')
Request.process(self)
class PixelatedSite(Site):
requestFactory = AddCSPHeaderRequest
@classmethod
def enable_csp_requests(cls):
cls.requestFactory = AddCSPHeaderRequest
@classmethod
def disable_csp_requests(cls):
cls.requestFactory = Site.requestFactory
| from twisted.web.server import Site, Request
class AddSecurityHeadersRequest(Request):
CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'"
def process(self):
self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES)
self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES)
self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES)
self.setHeader('X-Frame-Options', 'SAMEORIGIN')
self.setHeader('X-XSS-Protection', '1; mode=block')
self.setHeader('X-Content-Type-Options', 'nosniff')
if self.isSecure():
self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')
Request.process(self)
class PixelatedSite(Site):
requestFactory = AddSecurityHeadersRequest
@classmethod
def enable_csp_requests(cls):
cls.requestFactory = AddSecurityHeadersRequest
@classmethod
def disable_csp_requests(cls):
cls.requestFactory = Site.requestFactory
| Rename class to match intent | Rename class to match intent
| Python | agpl-3.0 | pixelated-project/pixelated-user-agent,pixelated/pixelated-user-agent,pixelated-project/pixelated-user-agent,pixelated-project/pixelated-user-agent,pixelated-project/pixelated-user-agent,pixelated/pixelated-user-agent,pixelated-project/pixelated-user-agent,pixelated/pixelated-user-agent,pixelated/pixelated-user-agent,pixelated/pixelated-user-agent | ---
+++
@@ -1,7 +1,7 @@
from twisted.web.server import Site, Request
-class AddCSPHeaderRequest(Request):
+class AddSecurityHeadersRequest(Request):
CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'"
def process(self):
@@ -20,11 +20,11 @@
class PixelatedSite(Site):
- requestFactory = AddCSPHeaderRequest
+ requestFactory = AddSecurityHeadersRequest
@classmethod
def enable_csp_requests(cls):
- cls.requestFactory = AddCSPHeaderRequest
+ cls.requestFactory = AddSecurityHeadersRequest
@classmethod
def disable_csp_requests(cls): |
4b245b9a859552adb9c19fafc4bdfab5780782f2 | d1_common_python/src/d1_common/__init__.py | d1_common_python/src/d1_common/__init__.py | # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""d1_common
Shared code for DataONE Python libraries
"""
__version__ = "2.1.0"
__all__ = [
'const',
'exceptions',
'upload',
'xmlrunner',
'types.exceptions',
'types.dataoneTypes',
'types.dataoneErrors',
'ext.mimeparser',
]
| # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""d1_common
Shared code for DataONE Python libraries
"""
__version__ = "2.1.0"
# Set default logging handler to avoid "No handler found" warnings.
import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
| Add logging NullHandler to prevent "no handler found" errors | Add logging NullHandler to prevent "no handler found" errors
This fixes the issue where "no handler found" errors would be printed by
the library if library clients did not set up logging.
| Python | apache-2.0 | DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python | ---
+++
@@ -23,13 +23,14 @@
__version__ = "2.1.0"
-__all__ = [
- 'const',
- 'exceptions',
- 'upload',
- 'xmlrunner',
- 'types.exceptions',
- 'types.dataoneTypes',
- 'types.dataoneErrors',
- 'ext.mimeparser',
-]
+# Set default logging handler to avoid "No handler found" warnings.
+import logging
+
+try:
+ from logging import NullHandler
+except ImportError:
+ class NullHandler(logging.Handler):
+ def emit(self, record):
+ pass
+
+logging.getLogger(__name__).addHandler(NullHandler()) |
af8a96e08029e2dc746cfa1ecbd7a6d02be1c374 | InvenTree/company/forms.py | InvenTree/company/forms.py | """
Django Forms for interacting with Company app
"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from InvenTree.forms import HelperForm
from .models import Company
from .models import SupplierPart
from .models import SupplierPriceBreak
class EditCompanyForm(HelperForm):
""" Form for editing a Company object """
class Meta:
model = Company
fields = [
'name',
'description',
'website',
'address',
'phone',
'email',
'contact',
'is_customer',
'is_supplier',
'notes'
]
class CompanyImageForm(HelperForm):
""" Form for uploading a Company image """
class Meta:
model = Company
fields = [
'image'
]
class EditSupplierPartForm(HelperForm):
""" Form for editing a SupplierPart object """
class Meta:
model = SupplierPart
fields = [
'part',
'supplier',
'SKU',
'description',
'manufacturer',
'MPN',
'URL',
'note',
'base_cost',
'multiple',
'packaging',
'lead_time'
]
class EditPriceBreakForm(HelperForm):
""" Form for creating / editing a supplier price break """
class Meta:
model = SupplierPriceBreak
fields = [
'part',
'quantity',
'cost'
]
| """
Django Forms for interacting with Company app
"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from InvenTree.forms import HelperForm
from .models import Company
from .models import SupplierPart
from .models import SupplierPriceBreak
class EditCompanyForm(HelperForm):
""" Form for editing a Company object """
class Meta:
model = Company
fields = [
'name',
'description',
'website',
'address',
'phone',
'email',
'contact',
'is_customer',
'is_supplier',
'notes'
]
class CompanyImageForm(HelperForm):
""" Form for uploading a Company image """
class Meta:
model = Company
fields = [
'image'
]
class EditSupplierPartForm(HelperForm):
""" Form for editing a SupplierPart object """
class Meta:
model = SupplierPart
fields = [
'part',
'supplier',
'SKU',
'description',
'manufacturer',
'MPN',
'URL',
'note',
'base_cost',
'multiple',
'packaging',
'lead_time'
]
class EditPriceBreakForm(HelperForm):
""" Form for creating / editing a supplier price break """
class Meta:
model = SupplierPriceBreak
fields = [
'part',
'quantity',
'cost',
'currency',
]
| Add option to edit currency | Add option to edit currency
| Python | mit | SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree | ---
+++
@@ -70,5 +70,6 @@
fields = [
'part',
'quantity',
- 'cost'
+ 'cost',
+ 'currency',
] |
824c46b7d3953e1933a72def4edf058a577487ea | byceps/services/attendance/transfer/models.py | byceps/services/attendance/transfer/models.py | """
byceps.services.attendance.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from attr import attrib, attrs
from ....services.seating.models.seat import Seat
from ....services.user.models.user import User
@attrs(slots=True) # Not yet frozen b/c models are not immutable.
class Attendee:
user = attrib(type=User)
seat = attrib(type=Seat)
checked_in = attrib(type=bool)
| """
byceps.services.attendance.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from dataclasses import dataclass
from ....services.seating.models.seat import Seat
from ....services.user.models.user import User
@dataclass # Not yet frozen b/c models are not immutable.
class Attendee:
user: User
seat: Seat
checked_in: bool
| Use `dataclass` instead of `attr` for attendance model | Use `dataclass` instead of `attr` for attendance model
| Python | bsd-3-clause | m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps | ---
+++
@@ -6,14 +6,14 @@
:License: Modified BSD, see LICENSE for details.
"""
-from attr import attrib, attrs
+from dataclasses import dataclass
from ....services.seating.models.seat import Seat
from ....services.user.models.user import User
-@attrs(slots=True) # Not yet frozen b/c models are not immutable.
+@dataclass # Not yet frozen b/c models are not immutable.
class Attendee:
- user = attrib(type=User)
- seat = attrib(type=Seat)
- checked_in = attrib(type=bool)
+ user: User
+ seat: Seat
+ checked_in: bool |
7d52ee6030b2e59a6b6cb6dce78686e8d551281b | examples/horizontal_boxplot.py | examples/horizontal_boxplot.py | """
Horizontal boxplot with observations
====================================
_thumb: .7, .37
"""
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="ticks")
# Initialize the figure
f, ax = plt.subplots(figsize=(7, 6))
ax.set_xscale("log")
# Load the example planets dataset
planets = sns.load_dataset("planets")
# Plot the orbital period with horizontal boxes
sns.boxplot(x="distance", y="method", data=planets,
whis=np.inf, palette="vlag")
# Add in points to show each observation
sns.swarmplot(x="distance", y="method", data=planets,
size=2, color=".3", linewidth=0)
# Make the quantitative axis logarithmic
ax.xaxis.grid(True)
ax.set(ylabel="")
sns.despine(trim=True, left=True)
| """
Horizontal boxplot with observations
====================================
_thumb: .7, .37
"""
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="ticks")
# Initialize the figure with a logarithmic x axis
f, ax = plt.subplots(figsize=(7, 6))
ax.set_xscale("log")
# Load the example planets dataset
planets = sns.load_dataset("planets")
# Plot the orbital period with horizontal boxes
sns.boxplot(x="distance", y="method", data=planets,
whis=np.inf, palette="vlag")
# Add in points to show each observation
sns.swarmplot(x="distance", y="method", data=planets,
size=2, color=".3", linewidth=0)
# Tweak the visual presentation
ax.xaxis.grid(True)
ax.set(ylabel="")
sns.despine(trim=True, left=True)
| Fix comments in horizontal boxplot example | Fix comments in horizontal boxplot example
| Python | bsd-3-clause | mwaskom/seaborn,phobson/seaborn,arokem/seaborn,lukauskas/seaborn,anntzer/seaborn,arokem/seaborn,sauliusl/seaborn,mwaskom/seaborn,phobson/seaborn,petebachant/seaborn,anntzer/seaborn,lukauskas/seaborn | ---
+++
@@ -7,9 +7,10 @@
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
+
sns.set(style="ticks")
-# Initialize the figure
+# Initialize the figure with a logarithmic x axis
f, ax = plt.subplots(figsize=(7, 6))
ax.set_xscale("log")
@@ -24,8 +25,7 @@
sns.swarmplot(x="distance", y="method", data=planets,
size=2, color=".3", linewidth=0)
-
-# Make the quantitative axis logarithmic
+# Tweak the visual presentation
ax.xaxis.grid(True)
ax.set(ylabel="")
sns.despine(trim=True, left=True) |
7bc23b277e53bb1c826dc6af7296b688ba9a97f1 | blimp_boards/users/urls.py | blimp_boards/users/urls.py | from django.conf.urls import patterns, url
from . import views
api_urlpatterns = patterns(
# Prefix
'',
(r'auth/signin/$', views.SigninAPIView.as_view()),
(r'auth/signup/$', views.SignupAPIView.as_view()),
(r'auth/username/validate/$', views.ValidateUsernameAPIView.as_view()),
(r'auth/forgot_password/$', views.ForgotPasswordAPIView.as_view()),
(r'auth/reset_password/$', views.ResetPasswordAPIView.as_view()),
(r'users/me/$', views.UserSettingsAPIView.as_view()),
(r'users/me/change_password/$', views.ChangePasswordAPIView.as_view()),
)
urlpatterns = patterns(
# Prefix
'',
url(r'signin/$',
views.SigninValidateTokenHTMLView.as_view(),
name='auth-signin'),
url(r'signup/$',
views.SignupValidateTokenHTMLView.as_view(),
name='auth-signup'),
url(r'reset_password/$',
views.ResetPasswordHTMLView.as_view(),
name='auth-reset-password'),
)
| from django.conf.urls import patterns, url
from . import views
api_urlpatterns = patterns(
# Prefix
'',
(r'auth/signin/$', views.SigninAPIView.as_view()),
(r'auth/signup/$', views.SignupAPIView.as_view()),
(r'auth/username/validate/$', views.ValidateUsernameAPIView.as_view()),
(r'auth/forgot_password/$', views.ForgotPasswordAPIView.as_view()),
(r'auth/reset_password/$', views.ResetPasswordAPIView.as_view()),
(r'users/me/$', views.UserSettingsAPIView.as_view()),
(r'users/me/change_password/$', views.ChangePasswordAPIView.as_view()),
)
urlpatterns = patterns(
# Prefix
'',
url(r'signin/$',
views.SigninValidateTokenHTMLView.as_view(),
name='auth-signin'),
url(r'signup/',
views.SignupValidateTokenHTMLView.as_view(),
name='auth-signup'),
url(r'reset_password/$',
views.ResetPasswordHTMLView.as_view(),
name='auth-reset-password'),
)
| Change to signup url to allow steps | Change to signup url to allow steps | Python | agpl-3.0 | GetBlimp/boards-backend,jessamynsmith/boards-backend,jessamynsmith/boards-backend | ---
+++
@@ -25,7 +25,7 @@
views.SigninValidateTokenHTMLView.as_view(),
name='auth-signin'),
- url(r'signup/$',
+ url(r'signup/',
views.SignupValidateTokenHTMLView.as_view(),
name='auth-signup'),
|
582c0e22c2d91b11a667933532b0a802757b26f6 | templates/dns_param_template.py | templates/dns_param_template.py | import string
template = string.Template("""#
# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
#
# DNS configuration options
#
[DEFAULT]
# dns_config_file=dns_config.xml
hostip=$__contrail_host_ip__ # Resolved IP of `hostname`
hostname=$__contrail_hostname__ # Retrieved as `hostname`
# http_server_port=8092
# log_category=
# log_disable=0
log_file=/var/log/contrail/dns.log
# log_files_count=10
# log_file_size=10485760 # 10MB
# log_level=SYS_NOTICE
# log_local=0
# test_mode=0
[COLLECTOR]
# port=8086
# server= # Provided by discovery server
[DISCOVERY]
# port=5998
server=$__contrail_discovery_ip__ # discovery-server IP address
[IFMAP]
certs_store=$__contrail_cert_ops__
password=$__contrail_ifmap_paswd__
# server_url= # Provided by discovery server, e.g. https://127.0.0.1:8443
user=$__contrail_ifmap_usr__
""")
| import string
template = string.Template("""#
# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
#
# DNS configuration options
#
[DEFAULT]
# dns_config_file=dns_config.xml
hostip=$__contrail_host_ip__ # Resolved IP of `hostname`
hostname=$__contrail_hostname__ # Retrieved as `hostname`
# http_server_port=8092
# log_category=
# log_disable=0
log_file=/var/log/contrail/dns.log
# log_files_count=10
# log_file_size=1048576 # 1MB
# log_level=SYS_NOTICE
# log_local=0
# test_mode=0
[COLLECTOR]
# port=8086
# server= # Provided by discovery server
[DISCOVERY]
# port=5998
server=$__contrail_discovery_ip__ # discovery-server IP address
[IFMAP]
certs_store=$__contrail_cert_ops__
password=$__contrail_ifmap_paswd__
# server_url= # Provided by discovery server, e.g. https://127.0.0.1:8443
user=$__contrail_ifmap_usr__
""")
| Change log file size to 1MB | Change log file size to 1MB
| Python | apache-2.0 | Juniper/contrail-provisioning,Juniper/contrail-provisioning | ---
+++
@@ -15,7 +15,7 @@
# log_disable=0
log_file=/var/log/contrail/dns.log
# log_files_count=10
-# log_file_size=10485760 # 10MB
+# log_file_size=1048576 # 1MB
# log_level=SYS_NOTICE
# log_local=0
# test_mode=0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.