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 |
|---|---|---|---|---|---|---|---|---|---|---|
f9d0d6af3d4b2d4b4ca88ba5aa0565f29528bf96 | snakeplan/projects/urls.py | snakeplan/projects/urls.py | from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('snakeplan.projects.views',
(r'^$', 'projects.index'),
(r'^story/(.*)/', 'stories.index'),
(r'^iteration/(.*)/', 'iterations.index'),
(r'^create/', 'projects.create_project'),
url(r'^(.*)/', 'projects.project_iterations', n... | from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('snakeplan.projects.views',
(r'^$', 'projects.index'),
(r'^story/(.*)/', 'stories.index'),
(r'^iteration/(.*)/', 'iterations.index'),
(r'^create/', 'projects.create_project'),
(r'^(.*)/iterations', 'projects.project_iterati... | Add /project/<id>/iterations route for the hell of it(I think it makes more sense) | Add /project/<id>/iterations route for the hell of it(I think it makes more sense)
| Python | apache-2.0 | mcrute/snakeplan,mcrute/snakeplan,mcrute/snakeplan | ---
+++
@@ -6,5 +6,6 @@
(r'^story/(.*)/', 'stories.index'),
(r'^iteration/(.*)/', 'iterations.index'),
(r'^create/', 'projects.create_project'),
+ (r'^(.*)/iterations', 'projects.project_iterations'),
url(r'^(.*)/', 'projects.project_iterations', name='project_iterations'),
) |
43bd5b33a0342213e2c8e1782744624fadead61e | partner_compassion/model/mail_followers.py | partner_compassion/model/mail_followers.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __openerp__.p... | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __openerp__.p... | Fix typo in follower restrictions | Fix typo in follower restrictions
| Python | agpl-3.0 | CompassionCH/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,ecino/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland | ---
+++
@@ -34,7 +34,7 @@
mail_restrict_follower_selection
"""
model = vals['res_model']
- res_id = vals['res_id']
+ res_id = vals['partner_id']
domain = self._mail_restrict_follower_selection_get_domain(model)
allowed = self.env['res.partner'].search(eval(do... |
35966403b243f7ac7effa0bc69e2938b9324278b | tools/lxlcrawler/list_sao_terms.py | tools/lxlcrawler/list_sao_terms.py | #!/usr/bin/env python3
import lxlcrawler
start_url = "https://id.kb.se/find?q=*&limit=200&inScheme.@id=https://id.kb.se/term/sao"
for i, item in enumerate(lxlcrawler.crawl(start_url)):
print("[{}] {}, {}".format(i + 1, item['@id'], item.get('prefLabel')))
| #!/usr/bin/env python3
import lxlcrawler
start_url = "https://id.kb.se/find?q=*&_limit=1024&inScheme.@id=https://id.kb.se/term/sao"
for i, item in enumerate(lxlcrawler.crawl(start_url)):
print("[{}] {}, {}".format(i + 1, item['@id'], item.get('prefLabel')))
| Change limit in lxlcrawler sao example script | Change limit in lxlcrawler sao example script
| Python | cc0-1.0 | Kungbib/datalab,Kungbib/datalab | ---
+++
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
import lxlcrawler
-start_url = "https://id.kb.se/find?q=*&limit=200&inScheme.@id=https://id.kb.se/term/sao"
+start_url = "https://id.kb.se/find?q=*&_limit=1024&inScheme.@id=https://id.kb.se/term/sao"
for i, item in enumerate(lxlcrawler.crawl(start_url)):
prin... |
e37ae5f799e02cc2308793af585316557e59e6cf | froide/redaction/utils.py | froide/redaction/utils.py | import os
import base64
import tempfile
import subprocess
def convert_to_pdf(post):
path = tempfile.mkdtemp()
pagenr = 1
while True:
data = post.get('page_%s' % pagenr)
if data is None:
break
if not data.startswith('data:image/png;base64,'):
continue
... | import os
import base64
import tempfile
import subprocess
def convert_to_pdf(post):
path = tempfile.mkdtemp()
pagenr = 1
while True:
data = post.get('page_%s' % pagenr)
if data is None:
break
if not data.startswith('data:image/png;base64,'):
continue
... | Write to png file in binary mode | Write to png file in binary mode | Python | mit | stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide | ---
+++
@@ -15,7 +15,8 @@
continue
prefix, data = data.split(',', 1)
filename = os.path.join(path, 'page_%03d.png' % pagenr)
- open(filename, 'w').write(base64.b64decode(data))
+ with open(filename, 'wb') as f:
+ f.write(base64.b64decode(data))
pagenr +... |
2a5b68a9357ac576a684880549a93f32335e5761 | pyramid_zipkin/__init__.py | pyramid_zipkin/__init__.py | from pyramid.tweens import MAIN
def includeme(config): # pragma: no cover
"""
:type config: :class:`pyramid.config.Configurator`
"""
config.add_tween('pyramid_zipkin.zipkin.zipkin_tween', over=MAIN)
| from pyramid.tweens import EXCVIEW
def includeme(config): # pragma: no cover
"""
:type config: :class:`pyramid.config.Configurator`
"""
config.add_tween('pyramid_zipkin.zipkin.zipkin_tween', over=EXCVIEW)
| Change to over=EXCVIEW to make response status work correctly | Change to over=EXCVIEW to make response status work correctly
| Python | apache-2.0 | Yelp/pyramid_zipkin,bplotnick/pyramid_zipkin | ---
+++
@@ -1,8 +1,8 @@
-from pyramid.tweens import MAIN
+from pyramid.tweens import EXCVIEW
def includeme(config): # pragma: no cover
"""
:type config: :class:`pyramid.config.Configurator`
"""
- config.add_tween('pyramid_zipkin.zipkin.zipkin_tween', over=MAIN)
+ config.add_tween('pyramid_z... |
3cfbe13f53837a0cb5065b37f4c0a6ae5c9dd50d | cutthroat/views/signin.py | cutthroat/views/signin.py | from tornado import template
from tornado.web import authenticated
from cutthroat.handlers import ViewHandler
class SignIn(ViewHandler):
"""SignIn"""
def get(self):
self.render("signin.html")
class Landing(ViewHandler):
"""Landing"""
@authenticated
def get(self):
_, player =... | from tornado import template
from tornado.web import authenticated
from cutthroat.handlers import ViewHandler
class SignIn(ViewHandler):
"""SignIn"""
def get(self):
self.render("signin.html")
class Landing(ViewHandler):
"""Landing"""
@authenticated
def get(self):
_, player =... | Add room redirect clause to Landing | Add room redirect clause to Landing
| Python | agpl-3.0 | hfaran/LivesPool,hfaran/LivesPool,hfaran/LivesPool,hfaran/LivesPool | ---
+++
@@ -22,5 +22,8 @@
if player["current_game_id"]:
raise NotImplementedError
# self.redirect("<Insert URL to game view here>")
+ elif player["current_room"]:
+ raise NotImplementedError
+ # self.redirect("<Insert URL to room page here>")
el... |
5f0a4f33196c368318dba21aaa66956d4b973d60 | usig_normalizador_amba/settings.py | usig_normalizador_amba/settings.py | # coding: UTF-8
from __future__ import absolute_import
default_settings = {
'callejero_amba_server': 'http://servicios.usig.buenosaires.gob.ar/callejero-amba/',
'callejero_caba_server': 'http://usig.buenosaires.gov.ar/servicios/Callejero',
}
# Tipo de normalizacion
CALLE = 0
CALLE_ALTURA = 1
CALLE_Y_CALLE = 2... | # coding: UTF-8
from __future__ import absolute_import
default_settings = {
'callejero_amba_server': 'http://servicios.usig.buenosaires.gob.ar/callejero-amba/',
'callejero_caba_server': 'http://servicios.usig.buenosaires.gob.ar/callejero',
}
# Tipo de normalizacion
CALLE = 0
CALLE_ALTURA = 1
CALLE_Y_CALLE = 2... | Fix a la url del callejero CABA | Fix a la url del callejero CABA
| Python | mit | usig/normalizador-amba,hogasa/normalizador-amba | ---
+++
@@ -3,7 +3,7 @@
default_settings = {
'callejero_amba_server': 'http://servicios.usig.buenosaires.gob.ar/callejero-amba/',
- 'callejero_caba_server': 'http://usig.buenosaires.gov.ar/servicios/Callejero',
+ 'callejero_caba_server': 'http://servicios.usig.buenosaires.gob.ar/callejero',
}
# Tipo... |
8830b0e726a671fa2b0bbafd1487148ae23fc1d4 | admin/forms.py | admin/forms.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import riak
from wtforms.fields import TextField, TextAreaField, SelectField
from wtforms.validators import Required
from wtforms_tornado import Form
class ConnectionForm(Form):
name = TextField(validators=[Required()])
conection = TextField(validators=[Required(... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import riak
from wtforms.fields import TextField, TextAreaField, SelectField
from wtforms.validators import Required
from wtforms_tornado import Form
def ObjGenerate(bucket, key, value=None, _type=tuple):
myClient = riak.RiakClient(protocol='http',
... | Create new method object generate get riak bucket and generate tuple or list | Create new method object generate
get riak bucket and generate tuple or list
| Python | mit | chrisdamba/mining,seagoat/mining,avelino/mining,jgabriellima/mining,AndrzejR/mining,jgabriellima/mining,mining/mining,mlgruby/mining,chrisdamba/mining,mlgruby/mining,mlgruby/mining,seagoat/mining,AndrzejR/mining,avelino/mining,mining/mining | ---
+++
@@ -7,24 +7,30 @@
from wtforms_tornado import Form
+def ObjGenerate(bucket, key, value=None, _type=tuple):
+ myClient = riak.RiakClient(protocol='http',
+ http_port=8098,
+ host='127.0.0.1')
+ myBucket = myClient.bucket('openmining-admin')... |
46e9db6167a9c4f7f778381da888537c00d35bfd | emailsupport/admin.py | emailsupport/admin.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from models import Email, Resolution
class ResolutionInline(admin.StackedInline):
model = Resolution
max_num = 1
class EmailAdmin(admin.ModelAdmin):
list_display = ('subject', 'submitter', 'get_state_displ... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from models import Email, Resolution
class ResolutionInline(admin.StackedInline):
model = Resolution
max_num = 1
class EmailAdmin(admin.ModelAdmin):
list_display = ('subject', 'submitter', 'get_state_displ... | Add prev. and next email to context only if exist original (current) | Add prev. and next email to context only if exist original (current)
| Python | mit | rosti-cz/django-emailsupport | ---
+++
@@ -32,8 +32,9 @@
def render_change_form(self, *args, **kwargs):
response = super(EmailAdmin, self).render_change_form(*args, **kwargs)
email = response.context_data['original']
- response.context_data['previous_email'] = self.get_previous_email(email)
- response.context_d... |
9359a236bc955a84b53417246fb5b4b2e3d04389 | i18n/tests/loader_tests.py | i18n/tests/loader_tests.py | import unittest
import i18n
class TestFileLoader(unittest.TestCase):
def test_dummy(self):
self.assertTrue(hasattr(i18n, 'resource_loader'))
suite = unittest.TestLoader().loadTestsFromTestCase(TestFileLoader)
unittest.TextTestRunner(verbosity=2).run(suite)
| import unittest
from i18n import resource_loader
class TestFileLoader(unittest.TestCase):
def test_nonexisting_extension(self):
self.assertRaises(resource_loader.I18nFileLoadError, resource_loader.load_resource, "foo.bar")
suite = unittest.TestLoader().loadTestsFromTestCase(TestFileLoader)
unittest.Text... | Add test for nonexisting file extensions. | Add test for nonexisting file extensions.
| Python | mit | tuvistavie/python-i18n | ---
+++
@@ -1,10 +1,11 @@
import unittest
-import i18n
+from i18n import resource_loader
class TestFileLoader(unittest.TestCase):
- def test_dummy(self):
- self.assertTrue(hasattr(i18n, 'resource_loader'))
+ def test_nonexisting_extension(self):
+ self.assertRaises(resource_loader.I18nFileLo... |
d9b46a4d06bf6832aa5dbb394ae97325e0578400 | survey/tests/test_default_settings.py | survey/tests/test_default_settings.py | from survey.tests import BaseTest
from django.test import override_settings
from django.conf import settings
from django.test import tag
from survey import set_default_settings
@tag("set")
@override_settings()
class TestDefaultSettings(BaseTest):
def test_set_choices_separator(self):
url = "/admin/survey/... | from survey.tests import BaseTest
from django.test import override_settings
from django.conf import settings
from survey import set_default_settings
from survey.exporter.tex.survey2tex import Survey2Tex
@override_settings()
class TestDefaultSettings(BaseTest):
def test_set_choices_separator(self):
url = "... | Add - Test for setting ROOT | Add - Test for setting ROOT
| Python | agpl-3.0 | Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey | ---
+++
@@ -1,19 +1,26 @@
from survey.tests import BaseTest
from django.test import override_settings
from django.conf import settings
-from django.test import tag
from survey import set_default_settings
+from survey.exporter.tex.survey2tex import Survey2Tex
-@tag("set")
@override_settings()
class TestDefau... |
b4b905333f8847be730f30fbc53ac7a172195cdc | src/sentry/api/endpoints/group_events.py | src/sentry/api/endpoints/group_events.py | from __future__ import absolute_import
from sentry.api.base import DocSection
from sentry.api.bases import GroupEndpoint
from sentry.api.serializers import serialize
from sentry.api.paginator import DateTimePaginator
from sentry.models import Event, Group
from sentry.utils.apidocs import scenario, attach_scenarios
@... | from __future__ import absolute_import
from sentry.api.base import DocSection
from sentry.api.bases import GroupEndpoint
from sentry.api.serializers import serialize
from sentry.api.paginator import DateTimePaginator
from sentry.models import Event, Group
from sentry.utils.apidocs import scenario, attach_scenarios
@... | Add query param to event list | Add query param to event list
| Python | bsd-3-clause | looker/sentry,BuildingLink/sentry,mvaled/sentry,fotinakis/sentry,zenefits/sentry,BuildingLink/sentry,gencer/sentry,gencer/sentry,JamesMura/sentry,zenefits/sentry,alexm92/sentry,ifduyue/sentry,BuildingLink/sentry,JamesMura/sentry,JackDanger/sentry,gencer/sentry,fotinakis/sentry,nicholasserra/sentry,JackDanger/sentry,mva... | ---
+++
@@ -36,6 +36,12 @@
group=group
)
+ query = request.GET.get('query')
+ if query:
+ events = events.filter(
+ message__iexact=query,
+ )
+
return self.paginate(
request=request,
queryset=events, |
4842b266bb1649477f41e0b914fc16be94696c01 | handlers/websockets.py | handlers/websockets.py | from tornado.websocket import WebSocketHandler
from zmq.eventloop.zmqstream import ZMQStream
from pocs.utils.logger import get_logger
clients = []
class PanWebSocket(WebSocketHandler):
logger = get_logger(self)
def open(self, channel):
""" Client opening connection to unit """
if channel i... | import logging
from tornado.websocket import WebSocketHandler
from zmq.eventloop.zmqstream import ZMQStream
clients = []
class PanWebSocket(WebSocketHandler):
def open(self, channel):
""" Client opening connection to unit """
if channel is None:
channel = self.settings['name']
... | Clean up the logging ofr PAWS | Clean up the logging ofr PAWS
| Python | mit | panoptes/PAWS,panoptes/PAWS,panoptes/PAWS,panoptes/PAWS | ---
+++
@@ -1,13 +1,12 @@
+import logging
+
from tornado.websocket import WebSocketHandler
from zmq.eventloop.zmqstream import ZMQStream
-
-from pocs.utils.logger import get_logger
clients = []
class PanWebSocket(WebSocketHandler):
- logger = get_logger(self)
def open(self, channel):
""" ... |
6f5be9af15898f089c3ee83ca1f05fbd4570fcfa | src/cms/apps/news/models.py | src/cms/apps/news/models.py | """Models used by the news publication application."""
from django.db import models
from cms.apps.pages.models import Page, PageBase, PageField, HtmlField
from cms.apps.news.content import NewsFeed, NewsArticle
class Article(PageBase):
"""A news article."""
news_feed = PageField(Page,
... | """Models used by the news publication application."""
from django.db import models
from cms.apps.pages.models import Page, PageBase, PageField, HtmlField
from cms.apps.news.content import NewsFeed, NewsArticle
class Article(PageBase):
"""A news article."""
news_feed = PageField(Page,
... | Set unique together on news article. | Set unique together on news article. | Python | bsd-3-clause | lewiscollard/cms,etianen/cms,etianen/cms,danielsamuels/cms,jamesfoley/cms,lewiscollard/cms,jamesfoley/cms,dan-gamble/cms,lewiscollard/cms,jamesfoley/cms,dan-gamble/cms,dan-gamble/cms,jamesfoley/cms,danielsamuels/cms,etianen/cms,danielsamuels/cms | ---
+++
@@ -31,8 +31,7 @@
class Meta:
verbose_name = "news article"
-
-
+ unique_together = (("news_feed", "url_title",),)
Page.register_content(NewsFeed) |
824ead425a80feeb7dc1fbd6505cf50c6e2ffd90 | ui_extensions/playground/views.py | ui_extensions/playground/views.py | from django.shortcuts import render
from extensions.views import admin_extension, tab_extension, \
TabExtensionDelegate, dashboard_extension
from resourcehandlers.models import ResourceHandler
from utilities.logger import ThreadLogger
logger = ThreadLogger(__name__)
class ResourceHandlerTabDelegate(TabExtension... | from django.shortcuts import render
from extensions.views import admin_extension, tab_extension, \
TabExtensionDelegate, dashboard_extension
from resourcehandlers.models import ResourceHandler
from utilities.logger import ThreadLogger
logger = ThreadLogger(__name__)
class ResourceHandlerTabDelegate(TabExtension... | Add more info to TabDelegate example | Add more info to TabDelegate example
Provide details on how to limit a tab delegate to a specific resource handler.
| Python | apache-2.0 | CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge | ---
+++
@@ -9,6 +9,11 @@
class ResourceHandlerTabDelegate(TabExtensionDelegate):
+ # We want this tab to display for all resource handlers, so we return
+ # True regardless of what Resource Handler is being displayed.
+ # If the goal is to target a specific Resource
+ # Handler, say AWSHandler, the b... |
b496353400718ef822b686c2e8d452e0df305aa8 | ansible/roles/jenkins/files/scripts/get_siteconfig.py | ansible/roles/jenkins/files/scripts/get_siteconfig.py | import os, yaml
from nucleator.cli import properties
# Read sources.yml
# find the src= for name: siteconfig
# TODO handle version?
import yaml
sources = os.path.join(properties.NUCLEATOR_CONFIG_DIR, "sources.yml")
stream = open(sources, 'r')
slist = yaml.load(stream)
for sname in slist:
if sname['name'] == "site... | # Copyright 2015 47Lining LLC.
#
# 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... | Remove repo URL prefix of git+ | Remove repo URL prefix of git+
| Python | apache-2.0 | 47lining/nucleator-core-builder,47lining/nucleator-core-builder,47lining/nucleator-core-builder | ---
+++
@@ -1,9 +1,27 @@
+# Copyright 2015 47Lining LLC.
+#
+# 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 ap... |
1f2ad74d0ba33de7a964c5d675493434bd6fde74 | days/apps/days/models.py | days/apps/days/models.py | """Models for the days app."""
from django.db import models
class Event(models.Model):
"""Representation of a notable historical event."""
date = models.DateField(
help_text='When the event occurred.'
)
description = models.TextField(
help_text='A description of the event.'
)
... | """Models for the days app."""
from django.db import models
class Event(models.Model):
"""Representation of a notable historical event."""
# How to perform lookups on this field: https://docs.djangoproject.com/en/1.9/ref/models/querysets/#month
date = models.DateField(
help_text='When the event oc... | Document info for performing lookups on date fields | Document info for performing lookups on date fields
| Python | mit | rlucioni/days | ---
+++
@@ -4,6 +4,7 @@
class Event(models.Model):
"""Representation of a notable historical event."""
+ # How to perform lookups on this field: https://docs.djangoproject.com/en/1.9/ref/models/querysets/#month
date = models.DateField(
help_text='When the event occurred.'
) |
25cebf23c84d8e1136a3e2b503e574aa1c7263e6 | dbaas_zabbix/dbaas_api.py | dbaas_zabbix/dbaas_api.py | # -*- coding: utf-8 -*-
class DatabaseAsAServiceApi(object):
def __init__(self, databaseinfra):
self.databaseinfra = databaseinfra
self.driver = self.get_databaseinfra_driver()
self.database_instances = self.get_database_instances()
def get_all_instances(self, ):
return self.d... | # -*- coding: utf-8 -*-
class DatabaseAsAServiceApi(object):
def __init__(self, databaseinfra):
self.databaseinfra = databaseinfra
self.driver = self.get_databaseinfra_driver()
self.database_instances = self.get_database_instances()
def get_all_instances(self, ):
return self.d... | Add databaseinfra get engine name | Add databaseinfra get engine name
| Python | bsd-3-clause | globocom/dbaas-zabbix,globocom/dbaas-zabbix | ---
+++
@@ -34,3 +34,6 @@
def get_databaseinfra_availability(self):
return self.databaseinfra.plan.is_ha
+
+ def get_databaseinfra_engine_name(self):
+ return self.databaseinfra.engine.engine_type.name |
ab9a38793645a9c61cf1c320e5a4db9bf7b03ccf | grow/deployments/utils.py | grow/deployments/utils.py | from .indexes import messages
import git
class Error(Exception):
pass
class NoGitHeadError(Error, ValueError):
pass
def create_commit_message(repo):
message = messages.CommitMessage()
try:
commit = repo.head.commit
except ValueError:
raise NoGitHeadError('On initial commit, no HEAD yet.')
try:... | from .indexes import messages
import git
class Error(Exception):
pass
class NoGitHeadError(Error, ValueError):
pass
def create_commit_message(repo):
message = messages.CommitMessage()
try:
commit = repo.head.commit
except ValueError:
raise NoGitHeadError('On initial commit, no HEAD yet.')
try:... | Allow operating in an environment with a detached HEAD. | Allow operating in an environment with a detached HEAD.
| Python | mit | grow/pygrow,denmojo/pygrow,grow/grow,grow/grow,grow/pygrow,codedcolors/pygrow,grow/grow,grow/pygrow,denmojo/pygrow,denmojo/pygrow,denmojo/pygrow,codedcolors/pygrow,codedcolors/pygrow,grow/grow | ---
+++
@@ -24,7 +24,11 @@
message.has_unstaged_changes = has_unstaged_changes
message.sha = commit.hexsha
message.message = commit.message
- message.branch = repo.head.ref.name
+ try:
+ message.branch = repo.head.ref.name
+ except TypeError:
+ # Allow operating in an environment with a detached HEA... |
2b39c89e86ca00ca6bbca88d68e1bccf9c94efd4 | grab/spider/decorators.py | grab/spider/decorators.py | import functools
import logging
from weblib.error import ResponseNotValid
def integrity(integrity_func, integrity_errors=(ResponseNotValid,),
ignore_errors=()):
"""
Args:
:param integrity_func: couldb callable or string contains name of
method to call
"""
def build_d... | import functools
import logging
from weblib.error import ResponseNotValid
def integrity(integrity_func, integrity_errors=(ResponseNotValid,),
ignore_errors=()):
"""
Args:
:param integrity_func: couldb callable or string contains name of
method to call
"""
def build_d... | Fix exception handling in integrity decorator | Fix exception handling in integrity decorator
| Python | mit | SpaceAppsXploration/grab,alihalabyah/grab,giserh/grab,raybuhr/grab,SpaceAppsXploration/grab,maurobaraldi/grab,lorien/grab,DDShadoww/grab,pombredanne/grab-1,maurobaraldi/grab,lorien/grab,raybuhr/grab,DDShadoww/grab,huiyi1990/grab,liorvh/grab,shaunstanislaus/grab,istinspring/grab,kevinlondon/grab,pombredanne/grab-1,huiyi... | ---
+++
@@ -35,6 +35,8 @@
yield task.clone(refresh_cache=True)
self.stat.inc(ex.__class__.__name__)
#logging.error(ex)
+ except Exception as ex:
+ raise
else:
grab.meta['integrity_error'] = None
... |
257b186eb64638d6638be93633d4db02ce14d390 | docker_log_es/storage.py | docker_log_es/storage.py | #!/usr/bin/env python
# encoding: utf-8
import socket
from os import environ as env
from tornado.netutil import Resolver
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
class UnixResolver(Resolver):
def initialize(self, resolver):
self.resolver = resolver
def close(self):
... | #!/usr/bin/env python
# encoding: utf-8
import socket
from os import environ as env
from tornado.netutil import Resolver
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
class UnixResolver(Resolver):
def initialize(self, resolver):
self.resolver = resolver
def close(self):
... | Connect to the "elasticsearch" host by default | Connect to the "elasticsearch" host by default
| Python | mit | ei-grad/docker-log-es | ---
+++
@@ -46,5 +46,5 @@
class Storage(object):
CONTAINERS = set([])
DOCKER = env.get('DOCKER_HOST', 'unix:///var/run/docker.sock')
- ELASTICSEARCH = env.get('ELASTICSEARCH', 'http://127.0.0.1:9200')
+ ELASTICSEARCH = env.get('ELASTICSEARCH', 'http://elasticsearch:9200')
http = AsyncHTTPClient(... |
27a944d5fc74972a90e8dd69879ebc27c4412b99 | test/python_api/default-constructor/sb_frame.py | test/python_api/default-constructor/sb_frame.py | """
Fuzz tests an object after the default construction to make sure it does not crash lldb.
"""
import sys
import lldb
def fuzz_obj(obj):
obj.GetFrameID()
obj.GetPC()
obj.SetPC(0xffffffff)
obj.GetSP()
obj.GetFP()
obj.GetPCAddress()
obj.GetSymbolContext(0)
obj.GetModule()
obj.GetCo... | """
Fuzz tests an object after the default construction to make sure it does not crash lldb.
"""
import sys
import lldb
def fuzz_obj(obj):
obj.GetFrameID()
obj.GetPC()
obj.SetPC(0xffffffff)
obj.GetSP()
obj.GetFP()
obj.GetPCAddress()
obj.GetSymbolContext(0)
obj.GetModule()
obj.GetCo... | Add FindValue() and WatchValue() fuzz calls to the mix. | Add FindValue() and WatchValue() fuzz calls to the mix.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@140439 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb | ---
+++
@@ -31,5 +31,8 @@
obj.GetRegisters()
obj.FindVariable("my_var")
obj.FindVariable("my_var", lldb.eDynamicCanRunTarget)
+ obj.FindValue("your_var", lldb.eValueTypeVariableGlobal)
+ obj.FindValue("your_var", lldb.eValueTypeVariableStatic, lldb.eDynamicCanRunTarget)
+ obj.WatchValue("globa... |
5ff559f386957844f32d6f96987bcece5c9a43cc | webserver/profiles/templatetags/profile_tags.py | webserver/profiles/templatetags/profile_tags.py | """
gravatar_url from https://en.gravatar.com/site/implement/images/django/
"""
from django import template
from django.conf import settings
import urllib
import hashlib
register = template.Library()
class GravatarUrlNode(template.Node):
def __init__(self, email):
self.email = template.Variable(email)
... | """
gravatar_url from https://en.gravatar.com/site/implement/images/django/
"""
from django import template
from django.conf import settings
import urllib
import hashlib
register = template.Library()
class GravatarUrlNode(template.Node):
def __init__(self, email):
self.email = template.Variable(email)
... | Use secure gravatar and fix gravatar image size | Use secure gravatar and fix gravatar image size
Fixes #106
Fixes #112
| Python | bsd-3-clause | siggame/webserver,siggame/webserver,siggame/webserver | ---
+++
@@ -20,9 +20,10 @@
return ''
email_hash = hashlib.md5(email.lower()).hexdigest()
- query_str = urllib.urlencode({'d': 'megaminerai.com/static/img/default_profile_image.png'})
+ query_str = urllib.urlencode({'d': 'megaminerai.com/static/img/default_profile_image.png',
+ ... |
ff445030337b087513114f327b05e89fdfc7d31d | test_sempai.py | test_sempai.py | import jsonsempai
import os
import shutil
import sys
import tempfile
TEST_FILE = '''{
"three": 3
}'''
class TestSempai(object):
def setup(self):
self.direc = tempfile.mkdtemp(prefix='jsonsempai')
sys.path.append(self.direc)
with open(os.path.join(self.direc, 'test_sempai.json'), 'w') a... | import jsonsempai
import os
import shutil
import sys
import tempfile
TEST_FILE = '''{
"three": 3
}'''
class TestSempai(object):
def setup(self):
self.direc = tempfile.mkdtemp(prefix='jsonsempai')
sys.path.append(self.direc)
with open(os.path.join(self.direc, 'sempai.json'), 'w') as f:
... | Add a couple more tests | Add a couple more tests
| Python | mit | kragniz/json-sempai | ---
+++
@@ -16,11 +16,20 @@
self.direc = tempfile.mkdtemp(prefix='jsonsempai')
sys.path.append(self.direc)
- with open(os.path.join(self.direc, 'test_sempai.json'), 'w') as f:
+ with open(os.path.join(self.direc, 'sempai.json'), 'w') as f:
f.write(TEST_FILE)
def t... |
d594747d7f5027b6994d98eaa17ed59d6dcb40de | tests/model/test_pwave_classifiers.py | tests/model/test_pwave_classifiers.py | from unittest import TestCase
import numpy as np
from construe.knowledge.abstraction_patterns.segmentation.pwave import _CLASSIFIERS as classifier
class TestClassifier(TestCase):
def test_classifier(self):
limb = classifier[0]
prec = classifier[1]
X_test = np.loadtxt("pw_samples.csv", del... | from unittest import TestCase
import os
import numpy as np
from construe.knowledge.abstraction_patterns.segmentation.pwave import _CLASSIFIERS as classifier
path = os.path.dirname(__file__)
class TestClassifier(TestCase):
def test_classifier(self):
limb = classifier[0]
prec = classifier[1]
... | Fix test path to file dir to be able to load classifier data | Fix test path to file dir to be able to load classifier data
| Python | agpl-3.0 | citiususc/construe,citiususc/construe,citiususc/construe | ---
+++
@@ -1,6 +1,9 @@
from unittest import TestCase
+import os
import numpy as np
from construe.knowledge.abstraction_patterns.segmentation.pwave import _CLASSIFIERS as classifier
+
+path = os.path.dirname(__file__)
class TestClassifier(TestCase):
@@ -8,7 +11,7 @@
limb = classifier[0]
prec... |
183234c5b66d12ffa3e57b042dc06a34e60084d2 | controllers/main.py | controllers/main.py | # -*- coding: utf-8 -*-
from odoo import http
from odoo.http import request
class Website_coupon(http.Controller):
@http.route(['/shop/apply_coupon'], type='json', auth="public", website=True)
def shop_apply_coupon(self, promo_code, **post):
order = request.website.sale_get_order()
coupon_stat... | # -*- coding: utf-8 -*-
from odoo import http
from odoo.http import request
class Website_coupon(http.Controller):
@http.route(['/shop/apply_coupon'], type='json', auth="public", website=True)
def shop_apply_coupon(self, promo_code, **post):
order = request.website.sale_get_order()
coupon_stat... | Allow public users to use coupons on website | [FIX] website_sale_coupon: Allow public users to use coupons on website
| Python | agpl-3.0 | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo | ---
+++
@@ -7,5 +7,5 @@
@http.route(['/shop/apply_coupon'], type='json', auth="public", website=True)
def shop_apply_coupon(self, promo_code, **post):
order = request.website.sale_get_order()
- coupon_status = request.env['sale.coupon.apply.code'].apply_coupon(order, promo_code)
+ cou... |
c9940a91dd78eb2215559f02b356e15a89fcea28 | indra/tests/test_eidos.py | indra/tests/test_eidos.py | import os
from indra.sources import eidos
from indra.statements import Influence
path_this = os.path.dirname(os.path.abspath(__file__))
test_json = os.path.join(path_this, 'eidos_test.json')
def test_process_json():
ep = eidos.process_json_file(test_json)
assert ep is not None
assert len(ep.statements) ... | import os
from indra.sources import eidos
from indra.statements import Influence
path_this = os.path.dirname(os.path.abspath(__file__))
test_json = os.path.join(path_this, 'eidos_test.json')
def test_process_json():
ep = eidos.process_json_file(test_json)
assert ep is not None
assert len(ep.statements) ... | Add tests for eidos found_by annotation | Add tests for eidos found_by annotation
| Python | bsd-2-clause | johnbachman/indra,johnbachman/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,johnbachman/belpy,sorgerlab/belpy,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/indra,sorgerlab/belpy,pvtodorov/indra,johnbachman/indra,bgyori/indra,bgyori/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/indra | ---
+++
@@ -17,6 +17,9 @@
assert stmt.obj_delta.get('polarity') == -1
assert stmt.subj_delta.get('adjectives') == ['large']
assert stmt.obj_delta.get('adjectives') == ['seriously']
+
+ assert(stmt.evidence[0].annotations['found_by'] == \
+ 'causeEffect_ported_syntax_1_verb-${addlabel}')
... |
6d83e409dcf56806b433c10012717b3551c69a4f | kobo/hub/decorators.py | kobo/hub/decorators.py | # -*- coding: utf-8 -*-
import socket
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from kobo.decorators import decorator_with_args
from kobo.django.xmlrpc.decorators import *
def validate_worker(func):
def _new_func(request, *args, **kwargs):
if not request.user.is_authentic... | # -*- coding: utf-8 -*-
import socket
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from kobo.decorators import decorator_with_args
from kobo.django.xmlrpc.decorators import *
def validate_worker(func):
def _new_func(request, *args, **kwargs):
if not request.user.is_authentic... | Remove reverse DNS validation for Kobo worker | Remove reverse DNS validation for Kobo worker
| Python | lgpl-2.1 | release-engineering/kobo,release-engineering/kobo,release-engineering/kobo,release-engineering/kobo | ---
+++
@@ -16,11 +16,6 @@
if getattr(request, 'worker', None) is None:
raise SuspiciousOperation("User doesn't match any worker: %s" % request.user.username)
- fqdn = socket.getfqdn(request.META["REMOTE_ADDR"])
- prefix, hostname = request.user.username.split("/", 1)
- if... |
3d8f50f39f76cbeb07136c75d6e65dc4132d7aa2 | hr_expense_sequence/models/hr_expense_expense.py | hr_expense_sequence/models/hr_expense_expense.py | # -*- encoding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models, fields, api
class HrExpens... | # -*- encoding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models, fields, api
class HrExpens... | Write expense number on account move | Write expense number on account move
| Python | agpl-3.0 | acsone/hr,Antiun/hr,raycarnes/hr,Vauxoo/hr,feketemihai/hr,alanljj/oca_hr,xpansa/hr,thinkopensolutions/hr,open-synergy/hr,yelizariev/hr,microcom/hr,microcom/hr,charbeljc/hr,open-synergy/hr,Endika/hr,iDTLabssl/hr,Endika/hr,hbrunn/hr,alanljj/oca_hr,VitalPet/hr,thinkopensolutions/hr,iDTLabssl/hr,rschnapka/hr,damdam-s/hr,An... | ---
+++
@@ -16,3 +16,11 @@
if vals.get('number', '/') == '/':
vals['number'] = self.env['ir.sequence'].get('hr.expense')
return super(HrExpense, self).create(vals)
+
+ @api.model
+ def account_move_get(self, expense_id):
+ '''Write expense number on account move'''
+ ... |
a22b0c562a332761fb1094ad72ae607810cccc49 | manager/apps/brand/urls.py | manager/apps/brand/urls.py | from django.conf.urls import patterns, url
from manager.apps.brand.views import BrandListView, BrandView
from manager.apps.brand.views import OwnerListView, OwnerView
urlpatterns = patterns(
'',
url(r'^brand$', BrandListView.as_view(), name='brandlist'),
url(r'^brand/(?P<bsin>[1-9A-NP-Z]{6})', BrandView.as... | from django.conf.urls import patterns, url
from manager.apps.brand.views import BrandListView, BrandView
from manager.apps.brand.views import OwnerListView, OwnerView
urlpatterns = patterns(
'',
url(r'^brand/$', BrandListView.as_view(), name='brandlist'),
url(r'^brand/(?P<bsin>[1-9A-NP-Z]{6})', BrandView.a... | Fix Brand and Owner public links (missing / would get a 404 on brand/ and owner/) | Fix Brand and Owner public links (missing / would get a 404 on brand/ and owner/)
Also follow the same URL scheme as admin (which always have trailing
slash)
| Python | mit | okfn/brand-manager,okfn/opd-brand-manager,okfn/brand-manager,okfn/opd-brand-manager | ---
+++
@@ -4,9 +4,9 @@
urlpatterns = patterns(
'',
- url(r'^brand$', BrandListView.as_view(), name='brandlist'),
+ url(r'^brand/$', BrandListView.as_view(), name='brandlist'),
url(r'^brand/(?P<bsin>[1-9A-NP-Z]{6})', BrandView.as_view(), name='brand'),
- url(r'^owner$', OwnerListView.as_view()... |
cab50585aca7a25d52436ab5d7fd9f75f08a185b | epiphany/test/test_compiled_c.py | epiphany/test/test_compiled_c.py | from epiphany.sim import Epiphany
import os.path
import pytest
elf_dir = os.path.join('epiphany', 'test', 'c')
@pytest.mark.parametrize("elf_file,expected", [('nothing.elf', 176),
])
def test_compiled_c(elf_file, expected, capsys):
"""Test an ELF file that has bee... | from epiphany.sim import Epiphany
import os.path
import pytest
elf_dir = os.path.join('epiphany', 'test', 'c')
@pytest.mark.parametrize("elf_file,expected", [('nothing.elf', 176),
('fib.elf', 441),
])
def test_compi... | Add fib.elf to integration tests. | Add fib.elf to integration tests.
| Python | bsd-3-clause | futurecore/revelation,moreati/revelation,moreati/revelation,futurecore/revelation,futurecore/revelation | ---
+++
@@ -7,6 +7,7 @@
@pytest.mark.parametrize("elf_file,expected", [('nothing.elf', 176),
+ ('fib.elf', 441),
])
def test_compiled_c(elf_file, expected, capsys):
"""Test an ELF file that has been compile... |
a412166af39edd7a78a1127dba2ecb5c65986049 | feder/cases/factories.py | feder/cases/factories.py | from feder.cases import models
from feder.institutions.factories import InstitutionFactory
from feder.monitorings.factories import MonitoringFactory
import factory
from feder.users.factories import UserFactory
class CaseFactory(factory.django.DjangoModelFactory):
name = factory.Sequence('case-{0}'.format)
use... | from feder.institutions.factories import InstitutionFactory
from feder.monitorings.factories import MonitoringFactory
import factory
from feder.users.factories import UserFactory
from .models import Case
class CaseFactory(factory.django.DjangoModelFactory):
name = factory.Sequence('case-{0}'.format)
user = fa... | Clean up import in CaseFactory | Clean up import in CaseFactory
| Python | mit | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder | ---
+++
@@ -1,8 +1,8 @@
-from feder.cases import models
from feder.institutions.factories import InstitutionFactory
from feder.monitorings.factories import MonitoringFactory
import factory
from feder.users.factories import UserFactory
+from .models import Case
class CaseFactory(factory.django.DjangoModelFact... |
e96e39bc3b5c540dc2cdcee26c6562c358745f93 | citrination_client/base/tests/test_base_client.py | citrination_client/base/tests/test_base_client.py | from citrination_client.base import BaseClient
from citrination_client.base.errors import CitrinationClientError
def test_none_api_key():
"""
Ensures that an error is thrown if a client is instantiated
without an API key
"""
try:
client = BaseClient(None, "mycitrinationsite")
assert False
except Ci... | from citrination_client.base import BaseClient
from citrination_client.base.errors import CitrinationClientError
from citrination_client import __version__
def test_none_api_key():
"""
Ensures that an error is thrown if a client is instantiated
without an API key
"""
try:
client = BaseClient(None, "mycit... | Update test to use new version location | Update test to use new version location
| Python | apache-2.0 | CitrineInformatics/python-citrination-client | ---
+++
@@ -1,5 +1,6 @@
from citrination_client.base import BaseClient
from citrination_client.base.errors import CitrinationClientError
+from citrination_client import __version__
def test_none_api_key():
"""
@@ -27,8 +28,7 @@
"""
Tests that the version is extracted
"""
- client = BaseClient("asdf"... |
be315047f477377d19681063906480eb74f1e59f | mqtt_logger/serializers.py | mqtt_logger/serializers.py | """Serializers for the use with rest-pandas"""
from rest_framework import serializers
from .models import MQTTMessage
import re
import copy
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = MQTTMessage
fields = ['id', 'time_recorded', 'topic', 'payload']
pandas_in... | """Serializers for the use with rest-pandas"""
from rest_framework import serializers
from .models import MQTTMessage
import re
import copy
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = MQTTMessage
fields = ['id', 'time_recorded', 'topic', 'payload']
pandas_in... | Remove the topic and time from the pandas index so they are included in the json output again. | Remove the topic and time from the pandas index so they are included in the json output again.
| Python | mit | ast0815/mqtt-hub,ast0815/mqtt-hub | ---
+++
@@ -11,7 +11,7 @@
class Meta:
model = MQTTMessage
fields = ['id', 'time_recorded', 'topic', 'payload']
- pandas_index = ['time_recorded', 'topic', 'id']
+ pandas_index = ['id']
def generate_parsing_serializer_class(regex):
"""Generate a serializer class from a regu... |
ee35232228b8959bb790b971bf1661b1b3ea41fe | tests/manage.py | tests/manage.py | #!/usr/bin/env python
import channels.log
import logging
import os
import sys
PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
sys.path.insert(0, PROJECT_ROOT)
def get_channels_logger(*args, **kwargs):
"""Return logger for channels."""
return logging.getLogger("django.channels")
#... | #!/usr/bin/env python
import logging
import os
import sys
PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
sys.path.insert(0, PROJECT_ROOT)
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings")
# if len(sys.argv) > 1 and sys.argv[1] == 'runser... | Fix logging compatibility with the latest Channels | Fix logging compatibility with the latest Channels
| Python | apache-2.0 | genialis/resolwe,jberci/resolwe,jberci/resolwe,genialis/resolwe | ---
+++
@@ -1,5 +1,4 @@
#!/usr/bin/env python
-import channels.log
import logging
import os
import sys
@@ -7,15 +6,6 @@
PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
sys.path.insert(0, PROJECT_ROOT)
-
-def get_channels_logger(*args, **kwargs):
- """Return logger for channels.""... |
9bd88d618223b47a520bfd3e2f70ae1cfcc3b02e | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/urls.py | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/urls.py | from django.conf.urls import include, url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtailsearch import urls as wagtailsearch_urls
from wagtail.wagtaildocs import urls as wagtaild... | from django.conf.urls import include, url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtailsearch import urls as wagtailsearch_urls
from wagtail.wagtaildocs import urls as wagtaild... | Add views for testing 404 and 500 templates | Add views for testing 404 and 500 templates
| Python | bsd-3-clause | torchbox/cookiecutter-wagtail,torchbox/wagtail-cookiecutter,RocketPod/wagtail-cookiecutter,torchbox/cookiecutter-wagtail,torchbox/cookiecutter-wagtail,RocketPod/wagtail-cookiecutter,RocketPod/wagtail-cookiecutter,torchbox/cookiecutter-wagtail,torchbox/wagtail-cookiecutter,torchbox/wagtail-cookiecutter,torchbox/wagtail-... | ---
+++
@@ -18,13 +18,24 @@
url(r'^admin/', include(wagtailadmin_urls)),
url(r'^search/', include(wagtailsearch_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
-
- url(r'', include(wagtail_urls)),
]
if settings.DEBUG:
from django.contrib.staticfiles.urls import staticfiles_urlpatt... |
d197f74334d1733189f77dd3b12cb7db934ccd18 | lc0007_reverse_integer.py | lc0007_reverse_integer.py | """Leetcode 7. Reverse Integer
Easy
URL: https://leetcode.com/problems/reverse-integer/description/
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer.
Your function should return 0 when the r... | """Leetcode 7. Reverse Integer
Easy
URL: https://leetcode.com/problems/reverse-integer/description/
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer.
Your function should return 0 when the r... | Add comments & space lines | Add comments & space lines
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -29,8 +29,11 @@
x_rev = int(str(x)[::-1][-1] + str(x)[::-1][:-1])
else:
x_rev = int(str(x)[::-1])
+
+ # If reversed integer is overflow.
if abs(x_rev) > 0x7FFFFFFF:
x_rev = 0
+
return x_rev
|
1838a160221859a40d208bc95352b105c53edb5f | partner_communication_switzerland/models/res_users.py | partner_communication_switzerland/models/res_users.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import api, models
_logger = logging.getLogger(__name__)
class ResUsers(models.Model):
_inherit = 'res.users'
@api.multi
def action_reset_password(self):
create_mode = boo... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import api, models
from odoo.addons.auth_signup.models.res_partner import now
_logger = logging.getLogger(__name__)
class ResUsers(models.Model):
_inherit = 'res.users'
@api.multi
... | FIX password reset method that was not resetting the password | FIX password reset method that was not resetting the password
| Python | agpl-3.0 | CompassionCH/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland | ---
+++
@@ -3,6 +3,8 @@
import logging
from odoo import api, models
+
+from odoo.addons.auth_signup.models.res_partner import now
_logger = logging.getLogger(__name__)
@@ -17,6 +19,9 @@
if create_mode:
super(ResUsers, self).action_reset_password()
else:
+ expiration ... |
b071e9c5ac8ae479c8c5ab38c2e0a886c846b0e5 | pybossa/repositories/project_stats_repository.py | pybossa/repositories/project_stats_repository.py | # -*- coding: utf8 -*-
# This file is part of PYBOSSA.
#
# Copyright (C) 2015 Scifabric LTD.
#
# PYBOSSA 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 op... | # -*- coding: utf8 -*-
# This file is part of PYBOSSA.
#
# Copyright (C) 2015 Scifabric LTD.
#
# PYBOSSA 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 op... | Add desc and orderby to repo | Add desc and orderby to repo
| Python | agpl-3.0 | Scifabric/pybossa,PyBossa/pybossa,Scifabric/pybossa,PyBossa/pybossa | ---
+++
@@ -33,6 +33,8 @@
return self.db.session.query(ProjectStats).get(id)
def filter_by(self, limit=None, offset=0, yielded=False, last_id=None,
- desc=False, **filters):
+ fulltextsearch=None, desc=False, orderby='id',
+ **filters):
retur... |
0da4c663e8a48bb759a140ca304ce35d3a8b5dcf | pyconde/events/templatetags/event_tags.py | pyconde/events/templatetags/event_tags.py | import datetime
from django import template
from .. import models
register = template.Library()
@register.inclusion_tag('events/tags/list_events.html')
def list_events(number_of_events=3):
now = datetime.datetime.now()
events = models.Event.objects.filter(date__gte=now).all()[:number_of_events]
has_ra... | from django import template
from .. import models
register = template.Library()
@register.inclusion_tag('events/tags/list_events.html')
def list_events(number_of_events=None):
events = models.Event.objects.all()
if number_of_events is not None:
events = events[:number_of_events]
has_range = Fal... | Remove future-restriction on list_events tag | Remove future-restriction on list_events tag
| Python | bsd-3-clause | zerok/pyconde-website-mirror,EuroPython/djep,EuroPython/djep,EuroPython/djep,pysv/djep,pysv/djep,EuroPython/djep,zerok/pyconde-website-mirror,pysv/djep,pysv/djep,pysv/djep,zerok/pyconde-website-mirror | ---
+++
@@ -1,5 +1,3 @@
-import datetime
-
from django import template
from .. import models
@@ -9,9 +7,10 @@
@register.inclusion_tag('events/tags/list_events.html')
-def list_events(number_of_events=3):
- now = datetime.datetime.now()
- events = models.Event.objects.filter(date__gte=now).all()[:number... |
2114527f8de7b7e5175b43c54b4b84db2f169a01 | djangocms_forms/migrations/0004_redirect_delay.py | djangocms_forms/migrations/0004_redirect_delay.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('djangocms_forms', '0003_add_referrer_field'),
]
operations = [
migrations.AddField(
model_name='formdefinition',... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('djangocms_forms', '0003_add_referrer_field'),
]
operations = [
migrations.AddField(
model_name='formdefinition',... | Update migrations — `verbose_name` for `redirect_delay` fields | Update migrations — `verbose_name` for `redirect_delay` fields
| Python | bsd-3-clause | mishbahr/djangocms-forms,mishbahr/djangocms-forms,mishbahr/djangocms-forms | ---
+++
@@ -14,6 +14,6 @@
migrations.AddField(
model_name='formdefinition',
name='redirect_delay',
- field=models.PositiveIntegerField(verbose_name='Redirect Delay', blank=True, null=True, help_text="Wait this number of milliseconds before redirecting."),
+ fie... |
8b84353d366daf1b1f0a19aff51d9d817428c6b9 | primestg/message.py | primestg/message.py | from lxml.objectify import fromstring
import binascii
import zlib
def is_gziped(content):
return binascii.hexlify(content[:2].encode('utf-8')) == b'1f8b'
class BaseMessage(object):
"""
Base XML message.
"""
def __init__(self, xml):
"""
Create an object of BaseMessage.
:p... | from lxml.objectify import fromstring
import binascii
import zlib
def is_gziped(content):
signature = content[:2]
try:
res = binascii.hexlify(signature) == b'1f8b'
except:
res = binascii.hexlify(signature.encode('utf-8')) == b'1f8b'
return res
class BaseMessage(object):
"""
... | FIX works with py3 binary data and string data | FIX works with py3 binary data and string data
| Python | agpl-3.0 | gisce/primestg | ---
+++
@@ -4,7 +4,13 @@
def is_gziped(content):
- return binascii.hexlify(content[:2].encode('utf-8')) == b'1f8b'
+ signature = content[:2]
+ try:
+ res = binascii.hexlify(signature) == b'1f8b'
+ except:
+ res = binascii.hexlify(signature.encode('utf-8')) == b'1f8b'
+
+ return res
... |
b63edf8067c070f988f2ded4e33592d33bbbcab5 | frappe/patches/v11_0/set_primary_key_in_series.py | frappe/patches/v11_0/set_primary_key_in_series.py | import frappe
def execute():
keys_encountered = set()
#if current = 0, simply delete the key as it'll be recreated on first entry
frappe.db.sql('delete from `tabSeries` where current = 0')
duplicate_keys = frappe.db.sql('''
SELECT distinct name, current
from
`tabSeries`
... | import frappe
def execute():
keys_encountered = set()
#if current = 0, simply delete the key as it'll be recreated on first entry
frappe.db.sql('delete from `tabSeries` where current = 0')
duplicate_keys = frappe.db.sql('''
SELECT distinct name, current
from
`tabSeries`
... | Check duplicates > 1 instead of > 2 | Check duplicates > 1 instead of > 2 | Python | mit | adityahase/frappe,almeidapaulopt/frappe,almeidapaulopt/frappe,StrellaGroup/frappe,mhbu50/frappe,StrellaGroup/frappe,vjFaLk/frappe,vjFaLk/frappe,yashodhank/frappe,adityahase/frappe,yashodhank/frappe,adityahase/frappe,mhbu50/frappe,yashodhank/frappe,almeidapaulopt/frappe,frappe/frappe,saurabh6790/frappe,mhbu50/frappe,vjF... | ---
+++
@@ -9,7 +9,7 @@
from
`tabSeries`
where
- name in (Select name from `tabSeries` group by name having count(name) > 2)
+ name in (Select name from `tabSeries` group by name having count(name) > 1)
''', as_dict=True)
for row in duplicate_keys:
... |
834a6a65f144e17f22851230d2baf3524f5e98c0 | flexget/plugins/est_released.py | flexget/plugins/est_released.py | import logging
from flexget.plugin import get_plugins_by_group, register_plugin
log = logging.getLogger('est_released')
class EstimateRelease(object):
"""
Front-end for estimator plugins that estimate release times
for various things (series, movies).
"""
def estimate(self, entry):
"""
... | import logging
from flexget.plugin import get_plugins_by_group, register_plugin
log = logging.getLogger('est_released')
class EstimateRelease(object):
"""
Front-end for estimator plugins that estimate release times
for various things (series, movies).
"""
def estimate(self, entry):
"""
... | Fix estimator loop, consider rest plugins as well. | Fix estimator loop, consider rest plugins as well.
| Python | mit | ianstalk/Flexget,qk4l/Flexget,malkavi/Flexget,crawln45/Flexget,tobinjt/Flexget,xfouloux/Flexget,asm0dey/Flexget,Flexget/Flexget,ibrahimkarahan/Flexget,vfrc2/Flexget,jacobmetrick/Flexget,crawln45/Flexget,tarzasai/Flexget,Pretagonist/Flexget,xfouloux/Flexget,spencerjanssen/Flexget,lildadou/Flexget,JorisDeRieck/Flexget,ja... | ---
+++
@@ -22,6 +22,9 @@
log.info(entry['title'])
estimators = get_plugins_by_group('estimate_release')
for estimator in estimators:
- return estimator.instance.estimate(entry)
+ estimate = estimator.instance.estimate(entry)
+ # return first successful esti... |
965dc806c5577fea89f1fcf78e3cdfcbff84b65f | moto/iam/exceptions.py | moto/iam/exceptions.py | from __future__ import unicode_literals
from moto.core.exceptions import RESTError
class IAMNotFoundException(RESTError):
code = 404
def __init__(self, message):
super(IAMNotFoundException, self).__init__(
"Not Found", message)
class IAMConflictException(RESTError):
code = 409
... | from __future__ import unicode_literals
from moto.core.exceptions import RESTError
class IAMNotFoundException(RESTError):
code = 404
def __init__(self, message):
super(IAMNotFoundException, self).__init__(
"NoSuchEntity", message)
class IAMConflictException(RESTError):
code = 409
... | Fix the error code for IAMNotFoundException to NoSuchEntity used by AWS. | Fix the error code for IAMNotFoundException to NoSuchEntity used by AWS.
| Python | apache-2.0 | spulec/moto,spulec/moto,botify-labs/moto,kefo/moto,kefo/moto,william-richard/moto,dbfr3qs/moto,Affirm/moto,ZuluPro/moto,kefo/moto,botify-labs/moto,botify-labs/moto,whummer/moto,Affirm/moto,botify-labs/moto,ZuluPro/moto,Brett55/moto,Brett55/moto,Affirm/moto,rocky4570/moto,william-richard/moto,rocky4570/moto,whummer/moto... | ---
+++
@@ -7,7 +7,7 @@
def __init__(self, message):
super(IAMNotFoundException, self).__init__(
- "Not Found", message)
+ "NoSuchEntity", message)
class IAMConflictException(RESTError): |
ca563ca11fe04202ae38799ee992a48e0a01fd86 | material/admin/modules.py | material/admin/modules.py | from karenina import modules
class Admin(modules.InstallableModule):
icon = "mdi-action-settings-applications"
order = 1000
@property
def label(self):
return 'Administration'
def has_perm(self, user):
return user.is_staff | from karenina import modules
class Admin(modules.Module):
icon = "mdi-action-settings-applications"
order = 1000
@property
def label(self):
return 'Administration'
def has_perm(self, user):
return user.is_staff | Add module declaration for karenina | Add module declaration for karenina
| Python | bsd-3-clause | thiagoramos-luizalabs/django-material,refnode/django-material,lukasgarcya/django-material,viewflow/django-material,MonsterKiller/django-material,viewflow/django-material,barseghyanartur/django-material,MonsterKiller/django-material,un33k/django-material,afifnz/django-material,Axelio/django-material,viewflow/django-mate... | ---
+++
@@ -1,7 +1,7 @@
from karenina import modules
-class Admin(modules.InstallableModule):
+class Admin(modules.Module):
icon = "mdi-action-settings-applications"
order = 1000
|
4cf56e47f27053bcfe01059427fceceb55d7da91 | labs/01_keras/solutions/keras_sgd_and_momentum.py | labs/01_keras/solutions/keras_sgd_and_momentum.py | model = Sequential()
model.add(Dense(hidden_dim, input_dim=input_dim,
activation="tanh"))
model.add(Dense(output_dim, activation="softmax"))
model.add(Activation("softmax"))
optimizer = optimizers.SGD(lr=0.1, momentum=0.9, nesterov=True)
model.compile(optimizer=optimizer, loss='categorical_crossentropy... | model = Sequential()
model.add(Dense(hidden_dim, input_dim=input_dim,
activation="tanh"))
model.add(Dense(output_dim, activation="softmax"))
optimizer = optimizers.SGD(lr=0.1, momentum=0.9, nesterov=True)
model.compile(optimizer=optimizer, loss='categorical_crossentropy',
metrics=['accura... | Remove leftover line in solution for 01_keras | Remove leftover line in solution for 01_keras
| Python | mit | m2dsupsdlclass/lectures-labs,m2dsupsdlclass/lectures-labs | ---
+++
@@ -2,7 +2,6 @@
model.add(Dense(hidden_dim, input_dim=input_dim,
activation="tanh"))
model.add(Dense(output_dim, activation="softmax"))
-model.add(Activation("softmax"))
optimizer = optimizers.SGD(lr=0.1, momentum=0.9, nesterov=True)
model.compile(optimizer=optimizer, loss='categorical_... |
5dcba5d842209791918ea67ea95895a23475a803 | apps/smeuhoverride/models.py | apps/smeuhoverride/models.py | from django.db import models
# Create your models here.
| from django.contrib.contenttypes.models import ContentType
from django.db.models import signals
from tagging.models import TaggedItem
def taggeditem_delete(sender, **kwargs):
"""
Deletes TaggedItems for ALL deleted model instances
Workaround for bug:
http://code.google.com/p/django-tagging/issues/d... | Delete tags for deleted items | Delete tags for deleted items
| Python | mit | amarandon/smeuhsocial,amarandon/smeuhsocial,fgirault/smeuhsocial,fgirault/smeuhsocial,amarandon/smeuhsocial,fgirault/smeuhsocial | ---
+++
@@ -1,3 +1,23 @@
-from django.db import models
+from django.contrib.contenttypes.models import ContentType
+from django.db.models import signals
+from tagging.models import TaggedItem
-# Create your models here.
+def taggeditem_delete(sender, **kwargs):
+ """
+ Deletes TaggedItems for ALL deleted mode... |
d4e721e3179c1f3fbce283b96b937fa4864786c3 | src/amber/hokuyo/hokuyo.py | src/amber/hokuyo/hokuyo.py | import serial
import sys
import os
from amber.hokuyo.hokuyo_common import HokuyoController
from amber.tools import serial_port, config
__author__ = 'paoolo'
pwd = os.path.dirname(os.path.abspath(__file__))
config.add_config_ini('%s/hokuyo.ini' % pwd)
SERIAL_PORT = config.HOKUYO_SERIAL_PORT
BAUD_RATE = config.HOKU... | import logging.config
import sys
import os
import time
import serial
from amber.hokuyo.hokuyo_common import HokuyoController
from amber.tools import serial_port, config
__author__ = 'paoolo'
LOGGER_NAME = 'AmberPipes'
pwd = os.path.dirname(os.path.abspath(__file__))
config.add_config_ini('%s/hokuyo.ini' % pwd)
log... | Add restart mechanism for Hokuyo, update logging mechanism | Add restart mechanism for Hokuyo, update logging mechanism
| Python | mit | project-capo/amber-python-drivers,project-capo/amber-python-drivers | ---
+++
@@ -1,24 +1,36 @@
-import serial
+import logging.config
import sys
import os
+import time
+
+import serial
from amber.hokuyo.hokuyo_common import HokuyoController
-
from amber.tools import serial_port, config
__author__ = 'paoolo'
+LOGGER_NAME = 'AmberPipes'
pwd = os.path.dirname(os.path.abspath... |
bd39a28e25dc8a3c79ef9b1b9ba7e6924a3f682b | test/test_basic.py | test/test_basic.py | #!/usr/bin/env python
# vim: set ts=4 sw=4 et sts=4 ai:
#
# Test some basic functionality.
#
import unittest
import os
import sys
sys.path.append('..')
class TestQBasic(unittest.TestCase):
def setUp(self):
if os.path.exists('/tmp/q'):
os.remove('/tmp/q')
def tearDown(self):
self... | #!/usr/bin/env python
# vim: set ts=4 sw=4 et sts=4 ai:
#
# Test some basic functionality.
#
import unittest
import os
import sys
sys.path.append('..')
class TestQBasic(unittest.TestCase):
def setUp(self):
if os.path.exists('/tmp/q'):
os.remove('/tmp/q')
def tearDown(self):
self... | Work on older Python without assertIn method. | Work on older Python without assertIn method.
| Python | apache-2.0 | zestyping/q | ---
+++
@@ -21,7 +21,11 @@
def assertInQLog(self, string):
self.assertTrue(os.path.exists('/tmp/q'))
- self.assertIn(string, open('/tmp/q', 'r').read())
+ logdata = open('/tmp/q', 'r').read()
+ try:
+ self.assertIn(string, logdata)
+ except AttributeError:
+ ... |
541592ba6d2a914b2b98ee11b8e31c7589b2b6d7 | mezzanine/project_template/manage.py | mezzanine/project_template/manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
from mezzanine.utils.conf import real_project_name
settings_module = "%s.settings" % real_project_name("{{ project_name }}")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
from django.core.management import e... | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
from mezzanine.utils.conf import real_project_name
settings_module = "%s.settings" % real_project_name("{{ project_name }}")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
from django.core.management import execu... | Remove whitespace from blank line | Remove whitespace from blank line | Python | bsd-2-clause | emile2016/mezzanine,molokov/mezzanine,ZeroXn/mezzanine,ryneeverett/mezzanine,promil23/mezzanine,dustinrb/mezzanine,viaregio/mezzanine,adrian-the-git/mezzanine,dsanders11/mezzanine,spookylukey/mezzanine,wyzex/mezzanine,saintbird/mezzanine,readevalprint/mezzanine,frankchin/mezzanine,jjz/mezzanine,mush42/mezzanine,theclan... | ---
+++
@@ -3,7 +3,7 @@
import sys
if __name__ == "__main__":
-
+
from mezzanine.utils.conf import real_project_name
settings_module = "%s.settings" % real_project_name("{{ project_name }}") |
f5984fbd4187f4af65fb39b070f91870203d869b | openedx/stanford/djangoapps/register_cme/admin.py | openedx/stanford/djangoapps/register_cme/admin.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import ExtraInfo
admin.site.register(ExtraInfo)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import ExtraInfo
class ExtraInfoAdmin(admin.ModelAdmin):
""" Admin interface for ExtraInfo model. """
list_display = ('user', 'get_email', 'last_name', 'first_name',)
search_fields = ('user__user... | Change `ExtraInfo` to user fields, add search | Change `ExtraInfo` to user fields, add search
`Register_cme/extrainfo` in Django Admin was previously displaying users
as `ExtraInfo` objects which admins had to click on individually to see
each user's information. Each user is now displayed with fields:
username, email, last and first name. Username is clickable to ... | Python | agpl-3.0 | Stanford-Online/edx-platform,Stanford-Online/edx-platform,caesar2164/edx-platform,Stanford-Online/edx-platform,caesar2164/edx-platform,caesar2164/edx-platform,caesar2164/edx-platform,Stanford-Online/edx-platform | ---
+++
@@ -5,4 +5,16 @@
from .models import ExtraInfo
-admin.site.register(ExtraInfo)
+class ExtraInfoAdmin(admin.ModelAdmin):
+ """ Admin interface for ExtraInfo model. """
+ list_display = ('user', 'get_email', 'last_name', 'first_name',)
+ search_fields = ('user__username', 'user__email', 'last_name... |
19dc04eb48a9484540298aa9a15fca016486921b | shop/models/fields.py | shop/models/fields.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import connection
POSTGRES_FLAG = False
if str(connection.vendor) == 'postgresql':
POSTGRES_FLAG = True
try:
if POSTGRES_FLAG:
from django.contrib.postgres.fields import JSONField
else:
raise ImportError
except... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from distutils.version import LooseVersion
import re
from django.db import connection
POSTGRES_FLAG = False
if str(connection.vendor) == 'postgresql':
POSTGRES_FLAG = True
try:
import psycopg2
version = re.search('([0-9.]+)', psycopg2.__vers... | Add control over psycopg2's version (need to be bigger or equal than 2.5.4) | Add control over psycopg2's version (need to be bigger or equal than 2.5.4)
| Python | bsd-3-clause | nimbis/django-shop,nimbis/django-shop,jrief/django-shop,divio/django-shop,khchine5/django-shop,awesto/django-shop,divio/django-shop,khchine5/django-shop,divio/django-shop,awesto/django-shop,awesto/django-shop,jrief/django-shop,jrief/django-shop,nimbis/django-shop,khchine5/django-shop,nimbis/django-shop,jrief/django-sho... | ---
+++
@@ -1,14 +1,18 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
+from distutils.version import LooseVersion
+import re
from django.db import connection
POSTGRES_FLAG = False
if str(connection.vendor) == 'postgresql':
POSTGRES_FLAG = True
+try:
+ import psycopg2
-try:
- ... |
b9c30e894c313400b7f3bfc007c39fa6e1d5ee76 | run_local_server.py | run_local_server.py | """Launch."""
from dnstwister import app
app.run(debug=True)
| """Launch."""
from dnstwister import app
# At least until https://github.com/pallets/flask/pull/1910 is merged...
app.jinja_env.auto_reload = True
app.run(debug=True)
| Fix for template reloading issues in newer version of flask | Fix for template reloading issues in newer version of flask
| Python | unlicense | thisismyrobot/dnstwister,thisismyrobot/dnstwister,thisismyrobot/dnstwister | ---
+++
@@ -1,3 +1,7 @@
"""Launch."""
from dnstwister import app
+
+# At least until https://github.com/pallets/flask/pull/1910 is merged...
+app.jinja_env.auto_reload = True
+
app.run(debug=True) |
e500888a0fab56f5da3919a025a8f5ecf5bf1be3 | django_todo/apps/core/tests.py | django_todo/apps/core/tests.py | from django.test import TestCase
# Create your tests here.
| from datetime import datetime, timedelta
from django.contrib.auth.models import User
from django.test import TestCase
from django_todo.apps.core.models import Task
class TaskTestCase(TestCase):
def setUp(self):
self.user, created = User.objects.get_or_create(username='test_user', email='test@email.com', p... | Add unit testing. Initial version | Add unit testing. Initial version
| Python | mit | maxicecilia/django_todo | ---
+++
@@ -1,3 +1,36 @@
+from datetime import datetime, timedelta
+from django.contrib.auth.models import User
from django.test import TestCase
+from django_todo.apps.core.models import Task
-# Create your tests here.
+
+class TaskTestCase(TestCase):
+ def setUp(self):
+ self.user, created = User.object... |
f38081a1e8d136f5fab36090b177b7f12b3d25d9 | promgen/sender/__init__.py | promgen/sender/__init__.py | import logging
from promgen.models import Sender
logger = logging.getLogger(__name__)
class SenderBase(object):
def send(self, data):
sent = 0
for alert in data['alerts']:
project = alert['labels'].get('project')
for sender in Sender.objects.filter(sender=self.__module__,... | import logging
from promgen.models import Sender
logger = logging.getLogger(__name__)
class SenderBase(object):
def __init__(self):
# In case some of our sender plugins are not using celery,
# We store our calling function in self.__send so that send()
# and test() can call the correct f... | Support both celery _send task and non-celery _send method | Support both celery _send task and non-celery _send method
| Python | mit | kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen | ---
+++
@@ -6,12 +6,22 @@
class SenderBase(object):
+ def __init__(self):
+ # In case some of our sender plugins are not using celery,
+ # We store our calling function in self.__send so that send()
+ # and test() can call the correct function while leaving the
+ # original functio... |
1d26fddd3fb1581138117b2fbeeb21877bc48883 | sample_app/utils.py | sample_app/utils.py |
import tornado.web
import ipy_table
from transperth.location import Location
class BaseRequestHandler(tornado.web.RequestHandler):
@property
def args(self):
args = self.request.arguments
return {
k: [sv.decode() for sv in v]
for k, v in args.items()
}
def... |
import tornado.web
import ipy_table
from transperth.location import Location
class BaseRequestHandler(tornado.web.RequestHandler):
@property
def args(self):
args = self.request.arguments
return {
k: [sv.decode() for sv in v]
for k, v in args.items()
}
def... | Add dollar sign to fares, sort by fare type | Add dollar sign to fares, sort by fare type
| Python | mit | Mause/pytransperth,Mause/pytransperth | ---
+++
@@ -26,11 +26,11 @@
table_rows = [['Fare Type']]
table_rows[-1].extend(key.title() for key in keys)
- for key in values[0].keys():
+ for key in sorted(values[0].keys()):
table_rows.append([key.title()])
table_rows[-1].extend(
- ticket_type[key]
+ '${... |
b82a7beffac7ccd497f88e7f72a70e9c3ae7146a | syntacticframes_project/loadmapping/migrations/0002_auto_20140916_1053.py | syntacticframes_project/loadmapping/migrations/0002_auto_20140916_1053.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from os.path import join
from django.db import models, migrations
from django.conf import settings
from loadmapping.models import LVFVerb
def import_verbs(apps, schema_editor):
LVFVerb = apps.get_model('loadmapping', 'LVFVerb')
with... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from os.path import join
from django.db import models, migrations
from django.conf import settings
from loadmapping.models import LVFVerb
def import_verbs(apps, schema_editor):
LVFVerb = apps.get_model('loadmapping', 'LVFVerb')
LVFV... | Allow to reverse LVFVerb migration | Allow to reverse LVFVerb migration
| Python | mit | aymara/verbenet-editor,aymara/verbenet-editor,aymara/verbenet-editor | ---
+++
@@ -11,6 +11,7 @@
def import_verbs(apps, schema_editor):
LVFVerb = apps.get_model('loadmapping', 'LVFVerb')
+ LVFVerb.objects.all().delete()
with open(join(settings.SITE_ROOT, 'loadmapping/fixtures/lvfverb.json')) as fixture:
for entry in json.loads(fixture.read()):
... |
2c70c70099cffe88439fa082fb0e7942d8cfed88 | tests/run_tests.py | tests/run_tests.py | #!/bin/env python
"""Run HTCondor-CE unit tests"""
import glob
import unittest
TESTS = [test.strip('.py') for test in glob.glob('test*.py')]
SUITE = unittest.TestLoader().loadTestsFromNames(TESTS)
unittest.TextTestRunner(verbosity=2).run(SUITE)
| #!/bin/env python
"""Run HTCondor-CE unit tests"""
import glob
import unittest
import sys
TESTS = [test.strip('.py') for test in glob.glob('test*.py')]
SUITE = unittest.TestLoader().loadTestsFromNames(TESTS)
RESULTS = unittest.TextTestRunner(verbosity=2).run(SUITE)
if not RESULTS.wasSuccessful():
sys.exit(1)
| Exit non-zero if unit tests failed | Exit non-zero if unit tests failed
| Python | apache-2.0 | matyasselmeci/htcondor-ce,brianhlin/htcondor-ce,opensciencegrid/htcondor-ce,djw8605/htcondor-ce,brianhlin/htcondor-ce,brianhlin/htcondor-ce,matyasselmeci/htcondor-ce,opensciencegrid/htcondor-ce,bbockelm/htcondor-ce,opensciencegrid/htcondor-ce,matyasselmeci/htcondor-ce,djw8605/htcondor-ce,bbockelm/htcondor-ce,djw8605/ht... | ---
+++
@@ -3,10 +3,13 @@
import glob
import unittest
+import sys
TESTS = [test.strip('.py') for test in glob.glob('test*.py')]
SUITE = unittest.TestLoader().loadTestsFromNames(TESTS)
-unittest.TextTestRunner(verbosity=2).run(SUITE)
+RESULTS = unittest.TextTestRunner(verbosity=2).run(SUITE)
+
+if not RESULTS.... |
bb27b536193fcc6ada7ab6a4193ac1bf889569d7 | indra/sources/hypothesis/api.py | indra/sources/hypothesis/api.py | import requests
| import requests
from indra.config import get_config
from .processor import HypothesisProcessor
base_url = 'https://api.hypothes.is/api/'
api_key = get_config('HYPOTHESIS_API_KEY')
headers = {'Authorization': 'Bearer %s' % api_key,
'Accept': 'application/vnd.hypothesis.v1+json',
'content-type': '... | Implement fetching annotations for a given group | Implement fetching annotations for a given group
| Python | bsd-2-clause | bgyori/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/indra,sorgerlab/belpy,johnbachman/indra,sorgerlab/belpy,johnbachman/indra,sorgerlab/indra,bgyori/indra,johnbachman/belpy,johnbachman/belpy,sorgerlab/belpy,sorgerlab/indra,bgyori/indra | ---
+++
@@ -1 +1,27 @@
import requests
+from indra.config import get_config
+from .processor import HypothesisProcessor
+
+
+base_url = 'https://api.hypothes.is/api/'
+api_key = get_config('HYPOTHESIS_API_KEY')
+headers = {'Authorization': 'Bearer %s' % api_key,
+ 'Accept': 'application/vnd.hypothesis.v1+j... |
2f268a124a5aceabab6dcdb545cf14648c297e2c | lava_results_app/admin.py | lava_results_app/admin.py | # Copyright (C) 2015 Linaro Limited
#
# Author: Stevan Radakovic <stevan.radakovic@linaro.org>
#
# This file is part of Lava Server.
#
# Lava Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by the Free Software Foundat... | # Copyright (C) 2015 Linaro Limited
#
# Author: Stevan Radakovic <stevan.radakovic@linaro.org>
#
# This file is part of Lava Server.
#
# Lava Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by the Free Software Foundat... | Fix deprecation warnings - RemovedInDjango19Warning | Fix deprecation warnings - RemovedInDjango19Warning
Extend fix in review #9160 for subsequent changes.
Change-Id: I25fbe759cfd28ac683ef94b58a8da098141e8d48
| Python | agpl-3.0 | Linaro/lava-server,Linaro/lava-server,Linaro/lava-server,Linaro/lava-server | ---
+++
@@ -23,7 +23,7 @@
from django import forms
from django.contrib import admin
from django.contrib.admin.actions import delete_selected
-from django.contrib.contenttypes import generic
+from django.contrib.contenttypes import fields
from django.utils.translation import ugettext_lazy as _
from lava_results... |
3224ea27a23e1c254bb93a110be1bd481585cb99 | mosecom_air/api/models.py | mosecom_air/api/models.py | #coding: utf-8
from django.db import models
class Substance(models.Model):
name = models.TextField(unique=True, db_index=True)
alias = models.TextField()
class Station(models.Model):
name = models.TextField(unique=True, db_index=True)
alias = models.TextField()
class Unit(models.Model):
name = m... | #coding: utf-8
from django.db import models
class Substance(models.Model):
name = models.TextField(unique=True, db_index=True)
alias = models.TextField()
class Station(models.Model):
name = models.TextField(unique=True, db_index=True)
alias = models.TextField()
class Unit(models.Model):
name = m... | Add index for Measurement model | Add index for Measurement model
| Python | mit | elsid/mosecom-air,elsid/mosecom-air,elsid/mosecom-air | ---
+++
@@ -20,3 +20,8 @@
value = models.FloatField()
performed = models.DateTimeField()
written = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ index_together = [
+ ['station', 'substance', 'unit', 'performed']
+ ] |
8054982b3aa106a9551e792f6453993484a17f2a | tests/unit/test_factory.py | tests/unit/test_factory.py | # -*- coding: utf-8 -*-
"""Test Factory Module
This module contains the tests for the OpenRecords Application Factory
"""
import os
import flask
import json
import pytest
from app import create_app
def test_default_config():
"""Test the default config class is the DevelopmentConfig"""
assert isinstance(cr... | # -*- coding: utf-8 -*-
"""Test Factory Module
This module contains the tests for the OpenRecords Application Factory
"""
import os
import flask
import json
import pytest
from app import create_app
@pytest.mark.skip(reason="Scheduler is not functioning and needs to be replaced.")
def test_default_config():
"""... | Mark test_default_config as skip; Scheduler needs to be rewritten | Mark test_default_config as skip; Scheduler needs to be rewritten
| Python | apache-2.0 | CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords | ---
+++
@@ -12,7 +12,7 @@
from app import create_app
-
+@pytest.mark.skip(reason="Scheduler is not functioning and needs to be replaced.")
def test_default_config():
"""Test the default config class is the DevelopmentConfig"""
assert isinstance(create_app(), flask.app.Flask) |
e7cba721d78860d0151cc65793e567b0da719d39 | regserver/regulations/tests/partial_view_tests.py | regserver/regulations/tests/partial_view_tests.py | from unittest import TestCase
from mock import Mock, patch
from regulations.generator.layers.layers_applier import *
from regulations.views.partial import *
class PartialParagraphViewTests(TestCase):
@patch('regulations.views.partial.generator')
def test_get_context_data(self, generator):
generator.ge... | from unittest import TestCase
from mock import Mock, patch
from django.test import RequestFactory
from regulations.generator.layers.layers_applier import *
from regulations.views.partial import *
class PartialParagraphViewTests(TestCase):
@patch('regulations.views.partial.generator')
def test_get_context_da... | Change test, so that view has a request object | Change test, so that view has a request object
| Python | cc0-1.0 | ascott1/regulations-site,18F/regulations-site,ascott1/regulations-site,grapesmoker/regulations-site,tadhg-ohiggins/regulations-site,18F/regulations-site,adderall/regulations-site,adderall/regulations-site,ascott1/regulations-site,grapesmoker/regulations-site,EricSchles/regulations-site,EricSchles/regulations-site,willb... | ---
+++
@@ -1,10 +1,13 @@
from unittest import TestCase
from mock import Mock, patch
+
+from django.test import RequestFactory
from regulations.generator.layers.layers_applier import *
from regulations.views.partial import *
class PartialParagraphViewTests(TestCase):
+
@patch('regulations.views.partial.... |
b8e9a2af61e1b8fe45e32966495e46357a145a56 | dom/automation/detect_assertions.py | dom/automation/detect_assertions.py | #!/usr/bin/env python
def amiss(logPrefix):
global ignoreList
foundSomething = False
currentFile = file(logPrefix + "-err", "r")
# map from (assertion message) to (true, if seen in the current file)
seenInCurrentFile = {}
for line in currentFile:
line = line.strip("\x07").rstrip(... | #!/usr/bin/env python
import platform
def amiss(logPrefix):
global ignoreList
foundSomething = False
currentFile = file(logPrefix + "-err", "r")
# map from (assertion message) to (true, if seen in the current file)
seenInCurrentFile = {}
for line in currentFile:
line = line.stri... | Make known_assertions.txt cross-machine and hopefully also cross-platform. | Make known_assertions.txt cross-machine and hopefully also cross-platform.
| Python | mpl-2.0 | nth10sd/funfuzz,MozillaSecurity/funfuzz,MozillaSecurity/funfuzz,nth10sd/funfuzz,MozillaSecurity/funfuzz,nth10sd/funfuzz | ---
+++
@@ -1,4 +1,6 @@
#!/usr/bin/env python
+
+import platform
def amiss(logPrefix):
global ignoreList
@@ -24,23 +26,37 @@
def getIgnores():
- global ignoreList
+ global simpleIgnoreList
ignoreFile = open("known_assertions.txt", "r")
for line in ignoreFile:
line = line.strip... |
32ac109aec82210ccfa617b438a844b0f300157c | comics/core/context_processors.py | comics/core/context_processors.py | from django.conf import settings
from django.db.models import Count, Max
from comics.core.models import Comic
def site_settings(request):
return {
'site_title': settings.COMICS_SITE_TITLE,
'site_tagline': settings.COMICS_SITE_TAGLINE,
'google_analytics_code': settings.COMICS_GOOGLE_ANALYTI... | from django.conf import settings
from django.db.models import Count, Max
from comics.core.models import Comic
def site_settings(request):
return {
'site_title': settings.COMICS_SITE_TITLE,
'site_tagline': settings.COMICS_SITE_TAGLINE,
'google_analytics_code': settings.COMICS_GOOGLE_ANALYTI... | Add search_enabled to site settings context processor | Add search_enabled to site settings context processor
| Python | agpl-3.0 | jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,klette/comics,klette/comics,datagutten/comics,klette/comics,jodal/comics,datagutten/comics,jodal/comics | ---
+++
@@ -8,6 +8,7 @@
'site_title': settings.COMICS_SITE_TITLE,
'site_tagline': settings.COMICS_SITE_TAGLINE,
'google_analytics_code': settings.COMICS_GOOGLE_ANALYTICS_CODE,
+ 'search_enabled': 'comics.search' in settings.INSTALLED_APPS,
}
def all_comics(request): |
8ea3ab66f8a8a71a311bc30b3abec8b9ad681a4e | tpt/util/s3util.py | tpt/util/s3util.py | import boto
import logging
from tpt import private_settings
from boto.s3.key import Key
from django.http import StreamingHttpResponse
from django.http import Http404
logger = logging.getLogger(__name__)
def stream_object(key_name):
s3 = boto.connect_s3(
aws_access_key_id = private_settings.AWS_ACCESS... | import boto
import logging
from tpt import private_settings
from boto.s3.key import Key
from django.http import StreamingHttpResponse
from django.http import Http404
logger = logging.getLogger(__name__)
def stream_object(key_name):
s3 = boto.connect_s3(
aws_access_key_id = private_settings.AWS_ACCESS... | Add Etag header to proxy response from s3 | Add Etag header to proxy response from s3
| Python | apache-2.0 | youprofit/rust-ci-1,hansjorg/rust-ci,youprofit/rust-ci-1,hansjorg/rust-ci,youprofit/rust-ci-1,youprofit/rust-ci-1 | ---
+++
@@ -23,7 +23,10 @@
raise Http404()
response = StreamingHttpResponse(key)
-
+
+ if key.etag:
+ response['Etag'] = key.etag
+
if key.content_type:
response['Content-Type'] = key.content_type
else: |
1edd6ee6b71b3f3ac9654cc47804592613dd61ec | clowder/clowder/cli/init_controller.py | clowder/clowder/cli/init_controller.py | from cement.ext.ext_argparse import expose
from clowder.cli.abstract_base_controller import AbstractBaseController
class InitController(AbstractBaseController):
class Meta:
label = 'init'
stacked_on = 'base'
stacked_type = 'nested'
description = 'Clone repository to clowder direct... | import sys
from cement.ext.ext_argparse import expose
from termcolor import colored, cprint
from clowder.cli.abstract_base_controller import AbstractBaseController
from clowder.util.decorators import network_connection_required
class InitController(AbstractBaseController):
class Meta:
label = 'init'
... | Add `clowder init` logic to Cement controller | Add `clowder init` logic to Cement controller
| Python | mit | JrGoodle/clowder,JrGoodle/clowder,JrGoodle/clowder | ---
+++
@@ -1,6 +1,10 @@
+import sys
+
from cement.ext.ext_argparse import expose
+from termcolor import colored, cprint
from clowder.cli.abstract_base_controller import AbstractBaseController
+from clowder.util.decorators import network_connection_required
class InitController(AbstractBaseController):
@@ -1... |
8846747540b54b47e97a06471cd3daedc3a28f47 | modules/pipeurlbuilder.py | modules/pipeurlbuilder.py | # pipeurlbuilder.py
#
import urllib
from pipe2py import util
def pipe_urlbuilder(context, _INPUT, conf, **kwargs):
"""This source builds a url and yields it forever.
Keyword arguments:
context -- pipeline context
_INPUT -- not used
conf:
BASE -- base
PATH -- path elements
... | # pipeurlbuilder.py
#
import urllib
from pipe2py import util
def pipe_urlbuilder(context, _INPUT, conf, **kwargs):
"""This source builds a url and yields it forever.
Keyword arguments:
context -- pipeline context
_INPUT -- not used
conf:
BASE -- base
PATH -- path elements
... | Remove trailing slash (google charts don't like it) | Remove trailing slash (google charts don't like it)
| Python | mit | nerevu/riko,nerevu/riko | ---
+++
@@ -30,6 +30,7 @@
path = [path]
url += "/".join(path)
+ url = url.rstrip("/")
params = dict([(util.get_value(p['key'], item, **kwargs), util.get_value(p['value'], item, **kwargs)) for p in conf['PARAM']])
if params: |
9532a28dacefec67ea67f94cf992a505d8a6629d | utilities/ticker-update.py | utilities/ticker-update.py | import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
secutities = []
with open("ticker-updates,cong", r) as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
for security in securities:
query = URL + security
page = reques... | import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = "ticker-updates.conf"
secutities = []
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
print(securities)
for security in securitie... | Fix file read, start on sell price | Fix file read, start on sell price | Python | mit | daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various | ---
+++
@@ -2,20 +2,25 @@
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
+CONF_FILE = "ticker-updates.conf"
secutities = []
-with open("ticker-updates,cong", r) as conf_file:
+with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() f... |
06ec5baaa799836c656f67b083b77197943d97f2 | drogher/__init__.py | drogher/__init__.py | from . import shippers
def barcode(b):
for klass in ['DHL', 'FedExExpress', 'FedExGround96', 'UPS', 'USPSIMpb', 'USPS13']:
shipper = getattr(shippers, klass)(b)
if shipper.is_valid:
return shipper
return shippers.Unknown(b)
| from . import shippers
def barcode(b, barcode_classes=None):
if barcode_classes is None:
barcode_classes = ['DHL', 'FedExExpress', 'FedExGround96', 'UPS', 'USPSIMpb', 'USPS13']
for klass in barcode_classes:
shipper = getattr(shippers, klass)(b)
if shipper.is_valid:
return s... | Allow barcode classes to be optionally specified | Allow barcode classes to be optionally specified
| Python | bsd-3-clause | jbittel/drogher | ---
+++
@@ -1,8 +1,10 @@
from . import shippers
-def barcode(b):
- for klass in ['DHL', 'FedExExpress', 'FedExGround96', 'UPS', 'USPSIMpb', 'USPS13']:
+def barcode(b, barcode_classes=None):
+ if barcode_classes is None:
+ barcode_classes = ['DHL', 'FedExExpress', 'FedExGround96', 'UPS', 'USPSIMpb', ... |
6f16efcce43683868fde945ce59d87311f81a87c | virtool/downloads/utils.py | virtool/downloads/utils.py | """
Utilities focussing on formatting FASTA files.
"""
def format_fasta_entry(otu_name: str, isolate_name: str, sequence_id: str, sequence: str) -> str:
"""
Create a FASTA header and sequence block for a sequence in a otu DNA FASTA file downloadable from Virtool.
:param otu_name: the otu name to include... | """
Utilities focussing on formatting FASTA files.
"""
def format_fasta_entry(otu_name: str, isolate_name: str, sequence_id: str, sequence: str) -> str:
"""
Create a FASTA header and sequence block for a sequence in a otu DNA FASTA file downloadable from Virtool.
:param otu_name: the otu name to include... | Add function to format subtraction filename | Add function to format subtraction filename
| Python | mit | igboyes/virtool,virtool/virtool,igboyes/virtool,virtool/virtool | ---
+++
@@ -35,3 +35,16 @@
filename = ".".join(args).replace(" ", "_") + ".fa"
return filename.lower()
+
+
+def format_subtraction_filename(subtraction_id: str, subtraction_name: str):
+ """
+ Format a subtraction filename of the form "subtraction-subtraction_id-subtraction_name.fa.gz".
+
+ :para... |
610a1b000fd9de6e7e4c994e10c30c1aa9acbb82 | csunplugged/utils/check_glossary_links.py | csunplugged/utils/check_glossary_links.py | """Module for checking glossary links found within Markdown conversions."""
from utils.errors.CouldNotFindGlossaryTerm import CouldNotFindGlossaryTerm
from topics.models import GlossaryTerm
def check_converter_glossary_links(glossary_links, md_file_path):
"""Process glossary links found by Markdown converter.
... | """Module for checking glossary links found within Markdown conversions."""
from django.core.exceptions import DoesNotExist
from utils.errors.CouldNotFindGlossaryTerm import CouldNotFindGlossaryTerm
from topics.models import GlossaryTerm
def check_converter_glossary_links(glossary_links, md_file_path):
"""Proces... | Add import for Django exception | Add import for Django exception
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | ---
+++
@@ -1,5 +1,6 @@
"""Module for checking glossary links found within Markdown conversions."""
+from django.core.exceptions import DoesNotExist
from utils.errors.CouldNotFindGlossaryTerm import CouldNotFindGlossaryTerm
from topics.models import GlossaryTerm
@@ -13,5 +14,5 @@
for term in glossary_link... |
71c5cddd3c9e459da7ceb71942dbc95abbfac518 | tvecs/logger/init_logger.py | tvecs/logger/init_logger.py | """Initialise logging functionality."""
import sys
import logging
def initialise(handler_name):
"""Initialise the logger based on user preference."""
logging.basicConfig(
stream=sys.stdout,
format='%(asctime)s-%(levelname)s-%(name)s-%(message)s'
)
logger = logging.getLogger(handler_nam... | """Initialise logging functionality."""
import sys
import logging
def initialise(handler_name):
"""
Initialise the logger based on user preference.
API Documentation
:param handler_name: Handler name specified for logger.
:type handler_name: :class:`String`
:rtype: :class:`logging... | Add Docstring for public modules | Logger: Add Docstring for public modules
| Python | mit | KshitijKarthick/tvecs,KshitijKarthick/tvecs,KshitijKarthick/tvecs | ---
+++
@@ -4,7 +4,17 @@
def initialise(handler_name):
- """Initialise the logger based on user preference."""
+ """
+ Initialise the logger based on user preference.
+
+ API Documentation
+ :param handler_name: Handler name specified for logger.
+ :type handler_name: :class:`String`
+ ... |
bacff0ca6cae1f7488853f565b3030eb49ebad01 | cherryontop/decorators/qp.py | cherryontop/decorators/qp.py | import functools
import inspect
import cherrypy
from cherrypy.lib.httputil import parse_query_string
from cherryontop.errors import InvalidParameter, UnexpectedParameter
def typecast_query_params(*a, **kw):
allowed, cast_funcs = _get_checks(*a, **kw)
def wrap(f):
dynamic_url_args = _positional_arg_... | import functools
from cherryontop.errors import InvalidParameter, UnexpectedParameter
def typecast_query_params(*a, **kw):
allowed, cast_funcs = _get_checks(*a, **kw)
def wrap(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
# all supplied parameters allowed?
for... | Revert "confirm query params never overwrite dynamic url components" | Revert "confirm query params never overwrite dynamic url components"
This reverts commit 9aa3a57a289985d24877515995b3f1d589624a8d.
Conflicts:
cherryontop/decorators/qp.py
| Python | bsd-3-clause | csira/cherryontop | ---
+++
@@ -1,8 +1,4 @@
import functools
-import inspect
-
-import cherrypy
-from cherrypy.lib.httputil import parse_query_string
from cherryontop.errors import InvalidParameter, UnexpectedParameter
@@ -11,35 +7,20 @@
allowed, cast_funcs = _get_checks(*a, **kw)
def wrap(f):
- dynamic_url_args... |
88f00611ea000d0fed984e93aaa661db2c2bd79e | contrib/tempest/tempest/exceptions/share_exceptions.py | contrib/tempest/tempest/exceptions/share_exceptions.py | # Copyright 2014 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | # Copyright 2014 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | Add exception to tempest plugin | Add exception to tempest plugin
Exception 'SnapshotBuildErrorException' was used, but
was not defined.
Change-Id: Ida7554d65eb6657fa05b7d53cbfa452cc0239f74
| Python | apache-2.0 | bswartz/manila,openstack/manila,vponomaryov/manila,weiting-chen/manila,jcsp/manila,scality/manila,NetApp/manila,NetApp/manila,openstack/manila,sajuptpm/manila,vponomaryov/manila,redhat-openstack/manila,sajuptpm/manila,jcsp/manila,bswartz/manila,redhat-openstack/manila,scality/manila,weiting-chen/manila | ---
+++
@@ -24,6 +24,10 @@
message = "Share's rule with id %(rule_id) is in ERROR status"
+class SnapshotBuildErrorException(base.TempestException):
+ message = "Snapshot %(snapshot_id)s failed to build and is in ERROR status"
+
+
class ShareProtocolNotSpecified(base.TempestException):
message = "Sh... |
17cf285748ee519c6d28971baefbf4ed506fac1e | water_level/water_level.py | water_level/water_level.py | '''
Created on Aug 1, 2017
@author: alkaitz
'''
'''
[3 2 3] -> 1
'''
if __name__ == '__main__':
pass | '''
Created on Aug 1, 2017
@author: alkaitz
'''
'''
An integer array defines the height of a 2D set of columns. After it rains enough amount of water,
how much water will be contained in the valleys formed by these mountains?
Ex: [3 2 3]
X X X W X
X X X -> X X X -> 1
X X X X X X
'''
d... | Include initial solution for the water level problem problem | Include initial solution for the water level problem problem
| Python | mit | alkaitz/general-programming | ---
+++
@@ -5,7 +5,34 @@
'''
'''
- [3 2 3] -> 1
+ An integer array defines the height of a 2D set of columns. After it rains enough amount of water,
+ how much water will be contained in the valleys formed by these mountains?
+ Ex: [3 2 3]
+ X X X W X
+ X X X -> X X X -> 1
+ X X X X X... |
d3f5e0e2d6104963237a0626d608cc1b0949b762 | zounds/learn/functional.py | zounds/learn/functional.py | import numpy as np
def hyperplanes(means, stds, n_planes):
if len(means) != len(stds):
raise ValueError('means and stds must have the same length')
n_features = len(means)
a = np.random.normal(means, stds, (n_planes, n_features))
b = np.random.normal(means, stds, (n_planes, n_features))
p... | import numpy as np
def hyperplanes(means, stds, n_planes):
if len(means) != len(stds):
raise ValueError('means and stds must have the same length')
n_features = len(means)
a = np.random.normal(means, stds, (n_planes, n_features))
b = np.random.normal(means, stds, (n_planes, n_features))
p... | Add an option to also return intermediate example norms | Add an option to also return intermediate example norms
| Python | mit | JohnVinyard/zounds,JohnVinyard/zounds,JohnVinyard/zounds,JohnVinyard/zounds | ---
+++
@@ -20,9 +20,17 @@
return output
-def example_wise_unit_norm(x):
+def example_wise_unit_norm(x, return_norms=False):
original_shape = x.shape
+
+ # flatten all dimensions of x, treating the first axis as examples and all
+ # other axes as features
x = x.reshape((len(x), -1))
norm... |
6068905219a04974f18033b3cf64b2a037f05d7b | opps/core/__init__.py | opps/core/__init__.py | # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Opps')
settings.INSTALLED_APPS += ('opps.article',
'opps.image',
'opps.channel',
'opps.source',
'redactor',
'tagging',)
settings.REDACTOR_OPT... | # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Opps')
settings.INSTALLED_APPS += ('opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'redactor',
... | Add django contrib redirects on opps core init | Add django contrib redirects on opps core init
| Python | mit | opps/opps,opps/opps,williamroot/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,opps/opps | ---
+++
@@ -10,8 +10,12 @@
'opps.image',
'opps.channel',
'opps.source',
+ 'django.contrib.redirects',
'redactor',
'tagging',)
+settings.MIDDLEWARE_CLASSES += (
+ 'django.contrib.redirects.middleware.RedirectFallbackMiddleware',)
+
settings.REDACTOR_OPTIONS... |
cf49e996f07a2fd7107b953369fdccdc850d51d8 | test_tws/test_EReader.py | test_tws/test_EReader.py | '''Unit test package for module "tws._EReader".'''
__copyright__ = "Copyright (c) 2008 Kevin J Bluck"
__version__ = "$Id$"
import unittest
from StringIO import StringIO
from tws import EClientSocket, EReader
from test_tws import mock_wrapper
class test_EReader(unittest.TestCase):
'''Test class "tws.EReader"''... | '''Unit test package for module "tws._EReader".'''
__copyright__ = "Copyright (c) 2008 Kevin J Bluck"
__version__ = "$Id$"
import unittest
from StringIO import StringIO
from tws import EClientSocket, EReader
from test_tws import mock_wrapper
class test_EReader(unittest.TestCase):
'''Test class "tws.EReader"''... | Create EReader object using EClientSocket.createReader() | Create EReader object using EClientSocket.createReader() | Python | bsd-3-clause | kbluck/pytws,kbluck/pytws | ---
+++
@@ -16,7 +16,7 @@
self.wrapper = mock_wrapper()
self.parent = EClientSocket(self.wrapper)
self.stream = StringIO()
- self.reader = EReader(self.parent, self.stream)
+ self.reader = self.parent.createReader(self.parent, self.stream)
def test_init(self):
... |
28b570b98f802b5c15e88669776ed3a87b553dd7 | tests/functional/base.py | tests/functional/base.py | from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
class FunctionalTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.PhantomJS()
# Wait up tp 5 seconds for an element to appear
self.browser.implicitly_wait(5)
... | from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
class FunctionalTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.PhantomJS()
# Wait up tp 10 seconds for an element to appear
self.browser.implicitly_wait(10)
... | Increase implicitly wait limit to 10 seconds | Increase implicitly wait limit to 10 seconds
This is due to loading external scripts e.g. sharethis which take a
longer to load
| Python | bsd-3-clause | andela-kndungu/compshop,kevgathuku/compshop,andela-kndungu/compshop,andela-kndungu/compshop,andela-kndungu/compshop,kevgathuku/compshop,kevgathuku/compshop,kevgathuku/compshop | ---
+++
@@ -5,8 +5,8 @@
class FunctionalTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.PhantomJS()
- # Wait up tp 5 seconds for an element to appear
- self.browser.implicitly_wait(5)
+ # Wait up tp 10 seconds for an element to appear
+ self.browser... |
540493a69ff2e9a5e6cc93a75b34af3c9f79b808 | plugins/generic/syntax.py | plugins/generic/syntax.py | #!/usr/bin/env python
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import re
from lib.core.exception import SqlmapUndefinedMethod
class Syntax:
"""
This class defines generic syntax functionalities for plugins.
"""
def __in... | #!/usr/bin/env python
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import re
from lib.core.exception import SqlmapUndefinedMethod
class Syntax:
"""
This class defines generic syntax functionalities for plugins.
"""
def __in... | Fix for empty strings (previously '' was just removed) | Fix for empty strings (previously '' was just removed)
| Python | apache-2.0 | RexGene/monsu-server,RexGene/monsu-server,dtrip/.ubuntu,dtrip/.ubuntu | ---
+++
@@ -23,7 +23,9 @@
if quote:
for item in re.findall(r"'[^']*'+", expression, re.S):
- retVal = retVal.replace(item, escaper(item[1:-1]))
+ _ = item[1:-1]
+ if _:
+ retVal = retVal.replace(item, escaper(_))
else:
... |
22cfc216d3c0a11f5c90b27919fb0590cd3a210f | doc/render.py | doc/render.py | # Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | # Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | Make documentation generator strip copyright header from inline examples | Make documentation generator strip copyright header from inline examples
| Python | apache-2.0 | google/jsonnet,bowlofstew/jsonnet,davidzchen/jsonnet,Neeke/jsonnet,huggsboson/jsonnet,bowlofstew/jsonnet,sparkprime/jsonnet,google/jsonnet,huggsboson/jsonnet,Neeke/jsonnet,habibmasuro/jsonnet,lamuguo/jsonnet,bowlofstew/jsonnet,google/jsonnet,huggsboson/jsonnet,darioajr/jsonnet,sparkprime/jsonnet,bowlofstew/jsonnet,lamu... | ---
+++
@@ -22,7 +22,11 @@
def myinclude(filename):
with codecs.open(filename, 'r', 'utf-8') as f:
- return f.read()
+ lines = f.readlines()
+ # Strip copyright header, if it has one.
+ if lines[1][0:10] == "Copyright ":
+ lines = lines[16:]
+ return "".join(lines)
... |
0bdc48ce94a8c501dba1ce2925615714a46a1728 | pygameMidi_extended.py | pygameMidi_extended.py | #import pygame.midi.Output
from pygame.midi import Output
class Output(Output):#pygame.midi.Output):
def set_pan(self, pan, channel):
assert (0 <= channel <= 15)
assert pan <= 127
self.write_short(0xB0 + channel, 0x0A, pan)
def set_volume(self, volume, channel):
... | #import pygame.midi.Output
from pygame.midi import Output
class Output(Output):#pygame.midi.Output):
def set_pan(self, pan, channel):
assert (0 <= channel <= 15)
assert pan <= 127
self.write_short(0xB0 + channel, 0x0A, pan)
def set_volume(self, volume, channel):
... | Add method for instrument bank | Add method for instrument bank
| Python | bsd-3-clause | RenolY2/py-playBMS | ---
+++
@@ -26,3 +26,9 @@
pitch_msb = pitch & 127
self.write_short(0xE0 + channel, pitch_lsb, pitch_msb)
+
+ def set_instrument_bank(self, bank, channel):
+ assert (0 <= channel <= 15)
+ assert bank <= 127
+
+ self.write_short(0xB0 + channel, 0x00, bank) |
54c4efdcbd87b32788760f1d40e6148ae264abdc | crawler/models.py | crawler/models.py | from django.db import models
class DataIngredient(models.Model):
""""Class used to Store Ingredients of the recipes found in the crawling process"""
ingredient = models.CharField(max_length=1000)
recipe = models.CharField(max_length=500)
group = models.CharField(max_length=500, default='Ingredientes'... | from django.db import models
class DataIngredient(models.Model):
""""Class used to Store Ingredients of the recipes found in the crawling process"""
ingredient = models.CharField(max_length=1000)
recipe = models.CharField(max_length=500)
group = models.CharField(max_length=500, default='Ingredientes'... | Make count of words default 0 | Make count of words default 0
| Python | mit | lucasgr7/silverplate,lucasgr7/silverplate,lucasgr7/silverplate | ---
+++
@@ -25,7 +25,7 @@
class IngredientSpec(models.Model):
"""Class used to manipulate Ingredients found and change data to data mining and found patterns of ingredients"""
word = models.CharField(max_length=500)
- count = models.IntegerField()
+ count = models.IntegerField(default=0)
type = ... |
cd7c9653944a2d90d64ef1b3847b9e63d0309321 | corehq/apps/importer/urls.py | corehq/apps/importer/urls.py | from django.conf.urls.defaults import *
urlpatterns = patterns('corehq.apps.importer.views',
url(r'^excel/config/$', 'excel_config', name='excel_config'),
url(r'^excel/fields/$', 'excel_fields', name='excel_fields'),
url(r'^excel/commit/$', 'excel_commit', name='excel_commit'),
url(r'^importer_ajax/(?P... | from django.conf.urls.defaults import *
urlpatterns = patterns('corehq.apps.importer.views',
url(r'^excel/config/$', 'excel_config', name='excel_config'),
url(r'^excel/fields/$', 'excel_fields', name='excel_fields'),
url(r'^excel/commit/$', 'excel_commit', name='excel_commit'),
url(r'^importer_ajax/(?P... | Add trailing slash to url | Add trailing slash to url
| Python | bsd-3-clause | SEL-Columbia/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,gmimano/commcaretest,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq... | ---
+++
@@ -4,6 +4,6 @@
url(r'^excel/config/$', 'excel_config', name='excel_config'),
url(r'^excel/fields/$', 'excel_fields', name='excel_fields'),
url(r'^excel/commit/$', 'excel_commit', name='excel_commit'),
- url(r'^importer_ajax/(?P<download_id>[0-9a-fA-Z]{25,32})$',
+ url(r'^importer_ajax/(?... |
7f359fef5791aa8615c4298261c28e584f791c17 | dform/tests/urls.py | dform/tests/urls.py | from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'admin/', include(admin.site.urls)),
url(r'rankedmodel/', include('awl.rankedmodel.urls')),
url(r'dform/', include('dform.urls')),
url(r'dform_admin/', include('dform.admin_urls')),
]
| from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^rankedmodel/', include('awl.rankedmodel.urls')),
url(r'^dform/', include('dform.urls')),
url(r'^dform_admin/', include('dform.admin_urls')),
]
| Fix missing ^ in url patterns | Fix missing ^ in url patterns
| Python | mit | cltrudeau/django-dform,cltrudeau/django-dform,cltrudeau/django-dform | ---
+++
@@ -2,10 +2,10 @@
from django.contrib import admin
urlpatterns = [
- url(r'admin/', include(admin.site.urls)),
+ url(r'^admin/', include(admin.site.urls)),
- url(r'rankedmodel/', include('awl.rankedmodel.urls')),
+ url(r'^rankedmodel/', include('awl.rankedmodel.urls')),
- url(r'dform/',... |
38cf3aed45ac604884d4ae1fed30714755f46cc8 | discussion/forms.py | discussion/forms.py | from django import forms
from discussion.models import Comment, Post, Discussion
class CommentForm(forms.ModelForm):
class Meta:
exclude = ('user', 'post')
model = Comment
class PostForm(forms.ModelForm):
class Meta:
exclude = ('user', 'discussion')
model = Post
class Sear... | from django import forms
from discussion.models import Comment, Post, Discussion
class CommentForm(forms.ModelForm):
class Meta:
exclude = ('user', 'post')
model = Comment
widgets = {
'body' : forms.Textarea(attrs={'placeholder' : 'Reply to this conversation'}),
}
cl... | Set widgets for textareas so we can set placeholder attribute | Set widgets for textareas so we can set placeholder attribute
| Python | bsd-2-clause | lehins/lehins-discussion,incuna/django-discussion,incuna/django-discussion,lehins/lehins-discussion,lehins/lehins-discussion | ---
+++
@@ -7,13 +7,18 @@
class Meta:
exclude = ('user', 'post')
model = Comment
+ widgets = {
+ 'body' : forms.Textarea(attrs={'placeholder' : 'Reply to this conversation'}),
+ }
class PostForm(forms.ModelForm):
class Meta:
exclude = ('user', 'discus... |
61679e3faf44bc1d54388f617554f03809b2eead | gpytorch/kernels/periodic_kernel.py | gpytorch/kernels/periodic_kernel.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import math
import torch
from torch import nn
from .kernel import Kernel
class PeriodicKernel(Kernel):
def __init__(
self,
log_lengthscale_bounds=... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import math
import torch
from torch import nn
from .kernel import Kernel
class PeriodicKernel(Kernel):
def __init__(
self,
log_lengthscale_bounds=... | Fix dimensions of periodic kernel parameters | Fix dimensions of periodic kernel parameters
| Python | mit | jrg365/gpytorch,jrg365/gpytorch,jrg365/gpytorch | ---
+++
@@ -27,7 +27,7 @@
self.eps = eps
self.register_parameter(
'log_period_length',
- nn.Parameter(torch.zeros(1, 1)),
+ nn.Parameter(torch.zeros(1, 1, 1)),
bounds=log_period_length_bounds,
)
@@ -36,4 +36,4 @@
period_length = (se... |
d2d81cfe441171085f954c30eec718a0220ac286 | hoomd/md/pytest/test_table_pressure.py | hoomd/md/pytest/test_table_pressure.py | import hoomd
import io
def test_table_pressure(simulation_factory, two_particle_snapshot_factory):
"""Test that write.table can log MD pressure values."""
thermo = hoomd.md.compute.ThermodynamicQuantities(hoomd.filter.All())
snap = two_particle_snapshot_factory()
if snap.communicator.rank == 0:
... | import hoomd
import io
import numpy
def test_table_pressure(simulation_factory, two_particle_snapshot_factory):
"""Test that write.table can log MD pressure values."""
thermo = hoomd.md.compute.ThermodynamicQuantities(hoomd.filter.All())
snap = two_particle_snapshot_factory()
if snap.communicator.rank... | Add output check on the pressure quantity | Add output check on the pressure quantity
| Python | bsd-3-clause | joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue | ---
+++
@@ -1,5 +1,6 @@
import hoomd
import io
+import numpy
def test_table_pressure(simulation_factory, two_particle_snapshot_factory):
@@ -11,15 +12,22 @@
sim = simulation_factory(snap)
sim.operations.add(thermo)
- integrator = hoomd.md.Integrator(dt=0.0001)
+ integrator = hoomd.md.Integrat... |
b690b87094b4205b448ba1ea5dda546c3e7a976d | python/xi_plugin/style.py | python/xi_plugin/style.py | # Copyright 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http:#www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | # Copyright 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http:#www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | Support setting alpha in colors | Support setting alpha in colors
| Python | apache-2.0 | google/xi-editor,fuchsia-mirror/third_party-xi-editor,modelorganism/xi-editor,fuchsia-mirror/third_party-xi-editor,modelorganism/xi-editor,google/xi-editor,modelorganism/xi-editor,fuchsia-mirror/third_party-xi-editor,google/xi-editor,fuchsia-mirror/third_party-xi-editor,google/xi-editor | ---
+++
@@ -19,8 +19,8 @@
ITALIC = 4
-def color_for_rgb_float(red, green, blue):
- if any(map(lambda x: x < 0 or x > 1, (red, green, blue))):
+def color_for_rgba_float(red, green, blue, alpha=1):
+ if any(map(lambda x: x < 0 or x > 1, (red, green, blue, alpha))):
raise ValueError("Values must be i... |
8dc1bab80e52442999eb59e096abd5848c4e8d66 | unicornclient/routine.py | unicornclient/routine.py | import threading
import queue
class Routine(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.queue = queue.Queue()
self.manager = None
self.no_wait = False
def run(self):
while True:
got_task = False
data = None
... | import threading
import queue
class Routine(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.queue = queue.Queue()
self.manager = None
self.no_wait = False
self.is_stopping = False
def run(self):
while True:
got_task = Fals... | Allow one last call to process before stopping | Allow one last call to process before stopping
| Python | mit | amm0nite/unicornclient,amm0nite/unicornclient | ---
+++
@@ -7,6 +7,7 @@
self.queue = queue.Queue()
self.manager = None
self.no_wait = False
+ self.is_stopping = False
def run(self):
while True:
@@ -29,12 +30,15 @@
routine_command = data[index] if index in data else None
if routin... |
b1685dc4a0a2036378d47f07d7315e5b1935a4ad | hyrodactil/tests/openings/models.py | hyrodactil/tests/openings/models.py | from django.test import TestCase
from ..factories._applications import ApplicationFactory
from ..factories._companysettings import InterviewStageFactory
from ..factories._openings import OpeningFactory
class OpeningsModelsTests(TestCase):
def test_applicants_stats(self):
opening = OpeningFactory()
... | from django.test import TestCase
from ..factories._applications import ApplicationFactory
from ..factories._companysettings import InterviewStageFactory
from ..factories._openings import OpeningFactory
class OpeningsModelsTests(TestCase):
def test_applicants_stats(self):
opening = OpeningFactory()
... | Fix tests for positioned stages | openings: Fix tests for positioned stages
| Python | mit | hizardapp/Hizard,hizardapp/Hizard,hizardapp/Hizard | ---
+++
@@ -9,7 +9,7 @@
def test_applicants_stats(self):
opening = OpeningFactory()
self.assertEqual(opening.applicants_stats(), [])
- s1 = InterviewStageFactory(name="L220", initial=True,
+ s1 = InterviewStageFactory(name="L220",
company=opening.company)
... |
6826f4ecef0573f22430e5ed040618f8ded4d73f | dmagellan/launch.py | dmagellan/launch.py | # run this with python -i
import dask, distributed
from distributed import Client
from distributed.deploy.adaptive import Adaptive
from dask_condor import HTCondorCluster
import logging, os
logging.basicConfig(level=0)
logging.getLogger("distributed.comm.tcp").setLevel(logging.ERROR)
logging.getLogger("distributed.dep... | # run this with python -i
import dask, distributed
from distributed import Client
from distributed.deploy.adaptive import Adaptive
from dask_condor import HTCondorCluster
import logging, os
logging.basicConfig(level=0)
logging.getLogger("distributed.comm.tcp").setLevel(logging.ERROR)
logging.getLogger("distributed.dep... | Use new dmagellan worker tarball (854e51d) | Use new dmagellan worker tarball (854e51d)
| Python | apache-2.0 | matyasselmeci/dask_condor,matyasselmeci/dask_condor | ---
+++
@@ -9,7 +9,7 @@
logging.getLogger("distributed.comm.tcp").setLevel(logging.ERROR)
logging.getLogger("distributed.deploy.adaptive").setLevel(logging.WARNING)
-worker_tarball="dask_condor_worker_dmagellan.SL6.tar.gz"
+worker_tarball="dask_condor_worker_dmagellan.854e51d.SL6.tar.gz"
if os.path.exists(os.p... |
c579ff6d920922d317d2d11aa7ca7cefdefafaec | python_scripts/mc_solr.py | python_scripts/mc_solr.py | import requests
import ipdb
import mc_config
import psycopg2
import psycopg2.extras
import time
def get_solr_location():
##TODO -- get this from the yaml file
return 'http://localhost:8983'
def get_solr_collection_url_prefix():
return get_solr_location + '/solr/collection1'
def solr_request( path, params... | import requests
import ipdb
import mc_config
import psycopg2
import psycopg2.extras
import time
def get_solr_location():
##TODO -- get this from the yaml file
return 'http://localhost:8983'
def get_solr_collection_url_prefix():
return get_solr_location() + '/solr/collection1'
def solr_request( path, para... | Fix URL typo full_import ==> full-import | Fix URL typo full_import ==> full-import
| Python | agpl-3.0 | AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter... | ---
+++
@@ -10,12 +10,17 @@
return 'http://localhost:8983'
def get_solr_collection_url_prefix():
- return get_solr_location + '/solr/collection1'
+ return get_solr_location() + '/solr/collection1'
def solr_request( path, params):
+ ipdb.set_trace()
url = get_solr_collection_url_prefix() + '/'... |
8c78095c75c5862de12d33e94610a35bfbacf2bf | react_router/templates.py | react_router/templates.py | MOUNT_JS = \
"""
if (typeof {var}.React === 'undefined') throw new Error('Cannot find `React` variable. Have you added an object to your JS export which points to React?');
if (typeof {var}.router === 'undefined') throw new Error('Cannot find `router` variable. Have you added an object to your JS export which points to... | MOUNT_JS = \
"""
if (typeof {var}.React === 'undefined') throw new Error('Cannot find `React` variable. Have you added an object to your JS export which points to React?');
if (typeof {var}.router === 'undefined') throw new Error('Cannot find `router` variable. Have you added an object to your JS export which points to... | Update template to use new react-dom | Update template to use new react-dom
In React 0.14, the DOM manipulation algorithms have been pulled out into
a new package called react-dom. We update our template to use this new
package.
| Python | mit | HorizonXP/python-react-router,HorizonXP/python-react-router,HorizonXP/python-react-router | ---
+++
@@ -9,5 +9,5 @@
var container = document.getElementById(containerId);
if (!container) throw new Error('Cannot find the container element `#{container_id}` for component `{var}`');
React.render(element, container);
-}})({var}.React, {var}.routes, {var}.router, '{container_id}');
+}})({var}.ReactDOM, {... |
ac27cb2348748a774ab2ae14ade2c49de94c2b4f | frigg/worker/cli.py | frigg/worker/cli.py | # -*- coding: utf8 -*-
from fabric import colors
from frigg.worker.fetcher import fetcher
class Commands(object):
@staticmethod
def start():
print(colors.green("Starting frigg worker"))
fetcher()
@staticmethod
def unknown_command():
print(colors.red("Unknown command"))
def ... | # -*- coding: utf8 -*-
import os
import logging.config
from fabric import colors
from .fetcher import fetcher
class Commands(object):
@staticmethod
def start():
print(colors.green("Starting frigg worker"))
fetcher()
@staticmethod
def unknown_command():
print(colors.red("Unk... | Add loading of logging config | Add loading of logging config
| Python | mit | frigg/frigg-worker | ---
+++
@@ -1,6 +1,10 @@
# -*- coding: utf8 -*-
+import os
+import logging.config
+
from fabric import colors
-from frigg.worker.fetcher import fetcher
+
+from .fetcher import fetcher
class Commands(object):
@@ -18,6 +22,11 @@
def main():
import argparse
+ try:
+ logging.config.fileConfig(os.... |
a4fcd6c4f628de22064ea054bac5603838b35459 | councilmatic_core/migrations/0041_event_extras.py | councilmatic_core/migrations/0041_event_extras.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-05-07 16:20
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('councilmatic_core', '0040_mediaevent_meta'),
]
... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-05-07 16:20
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('councilmatic_core', '0040_mediaevent_meta'),
]
... | Use json_build_object, rather than jsonb_build_object | Use json_build_object, rather than jsonb_build_object
| Python | mit | datamade/django-councilmatic,datamade/django-councilmatic,datamade/django-councilmatic,datamade/django-councilmatic | ---
+++
@@ -20,7 +20,7 @@
),
migrations.RunSQL('''
UPDATE councilmatic_core_event
- SET extras = jsonb_build_object('guid', guid)
+ SET extras = json_build_object('guid', guid)
WHERE guid IS NOT NULL
''', reverse_sql='''
UPD... |
98e5a1fe20e6eefa108ca3e5323da1bf3ad65be9 | corehq/apps/hqadmin/management/commands/shutdown_celery_worker_by_hostname.py | corehq/apps/hqadmin/management/commands/shutdown_celery_worker_by_hostname.py | from django.core.management.base import BaseCommand
from django.conf import settings
from celery import Celery
class Command(BaseCommand):
help = "Gracefully shutsdown a celery worker"
args = 'hostname'
def handle(self, hostname, *args, **options):
celery = Celery()
celery.config_from_obj... | from django.core.management.base import BaseCommand
from django.conf import settings
from celery import Celery
from corehq.apps.hqadmin.utils import parse_celery_pings
class Command(BaseCommand):
help = "Gracefully shutsdown a celery worker"
args = 'hostname'
def handle(self, hostname, *args, **options)... | Exit 1 based on whether or not it was shutdown correctly | Exit 1 based on whether or not it was shutdown correctly
| Python | bsd-3-clause | dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq | ---
+++
@@ -1,6 +1,8 @@
from django.core.management.base import BaseCommand
from django.conf import settings
from celery import Celery
+
+from corehq.apps.hqadmin.utils import parse_celery_pings
class Command(BaseCommand):
@@ -11,3 +13,9 @@
celery = Celery()
celery.config_from_object(setting... |
2d1488669721a46350b5c0f06a049f5d4816f931 | sauna/plugins/ext/disk.py | sauna/plugins/ext/disk.py | from sauna.plugins import PluginRegister
from sauna.plugins.base import PsutilPlugin
my_plugin = PluginRegister('Disk')
@my_plugin.plugin()
class Disk(PsutilPlugin):
@my_plugin.check()
def used_percent(self, check_config):
check_config = self._strip_percent_sign_from_check_config(check_config)
... | import os
from sauna.plugins import PluginRegister
from sauna.plugins.base import PsutilPlugin
my_plugin = PluginRegister('Disk')
@my_plugin.plugin()
class Disk(PsutilPlugin):
@my_plugin.check()
def used_percent(self, check_config):
check_config = self._strip_percent_sign_from_check_config(check_co... | Create Disk check to monitor inodes | Create Disk check to monitor inodes
| Python | bsd-2-clause | bewiwi/sauna,NicolasLM/sauna,NicolasLM/sauna,bewiwi/sauna | ---
+++
@@ -1,3 +1,5 @@
+import os
+
from sauna.plugins import PluginRegister
from sauna.plugins.base import PsutilPlugin
@@ -21,6 +23,26 @@
)
return 0, 'Disk usage correct'
+ @my_plugin.check()
+ def used_inodes_percent(self, check_config):
+ check_config = self._strip_pe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.