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 |
|---|---|---|---|---|---|---|---|---|---|---|
528edba420089249bd58c0621e06225db84e223f | opps/contrib/logging/models.py | opps/contrib/logging/models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from opps.core.models import NotUserPublishable
class Logging(NotUserPublishable):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from opps.core.models import NotUserPublishable
class Logging(NotUserPublishable):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
... | Add missing translation on logging contrib app | Add missing translation on logging contrib app
| Python | mit | jeanmask/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,opps/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps | ---
+++
@@ -11,6 +11,7 @@
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
null=True, blank=True,
+ verbose_name=_(u'User')
)
application = models.CharField(
_(u"Application"),
@@ -30,3 +31,7 @@
def save(self, *args, **kwargs):
self.published = True
... |
411decbdb193b28bb3060e02e81bfa29483e85a9 | staticgen_demo/blog/staticgen_views.py | staticgen_demo/blog/staticgen_views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
class BlogPostListView(StaticgenView):
is_paginated = True
i18n = True
def items(self):
return ('blog... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
class BlogPostListView(StaticgenView):
is_paginated = True
i18n = True
def items(self):
return ('blog... | Remove debug code from staticgen views. | Remove debug code from staticgen views.
| Python | bsd-3-clause | mishbahr/staticgen-demo,mishbahr/staticgen-demo,mishbahr/staticgen-demo | ---
+++
@@ -15,25 +15,6 @@
def items(self):
return ('blog:posts_list', )
- def _get_paginator(self, url):
- response = self.client.get(url)
- print 'status_code: %s' % response.status_code
- if not response.status_code == 200:
- pass
- else:
- conte... |
673d6cecfaeb0e919f30997f793ee2bb18e399ee | tempest/api_schema/response/compute/v2/hypervisors.py | tempest/api_schema/response/compute/v2/hypervisors.py | # Copyright 2014 NEC Corporation. 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 ... | # Copyright 2014 NEC Corporation. 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 ... | Fix V2 hypervisor server schema attribute | Fix V2 hypervisor server schema attribute
Nova v2 hypervisor server API return attribute "uuid" in response's
server dict. Current response schema does not have this attribute instead
it contain "id" which is wrong.
This patch fix the above issue.
NOTE- "uuid" attribute in this API response is always a uuid.
Change... | Python | apache-2.0 | jaspreetw/tempest,openstack/tempest,Vaidyanath/tempest,vedujoshi/tempest,NexusIS/tempest,FujitsuEnablingSoftwareTechnologyGmbH/tempest,tonyli71/tempest,hayderimran7/tempest,xbezdick/tempest,akash1808/tempest,roopali8/tempest,tudorvio/tempest,alinbalutoiu/tempest,flyingfish007/tempest,manasi24/jiocloud-tempest-qatempest... | ---
+++
@@ -26,11 +26,7 @@
'items': {
'type': 'object',
'properties': {
- # NOTE: Now the type of 'id' is integer,
- # but here allows 'string' also because we
- # will be able to change it to 'uuid' in
- # the future.
- ... |
69c6759625c8faacd2ce5194c9845349c61dda7f | tests/py39compat.py | tests/py39compat.py | try:
from test.support.os_helpers import FS_NONASCII
except ImportError:
from test.support import FS_NONASCII # noqa
| try:
from test.support.os_helper import FS_NONASCII
except ImportError:
from test.support import FS_NONASCII # noqa
| Use os_helper to fix ImportError in Python 3.10 | Use os_helper to fix ImportError in Python 3.10
| Python | apache-2.0 | python/importlib_metadata | ---
+++
@@ -1,4 +1,4 @@
try:
- from test.support.os_helpers import FS_NONASCII
+ from test.support.os_helper import FS_NONASCII
except ImportError:
from test.support import FS_NONASCII # noqa |
6de1083784d8a73e234dd14cabd17e7ee5852949 | tools/clean_output_directory.py | tools/clean_output_directory.py | #!/usr/bin/env python
#
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
#
import shutil
import sys
import utils
def Main():
build_root = utils.GetBuild... | #!/usr/bin/env python
#
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
#
import shutil
import sys
import subprocess
import utils
def Main():
build_roo... | Add missing import to utility python script | Add missing import to utility python script
BUG=
R=kustermann@google.com
Review URL: https://codereview.chromium.org//1222793010.
| Python | bsd-3-clause | dart-lang/sdk,dart-lang/sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/da... | ---
+++
@@ -7,6 +7,7 @@
import shutil
import sys
+import subprocess
import utils
def Main(): |
13c968f9f345f58775750f1f83ca7881cee2755a | bootstrap/conf/salt/state/run-tracking-db/scripts/import_sample_data.py | bootstrap/conf/salt/state/run-tracking-db/scripts/import_sample_data.py | import pandas as pd
import sys
df = pd.read_csv(sys.argv[1])
df.columns = [c.lower() for c in df.columns]
from sqlalchemy import create_engine
engine = create_engine('postgresql://pcawg_admin:pcawg@localhost:5432/germline_genotype_tracking')
df.to_sql("pcawg_samples", engine) | import pandas as pd
import sys
df = pd.read_csv(sys.argv[1])
df.columns = [c.lower() for c in df.columns]
from sqlalchemy import create_engine
engine = create_engine('postgresql://pcawg_admin:pcawg@run-tracking-db.service.consul:5432/germline_genotype_tracking')
df.to_sql("pcawg_samples", engine) | Use Tracking DB Service URL rather than localhost in the DB connection string. | Use Tracking DB Service URL rather than localhost in the DB connection string.
| Python | mit | llevar/germline-regenotyper,llevar/germline-regenotyper | ---
+++
@@ -6,6 +6,6 @@
df.columns = [c.lower() for c in df.columns]
from sqlalchemy import create_engine
-engine = create_engine('postgresql://pcawg_admin:pcawg@localhost:5432/germline_genotype_tracking')
+engine = create_engine('postgresql://pcawg_admin:pcawg@run-tracking-db.service.consul:5432/germline_genotyp... |
fedff2e76d8d96f1ea407f7a3a48aa8dc7a7e50a | analysis/opensimulator-stats-analyzer/src/ostagraph.py | analysis/opensimulator-stats-analyzer/src/ostagraph.py | #!/usr/bin/python
import argparse
import matplotlib.pyplot as plt
from pylab import *
from osta.osta import *
############
### MAIN ###
############
parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter)
parser.add_argument(
'--select',
help = "Select the full name of a stat to gr... | #!/usr/bin/python
import argparse
import matplotlib.pyplot as plt
from pylab import *
from osta.osta import *
############
### MAIN ###
############
parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter)
parser.add_argument(
'--select',
help = "Select the full name of a stat to gr... | Make x axis label samples for now, though eventually should have a date option | Make x axis label samples for now, though eventually should have a date option
| Python | bsd-3-clause | justinccdev/opensimulator-tools,justinccdev/opensimulator-tools,justinccdev/opensimulator-tools,justinccdev/opensimulator-tools | ---
+++
@@ -34,6 +34,7 @@
if not stat == None:
plt.plot(stat['abs']['values'])
plt.title(stat['fullName'])
+ plt.xlabel("samples")
plt.ylabel(stat['name'])
if 'out' in opts: |
114b3f3403e970943618e7096b0b898b8aa5589f | microdrop/core_plugins/electrode_controller_plugin/on_plugin_install.py | microdrop/core_plugins/electrode_controller_plugin/on_plugin_install.py | from datetime import datetime
import logging
from path_helpers import path
from pip_helpers import install
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
logging.info(str(datetime.now()))
requirements_file = path(__file__).parent.joinpath('requirements.txt')
if requirements_file.e... | from datetime import datetime
import logging
from path_helpers import path
from pip_helpers import install
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
logging.info(str(datetime.now()))
requirements_file = path(__file__).parent.joinpath('requirements.txt')
if requirements_file.e... | Remove verbose keywork for pip install | Remove verbose keywork for pip install
| Python | bsd-3-clause | wheeler-microfluidics/microdrop | ---
+++
@@ -10,4 +10,4 @@
logging.info(str(datetime.now()))
requirements_file = path(__file__).parent.joinpath('requirements.txt')
if requirements_file.exists():
- logging.info(install(['-U', '-r', requirements_file], verbose=True))
+ logging.info(install(['-U', '-r', requirements_file])) |
a35c2c4e3d332c8ee581608317c4496722fb9b77 | us_ignite/advertising/models.py | us_ignite/advertising/models.py | from django.db import models
from django_extensions.db.fields import (
AutoSlugField, CreationDateTimeField, ModificationDateTimeField)
from us_ignite.advertising import managers
class Advert(models.Model):
PUBLISHED = 1
DRAFT = 2
REMOVED = 3
STATUS_CHOICES = (
(PUBLISHED, 'Published'),
... | from django.db import models
from django_extensions.db.fields import (
AutoSlugField, CreationDateTimeField, ModificationDateTimeField)
from us_ignite.advertising import managers
class Advert(models.Model):
PUBLISHED = 1
DRAFT = 2
REMOVED = 3
STATUS_CHOICES = (
(PUBLISHED, 'Published'),
... | Update wording on path of the image. | Update wording on path of the image.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite | ---
+++
@@ -20,7 +20,7 @@
slug = AutoSlugField(populate_from='name')
status = models.IntegerField(choices=STATUS_CHOICES, default=DRAFT)
url = models.URLField(max_length=500)
- image = models.ImageField(upload_to="ads")
+ image = models.ImageField(upload_to="featured")
is_featured = models.B... |
aaa88075d4cf799509584de439f207476e092584 | doc/conf.py | doc/conf.py | import os
import sys
import qirest
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo']
autoclass_content = "both"
autodoc_default_flags= ['members', 'show-inheritance']
source_suffix = '.rst'
master_doc = 'index'
project = u'qirest'
copyright = u'2014, OHSU Knight Cancer Institute. This so... | import os
import sys
try:
import qirest
except ImportError:
# A ReadTheDocs build does not install qirest. In that case,
# load the module directly.
src_dir = os.path.join(os.path.dirname(__file__), '..')
sys.path.append(src_dir)
import qirest
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.int... | Use alternate import for RTD. | Use alternate import for RTD.
| Python | bsd-2-clause | ohsu-qin/qiprofile-rest,ohsu-qin/qirest | ---
+++
@@ -1,6 +1,13 @@
import os
import sys
-import qirest
+try:
+ import qirest
+except ImportError:
+ # A ReadTheDocs build does not install qirest. In that case,
+ # load the module directly.
+ src_dir = os.path.join(os.path.dirname(__file__), '..')
+ sys.path.append(src_dir)
+ import qirest
... |
0ac28421fe8ed4234db13ebdbb95c700191ba042 | bugle_project/bugle/templatetags/bugle.py | bugle_project/bugle/templatetags/bugle.py | from django import template
from django.contrib.auth.models import User
from django.utils.safestring import mark_safe
import re
import urllib
register = template.Library()
username_re = re.compile('@[0-9a-zA-Z]+')
hashtag_re = re.compile('(?:^|\s)(#\S+)')
@register.filter
def buglise(s):
s = unicode(s)
... | from django import template
from django.contrib.auth.models import User
from django.utils.safestring import mark_safe
import re
import urllib
register = template.Library()
username_re = re.compile('@[0-9a-zA-Z]+')
hashtag_re = re.compile('(^|\s)(#\S+)')
@register.filter
def buglise(s):
s = unicode(s)
us... | Remove spaces from hash tag links | Remove spaces from hash tag links
| Python | bsd-2-clause | devfort/bugle,devfort/bugle,simonw/bugle_project,devfort/bugle,simonw/bugle_project | ---
+++
@@ -7,7 +7,7 @@
register = template.Library()
username_re = re.compile('@[0-9a-zA-Z]+')
-hashtag_re = re.compile('(?:^|\s)(#\S+)')
+hashtag_re = re.compile('(^|\s)(#\S+)')
@register.filter
def buglise(s):
@@ -26,9 +26,10 @@
s = username_re.sub(replace_username, s)
s = hashtag_re.sub(
- ... |
7a78525bb8cc6176dfbe348e5f95373c1d70628f | functions.py | functions.py | #-*- coding: utf-8 -*-
def getClientIP( req ):
'''
Get the client ip address
'''
xForwardedFor=req.META.get('HTTP_X_FORWARDED_FOR')
if xForwardedFor:
ip=xForwardedFor.split(',')[0]
else:
ip=req.META.get('REMOTE_ADDR')
return ip
def getBool( val, trueOpts=['YES', 'Y', '1', 'TRUE', 'T'] ):
'''
Retrieve the... | #-*- coding: utf-8 -*-
def getClientIP( req ):
'''
Get the client ip address
@param req The request;
'''
xForwardedFor=req.META.get('HTTP_X_FORWARDED_FOR')
if xForwardedFor:
ip=xForwardedFor.split(',')[0]
else:
ip=req.META.get('REMOTE_ADDR')
return ip
def getBool( val, defVal=False, trueOpts=['YES', 'Y',... | Add the checkRecaptcha( req, secret, simple=True ) function | Add the checkRecaptcha( req, secret, simple=True ) function
| Python | apache-2.0 | kensonman/webframe,kensonman/webframe,kensonman/webframe | ---
+++
@@ -3,6 +3,8 @@
def getClientIP( req ):
'''
Get the client ip address
+
+ @param req The request;
'''
xForwardedFor=req.META.get('HTTP_X_FORWARDED_FOR')
if xForwardedFor:
@@ -11,10 +13,34 @@
ip=req.META.get('REMOTE_ADDR')
return ip
-def getBool( val, trueOpts=['YES', 'Y', '1', 'TRUE', 'T'] )... |
f2f74f53fe8f5b4ac4cd728c4181b3a66b4e873d | euler009.py | euler009.py | # euler 009
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a^2 + b^2 = c^2
#
# For example, 32 + 42 = 9 + 16 = 25 = 52.
#
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
| # Project Euler
# 9 - Special Pythagorean triplet
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a^2 + b^2 = c^2
#
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
#
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
| Change problem description so it actually makes sense | Change problem description so it actually makes sense
| Python | mit | josienb/project_euler,josienb/project_euler | ---
+++
@@ -1,10 +1,11 @@
-# euler 009
+# Project Euler
+# 9 - Special Pythagorean triplet
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a^2 + b^2 = c^2
#
-# For example, 32 + 42 = 9 + 16 = 25 = 52.
-#
+# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
+#
# There exists exactly... |
87f892731678049b5a706a36487982ebb9da3991 | pybossa_discourse/globals.py | pybossa_discourse/globals.py | # -*- coding: utf8 -*-
"""Jinja globals module for pybossa-discourse."""
from flask import Markup, request
from . import discourse_client
class DiscourseGlobals(object):
"""A class to implement Discourse Global variables."""
def __init__(self, app):
self.url = app.config['DISCOURSE_URL']
app... | # -*- coding: utf8 -*-
"""Jinja globals module for pybossa-discourse."""
from flask import Markup, request
from . import discourse_client
class DiscourseGlobals(object):
"""A class to implement Discourse Global variables."""
def __init__(self, app):
self.url = app.config['DISCOURSE_URL']
sel... | Add API client to global envar | Add API client to global envar
| Python | bsd-3-clause | alexandermendes/pybossa-discourse | ---
+++
@@ -10,6 +10,7 @@
def __init__(self, app):
self.url = app.config['DISCOURSE_URL']
+ self.api = discourse_client
app.jinja_env.globals.update(discourse=self)
def comments(self): |
edb07b507aa93ead278cecd168da83a4be68b2ba | bluebottle/settings/travis.py | bluebottle/settings/travis.py |
# SECRET_KEY and DATABASES needs to be defined before the base settings is imported.
SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q=='
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
from .base import *
#
# Put the travis-ci e... |
# SECRET_KEY and DATABASES needs to be defined before the base settings is imported.
SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q=='
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
from .base import *
#
# Put the travis-ci e... | Disable front-end testing on Travis | Disable front-end testing on Travis
Travis has dificulty running the front-end tests.
For now we'll disable them.
| Python | bsd-3-clause | onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site | ---
+++
@@ -15,4 +15,5 @@
# Put the travis-ci environment specific overrides below.
#
-SELENIUM_TESTS = True
+# Disable Selenium testing for now on Travis because it fails inconsistent.
+# SELENIUM_TESTS = True |
f3f428480a8e61bf22532503680e718fd5f0d286 | fb/views.py | fb/views.py | from django.shortcuts import render
# Create your views here.
| from django.shortcuts import render
from fb.models import UserPost
def index(request):
if request.method == 'GET':
posts = UserPost.objects.all()
context = {
'posts': posts,
}
return render(request, 'index.html', context)
| Write the first view - news feed. | Write the first view - news feed.
| Python | apache-2.0 | pure-python/brainmate | ---
+++
@@ -1,3 +1,12 @@
from django.shortcuts import render
-# Create your views here.
+from fb.models import UserPost
+
+
+def index(request):
+ if request.method == 'GET':
+ posts = UserPost.objects.all()
+ context = {
+ 'posts': posts,
+ }
+ return render(request, 'ind... |
e978b8be7ccfd9206d618f5a3de855a306ceccfe | test.py | test.py | import unittest
from enigma import Enigma, Steckerbrett, Umkehrwalze, Walzen
class RotorTestCase(unittest.TestCase):
def test_rotor_encoding(self):
rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q')
self.assertEqual('E', rotor.encode('A'))
def test_rotor_reverse_encoding(self):
... | import unittest
from enigma import Enigma, Steckerbrett, Umkehrwalze, Walzen
class RotorTestCase(unittest.TestCase):
def test_rotor_encoding(self):
rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q')
self.assertEqual('E', rotor.encode('A'))
def test_rotor_reverse_encoding(self):
... | Test if rotor encodes with different offset properly | Test if rotor encodes with different offset properly
| Python | mit | ranisalt/enigma | ---
+++
@@ -19,6 +19,12 @@
self.assertEqual('K', rotor.encode('A'))
self.assertEqual('K', rotor.encode_reverse('A'))
+ def test_rotor_different_offset(self):
+ rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q',
+ offset='B')
+ self.assertEqual('D'... |
691093e38598959f98b319f7c57852496a26ba90 | apps/careers/models.py | apps/careers/models.py | import watson
from cms.apps.pages.models import ContentBase
from cms.models import HtmlField, SearchMetaBase
from django.db import models
class Careers(ContentBase):
# The heading that the admin places this content under.
classifier = "apps"
# The urlconf used to power this content's views.
urlconf ... | import watson
from cms.apps.pages.models import ContentBase
from cms.models import HtmlField, SearchMetaBase
from django.db import models
class Careers(ContentBase):
# The heading that the admin places this content under.
classifier = "apps"
# The urlconf used to power this content's views.
urlconf ... | Fix project name in urlconf | Fix project name in urlconf
| Python | mit | onespacemedia/cms-jobs,onespacemedia/cms-jobs | ---
+++
@@ -10,7 +10,7 @@
classifier = "apps"
# The urlconf used to power this content's views.
- urlconf = "phixflow.apps.careers.urls"
+ urlconf = "{{ project_name }}.apps.careers.urls"
standfirst = models.TextField(
blank=True, |
88e0ec5ff58f7dabb531749472a410498c8e7827 | py_skiplist/iterators.py | py_skiplist/iterators.py | from itertools import dropwhile, count, cycle
import random
def geometric(p):
return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in cycle([1]))
def uniform(n):
"""
Simple deterministic distribution for testing internal of the skiplist
"""
return (n for _ in cyc... | from itertools import dropwhile, count, repeat
import random
def geometric(p):
return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in repeat(1))
# Simple deterministic distribution for testing internals of the skiplist.
uniform = repeat
| Use itertools.repeat over slower alternatives. | Use itertools.repeat over slower alternatives. | Python | mit | ZhukovAlexander/skiplist-python | ---
+++
@@ -1,13 +1,10 @@
-from itertools import dropwhile, count, cycle
+from itertools import dropwhile, count, repeat
import random
def geometric(p):
- return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in cycle([1]))
+ return (next(dropwhile(lambda _: random.randint(... |
52d65ff926a079b4e07e8bc0fda3e3c3fe8f9437 | thumbor/detectors/queued_detector/__init__.py | thumbor/detectors/queued_detector/__init__.py | from remotecv import pyres_tasks
from remotecv.unique_queue import UniqueQueue
from thumbor.detectors import BaseDetector
class QueuedDetector(BaseDetector):
queue = UniqueQueue()
def detect(self, callback):
engine = self.context.modules.engine
self.queue.enqueue_unique(pyres_tasks.DetectTask... | from remotecv.unique_queue import UniqueQueue
from thumbor.detectors import BaseDetector
class QueuedDetector(BaseDetector):
queue = UniqueQueue()
def detect(self, callback):
engine = self.context.modules.engine
self.queue.enqueue_unique_from_string('remotecv.pyres_tasks.DetectTask', 'Detect'... | Remove dependency from remotecv worker on queued detector | Remove dependency from remotecv worker on queued detector
| Python | mit | fanhero/thumbor,fanhero/thumbor,fanhero/thumbor,fanhero/thumbor | ---
+++
@@ -1,4 +1,3 @@
-from remotecv import pyres_tasks
from remotecv.unique_queue import UniqueQueue
from thumbor.detectors import BaseDetector
@@ -8,7 +7,7 @@
def detect(self, callback):
engine = self.context.modules.engine
- self.queue.enqueue_unique(pyres_tasks.DetectTask,
+ se... |
c9f8663e6b0bf38f6c041a3a6b77b8a0007a9f09 | urls.py | urls.py | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.views.generic.simple import direct_to_template
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^i4p/', include('i4p.foo.urls')),
# Uncomment the admin/d... | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.views.generic.simple import direct_to_template
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^i4p/', include('i4p.foo.urls')),
# Uncomment the admin/d... | Add a name to the index URL | Add a name to the index URL
| Python | agpl-3.0 | ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople | ---
+++
@@ -14,6 +14,6 @@
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
- (r'^$', direct_to_template, {'template' : 'base.html'}),
+ url(r'^$', direct_to_template, {'template' : 'base.html'}, name="i4p-index"),
(r'^accounts/', include('registration.backe... |
73ff56f4b8859e82b0d69a6505c982e26de27859 | util.py | util.py |
def product(nums):
r = 1
for n in nums:
r *= n
return r
def choose(n, k):
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in range(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
return 0
def ... | import colorsys
import random
def randcolor():
hue = random.random()
sat = random.randint(700, 1000) / 1000
val = random.randint(700, 1000) / 1000
return tuple(int(f*255) for f in colorsys.hsv_to_rgb(hue, sat, val))
def product(nums):
r = 1
for n in nums:
r *= n
return r
def choos... | Add randcolor function to uitl | Add randcolor function to uitl
| Python | unlicense | joseph346/cellular | ---
+++
@@ -1,3 +1,11 @@
+import colorsys
+import random
+
+def randcolor():
+ hue = random.random()
+ sat = random.randint(700, 1000) / 1000
+ val = random.randint(700, 1000) / 1000
+ return tuple(int(f*255) for f in colorsys.hsv_to_rgb(hue, sat, val))
def product(nums):
r = 1 |
7801c5d7430233eb78ab8b2a91f5960bd808b2c7 | app/admin/views.py | app/admin/views.py | from flask import Blueprint, render_template
from flask_security import login_required
admin = Blueprint('admin', __name__)
@admin.route('/')
@admin.route('/index')
@login_required
def index():
return render_template('admin/index.html', title='Admin')
| from flask import Blueprint, render_template, redirect, url_for
from flask_security import current_user
admin = Blueprint('admin', __name__)
@admin.route('/')
@admin.route('/index')
def index():
return render_template('admin/index.html', title='Admin')
@admin.before_request
def require_login():
if not curr... | Move admin authentication into before_request handler | Move admin authentication into before_request handler
| Python | mit | Encrylize/flask-blogger,Encrylize/flask-blogger,Encrylize/flask-blogger | ---
+++
@@ -1,11 +1,16 @@
-from flask import Blueprint, render_template
-from flask_security import login_required
+from flask import Blueprint, render_template, redirect, url_for
+from flask_security import current_user
admin = Blueprint('admin', __name__)
@admin.route('/')
@admin.route('/index')
-@login_re... |
6ce14f21cec2c37939f68aaf40d5227c80636e53 | app_bikes/forms.py | app_bikes/forms.py | from dal import autocomplete
from django import forms
class BikeModelForm(forms.ModelForm):
def __init__(self, *args, **kw):
super(BikeModelForm, self).__init__(*args, **kw)
if self.instance is not None:
# Saved instance is loaded, setup choices to display the selected value
... | from dal import autocomplete
from django import forms
class BikeModelForm(forms.ModelForm):
def __init__(self, *args, **kw):
super(BikeModelForm, self).__init__(*args, **kw)
if self.instance is not None:
# Saved instance is loaded, setup choices to display the selected value
... | Add docstring to explain the code | Add docstring to explain the code
| Python | agpl-3.0 | laboiteproject/laboite-backend,laboiteproject/laboite-backend,bgaultier/laboitepro,bgaultier/laboitepro,bgaultier/laboitepro,laboiteproject/laboite-backend | ---
+++
@@ -10,9 +10,9 @@
self.fields['id_station'].widget.choices = ((self.instance.id_station, self.instance.station),)
def validate_unique(self):
+ """If the form had an error and a station was chosen, we need to setup the widget choices to the previously selected value for the autocompl... |
0b1f38b8354a0ad6a021f247a7bc1336ae5d50fb | arcade/__init__.py | arcade/__init__.py | """
The Arcade Library
A Python simple, easy to use module for creating 2D games.
"""
import arcade.key
import arcade.color
from .version import *
from .window_commands import *
from .draw_commands import *
from .sprite import *
from .physics_engines import *
from .physics_engine_2d import *
from .application import ... | """
The Arcade Library
A Python simple, easy to use module for creating 2D games.
"""
import arcade.key
import arcade.color
from arcade.version import *
from arcade.window_commands import *
from arcade.draw_commands import *
from arcade.sprite import *
from arcade.physics_engines import *
from arcade.physics_engine_2... | Change some of the relative imports, which fail in doctests, to absolute imports. | Change some of the relative imports, which fail in doctests, to absolute imports.
| Python | mit | mikemhenry/arcade,mikemhenry/arcade | ---
+++
@@ -6,12 +6,12 @@
import arcade.key
import arcade.color
-from .version import *
-from .window_commands import *
-from .draw_commands import *
-from .sprite import *
-from .physics_engines import *
-from .physics_engine_2d import *
-from .application import *
-from .sound import *
-from .shape_objects impo... |
ed4f786de54dde50cb26cfe4859507579806a14b | portal_sale_distributor/models/ir_action_act_window.py | portal_sale_distributor/models/ir_action_act_window.py | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import models, api
from odoo.tools.safe_eval import safe_eval
... | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import models, api
from odoo.tools.safe_eval import safe_eval
... | Adjust to avoid bugs with other values in context | [FIX] portal_sale_distributor: Adjust to avoid bugs with other values in context
closes ingadhoc/sale#493
X-original-commit: 441d30af0c3fa8cbbe129893107436ea69cca740
Signed-off-by: Juan José Scarafía <1d1652a8631a1f5a0ea40ef8dcad76f737ce6379@adhoc.com.ar>
| Python | agpl-3.0 | ingadhoc/sale,ingadhoc/sale,ingadhoc/sale,ingadhoc/sale | ---
+++
@@ -11,10 +11,14 @@
def read(self, fields=None, load='_classic_read'):
result = super().read(fields, load=load)
- if result and result[0].get('context'):
- ctx = safe_eval(result[0].get('context', '{}'))
- if ctx.get('portal_products'):
+ for value in result... |
cf0d928cffc86e7ba2a68a7e95c54c7e530d2da8 | packages/Python/lldbsuite/test/lang/swift/accelerate_simd/TestAccelerateSIMD.py | packages/Python/lldbsuite/test/lang/swift/accelerate_simd/TestAccelerateSIMD.py | # TestAccelerateSIMD.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTR... | # TestAccelerateSIMD.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTR... | Disable accelerate_simd test for now. | Disable accelerate_simd test for now.
| Python | apache-2.0 | apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb | ---
+++
@@ -13,4 +13,5 @@
from lldbsuite.test.decorators import *
lldbinline.MakeInlineTest(__file__, globals(),
- decorators=[swiftTest,skipUnlessDarwin])
+ decorators=[swiftTest,skipUnlessDarwin,
+ skipIf(bugnumber=46330565)]... |
4f3234433b97e7f243d54e9e95399f5cabecd315 | common/djangoapps/course_modes/migrations/0005_auto_20151217_0958.py | common/djangoapps/course_modes/migrations/0005_auto_20151217_0958.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('course_modes', '0004_auto_20151113_1457'),
]
operations = [
migrations.RemoveField(
model_name='coursemode',
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('course_modes', '0004_auto_20151113_1457'),
]
operations = [
migrations.SeparateDatabaseAndState(
database_operat... | Change broken course_modes migration to not touch the database. | Change broken course_modes migration to not touch the database.
Changing a field name in the way that we did (updating the Python
variable name and switching it to point to the old DB column) confuses
Django's migration autodetector. No DB changes are actually necessary,
but it thinks that a field has been removed and... | Python | agpl-3.0 | antoviaque/edx-platform,pepeportela/edx-platform,edx/edx-platform,teltek/edx-platform,ahmedaljazzar/edx-platform,mitocw/edx-platform,edx-solutions/edx-platform,hastexo/edx-platform,IndonesiaX/edx-platform,pepeportela/edx-platform,Lektorium-LLC/edx-platform,mitocw/edx-platform,marcore/edx-platform,romain-li/edx-platform... | ---
+++
@@ -11,13 +11,18 @@
]
operations = [
- migrations.RemoveField(
- model_name='coursemode',
- name='expiration_datetime',
- ),
- migrations.AddField(
- model_name='coursemode',
- name='_expiration_datetime',
- field=models.D... |
b6937405a9b85026f3e9cffc94fa65c87ee793c0 | kirppu/views/csv_utils.py | kirppu/views/csv_utils.py | # -*- coding: utf-8 -*-
import functools
import io
from urllib.parse import quote
from django.http import StreamingHttpResponse
def strip_generator(fn):
@functools.wraps(fn)
def inner(output, event, generator=False):
if generator:
# Return the generator object only when using StringIO.
... | # -*- coding: utf-8 -*-
import functools
import html
import io
from urllib.parse import quote
from django.conf import settings
from django.http import HttpResponse, StreamingHttpResponse
def strip_generator(fn):
@functools.wraps(fn)
def inner(output, event, generator=False):
if generator:
... | Add possibility to debug csv streamer views. | Add possibility to debug csv streamer views.
| Python | mit | jlaunonen/kirppu,jlaunonen/kirppu,jlaunonen/kirppu,jlaunonen/kirppu | ---
+++
@@ -1,10 +1,11 @@
# -*- coding: utf-8 -*-
import functools
+import html
import io
from urllib.parse import quote
-
-from django.http import StreamingHttpResponse
+from django.conf import settings
+from django.http import HttpResponse, StreamingHttpResponse
def strip_generator(fn):
@@ -20,15 +21,28 ... |
faba2bc98f08cddea51d2e0093aa5c2981c8bf15 | gdrived.py | gdrived.py | #!/usr/bin/env python
#
# Copyright 2012 Jim Lawton. 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 requir... | #!/usr/bin/env python
#
# Copyright 2012 Jim Lawton. 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 requir... | Add update interval constant. Add detail to constructor. | Add update interval constant. Add detail to constructor.
| Python | apache-2.0 | babycaseny/gdrive-linux,jimlawton/gdrive-linux-googlecode,jimlawton/gdrive-linux,jmfield2/gdrive-linux | ---
+++
@@ -19,8 +19,28 @@
import daemon
-class GDriveDaemon(daemon.Daemon):
+UPDATE_INTERVAL = 30 # Sync update interval in seconds.
+
+class GDriveDaemon(daemon.Daemon, object):
+
+ def __init__(self):
+ "Class constructor."
+
+ # Use pidfile in Gdrive config directory.
+ ... |
ee3941e2c3a0355314b270c04de6a623f5a0730c | plugins/stats.py | plugins/stats.py | import operator
class Plugin:
def __call__(self, bot):
bot.on_hear(r"(lol|:D|:P)", self.on_hear)
bot.on_respond(r"stats", self.on_respond)
bot.on_help("stats", self.on_help)
def on_hear(self, bot, msg, reply):
stats = bot.storage.get("stats", {})
for word in msg["match... | import operator
class Plugin:
def __call__(self, bot):
bot.on_hear(r".*", self.on_hear_anything)
bot.on_hear(r"(lol|:D|:P)", self.on_hear)
bot.on_respond(r"stats", self.on_respond)
bot.on_help("stats", self.on_help)
def on_hear_anything(self, bot, msg, reply):
stats = b... | Add statistics about general speaking | Add statistics about general speaking
| Python | mit | thomasleese/smartbot-old,Cyanogenoid/smartbot,tomleese/smartbot,Muzer/smartbot | ---
+++
@@ -2,9 +2,17 @@
class Plugin:
def __call__(self, bot):
+ bot.on_hear(r".*", self.on_hear_anything)
bot.on_hear(r"(lol|:D|:P)", self.on_hear)
bot.on_respond(r"stats", self.on_respond)
bot.on_help("stats", self.on_help)
+
+ def on_hear_anything(self, bot, msg, reply... |
5efca5a3e8fb978cb47e986b1bd7296fe2cae3ce | helpers.py | helpers.py | def get_readable_list(passed_list, sep=', '):
output = ""
for i, item in enumerate(passed_list):
if len(passed_list) is 1:
output += str(item)
else:
if i is not (len(passed_list) - 1):
output += str(item) + sep
else:
output += str(item)
return output
def get_list_as_english(passed_list):
ou... | def get_readable_list(passed_list, sep=', '):
output = ""
for i, item in enumerate(passed_list):
if len(passed_list) is 1:
output += str(item)
else:
if i is not (len(passed_list) - 1):
output += str(item) + sep
else:
output += str(item)
return output
def get_list_as_english(passed_list):
ou... | Add some spaces to get_list_as_english | Add some spaces to get_list_as_english
| Python | agpl-3.0 | hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook | ---
+++
@@ -17,14 +17,14 @@
output = ""
for i, item in enumerate(passed_list):
if len(passed_list) is 1:
- output += str(item)
+ output += str(item) + ' '
elif len(passed_list) is 2:
output += str(item)
if i is not (len(passed_list) - 1):
output += " and "
else:
- output += ""
+ ... |
f2fd7fa693b5be7ae37445fc185611e80aacddf3 | pebble/PblBuildCommand.py | pebble/PblBuildCommand.py | import sh, os
from PblCommand import PblCommand
class PblBuildCommand(PblCommand):
name = 'build'
help = 'Build your Pebble project'
def configure_subparser(self, parser):
parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)')
def run(self, args):
waf_path = os.path... | import sh, os
from PblCommand import PblCommand
class PblBuildCommand(PblCommand):
name = 'build'
help = 'Build your Pebble project'
def configure_subparser(self, parser):
parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)')
def run(self, args):
waf_path = os.path... | Fix bug to actually find the sdk | Fix bug to actually find the sdk
| Python | mit | pebble/libpebble,pebble/libpebble,pebble/libpebble,pebble/libpebble | ---
+++
@@ -21,4 +21,4 @@
if args.sdk:
return args.sdk
else:
- return os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.join('..', '..', '..')))
+ return os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..')) |
898028dea2e04d52c32854752bda34d331c7696f | ynr/apps/candidatebot/management/commands/candidatebot_import_email_from_csv.py | ynr/apps/candidatebot/management/commands/candidatebot_import_email_from_csv.py | from __future__ import unicode_literals
import csv
from django.core.management.base import BaseCommand
from candidatebot.helpers import CandidateBot
from popolo.models import Person
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'filename',
hel... | from __future__ import unicode_literals
import csv
from django.core.management.base import BaseCommand
from candidatebot.helpers import CandidateBot
from popolo.models import Person
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'filename',
hel... | Move on if email exists | Move on if email exists
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | ---
+++
@@ -31,9 +31,12 @@
try:
bot = CandidateBot(row['democlub_id'])
- bot.add_email(row['email'])
- bot.save(source)
- # print(person)
+ try:
+ bot.add_email(row['email'])
+ ... |
4616fdefc1c7df8acccdd89ea792fa24ecfa9ca6 | perf-tests/src/perf-tests.py | perf-tests/src/perf-tests.py | def main():
pass
if __name__ == "__main__":
# execute only if run as a script
main()
| import json
import time
import datetime
import subprocess
import os.path
import sys
import queue
import threading
from coreapi import *
from jobsapi import *
import benchmarks
import graph
def check_environment_variable(env_var_name):
print("Checking: {e} environment variable existence".format(
e=env_var... | Check environment variables before the tests are started | Check environment variables before the tests are started
| Python | apache-2.0 | tisnik/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,jpopelka/fabric8-analytics-common | ---
+++
@@ -1,4 +1,45 @@
+import json
+import time
+import datetime
+import subprocess
+import os.path
+import sys
+import queue
+import threading
+
+from coreapi import *
+from jobsapi import *
+import benchmarks
+import graph
+
+
+def check_environment_variable(env_var_name):
+ print("Checking: {e} environment v... |
2a4d78be3df2d068431fe007b6f2d73956dc23d4 | sitecontent/urls.py | sitecontent/urls.py | from django.conf.urls import patterns, url
from sitecontent import views
urlpatterns = patterns('',
url("^rss/(?P<format>.*)$",
"sitecontent.views.blog_post_feed_richtext_filters", name="blog_post_feed_richtext_filters"),
)
| from django.conf.urls import patterns, url
from sitecontent import views
urlpatterns = patterns('',
url("^feeds/(?P<format>.*)$",
"sitecontent.views.blog_post_feed_richtext_filters", name="blog_post_feed_richtext_filters"),
)
| Use feeds instead of rss | Use feeds instead of rss
| Python | mit | vjousse/viserlalune,vjousse/viserlalune,vjousse/viserlalune,vjousse/viserlalune | ---
+++
@@ -4,6 +4,6 @@
urlpatterns = patterns('',
- url("^rss/(?P<format>.*)$",
+ url("^feeds/(?P<format>.*)$",
"sitecontent.views.blog_post_feed_richtext_filters", name="blog_post_feed_richtext_filters"),
) |
72f763d9759438abd731585a1b5ef67e62e27181 | pyethapp/__init__.py | pyethapp/__init__.py | # -*- coding: utf-8 -*-
# ############# version ##################
from pkg_resources import get_distribution, DistributionNotFound
import os.path
import subprocess
try:
_dist = get_distribution('pyethapp')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.n... | # -*- coding: utf-8 -*-
# ############# version ##################
from pkg_resources import get_distribution, DistributionNotFound
import os.path
import subprocess
import re
GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$')
__version__ = None
try:
_dist = get_d... | Use version gathering logic from hydrachain | Use version gathering logic from hydrachain
| Python | mit | gsalgado/pyethapp,RomanZacharia/pyethapp,ethereum/pyethapp,RomanZacharia/pyethapp,ethereum/pyethapp,changwu-tw/pyethapp,changwu-tw/pyethapp,gsalgado/pyethapp | ---
+++
@@ -3,6 +3,13 @@
from pkg_resources import get_distribution, DistributionNotFound
import os.path
import subprocess
+import re
+
+
+GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$')
+
+
+__version__ = None
try:
_dist = get_distribution('pyethapp')
... |
4541605e27c9fef6cc23b245de50867ff22ea6aa | erpnext/accounts/doctype/accounting_dimension/test_accounting_dimension.py | erpnext/accounts/doctype/accounting_dimension/test_accounting_dimension.py | # -*- coding: utf-8 -*-
# Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestAccountingDimension(unittest.TestCase):
pass
| # -*- coding: utf-8 -*-
# Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
from erpnext.accounts.doctype.journal_entry.tes... | Test Case for accounting dimension | fix: Test Case for accounting dimension
| Python | agpl-3.0 | gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext | ---
+++
@@ -3,8 +3,52 @@
# See license.txt
from __future__ import unicode_literals
-# import frappe
+import frappe
import unittest
+from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
+from erpnext.accounts.doctype.journal_entry.test_journal_entry import make_journal_entry
... |
27112881583e53d790e66d31a2bb4d2a996ee405 | python/sparknlp/functions.py | python/sparknlp/functions.py | from pyspark.sql.functions import udf
from pyspark.sql.types import *
from pyspark.sql import DataFrame
import sys
import sparknlp
def map_annotations(f, output_type: DataType):
sys.modules['sparknlp.annotation'] = sparknlp # Makes Annotation() pickle serializable in top-level
return udf(
lambda con... | from pyspark.sql.functions import udf
from pyspark.sql.types import *
from pyspark.sql import DataFrame
from sparknlp.annotation import Annotation
import sys
import sparknlp
def map_annotations(f, output_type: DataType):
sys.modules['sparknlp.annotation'] = sparknlp # Makes Annotation() pickle serializable in t... | Move import to top level to avoid import fail after fist time on sys.modules hack | Move import to top level to avoid import fail after fist time on sys.modules hack
| Python | apache-2.0 | JohnSnowLabs/spark-nlp,JohnSnowLabs/spark-nlp,JohnSnowLabs/spark-nlp,JohnSnowLabs/spark-nlp | ---
+++
@@ -1,6 +1,7 @@
from pyspark.sql.functions import udf
from pyspark.sql.types import *
from pyspark.sql import DataFrame
+from sparknlp.annotation import Annotation
import sys
import sparknlp
@@ -14,7 +15,6 @@
def map_annotations_strict(f):
- from sparknlp.annotation import Annotation
sys.m... |
c266f5171e875d8dc3abe924e4b6c9ed2a486422 | tests/sentry/web/frontend/test_organization_home.py | tests/sentry/web/frontend/test_organization_home.py | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.testutils import TestCase, PermissionTestCase
class OrganizationHomePermissionTest(PermissionTestCase):
def setUp(self):
super(OrganizationHomePermissionTest, self).setUp()
self.path = reverse('sentry... | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.testutils import TestCase, PermissionTestCase
class OrganizationHomePermissionTest(PermissionTestCase):
def setUp(self):
super(OrganizationHomePermissionTest, self).setUp()
self.path = reverse('sentry... | Add test for non-member access | Add test for non-member access
| Python | bsd-3-clause | drcapulet/sentry,daevaorn/sentry,ifduyue/sentry,hongliang5623/sentry,Natim/sentry,wujuguang/sentry,jokey2k/sentry,korealerts1/sentry,llonchj/sentry,songyi199111/sentry,vperron/sentry,BayanGroup/sentry,BuildingLink/sentry,kevinlondon/sentry,fotinakis/sentry,imankulov/sentry,korealerts1/sentry,boneyao/sentry,jean/sentry,... | ---
+++
@@ -15,6 +15,9 @@
def test_org_member_can_load(self):
self.assert_org_member_can_access(self.path)
+
+ def test_non_member_cannot_load(self):
+ self.assert_non_member_cannot_access(self.path)
class OrganizationHomeTest(TestCase): |
5e2aae6070d60f2149c49e1137ab2a99f3966b3a | python/volumeBars.py | python/volumeBars.py | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
from random import randint
import numpy
import math
import time
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
height = ledMatrix.height
width = ledMatrix.width
barWidth = width / 4
pi = numpy.pi
barHeights = numpy.array([0, pi / 4... | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
from random import randint
import numpy
import math
import time
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
height = ledMatrix.height
width = ledMatrix.width
barWidth = width / 4
pi = numpy.pi
barHeights = numpy.array([0, pi / 4... | Add specific colors for heights | Add specific colors for heights
| Python | mit | DarkAce65/rpi-led-matrix,DarkAce65/rpi-led-matrix | ---
+++
@@ -22,8 +22,13 @@
barHeights += pi / 4
for x in range(width):
barHeight = int(heights[int(x / barWidth)] * height)
- for y in range(height):
+ for y in range(height):
if height - y <= barHeight:
- nextFrame.SetPixel(x, y, randint(0, 255), randint(0, 255), randint(0, 255))
+ if y > 14
+ ... |
214d5f7e09e9b5e854e7471c6dc337456f428647 | quickavro/_compat.py | quickavro/_compat.py | # -*- coding: utf-8 -*-
import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
default_encoding = "UTF-8"
def with_metaclass(meta, *bases):
class metaclass(meta):
__call__ = type.__call__
__init__ = type.__init__
def __new__(cls, name, this_bases, d):
if this... | # -*- coding: utf-8 -*-
import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
default_encoding = "UTF-8"
def with_metaclass(meta, *bases):
class metaclass(meta):
__call__ = type.__call__
__init__ = type.__init__
def __new__(cls, name, this_bases, d):
if this... | Add missing ensure_str for PY2 | Add missing ensure_str for PY2
| Python | apache-2.0 | ChrisRx/quickavro,ChrisRx/quickavro | ---
+++
@@ -34,3 +34,4 @@
range = xrange
ensure_bytes = lambda s: s
+ ensure_str = lambda s: s |
a88eb2c7fc2c2d875836f0a4c201ede0c082aceb | selectable/tests/__init__.py | selectable/tests/__init__.py | from django.db import models
from ..base import ModelLookup
from ..registry import registry
class Thing(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=100)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
... | from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from ..base import ModelLookup
from ..registry import registry
@python_2_unicode_compatible
class Thing(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=100)
def __s... | Update the test model definitions. | Update the test model definitions.
| Python | bsd-2-clause | affan2/django-selectable,affan2/django-selectable,mlavin/django-selectable,mlavin/django-selectable,affan2/django-selectable,mlavin/django-selectable | ---
+++
@@ -1,37 +1,32 @@
from django.db import models
+from django.utils.encoding import python_2_unicode_compatible
from ..base import ModelLookup
from ..registry import registry
+@python_2_unicode_compatible
class Thing(models.Model):
name = models.CharField(max_length=100)
description = models... |
c3b1f8c97f89e5b9e8b8e74992631bac33bdde5f | tests/test_read_user_choice.py | tests/test_read_user_choice.py | # -*- coding: utf-8 -*-
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTI... | # -*- coding: utf-8 -*-
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTI... | Implement a test if read_user_choice raises on invalid options | Implement a test if read_user_choice raises on invalid options
| Python | bsd-3-clause | lucius-feng/cookiecutter,foodszhang/cookiecutter,tylerdave/cookiecutter,atlassian/cookiecutter,kkujawinski/cookiecutter,Vauxoo/cookiecutter,sp1rs/cookiecutter,pjbull/cookiecutter,dajose/cookiecutter,benthomasson/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,luzfcb/cookiecutter,foodszhang/cookiecutter,vintas... | ---
+++
@@ -31,3 +31,13 @@
type=click.Choice(OPTIONS),
default='1'
)
+
+
+@pytest.fixture(params=[1, True, False, None, [], {}])
+def invalid_options(request):
+ return ['foo', 'bar', request.param]
+
+
+def test_raise_on_non_str_options(invalid_options):
+ with pytest.raises(TypeError):
... |
08d83f6999d8e5442acf8683bd8348baca386331 | wsgi/config.py | wsgi/config.py | # see http://docs.gunicorn.org/en/latest/configure.html#configuration-file
from os import getenv
bind = f'0.0.0.0:{getenv("PORT", "8000")}'
workers = getenv('WEB_CONCURRENCY', 2)
accesslog = '-'
errorlog = '-'
loglevel = getenv('LOGLEVEL', 'info')
# Larger keep-alive values maybe needed when directly talking to ELB... | # see http://docs.gunicorn.org/en/latest/configure.html#configuration-file
from os import getenv
bind = f'0.0.0.0:{getenv("PORT", "8000")}'
workers = getenv('WEB_CONCURRENCY', 2)
accesslog = '-'
errorlog = '-'
loglevel = getenv('LOGLEVEL', 'info')
# Larger keep-alive values maybe needed when directly talking to ELB... | Revert wsgi keep alive as well | Revert wsgi keep alive as well
it's one of the last remaining items different between our known good state and current wild cpu usage | Python | mpl-2.0 | craigcook/bedrock,flodolo/bedrock,flodolo/bedrock,alexgibson/bedrock,MichaelKohler/bedrock,flodolo/bedrock,MichaelKohler/bedrock,alexgibson/bedrock,sylvestre/bedrock,mozilla/bedrock,MichaelKohler/bedrock,sylvestre/bedrock,craigcook/bedrock,alexgibson/bedrock,craigcook/bedrock,pascalchevrel/bedrock,alexgibson/bedrock,pa... | ---
+++
@@ -11,7 +11,7 @@
# Larger keep-alive values maybe needed when directly talking to ELBs
# See https://github.com/benoitc/gunicorn/issues/1194
-keepalive = getenv("WSGI_KEEP_ALIVE", 118)
+keepalive = getenv("WSGI_KEEP_ALIVE", 2)
worker_class = getenv("GUNICORN_WORKER_CLASS", "meinheld.gmeinheld.MeinheldWo... |
47e79b3a01ca4541d79412cdab856f84871e68f8 | templates/vnc_api_lib_ini_template.py | templates/vnc_api_lib_ini_template.py | import string
template = string.Template("""
[global]
;WEB_SERVER = 127.0.0.1
;WEB_PORT = 9696 ; connection through quantum plugin
WEB_SERVER = 127.0.0.1
WEB_PORT = 8082 ; connection to api-server directly
BASE_URL = /
;BASE_URL = /tenants/infra ; common-prefix for all URLs
; Authentication settings (optional)
[aut... | import string
template = string.Template("""
[global]
;WEB_SERVER = 127.0.0.1
;WEB_PORT = 9696 ; connection through quantum plugin
WEB_SERVER = 127.0.0.1
WEB_PORT = 8082 ; connection to api-server directly
BASE_URL = /
;BASE_URL = /tenants/infra ; common-prefix for all URLs
; Authentication settings (optional)
[aut... | Add auth protocol for keystone connection in vnc_api | Add auth protocol for keystone connection in vnc_api
| Python | apache-2.0 | Juniper/contrail-provisioning,Juniper/contrail-provisioning | ---
+++
@@ -13,6 +13,7 @@
; Authentication settings (optional)
[auth]
AUTHN_TYPE = keystone
+AUTHN_PROTOCOL = http
AUTHN_SERVER=$__contrail_openstack_ip__
AUTHN_PORT = 35357
AUTHN_URL = /v2.0/tokens |
e8b50a70fc7de1842ebe8bc796736459bf154432 | dyconnmap/cluster/__init__.py | dyconnmap/cluster/__init__.py | # -*- coding: utf-8 -*-
"""
"""
# Author: Avraam Marimpis <avraam.marimpis@gmail.com>
from .ng import NeuralGas
from .mng import MergeNeuralGas
from .rng import RelationalNeuralGas
from .gng import GrowingNeuralGas
from .som import SOM
from .umatrix import umatrix
__all__ = [
"NeuralGas",
"MergeNeuralGas",... | # -*- coding: utf-8 -*-
"""
"""
# Author: Avraam Marimpis <avraam.marimpis@gmail.com>
from .ng import NeuralGas
from .mng import MergeNeuralGas
from .rng import RelationalNeuralGas
from .gng import GrowingNeuralGas
from .som import SOM
from .umatrix import umatrix
from .validity import ray_turi, davies_bouldin
__a... | Add the new cluster validity methods in the module. | Add the new cluster validity methods in the module.
| Python | bsd-3-clause | makism/dyfunconn | ---
+++
@@ -11,6 +11,7 @@
from .gng import GrowingNeuralGas
from .som import SOM
from .umatrix import umatrix
+from .validity import ray_turi, davies_bouldin
__all__ = [
@@ -20,4 +21,6 @@
"GrowingNeuralGas",
"SOM",
"umatrix",
+ "ray_turi",
+ "davies_bouldin",
] |
f1099e777d2e14fa1429f72352dfd90fc08250e6 | pentagon/filters.py | pentagon/filters.py | import re
def register_filters():
"""Register a function with decorator"""
registry = {}
def registrar(func):
registry[func.__name__] = func
return func
registrar.all = registry
return registrar
filter = register_filters()
def get_jinja_filters():
"""Return all registered custom jinja filters"""
ret... | import re
def register_filters():
"""Register a function with decorator"""
registry = {}
def registrar(func):
registry[func.__name__] = func
return func
registrar.all = registry
return registrar
filter = register_filters()
def get_jinja_filters():
"""Return all registered custom jinja filters"""
retur... | Fix newlines to match formatting in the rest of project. | Fix newlines to match formatting in the rest of project.
| Python | apache-2.0 | reactiveops/pentagon,reactiveops/pentagon,reactiveops/pentagon | ---
+++
@@ -1,5 +1,4 @@
import re
-
def register_filters():
@@ -13,7 +12,6 @@
filter = register_filters()
-
def get_jinja_filters(): |
3d38848287b168cfbe3c9fe5297e7f322027634d | tests/test_parsePoaXml_test.py | tests/test_parsePoaXml_test.py | import unittest
import os
import re
os.sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import parsePoaXml
import generatePoaXml
# Import test settings last in order to override the regular settings
import poa_test_settings as settings
def override_settings():
# For now need to ov... | import unittest
import os
import re
os.sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import parsePoaXml
import generatePoaXml
# Import test settings last in order to override the regular settings
import poa_test_settings as settings
class TestParsePoaXml(unittest.TestCase):
d... | Delete excess code in the latest test scenario. | Delete excess code in the latest test scenario.
| Python | mit | gnott/elife-poa-xml-generation,gnott/elife-poa-xml-generation | ---
+++
@@ -10,29 +10,10 @@
# Import test settings last in order to override the regular settings
import poa_test_settings as settings
-def override_settings():
- # For now need to override settings to use test data
-
- generatePoaXml.settings = settings
-
-def create_test_directories():
- try:
- ... |
ddad1cf5c4b90ad7997fee72ecd4949dafa43315 | custom/enikshay/model_migration_sets/private_nikshay_notifications.py | custom/enikshay/model_migration_sets/private_nikshay_notifications.py | from casexml.apps.case.util import get_datetime_case_property_changed
from custom.enikshay.const import (
ENROLLED_IN_PRIVATE,
REAL_DATASET_PROPERTY_VALUE,
)
class PrivateNikshayNotifiedDateSetter(object):
"""Sets the date_private_nikshay_notification property for use in reports
"""
def __init__(... | from casexml.apps.case.util import get_datetime_case_property_changed
from custom.enikshay.const import ENROLLED_IN_PRIVATE
class PrivateNikshayNotifiedDateSetter(object):
"""Sets the date_private_nikshay_notification property for use in reports
"""
def __init__(self, domain, person, episode):
se... | Remove redundant case property check | Remove redundant case property check
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -1,8 +1,5 @@
from casexml.apps.case.util import get_datetime_case_property_changed
-from custom.enikshay.const import (
- ENROLLED_IN_PRIVATE,
- REAL_DATASET_PROPERTY_VALUE,
-)
+from custom.enikshay.const import ENROLLED_IN_PRIVATE
class PrivateNikshayNotifiedDateSetter(object):
@@ -39,7 +36,4 ... |
b3224d83dd1fea7a4b50f93c775a824d82aec806 | scan/commands/include.py | scan/commands/include.py | '''
Created on Mar 8,2015
@author: qiuyx
'''
from scan.commands.command import Command
import xml.etree.ElementTree as ET
class Include(Command):
'''
classdocs
'''
def __init__(self, scanFile=None, macros=None,errHandler=None):
'''
@param scanFile: The included scan file path located... | '''
Created on Mar 8,2015
@author: qiuyx
'''
from scan.commands.command import Command
import xml.etree.ElementTree as ET
class Include(Command):
'''
classdocs
'''
def __init__(self, scan, macros=None, errhandler=None):
'''
@param scan: Name of included scan file, must be on the se... | Include command: All arguments lowercase. Require file, default to empty macros | Include command: All arguments lowercase. Require file, default to empty
macros | Python | epl-1.0 | PythonScanClient/PyScanClient,PythonScanClient/PyScanClient | ---
+++
@@ -12,18 +12,17 @@
'''
- def __init__(self, scanFile=None, macros=None,errHandler=None):
+ def __init__(self, scan, macros=None, errhandler=None):
'''
- @param scanFile: The included scan file path located at /scan/example
- Defaults as None.
- @p... |
c00bfab0c1bd00fcd1b075cfeaacb7a3b542017a | ynr/apps/candidates/search_indexes.py | ynr/apps/candidates/search_indexes.py | from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from popolo.models import Person
class PersonIndex(CelerySearchIndex, indexes.Indexable):
# FIXME: this doesn't seem to work for partial names despite what
# docs say
text = indexes.EdgeNgramField(document=True, use_templa... | from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from popolo.models import Person
class PersonIndex(CelerySearchIndex, indexes.Indexable):
# FIXME: this doesn't seem to work for partial names despite what
# docs say
text = indexes.EdgeNgramField(document=True, use_templa... | Add last modified to search index | Add last modified to search index
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | ---
+++
@@ -12,6 +12,7 @@
family_name = indexes.CharField(model_attr='family_name')
given_name = indexes.CharField(model_attr='given_name')
additional_name = indexes.CharField(model_attr='additional_name')
+ last_updated = indexes.DateTimeField(model_attr='updated_at')
def get_updated_field(s... |
b47ecb3464585d762c17694190286388c25dbaf8 | examples/convert_units.py | examples/convert_units.py | # -*- coding: utf-8 -*-
from chatterbot import ChatBot
bot = ChatBot(
"Unit Converter",
logic_adapters=[
"chatterbot.logic.UnitConversion",
],
input_adapter="chatterbot.input.VariableInputTypeAdapter",
output_adapter="chatterbot.output.OutputAdapter"
)
questions = ['How many meters are in... | # -*- coding: utf-8 -*-
from chatterbot import ChatBot
bot = ChatBot(
"Unit Converter",
logic_adapters=[
"chatterbot.logic.UnitConversion",
],
input_adapter="chatterbot.input.VariableInputTypeAdapter",
output_adapter="chatterbot.output.OutputAdapter"
)
questions = ['How many meters are in... | Break list declaration in multiple lines | Break list declaration in multiple lines
| Python | bsd-3-clause | gunthercox/ChatterBot,vkosuri/ChatterBot | ---
+++
@@ -11,7 +11,10 @@
output_adapter="chatterbot.output.OutputAdapter"
)
-questions = ['How many meters are in a kilometer?', 'How many meters are in one inch?', '0 celsius to fahrenheit', 'one hour is how many minutes ?']
+questions = ['How many meters are in a kilometer?',
+ 'How many meter... |
d38617dd6bf5c7b0f17245dd5a5e95a335ac6626 | tracpro/orgs_ext/middleware.py | tracpro/orgs_ext/middleware.py | from django.utils.translation import ugettext_lazy as _
from django.http import HttpResponseBadRequest
from temba_client.base import TembaAPIError
class HandleTembaAPIError(object):
""" Catch all Temba exception errors """
def process_exception(self, request, exception):
if isinstance(exception, Tem... | from django.utils.translation import ugettext_lazy as _
from django.http import HttpResponseBadRequest
from temba_client.base import TembaAPIError, TembaConnectionError
class HandleTembaAPIError(object):
""" Catch all Temba exception errors """
def process_exception(self, request, exception):
rapid... | Check forerror codes from temba connection issues | Check forerror codes from temba connection issues
| Python | bsd-3-clause | xkmato/tracpro,rapidpro/tracpro,rapidpro/tracpro,xkmato/tracpro,xkmato/tracpro,rapidpro/tracpro,xkmato/tracpro | ---
+++
@@ -1,16 +1,32 @@
from django.utils.translation import ugettext_lazy as _
from django.http import HttpResponseBadRequest
-from temba_client.base import TembaAPIError
+from temba_client.base import TembaAPIError, TembaConnectionError
class HandleTembaAPIError(object):
""" Catch all Temba exceptio... |
be19869d76bb655990464094ad17617b7b48ab3b | server/create_tiff.py | server/create_tiff.py | # A romanesco script to convert a slide to a TIFF using vips.
import subprocess
import os
out_path = os.path.join(_tempdir, out_filename)
convert_command = (
'vips',
'tiffsave',
'"%s"' % in_path,
'"%s"' % out_path,
'--compression', 'jpeg',
'--Q', '90',
'--tile',
'--tile-width', '256',
... | # A romanesco script to convert a slide to a TIFF using vips.
import subprocess
import os
out_path = os.path.join(_tempdir, out_filename)
convert_command = (
'vips',
'tiffsave',
'"%s"' % in_path,
'"%s"' % out_path,
'--compression', 'jpeg',
'--Q', '90',
'--tile',
'--tile-width', '256',
... | Print command in failure case | Print command in failure case
| Python | apache-2.0 | DigitalSlideArchive/large_image,DigitalSlideArchive/large_image,girder/large_image,DigitalSlideArchive/large_image,girder/large_image,girder/large_image | ---
+++
@@ -22,4 +22,5 @@
proc.wait()
if proc.returncode:
- raise Exception('VIPS process failed (rc=%d).' % proc.returncode)
+ raise Exception('VIPS command failed (rc=%d): %s' % (
+ proc.returncode, ' '.join(convert_command))) |
e5acbfc176de3b531528c8b15f57e5d3feab3ad1 | melody/constraints/abstract_constraint.py | melody/constraints/abstract_constraint.py | """
File: abstract_constraint.py
Purpose: Define a constraint, in an abstract sense, related to a number of actors.
"""
from abc import ABCMeta, abstractmethod
class AbstractConstraint(object):
"""
Class that represents a constraint, a set of actors that define a constraint amongst themselves.
Paramet... | """
File: abstract_constraint.py
Purpose: Define a constraint, in an abstract sense, related to a number of actors.
"""
from abc import ABCMeta, abstractmethod
class AbstractConstraint(object):
"""
Class that represents a constraint, a set of actors that define a constraint amongst themselves.
Paramet... | Add hash and eq methods | Add hash and eq methods
| Python | mit | dpazel/music_rep | ---
+++
@@ -50,3 +50,11 @@
:return: The set of all possible values for v_note's target.
Note: The return value is a set!
"""
+
+ def __hash__(self):
+ return hash(len(self.actors))
+
+ def __eq__(self, other):
+ if not isinstance(other, AbstractConstraint):
+ ... |
80025b77f42813a840533050331972d66febeb04 | python/src/setup.py | python/src/setup.py | #!/usr/bin/env python
"""Setup specs for packaging, distributing, and installing MR lib."""
import distribute_setup
# User may not have setuptools installed on their machines.
# This script will automatically install the right version from PyPI.
distribute_setup.use_setuptools()
# pylint: disable=g-import-not-at-top... | #!/usr/bin/env python
"""Setup specs for packaging, distributing, and installing MR lib."""
import distribute_setup
# User may not have setuptools installed on their machines.
# This script will automatically install the right version from PyPI.
distribute_setup.use_setuptools()
# pylint: disable=g-import-not-at-top... | Create PyPI Release for 1.9.5.0. | Python: Create PyPI Release for 1.9.5.0.
Revision created by MOE tool push_codebase.
MOE_MIGRATION=7043
| Python | apache-2.0 | bmenasha/appengine-mapreduce,talele08/appengine-mapreduce,soundofjw/appengine-mapreduce,aozarov/appengine-mapreduce,ankit318/appengine-mapreduce,talele08/appengine-mapreduce,Candreas/mapreduce,aozarov/appengine-mapreduce,soundofjw/appengine-mapreduce,westerhofffl/appengine-mapreduce,soundofjw/appengine-mapreduce,vendas... | ---
+++
@@ -14,7 +14,7 @@
# To debug, set DISTUTILS_DEBUG env var to anything.
setuptools.setup(
name="GoogleAppEngineMapReduce",
- version="1.9.0.0",
+ version="1.9.5.0",
packages=setuptools.find_packages(),
author="Google App Engine",
author_email="app-engine-pipeline-api@googlegroups.co... |
7fde39b0d4a41e8119893254d38460cf6914f028 | bashhub/view/status.py | bashhub/view/status.py | import dateutil.parser
import datetime
import humanize
status_view = """\
=== Bashhub Status
https://bashhub.com/u/{0}
Total Commands: {1}
Total Sessions: {2}
Total Systems: {3}
===
Session PID {4} Started {5}
Commands In Session: {6}
Commands Today: {7}
"""
def build_status_view(model):
date = datetime.datetime... | import dateutil.parser
import datetime
import humanize
status_view = """\
=== Bashhub Status
https://bashhub.com/{0}
Total Commands: {1}
Total Sessions: {2}
Total Systems: {3}
===
Session PID {4} Started {5}
Commands In Session: {6}
Commands Today: {7}
"""
def build_status_view(model):
date = datetime.datetime.f... | Remove /u/ from username path | Remove /u/ from username path
| Python | apache-2.0 | rcaloras/bashhub-client,rcaloras/bashhub-client | ---
+++
@@ -4,7 +4,7 @@
status_view = """\
=== Bashhub Status
-https://bashhub.com/u/{0}
+https://bashhub.com/{0}
Total Commands: {1}
Total Sessions: {2}
Total Systems: {3} |
8c2ad666266d4dbe8310007bd82dc907a288ee5a | databroker/__init__.py | databroker/__init__.py | # Import intake to run driver discovery first and avoid circular import issues.
import intake
del intake
import warnings
import logging
logger = logging.getLogger(__name__)
from .v1 import Broker, Header, ALL, temp, temp_config
from .utils import (lookup_config, list_configs, describe_configs,
... | # Import intake to run driver discovery first and avoid circular import issues.
import intake
import warnings
import logging
logger = logging.getLogger(__name__)
from .v1 import Broker, Header, ALL, temp, temp_config
from .utils import (lookup_config, list_configs, describe_configs,
wrap_in_doc... | Include intake.cat. YAML is easier than entry_points. | Include intake.cat. YAML is easier than entry_points.
| Python | bsd-3-clause | ericdill/databroker,ericdill/databroker | ---
+++
@@ -1,6 +1,5 @@
# Import intake to run driver discovery first and avoid circular import issues.
import intake
-del intake
import warnings
import logging
@@ -15,8 +14,8 @@
from .discovery import MergedCatalog, EntrypointsCatalog, V0Catalog
-# A catalog created from discovered entrypoints and v0 cata... |
0624417fbac1cf23316ee0a58ae41c0519a390c4 | go/apps/surveys/definition.py | go/apps/surveys/definition.py | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
from go.apps.surveys.tasks import export_vxpolls_data
class SendSurveyAction(ConversationAction):
action_name = 'send_survey'
action_display_name = 'Send Survey'
needs_confirmation = True
needs_gro... | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
from go.apps.surveys.tasks import export_vxpolls_data
class SendSurveyAction(ConversationAction):
action_name = 'send_survey'
action_display_name = 'Send Survey'
needs_confirmation = True
needs_gro... | Change download survey data display verb to 'Send CSV via e-mail'. | Change download survey data display verb to 'Send CSV via e-mail'.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -27,6 +27,7 @@
class DownloadUserDataAction(ConversationAction):
action_name = 'download_user_data'
action_display_name = 'Download User Data'
+ action_display_verb = 'Send CSV via e-mail'
def perform_action(self, action_data):
return export_vxpolls_data.delay(self._conv.user_... |
7a3c4eed8888c8c2befc94020bebbfc18e1d6156 | src/redis_client.py | src/redis_client.py | import txredisapi as redis
from twisted.internet import defer, reactor
import config
connection = None
@defer.inlineCallbacks
def run_redis_client(on_started):
pony = yield redis.makeConnection(config.redis['host'],
config.redis['port'],
... | import txredisapi as redis
from twisted.internet import defer, reactor
import config
connection = None
def run_redis_client(on_started):
df = redis.makeConnection(config.redis['host'],
config.redis['port'],
config.redis['db'],
... | Fix the Redis client connection to actually work | Fix the Redis client connection to actually work
It previously lied.
| Python | mit | prophile/compd,prophile/compd | ---
+++
@@ -4,15 +4,16 @@
connection = None
-@defer.inlineCallbacks
def run_redis_client(on_started):
- pony = yield redis.makeConnection(config.redis['host'],
- config.redis['port'],
- config.redis['db'],
- ... |
fdee90e6fd4669222c2da0530d9bc90131b5145e | djoser/social/views.py | djoser/social/views.py | from rest_framework import generics, permissions, status
from rest_framework.response import Response
from social_django.utils import load_backend, load_strategy
from djoser.conf import settings
from djoser.social.serializers import ProviderAuthSerializer
class ProviderAuthView(generics.CreateAPIView):
permissio... | from rest_framework import generics, permissions, status
from rest_framework.response import Response
from social_django.utils import load_backend, load_strategy
from djoser.conf import settings
from djoser.social.serializers import ProviderAuthSerializer
class ProviderAuthView(generics.CreateAPIView):
permissio... | Fix for Friendly tips when Missing SOCIAL_AUTH_ALLOWED_REDIRECT_URIS | Fix for Friendly tips when Missing SOCIAL_AUTH_ALLOWED_REDIRECT_URIS
i forget add SOCIAL_AUTH_ALLOWED_REDIRECT_URIS to my config
it return 400 error, i don't know why , i pay more time find the issues
so i add Friendly tips
-- sorry , my english is not well
and thank you all | Python | mit | sunscrapers/djoser,sunscrapers/djoser,sunscrapers/djoser | ---
+++
@@ -13,7 +13,7 @@
def get(self, request, *args, **kwargs):
redirect_uri = request.GET.get("redirect_uri")
if redirect_uri not in settings.SOCIAL_AUTH_ALLOWED_REDIRECT_URIS:
- return Response(status=status.HTTP_400_BAD_REQUEST)
+ return Response("Missing SOCIAL_AUTH... |
db14ed2c23b3838796e648faade2c73b786d61ff | tartpy/eventloop.py | tartpy/eventloop.py | """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import queue
import sys
import threading
import time
import traceback
from .singleton import Singleton
def ... | """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import queue
import sys
import threading
import time
import traceback
from .singleton import Singleton
def ... | Make exception message builder a nicer function | Make exception message builder a nicer function
It is used by clients in other modules. | Python | mit | waltermoreira/tartpy | ---
+++
@@ -21,9 +21,9 @@
from .singleton import Singleton
-def _format_exception(exc_info):
+def exception_message():
"""Create a message with details on the exception."""
- exc_type, exc_value, exc_tb = exc_info
+ exc_type, exc_value, exc_tb = exc_info = sys.exc_info()
return {'exception': {'ty... |
3976a5b38e1b5356b83d22d9113aa83c9f09fdec | admin/manage.py | admin/manage.py | from freeposte import manager, db
from freeposte.admin import models
from passlib import hash
@manager.command
def flushdb():
""" Flush the database
"""
db.drop_all()
@manager.command
def initdb():
""" Initialize the database
"""
db.create_all()
@manager.command
def admin(localpart, domain... | from freeposte import manager, db
from freeposte.admin import models
from passlib import hash
@manager.command
def flushdb():
""" Flush the database
"""
db.drop_all()
@manager.command
def initdb():
""" Initialize the database
"""
db.create_all()
@manager.command
def admin(localpart, domain... | Allow admin creation after initial setup | Allow admin creation after initial setup
| Python | mit | kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io | ---
+++
@@ -21,14 +21,16 @@
def admin(localpart, domain_name, password):
""" Create an admin user
"""
- domain = models.Domain(name=domain_name)
+ domain = models.Domain.query.get(domain_name)
+ if not domain:
+ domain = models.Domain(name=domain_name)
+ db.session.add(domain)
u... |
2a7d28573d1e4f07250da1d30209304fdb6de90d | sqlobject/tests/test_blob.py | sqlobject/tests/test_blob.py | import pytest
from sqlobject import BLOBCol, SQLObject
from sqlobject.compat import PY2
from sqlobject.tests.dbtest import setupClass, supports
########################################
# BLOB columns
########################################
class ImageData(SQLObject):
image = BLOBCol(default=b'emptydata', lengt... | import pytest
from sqlobject import BLOBCol, SQLObject
from sqlobject.compat import PY2
from sqlobject.tests.dbtest import setupClass, supports
########################################
# BLOB columns
########################################
class ImageData(SQLObject):
image = BLOBCol(default=b'emptydata', lengt... | Use byte string for test | Tests(blob): Use byte string for test
| Python | lgpl-2.1 | sqlobject/sqlobject,drnlm/sqlobject,sqlobject/sqlobject,drnlm/sqlobject | ---
+++
@@ -22,8 +22,7 @@
else:
data = bytes(range(256))
- prof = ImageData()
- prof.image = data
+ prof = ImageData(image=data)
iid = prof.id
ImageData._connection.cache.clear()
@@ -31,5 +30,5 @@
prof2 = ImageData.get(iid)
assert prof2.image == data
- ImageData(ima... |
95fa71c4439343764cac95a1667e08dc21cb6ebe | plugins.py | plugins.py | from fabric.api import *
import os
import re
__all__ = []
@task
def test(plugin_path):
"""
Symbolically link a host file that contains a redcap plugin into the ./redcap/plugins folder
:param plugin_path: path to plugin folder relative to VagrantFile
:return:
"""
if not os.path.exists(plugin_p... | from fabric.api import *
import os
import re
__all__ = []
@task
def test(plugin_path):
"""
Symbolically link a host file that contains a redcap plugin into the ./redcap/plugins folder
:param plugin_path: path to plugin folder relative to VagrantFile
:return:
"""
if not os.path.exists(plugin_p... | Fix plugin test by running scripts as user deploy | Fix plugin test by running scripts as user deploy
| Python | bsd-3-clause | ctsit/redcap_deployment,ctsit/redcap_deployment,ctsit/redcap_deployment,ctsit/redcap_deployment | ---
+++
@@ -18,4 +18,5 @@
source_path = "/vagrant/" + plugin_path
target_folder = "/".join([redcap_root, env.plugins_path])
- run("ln -sf %s %s" % (source_path, target_folder))
+ with settings(user=env.deploy_user):
+ run("ln -sf %s %s" % (source_path, target_folder)) |
9c35a41c6594d0ac482a558abf4772150c2a67e9 | squash/dashboard/urls.py | squash/dashboard/urls.py | from django.conf.urls import include, url
from django.contrib import admin
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register(r'job', views.JobViewSet)
router.register(r'metric', views.MetricViewSet)... | from django.conf.urls import include, url
from django.contrib import admin
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.routers import DefaultRouter
from . import views
<<<<<<< HEAD
router = DefaultRouter()
router.register(r'job', views.JobViewSet)
router.register(r'metric', views.M... | Make all API resource collection endpoints plural | Make all API resource collection endpoints plural
/api/job/ -> /api/jobs/
/api/metric/ -> /api/metrics/
It's a standard convention in RESTful APIs to make endpoints for
collections plural.
| Python | mit | lsst-sqre/qa-dashboard,lsst-sqre/qa-dashboard,lsst-sqre/qa-dashboard | ---
+++
@@ -4,9 +4,16 @@
from rest_framework.routers import DefaultRouter
from . import views
+<<<<<<< HEAD
router = DefaultRouter()
router.register(r'job', views.JobViewSet)
router.register(r'metric', views.MetricViewSet)
+=======
+api_router = DefaultRouter()
+api_router.register(r'jobs', views.JobViewSet)
+... |
32a61c6df871ad148a8c51b7b4cab3f392a2c61a | tsune/urls.py | tsune/urls.py | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'tsune.views.home', name='home'),
# url(r'^tsune/', include('tsune.foo.urls')),
# Uncomment... | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.http import HttpResponseRedirect
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'tsune.views.home', name='home'),
# url(r'^tsune/'... | Add redirect to cardbox if root url is accessed | Add redirect to cardbox if root url is accessed
| Python | mit | DummyDivision/Tsune,DummyDivision/Tsune,DummyDivision/Tsune | ---
+++
@@ -2,6 +2,8 @@
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
+from django.http import HttpResponseRedirect
+
admin.autodiscover()
urlpatterns = patterns('',
@@ -13,6 +15,7 @@
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment ... |
171bbf488db643d01d6a58c9376ba85c200711d5 | gtts/tokenizer/tests/test_pre_processors.py | gtts/tokenizer/tests/test_pre_processors.py | # -*- coding: utf-8 -*-
import unittest
from gtts.tokenizer.pre_processors import tone_marks, end_of_line, abbreviations, word_sub
class TestPreProcessors(unittest.TestCase):
def test_tone_marks(self):
_in = "lorem!ipsum?"
_out = "lorem! ipsum? "
self.assertEqual(tone_marks(_in), _out)
... | # -*- coding: utf-8 -*-
import unittest
from gtts.tokenizer.pre_processors import tone_marks, end_of_line, abbreviations, word_sub
class TestPreProcessors(unittest.TestCase):
def test_tone_marks(self):
_in = "lorem!ipsum?"
_out = "lorem! ipsum? "
self.assertEqual(tone_marks(_in), _out)
... | Update unit test for ad8bcd8 | Update unit test for ad8bcd8
| Python | mit | pndurette/gTTS | ---
+++
@@ -21,8 +21,8 @@
self.assertEqual(abbreviations(_in), _out)
def test_word_sub(self):
- _in = "M. Bacon"
- _out = "Monsieur Bacon"
+ _in = "Esq. Bacon"
+ _out = "Esquire Bacon"
self.assertEqual(word_sub(_in), _out)
|
46d64030c8724f016233703922cbc619eef2c179 | examples/push_pull/architect.py | examples/push_pull/architect.py | from functions import print_message
from osbrain.core import Proxy
pusher = Proxy('Pusher')
puller = Proxy('Puller')
addr = pusher.bind('push')
puller.connect(addr, print_message)
puller.run()
pusher.send(addr, 'Hello world!')
| from functions import print_message
from osbrain.core import Proxy
pusher = Proxy('Pusher')
puller = Proxy('Puller')
addr = pusher.bind('PUSH', alias='push')
puller.connect(addr, handler=print_message)
puller.run()
pusher.send('push', 'Hello, world!')
| Update push_pull example to work with latest changes | Update push_pull example to work with latest changes
| Python | apache-2.0 | opensistemas-hub/osbrain | ---
+++
@@ -5,8 +5,8 @@
pusher = Proxy('Pusher')
puller = Proxy('Puller')
-addr = pusher.bind('push')
-puller.connect(addr, print_message)
+addr = pusher.bind('PUSH', alias='push')
+puller.connect(addr, handler=print_message)
puller.run()
-pusher.send(addr, 'Hello world!')
+pusher.send('push', 'Hello, world!') |
ae14d59b40d18d8a5399286d356bdf6cae58994e | yuicompressor/yuicompressor.py | yuicompressor/yuicompressor.py | # -*- coding: utf-8 -*-
from pelican import signals
from subprocess import call
import logging
import os
logger = logging.getLogger(__name__)
# Display command output on DEBUG and TRACE
SHOW_OUTPUT = logger.getEffectiveLevel() <= logging.DEBUG
"""
Minify CSS and JS files in output path
with Yuicompressor from Yahoo... | # -*- coding: utf-8 -*-
from pelican import signals
from subprocess import call
import logging
import os
logger = logging.getLogger(__name__)
# Display command output on DEBUG and TRACE
SHOW_OUTPUT = logger.getEffectiveLevel() <= logging.DEBUG
"""
Minify CSS and JS files in output path
with Yuicompressor from Yahoo... | Fix typo in log message | Fix typo in log message | Python | agpl-3.0 | danmackinlay/pelican-plugins,MarkusH/pelican-plugins,mikitex70/pelican-plugins,howthebodyworks/pelican-plugins,howthebodyworks/pelican-plugins,talha131/pelican-plugins,mortada/pelican-plugins,MarkusH/pelican-plugins,xsteadfastx/pelican-plugins,howthebodyworks/pelican-plugins,danmackinlay/pelican-plugins,danmackinlay/pe... | ---
+++
@@ -25,7 +25,7 @@
for name in filenames:
if os.path.splitext(name)[1] in ('.css','.js'):
filepath = os.path.join(dirpath, name)
- logger.info('minifiy %s', filepath)
+ logger.info('minify %s', filepath)
verbose = '-v' if SHO... |
b223107cbed5ea4c01b98c8e6abcebd1e380d04d | example_project/posts/urls.py | example_project/posts/urls.py | from django.conf.urls import patterns, url
from .views import PostListView, PostDetailView
urlpatterns = patterns('',
url(r'(?P<pk>\d+)/$', PostDetailView.as_view(), name='detail'),
url(r'$', PostListView.as_view(), name='list'),
)
| from django.conf.urls import patterns, url
from .views import PostListView, PostDetailView
urlpatterns = patterns('',
url(r'(?P<pk>\d+)/$', PostDetailView.as_view(), name='detail'),
url(r'/$', PostListView.as_view(), name='list'),
)
| Fix appending slash in example project | Fix appending slash in example project
| Python | mit | jazzband/django-embed-video,mpachas/django-embed-video,yetty/django-embed-video,mpachas/django-embed-video,jazzband/django-embed-video,yetty/django-embed-video | ---
+++
@@ -4,5 +4,5 @@
urlpatterns = patterns('',
url(r'(?P<pk>\d+)/$', PostDetailView.as_view(), name='detail'),
- url(r'$', PostListView.as_view(), name='list'),
+ url(r'/$', PostListView.as_view(), name='list'),
) |
904d0fe5c357390f90d7ec9dd9833288a01f7328 | unnaturalcode/compile_error.py | unnaturalcode/compile_error.py | #!/usr/bin/python
# Copyright 2017 Joshua Charles Campbell
#
# This file is part of UnnaturalCode.
#
# UnnaturalCode 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 o... | #!/usr/bin/python
# Copyright 2017 Joshua Charles Campbell
#
# This file is part of UnnaturalCode.
#
# UnnaturalCode 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 o... | Update compiler_error; fixed typo line 30 | Update compiler_error; fixed typo line 30 | Python | agpl-3.0 | orezpraw/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,orezpraw/unnaturalcode,orezpraw/unnaturalcode,... | ---
+++
@@ -27,7 +27,7 @@
text=None,
errorname=None):
assert line is not None
- assert isintance(line, integer_types)
+ assert isinstance(line, integer_types)
self.filename = filename
self.line = line
self.functionname = functionnam... |
39da25f8d221605012c629b3d08478cfe858df36 | poradnia/cases/migrations/0024_auto_20150809_2148.py | poradnia/cases/migrations/0024_auto_20150809_2148.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.models import Count
def delete_empty(apps, schema_editor):
# We get the model from the versioned app registry;
# if we directly import it, it'll be the wrong version
Case = apps.get_mod... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.models import Count
def delete_empty(apps, schema_editor):
# We get the model from the versioned app registry;
# if we directly import it, it'll be the wrong version
Case = apps.get_mod... | Fix case migrations for MySQL | Fix case migrations for MySQL
| Python | mit | watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl | ---
+++
@@ -9,7 +9,7 @@
# We get the model from the versioned app registry;
# if we directly import it, it'll be the wrong version
Case = apps.get_model("cases", "Case")
- pks = Case.objects.annotate(record_count=Count('record')).filter(record_count=0).values('id')
+ pks = [x[0] for x in Case.obj... |
286cba2b3e7cf323835acd07f1e3bb510d74bcb2 | biopsy/tests.py | biopsy/tests.py | # -*- coding: utf-8 -*-
from django.test import TestCase
from django.db import models
from biopsy.models import Biopsy
class BiopsyTest(TestCase):
def biopy_test(self):
biopsy = Biopsy(
clinical_information= "clinica",
macroscopic= "macroscopia",
microscopic= "microscopia",
conclusion= "conclusao",
... | # -*- coding: utf-8 -*-
from django.test import TestCase
from django.db import models
from biopsy.models import Biopsy
class BiopsyTest(TestCase):
def biopy_test(self):
biopsy = Biopsy(
clinical_information= "clinica",
macroscopic= "macroscopia",
microscopic= "microscopia",
conclusion= "conclusao",
... | Add status and exam in test Biopsy | Add status and exam in test Biopsy
| Python | mit | msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub | ---
+++
@@ -12,7 +12,9 @@
microscopic= "microscopia",
conclusion= "conclusao",
notes= "nota",
- footer= "legenda"
+ footer= "legenda",
+ status = "status",
+ exam = "exame"
)
biopsy.save()
@@ -23,3 +25,5 @@
self.assertEquals("conclusao",biopsy.conclusion)
self.assertEquals("nota",bio... |
d0ec3ee9b974fb6956c32e8dfdd6d20ea4da7cff | pwndbg/inthook.py | pwndbg/inthook.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This hook is necessary for compatibility with Python2.7 versions of GDB
since they cannot directly cast to integer a gdb.Value object that is
not already an integer type.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import p... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This hook is necessary for compatibility with Python2.7 versions of GDB
since they cannot directly cast to integer a gdb.Value object that is
not already an integer type.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import p... | Add int hook to Python3 | Add int hook to Python3
Fixes #120
| Python | mit | pwndbg/pwndbg,cebrusfs/217gdb,cebrusfs/217gdb,pwndbg/pwndbg,cebrusfs/217gdb,chubbymaggie/pwndbg,disconnect3d/pwndbg,disconnect3d/pwndbg,pwndbg/pwndbg,0xddaa/pwndbg,zachriggle/pwndbg,0xddaa/pwndbg,disconnect3d/pwndbg,anthraxx/pwndbg,chubbymaggie/pwndbg,0xddaa/pwndbg,cebrusfs/217gdb,anthraxx/pwndbg,zachriggle/pwndbg,anth... | ---
+++
@@ -18,28 +18,30 @@
if sys.version_info < (3,0):
import __builtin__ as builtins
- _int = builtins.int
-
- # We need this class to get isinstance(7, xint) to return True
- class IsAnInt(type):
- def __instancecheck__(self, other):
- return isinstance(other, _int)
-
- class... |
caf2806124df489f28ceadf2db5d4abfdd27aae7 | core/management/commands/send_tweets.py | core/management/commands/send_tweets.py | import twitter
from django.core.management.base import BaseCommand
from django.conf import settings
from core.models import Tweet
class Command(BaseCommand):
help = "Send out tweets."
def handle(self, *args, **options):
for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5):
... | import twitter
from django.core.management.base import BaseCommand
from django.conf import settings
from core.models import Tweet
class Command(BaseCommand):
help = "Send out tweets."
def handle(self, *args, **options):
for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5):
... | Fix typo in field name | Fix typo in field name
| Python | agpl-3.0 | enjaz/enjaz,enjaz/enjaz,osamak/student-portal,osamak/student-portal,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz | ---
+++
@@ -8,7 +8,7 @@
help = "Send out tweets."
def handle(self, *args, **options):
- for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5):
+ for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5):
user_tokens = tweet.user.social_auth.all()[... |
92aa388d1b58c0e88979d299cc8deabab811f926 | tests/test_webapps/filestotest/rest_routing.py | tests/test_webapps/filestotest/rest_routing.py | """Routes configuration
The more specific and detailed routes should be defined first so they
may take precedent over the more generic routes. For more information
refer to the routes manual at http://routes.groovie.org/docs/
"""
from pylons import config
from routes import Mapper
def make_map():
"""Create, confi... | """Routes configuration
The more specific and detailed routes should be defined first so they
may take precedent over the more generic routes. For more information
refer to the routes manual at http://routes.groovie.org/docs/
"""
from pylons import config
from routes import Mapper
def make_map():
"""Create, confi... | Update to reflect not having trailing slashes | Update to reflect not having trailing slashes
| Python | bsd-3-clause | obeattie/pylons,obeattie/pylons | ---
+++
@@ -20,8 +20,7 @@
# CUSTOM ROUTES HERE
map.resource('restsample', 'restsamples')
- map.connect('/:controller/index', action='index')
- map.connect('/:controller/:action/')
+ map.connect('/:controller/:action')
map.connect('/:controller/:action/:id')
return map |
c8a0279d421c2837e4f7e4ef1eaf2cc9cb94210c | scripts/mkstdlibs.py | scripts/mkstdlibs.py | #!/usr/bin/env python3
from sphinx.ext.intersphinx import fetch_inventory
URL = "https://docs.python.org/{}/objects.inv"
PATH = "isort/stdlibs/py{}.py"
VERSIONS = [("2", "7"), ("3", "5"), ("3", "6"), ("3", "7"), ("3", "8")]
DOCSTRING = """
File contains the standard library of Python {}.
DO NOT EDIT. If the standar... | #!/usr/bin/env python3
from sphinx.ext.intersphinx import fetch_inventory
URL = "https://docs.python.org/{}/objects.inv"
PATH = "isort/stdlibs/py{}.py"
VERSIONS = [("2", "7"), ("3", "5"), ("3", "6"), ("3", "7"), ("3", "8"), ("3", "9")]
DOCSTRING = """
File contains the standard library of Python {}.
DO NOT EDIT. If... | Update script to include empty user agent | Update script to include empty user agent
| Python | mit | PyCQA/isort,PyCQA/isort | ---
+++
@@ -4,7 +4,7 @@
URL = "https://docs.python.org/{}/objects.inv"
PATH = "isort/stdlibs/py{}.py"
-VERSIONS = [("2", "7"), ("3", "5"), ("3", "6"), ("3", "7"), ("3", "8")]
+VERSIONS = [("2", "7"), ("3", "5"), ("3", "6"), ("3", "7"), ("3", "8"), ("3", "9")]
DOCSTRING = """
File contains the standard library... |
4160fd07d428e26c4de6aee280d948f5044f2c9e | kimochi/scripts/initializedb.py | kimochi/scripts/initializedb.py | import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
User,
Site,
SiteAPIKey,
)
def usage(argv):
cmd ... | import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
User,
Site,
SiteAPIKey,
)
def usage(argv):
cmd ... | Make sure we add the user to the site as well | Make sure we add the user to the site as well
| Python | mit | matslindh/kimochi,matslindh/kimochi | ---
+++
@@ -39,6 +39,9 @@
Base.metadata.create_all(engine)
with transaction.manager:
- DBSession.add(User(email='test@example.com', password='test', admin=True))
- DBSession.add(Site(name='asd', key='80d621df066348e5938a469730ae0cab'))
+ user = User(email='test@example.com', password=... |
525bfce19f593cb598669cdf2eec46747a4b6952 | goodreadsapi.py | goodreadsapi.py | #!/usr/bin/env python
import re
from xml.parsers.expat import ExpatError
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(r... | #!/usr/bin/env python
import re
from xml.parsers.expat import ExpatError
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(r... | Add `publication_year` to return data | Add `publication_year` to return data
| Python | mit | avinassh/Reddit-GoodReads-Bot | ---
+++
@@ -24,10 +24,10 @@
except (TypeError, KeyError, ExpatError):
return False
keys = ['title', 'average_rating', 'ratings_count', 'description',
- 'num_pages']
+ 'num_pages', 'publication_year']
book = {}
for k in keys:
- book[k] = book_data[k]
+ b... |
4c2dd9dd6dc0f9ff66a36a114c90897dab8da7e5 | goodreadsapi.py | goodreadsapi.py | #!/usr/bin/env python
import re
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(regex, comment_msg))
def get_book_detail... | #!/usr/bin/env python
import re
from xml.parsers.expat import ExpatError
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(r... | Update GR API to handle Expat Error | Update GR API to handle Expat Error
| Python | mit | avinassh/Reddit-GoodReads-Bot | ---
+++
@@ -1,6 +1,7 @@
#!/usr/bin/env python
import re
+from xml.parsers.expat import ExpatError
import requests
import xmltodict
@@ -20,7 +21,7 @@
r = requests.get(api_url.format(goodreads_id, goodreads_api_key))
try:
book_data = xmltodict.parse(r.content)['GoodreadsResponse']['book']
- ... |
7615bfa2a58db373c3e102e7d0205f265d9c4d57 | dxtbx/tst_dxtbx.py | dxtbx/tst_dxtbx.py | from boost.python import streambuf
from dxtbx import read_uint16
f = open('/Users/graeme/data/demo/insulin_1_001.img', 'rb')
hdr = f.read(512)
l = read_uint16(streambuf(f), 2304 * 2304)
print sum(l)
| from boost.python import streambuf
from dxtbx import read_uint16
import sys
from dxtbx.format.Registry import Registry
format = Registry.find(sys.argv[1])
i = format(sys.argv[1])
size = i.get_detector().get_image_size()
f = open(sys.argv[1], 'rb')
hdr = f.read(512)
l = read_uint16(streambuf(f), int(size[0] * size... | Clean up test case: not finished yet though | Clean up test case: not finished yet though | Python | bsd-3-clause | dials/dials,dials/dials,dials/dials,dials/dials,dials/dials | ---
+++
@@ -1,6 +1,13 @@
from boost.python import streambuf
from dxtbx import read_uint16
-f = open('/Users/graeme/data/demo/insulin_1_001.img', 'rb')
+import sys
+from dxtbx.format.Registry import Registry
+
+format = Registry.find(sys.argv[1])
+i = format(sys.argv[1])
+size = i.get_detector().get_image_size()... |
675c05bd685d550e3c46137f2f52dcdb125cefa0 | tests/test_speed.py | tests/test_speed.py | import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import glob
import fnmatch
import traceback
import logging
import numpy
import pytest
import lasio
test_dir = os.path.dirname(__file__)
egfn = lambda fn: os.path.join(os.path.dirname(__file__), "examples", fn)
stegfn = lambda vers, fn: o... | import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import glob
import fnmatch
import traceback
import logging
import numpy
import pytest
import lasio
test_dir = os.path.dirname(__file__)
egfn = lambda fn: os.path.join(os.path.dirname(__file__), "examples", fn)
stegfn = lambda vers, fn: o... | Add benchmark test for the speed of reading a LAS file | Add benchmark test for the speed of reading a LAS file
To run it you need to have `pytest-benchmark` installed, and
run the tests using:
```
$ pytest lasio/tests/tests_speed.py
```
To compare two branches, you need to run and store the benchmark from the first branch e.g. master
and then run and compare the benchmar... | Python | mit | kwinkunks/lasio,kinverarity1/lasio,kinverarity1/las-reader | ---
+++
@@ -19,5 +19,8 @@
logger = logging.getLogger(__name__)
-def test_read_v12_sample_big():
- l = lasio.read(stegfn("1.2", "sample_big.las"))
+def read_file():
+ las = lasio.read(stegfn("1.2", "sample_big.las"))
+
+def test_read_v12_sample_big(benchmark):
+ benchmark(read_file) |
f5477c30cb9fdbbb250800d379458e641ef97fd4 | dwitter/serializers.py | dwitter/serializers.py | from rest_framework import serializers
from dwitter.models import Dweet, Comment
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('pk', 'username')
class CommentSerializer(serializers.ModelSerializer):
author = serializers.Re... | from rest_framework import serializers
from dwitter.models import Dweet, Comment
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('pk', 'username')
class CommentSerializer(serializers.ModelSerializer):
author = serializers.Re... | Remove whitespace at end of file | Remove whitespace at end of file
| Python | apache-2.0 | lionleaf/dwitter,lionleaf/dwitter,lionleaf/dwitter | ---
+++
@@ -25,8 +25,3 @@
def get_latest_comments(self, obj):
cmnts = obj.comments.all().order_by('-posted')
return CommentSerializer(cmnts[:3], many=True).data
-
-
-
-
- |
16bd36fe6fdcbd267413eabe1997337165775f28 | taOonja/game/admin.py | taOonja/game/admin.py | from django.contrib import admin
# Register your models here.
| from django.contrib import admin
from game.models import *
class LocationAdmin(admin.ModelAdmin):
model = Location
admin.site.register(Location, LocationAdmin)
class DetailAdmin(admin.ModelAdmin):
model = Detail
admin.site.register(Detail, DetailAdmin)
| Add models to Admin Panel | Add models to Admin Panel
| Python | mit | Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja | ---
+++
@@ -1,3 +1,13 @@
from django.contrib import admin
+from game.models import *
-# Register your models here.
+class LocationAdmin(admin.ModelAdmin):
+ model = Location
+
+admin.site.register(Location, LocationAdmin)
+
+class DetailAdmin(admin.ModelAdmin):
+
+ model = Detail
+
+admin.site.register(Detai... |
f620dde75d65e1175829b524eec00d54e20bb2be | tests/test_views.py | tests/test_views.py | from __future__ import unicode_literals
from djet.testcases import ViewTestCase
from pgallery.views import TaggedPhotoListView
class TaggedPhotoListViewTestCase(ViewTestCase):
view_class = TaggedPhotoListView
def test_tag_in_response(self):
request = self.factory.get()
response = self.view(... | from __future__ import unicode_literals
from django.contrib.auth.models import AnonymousUser
from djet.testcases import ViewTestCase
from pgallery.views import GalleryListView, TaggedPhotoListView
from .factories import GalleryFactory, UserFactory
class GalleryListViewTestCase(ViewTestCase):
view_class = Galle... | Test drafts visible for staff users only. | Test drafts visible for staff users only.
| Python | mit | zsiciarz/django-pgallery,zsiciarz/django-pgallery | ---
+++
@@ -1,8 +1,28 @@
from __future__ import unicode_literals
+
+from django.contrib.auth.models import AnonymousUser
from djet.testcases import ViewTestCase
-from pgallery.views import TaggedPhotoListView
+from pgallery.views import GalleryListView, TaggedPhotoListView
+from .factories import GalleryFactory... |
7f1db4023f2310529822d721379b1019aaf320fc | tablib/formats/_df.py | tablib/formats/_df.py | """ Tablib - DataFrame Support.
"""
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
from pandas import DataFrame
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df', )
def detect(stream):
"""Returns True if gi... | """ Tablib - DataFrame Support.
"""
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
try:
from pandas import DataFrame
except ImportError:
DataFrame = None
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df'... | Raise NotImplementedError if pandas is not installed | Raise NotImplementedError if pandas is not installed
| Python | mit | kennethreitz/tablib | ---
+++
@@ -10,7 +10,10 @@
else:
from cStringIO import StringIO as BytesIO
-from pandas import DataFrame
+try:
+ from pandas import DataFrame
+except ImportError:
+ DataFrame = None
import tablib
@@ -21,6 +24,8 @@
def detect(stream):
"""Returns True if given stream is a DataFrame."""
+ i... |
5761364149b3171521cb4f72f591dc5f5cbd77d6 | temp-sensor02/main.py | temp-sensor02/main.py | from machine import Pin
from ds18x20 import DS18X20
import onewire
import time
import machine
import ujson
import urequests
def posttocloud(temperature):
keystext = open("sparkfun_keys.json").read()
keys = ujson.loads(keystext)
url = keys['inputUrl'] + "?private_key=" + keys['privateKey'] + "&temp=" + str(temper... | from machine import Pin
from ds18x20 import DS18X20
import onewire
import time
import ujson
import urequests
def posttocloud(temperature):
keystext = open("sparkfun_keys.json").read()
keys = ujson.loads(keystext)
params = {}
params['temp'] = temperature
params['private_key'] = keys['privateKey']
#dat... | Build a query string with params in a dictionary and append it to the URL. Makes the code readale. Remove commented code | Build a query string with params in a dictionary and append it to the URL. Makes the code readale. Remove commented code
| Python | mit | fuzzyhandle/esp8266hangout,fuzzyhandle/esp8266hangout,fuzzyhandle/esp8266hangout | ---
+++
@@ -2,20 +2,23 @@
from ds18x20 import DS18X20
import onewire
import time
-import machine
import ujson
import urequests
def posttocloud(temperature):
+
keystext = open("sparkfun_keys.json").read()
keys = ujson.loads(keystext)
- url = keys['inputUrl'] + "?private_key=" + keys['privateKey'] + "&... |
a427fab365ff3404748cdf8fb70b4ff542e81922 | fabfile.py | fabfile.py | from armstrong.dev.tasks import *
from d51.django.virtualenv.base import VirtualEnvironment
from fabric.api import task
settings = {
'DEBUG': True,
'INSTALLED_APPS': (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
... | from armstrong.dev.tasks import *
from fabric.api import task
settings = {
'DEBUG': True,
'INSTALLED_APPS': (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'armstrong.core.arm_sec... | Update to use the spec command in the latest armstrong.dev | Update to use the spec command in the latest armstrong.dev
| Python | apache-2.0 | texastribune/armstrong.core.tt_sections,texastribune/armstrong.core.tt_sections,texastribune/armstrong.core.tt_sections,armstrong/armstrong.core.arm_sections,armstrong/armstrong.core.arm_sections | ---
+++
@@ -1,5 +1,4 @@
from armstrong.dev.tasks import *
-from d51.django.virtualenv.base import VirtualEnvironment
from fabric.api import task
@@ -21,20 +20,6 @@
'SITE_ID': 1,
}
+full_name = "armstrong.core.arm_sections"
main_app = "arm_sections"
tested_apps = (main_app, )
-
-@task
-def lettuce(verb... |
327ba1797045235a420ce095d2cd2cac5257a1e9 | tutorials/models.py | tutorials/models.py | from django.db import models
# Create your models here.
class Tutorial(models.Model):
title = models.TextField()
html = models.TextField()
markdown = models.TextField() | from django.db import models
from markdownx.models import MarkdownxField
# Create your models here.
class Tutorial(models.Model):
# ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ??
# Category = models.TextField()
title = models.TextField()
html = models.TextFie... | Add missing Fields according to mockup, Add markdownfield | Add missing Fields according to mockup, Add markdownfield
| Python | agpl-3.0 | openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform | ---
+++
@@ -1,8 +1,14 @@
from django.db import models
+from markdownx.models import MarkdownxField
# Create your models here.
+
class Tutorial(models.Model):
+ # ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ??
+
+ # Category = models.TextField()
title = models... |
c058bd887348340c91ae3633d341031569114131 | smrt/__init__.py | smrt/__init__.py | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The SMRT module
import sys
import os
__version__ = '0.1'
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__SMRT_SETU... | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The SMRT module
import sys
import os
__version__ = '0.2'
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__SMRT_SETU... | Increment version to force build/coveralls | Increment version to force build/coveralls
| Python | bsd-3-clause | tgsmith61591/smrt,tgsmith61591/smrt | ---
+++
@@ -7,7 +7,7 @@
import sys
import os
-__version__ = '0.1'
+__version__ = '0.2'
try:
# this var is injected in the setup build to enable |
ea164b66cc93d5d7fb1f89a0297ea0a8da926b54 | server/core/views.py | server/core/views.py | from django.shortcuts import render
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def app(request):
return render(request, 'html.html')
| from django.shortcuts import render
def app(request):
return render(request, 'html.html')
| Stop inserting the CSRF token into the main app page | Stop inserting the CSRF token into the main app page
| Python | mit | Techbikers/techbikers,mwillmott/techbikers,mwillmott/techbikers,Techbikers/techbikers,mwillmott/techbikers,Techbikers/techbikers,Techbikers/techbikers,mwillmott/techbikers | ---
+++
@@ -1,7 +1,4 @@
from django.shortcuts import render
-from django.views.decorators.csrf import ensure_csrf_cookie
-
-@ensure_csrf_cookie
def app(request):
return render(request, 'html.html') |
6c314451e002db3213ff61d1e6935c091b605a8d | server/nurly/util.py | server/nurly/util.py | import traceback
class NurlyResult():
def __init__(self, code='200 OK', head=None, body=''):
self.head = {} if type(head) != dict else head
self.body = body
self.code = code
class NurlyStatus():
ST_IDLE = 0
ST_BUSY = 1
ST_STOP = 2
ST_MAP = {
ST_IDLE: 'IDLE',
... | import traceback
import types
class NurlyResult():
def __init__(self, code='200 OK', head=None, body=''):
self.head = {} if type(head) != dict else head
self.body = body
self.code = code
class NurlyStatus():
ST_IDLE = 0
ST_BUSY = 1
ST_STOP = 2
ST_MAP = {
ST_IDLE: ... | Support using a module as a call back if it has an function attribute by the same name. | Support using a module as a call back if it has an function attribute by the same name.
| Python | mit | mk23/nurly,mk23/nurly,mk23/nurly,mk23/nurly | ---
+++
@@ -1,4 +1,5 @@
import traceback
+import types
class NurlyResult():
def __init__(self, code='200 OK', head=None, body=''):
@@ -34,7 +35,7 @@
class NurlyAction():
def __init__(self, func, path='/', verb='GET'):
- self.func = func
+ self.func = func if type(func) is not types.Modu... |
293d50438fab81e74ab4559df7a4f7aa7cfd8f03 | etcdocker/container.py | etcdocker/container.py | import docker
from etcdocker import util
class Container:
def __init__(self, name, params):
self.name = name
self.params = params
def set_or_create_param(self, key, value):
self.params[key] = value
def ensure_running(self, force_restart=False):
# Ensure container is runn... | import ast
import docker
from etcdocker import util
class Container:
def __init__(self, name, params):
self.name = name
self.params = params
def set_or_create_param(self, key, value):
self.params[key] = value
def ensure_running(self, force_restart=False):
# Ensure contai... | Convert port list to dict | Convert port list to dict
| Python | mit | CloudBrewery/docrane | ---
+++
@@ -1,3 +1,4 @@
+import ast
import docker
from etcdocker import util
@@ -34,16 +35,20 @@
client.stop(self.name, 5)
client.remove_container(self.name)
+ # Convert our ports into a dict if necessary
+ ports = ast.literal_eval(self.params.get('ports'))
+
# C... |
c30181eed55cc1f2af6da4ee8608f4f2052ceb38 | serverless_helpers/__init__.py | serverless_helpers/__init__.py | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
from dotenv import load_dotenv, get_key, set_key, unset_key
def load_envs(path):
"""Recursively load .env files starting from `path`
Given the path "foo/bar/.env" and a directory structure like:
foo
\-... | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
from dotenv import load_dotenv, get_key, set_key, unset_key
def load_envs(path):
"""Recursively load .env files starting from `path`
Usage: from your Lambda function, call load_envs with the value __file__ to
give... | Document calling with __file__ as starting env path | Document calling with __file__ as starting env path
| Python | mit | serverless/serverless-helpers-py | ---
+++
@@ -6,11 +6,18 @@
def load_envs(path):
"""Recursively load .env files starting from `path`
- Given the path "foo/bar/.env" and a directory structure like:
+ Usage: from your Lambda function, call load_envs with the value __file__ to
+ give it the current location as a place to start looking f... |
5b5ad0e4fc97f540fdbda459adaa1ccc68cf6712 | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/urls.py | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/urls.py | from django.urls import path
from . import views
app_name = "users"
urlpatterns = [
path("", view=views.UserListView.as_view(), name="list"),
path("~redirect/", view=views.UserRedirectView.as_view(), name="redirect"),
path("~update/", view=views.UserUpdateView.as_view(), name="update"),
path(
... | from django.urls import path
from . import views
app_name = "users"
urlpatterns = [
path("", view=views.UserListView.as_view(), name="list"),
path("~redirect/", view=views.UserRedirectView.as_view(), name="redirect"),
path("~update/", view=views.UserUpdateView.as_view(), name="update"),
path(
... | Fix Py.Test unittests fail on new cookie | Fix Py.Test unittests fail on new cookie
Fixes #1674 | Python | bsd-3-clause | topwebmaster/cookiecutter-django,trungdong/cookiecutter-django,mistalaba/cookiecutter-django,ad-m/cookiecutter-django,luzfcb/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,mistalaba/cookiecutter-django,Parbhat/cookiecutter-django-foundation,Parbhat/cookiecutter-django-foundation,mistala... | ---
+++
@@ -8,7 +8,7 @@
path("~redirect/", view=views.UserRedirectView.as_view(), name="redirect"),
path("~update/", view=views.UserUpdateView.as_view(), name="update"),
path(
- "<str:username>",
+ "<str:username>/",
view=views.UserDetailView.as_view(),
name="detail",
... |
922acafc793b3d32f625fe18cd52b2bfd59a5f96 | ansible/wsgi.py | ansible/wsgi.py | from pecan.deploy import deploy
app = deploy('/opt/web/draughtcraft/src/production.py')
from paste.exceptions.errormiddleware import ErrorMiddleware
app = ErrorMiddleware(
app,
error_email=app.conf.error_email,
from_address=app.conf.error_email,
smtp_server=app.conf.error_smtp_server,
smtp_username... | from pecan import conf
from pecan.deploy import deploy
app = deploy('/opt/web/draughtcraft/src/production.py')
from paste.exceptions.errormiddleware import ErrorMiddleware
app = ErrorMiddleware(
app,
error_email=conf.error_email,
from_address=conf.error_email,
smtp_server=conf.error_smtp_server,
sm... | Fix a bug in the WSGI entrypoint. | Fix a bug in the WSGI entrypoint.
| Python | bsd-3-clause | ryanpetrello/draughtcraft,ryanpetrello/draughtcraft,ryanpetrello/draughtcraft,ryanpetrello/draughtcraft | ---
+++
@@ -1,13 +1,14 @@
+from pecan import conf
from pecan.deploy import deploy
app = deploy('/opt/web/draughtcraft/src/production.py')
from paste.exceptions.errormiddleware import ErrorMiddleware
app = ErrorMiddleware(
app,
- error_email=app.conf.error_email,
- from_address=app.conf.error_email,
-... |
b78b14214e317d1149b37bcdcf5ba0681212431b | rapidsms/contrib/httptester/models.py | rapidsms/contrib/httptester/models.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.db import models
DIRECTION_CHOICES = (
("I", "Incoming"),
("O", "Outgoing"))
class HttpTesterMessage(models.Model):
direction = models.CharField(max_length=1, choices=DIRECTION_CHOICES)
identity = models.CharField(max_length=100)
te... | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.db import models
DIRECTION_CHOICES = (
("I", "Incoming"),
("O", "Outgoing"))
class HttpTesterMessage(models.Model):
direction = models.CharField(max_length=1, choices=DIRECTION_CHOICES)
identity = models.CharField(max_length=100)
te... | Sort HTTP Tester Message model by id so they'll naturally be displayed in the order they were added. Branch: feature/httptester-update | Sort HTTP Tester Message model by id so they'll naturally be displayed in the order they were added.
Branch: feature/httptester-update
| Python | bsd-3-clause | eHealthAfrica/rapidsms,peterayeni/rapidsms,ehealthafrica-ci/rapidsms,ehealthafrica-ci/rapidsms,lsgunth/rapidsms,lsgunth/rapidsms,eHealthAfrica/rapidsms,lsgunth/rapidsms,caktus/rapidsms,ehealthafrica-ci/rapidsms,catalpainternational/rapidsms,catalpainternational/rapidsms,peterayeni/rapidsms,catalpainternational/rapidsms... | ---
+++
@@ -13,3 +13,8 @@
direction = models.CharField(max_length=1, choices=DIRECTION_CHOICES)
identity = models.CharField(max_length=100)
text = models.TextField()
+
+ class Meta(object):
+ # Ordering by id will order by when they were created, which is
+ # typically what we want
+ ... |
92eaa47b70d48874da032a21fbbd924936c0d518 | code/csv2map.py | code/csv2map.py | # csv2map.py -- Convert .csv into a .map format
# Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map
#
# jean-daniel.granet@mines-paristech.fr
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description='Convert .csv to .map')
parser.add_argument('cs... | # csv2map.py -- Convert .csv into a .map format
# Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map
#
# jean-daniel.granet@mines-paristech.fr
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description='Convert .csv to .map')
parser.add_argument('cs... | Add info about csv fields | Add info about csv fields
| Python | mit | chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan | ---
+++
@@ -8,9 +8,11 @@
def main():
parser = argparse.ArgumentParser(description='Convert .csv to .map')
- parser.add_argument('csv', help='CSV file to convert')
+ parser.add_argument('csv', help="""CSV file to convert. Fields are : Index,Illumina_SNP_Name,Alternative_SNP_Name,Chromosome,Build36_Positi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.