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 |
|---|---|---|---|---|---|---|---|---|---|---|
4a32fe3b3735df9ec56a4ca1769268740ef5d8f4 | tests/test_to_html.py | tests/test_to_html.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
class ToHTMLTest(unittest.TestCase):
SAMPLE = "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки."
def setUp(self):
from paka.cmark import to_html
self.func = to_html
def check(self, source, expe... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
class ToHTMLTest(unittest.TestCase):
SAMPLE = (
"Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки.\n\n"
"<p>Test of <em>HTML</em>.</p>")
def setUp(self):
from paka.cmark import to_html
... | Add HTML fragment to test sample | Add HTML fragment to test sample
| Python | bsd-3-clause | PavloKapyshin/paka.cmark,PavloKapyshin/paka.cmark,PavloKapyshin/paka.cmark | ---
+++
@@ -6,7 +6,9 @@
class ToHTMLTest(unittest.TestCase):
- SAMPLE = "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки."
+ SAMPLE = (
+ "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки.\n\n"
+ "<p>Test of <em>HTML</em>.</p>")
def setUp(self):
from pak... |
d0a02a8190d040eea3065a1141dbd41679c5eee3 | tools/casper_tests.py | tools/casper_tests.py | #!/usr/bin/env python
import multiprocessing
import subprocess
import glob
import os
if __name__ == "__main__":
os.environ["MLTSP_TEST_DB"] = "1"
from mltsp.Flask import flask_app
flask_app.db_init(force=True)
from mltsp.Flask.flask_app import app
p = multiprocessing.Process(target=app.run)
... | #!/usr/bin/env python
import multiprocessing
import subprocess
import glob
import os
import sys
if __name__ == "__main__":
os.environ["MLTSP_TEST_DB"] = "1"
from mltsp.Flask import flask_app
flask_app.db_init(force=True)
from mltsp.Flask.flask_app import app
p = multiprocessing.Process(target=ap... | Exit frontend tests with Casper status | Exit frontend tests with Casper status
| Python | bsd-3-clause | mltsp/mltsp,acrellin/mltsp,acrellin/mltsp,mltsp/mltsp,acrellin/mltsp,bnaul/mltsp,mltsp/mltsp,acrellin/mltsp,mltsp/mltsp,mltsp/mltsp,bnaul/mltsp,acrellin/mltsp,acrellin/mltsp,bnaul/mltsp,bnaul/mltsp,bnaul/mltsp,mltsp/mltsp,bnaul/mltsp | ---
+++
@@ -4,6 +4,7 @@
import subprocess
import glob
import os
+import sys
if __name__ == "__main__":
@@ -16,10 +17,10 @@
p.start()
tests = sorted(glob.glob('mltsp/tests/frontend/*.js'))
- subprocess.call(['external/casperjs/bin/casperjs', '--verbose',
- '--log-level=debug'... |
405c5cc9f88f3ea69f101ae36f3b3bf05b54a9eb | luckystrike/config.py | luckystrike/config.py | import argparse
import json
from os import path
import pinder
from twisted.words import service
rooms = {}
irc_users = {}
if path.exists(path.expanduser('~') + '/.luckystrike/config.json'):
with open(path.expanduser('~') + '/.luckystrike/config.json') as config_file:
configuration = dict(json.loads(conf... | import argparse
import json
from os import path
import pinder
from twisted.words import service
rooms = {}
irc_users = {}
if path.exists(path.expanduser('~') + '/.luckystrike/config.json'):
with open(path.expanduser('~') + '/.luckystrike/config.json') as config_file:
configuration = dict(json.loads(conf... | Add ability to increase debug level through multiple instances of flag | Add ability to increase debug level through multiple instances of flag
| Python | mit | mmichie/luckystrike | ---
+++
@@ -21,8 +21,8 @@
parser = argparse.ArgumentParser(description='Campfire to IRC Proxy')
parser.add_argument(
'-d', '--debug',
- action='store_true',
- help='increase debug level'
+ action='count',
+ help='add debug logging, add multiple times to increase level'
)
pa... |
c53e9266877f84d6a9f0d334a799a2e2d456471d | config/local_settings_staging.py | config/local_settings_staging.py | DEBUG = False
ENVIRONMENT = "staging"
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'lutris_staging',
'USER': 'lutris_staging',
'PASSWORD': 'admin'
}
}
| DEBUG = False
ENVIRONMENT = "staging"
ALLOWED_HOSTS = ('dev.lutris.net',)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'lutris_staging',
'USER': 'lutris_staging',
'PASSWORD': 'admin'
}
}
| Add ALLOWED_HOSTS on staging server settings | Add ALLOWED_HOSTS on staging server settings
| Python | agpl-3.0 | Turupawn/website,Turupawn/website,Turupawn/website,lutris/website,lutris/website,Turupawn/website,lutris/website,lutris/website | ---
+++
@@ -1,6 +1,6 @@
DEBUG = False
ENVIRONMENT = "staging"
-
+ALLOWED_HOSTS = ('dev.lutris.net',)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', |
005e7175f5fcd7e74637790e66e5cf46825195f6 | tests/cupy_tests/cuda_tests/test_nccl.py | tests/cupy_tests/cuda_tests/test_nccl.py | import unittest
from cupy import cuda
from cupy.testing import attr
@unittest.skipUnless(cuda.nccl_enabled, 'nccl is not installed')
class TestNCCL(unittest.TestCase):
@attr.gpu
def test_single_proc_ring(self):
id = cuda.nccl.get_unique_id()
comm = cuda.nccl.NcclCommunicator(1, id, 0)
... | import unittest
from cupy import cuda
from cupy.testing import attr
@unittest.skipUnless(cuda.nccl_enabled, 'nccl is not installed')
class TestNCCL(unittest.TestCase):
@attr.gpu
def test_single_proc_ring(self):
id = cuda.nccl.get_unique_id()
comm = cuda.nccl.NcclCommunicator(1, id, 0)
... | Add a test for initAll() | Add a test for initAll()
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy | ---
+++
@@ -30,3 +30,9 @@
comm = cuda.nccl.NcclCommunicator(1, id, 0)
comm.check_async_error()
comm.destroy()
+
+ @attr.gpu
+ def test_init_all(self):
+ comm = cuda.nccl.NcclCommunicator.initAll(1)
+ assert 0 == comm.rank_id()
+ comm.destroy() |
620d59b82e8a5c98fd4568217c74b485f802ac94 | tests/integration/test_authentication.py | tests/integration/test_authentication.py | from pyutrack import Connection
from pyutrack import Credentials
from pyutrack.errors import LoginError
from tests.integration import IntegrationTest
class AuthenticationTests(IntegrationTest):
def test_successful_authentication(self):
connection = Connection(
credentials=Credentials(username=... | from pyutrack import Connection
from pyutrack import Credentials
from pyutrack.errors import LoginError
from tests.integration import IntegrationTest
class AuthenticationTests(IntegrationTest):
def test_successful_authentication(self):
connection = Connection(
credentials=Credentials(username=... | Fix order of assertion arguments | Fix order of assertion arguments
| Python | mit | alisaifee/pyutrack,alisaifee/pyutrack | ---
+++
@@ -17,4 +17,4 @@
credentials=Credentials(username='root', password='rooted'),
base_url='http://localhost:9876'
)
- self.assertRaises(connection.login, LoginError)
+ self.assertRaises(LoginError, connection.login) |
5adbcbbce53985862f0cfcceadb4a3c0da2abe3d | tests/query_test/test_decimal_queries.py | tests/query_test/test_decimal_queries.py | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
... | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
... | Update decimal tests to only run on text/none. | Update decimal tests to only run on text/none.
Change-Id: I9a35f9e1687171fc3f06c17516bca2ea4b9af9e1
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2217
Tested-by: jenkins
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2431
Reviewed-b... | Python | apache-2.0 | michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,cloudera/Impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala | ---
+++
@@ -25,7 +25,8 @@
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
- v.get_value('table_format').file_format == 'text')
+ v.get_value('table_format').file_format == 't... |
245a6b190c1ad3c5e380c5957d6b98593fdb4006 | logserver/__main__.py | logserver/__main__.py | from argparse import ArgumentParser
import logging
from . import run_server
from .handlers import SQLiteHandler
parser = ArgumentParser(
description="Run a standalone log server using a SQLite database.")
parser.add_argument("-p", "--port", default=9123, help="Port to listen on")
parser.add_argument("-t", "--tabl... | from argparse import ArgumentParser
import logging
from . import run_server
from .handlers import SQLiteHandler
parser = ArgumentParser(
description="Run a standalone log server using a SQLite database.")
parser.add_argument("-p", "--port", default=9123, help="Port to listen on")
parser.add_argument("-t", "--tabl... | Format messages in stream handler | Format messages in stream handler
| Python | mit | mivade/logserver | ---
+++
@@ -13,8 +13,12 @@
help="SQLite filename")
args = parser.parse_args()
+stream_handler = logging.StreamHandler()
+stream_handler.setFormatter(logging.Formatter(
+ "[%(levelname)1.1s %(name)s %(asctime)s] %(msg)s"))
+
handlers = [
- logging.StreamHandler(),
+ stream_handler,
... |
0ac5a45c27b574c73d2660e96543220e274e1c64 | magpy/server/_ejdb.py | magpy/server/_ejdb.py | """EJDB driver for Magpy.
Currently does not do much except support certain command line scripts.
"""
import os
import pyejdb
class Database(object):
"""Simple database connection for use in serverside scripts etc."""
def __init__(self,
database_name=None,
config_file=None):
... | """EJDB driver for Magpy.
Currently does not do much except support certain command line scripts.
"""
import os
import pyejdb
class Database(object):
"""Simple database connection for use in serverside scripts etc."""
def __init__(self,
database_name=None,
config_file=None):
... | Deal with the weirdnesses of ejdb. | Deal with the weirdnesses of ejdb.
| Python | bsd-3-clause | zeth/magpy,catsmith/magpy,zeth/magpy,catsmith/magpy | ---
+++
@@ -44,4 +44,5 @@
def save(self, instance):
"""Save an instance."""
+ instance['id'] = instance.pop('_id')
self.database.database.save(self.name, instance) |
2ef97402219107fc632196bb0a7e3d6de38e5888 | latest_tweets/management/commands/latest_tweets_update.py | latest_tweets/management/commands/latest_tweets_update.py | from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils.timezone import utc
from datetime import datetime
from twitter import Twitter, OAuth
from latest_tweets.models import Tweet
from django.utils.six.moves import html_parser
def update_user(user):
t = Twitter(auth=... | from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils.timezone import utc
from datetime import datetime
from twitter import Twitter, OAuth
from latest_tweets.models import Tweet
from django.utils.six.moves import html_parser
def update_user(user):
t = Twitter(auth=... | Switch to update_or_create - Django 1.7+ | Switch to update_or_create - Django 1.7+
Can't use this on older versions of Django
| Python | bsd-3-clause | blancltd/django-latest-tweets | ---
+++
@@ -28,7 +28,7 @@
i['created_at'], '%a %b %d %H:%M:%S +0000 %Y'
).replace(tzinfo=utc)
- obj, created = Tweet.objects.get_or_create(tweet_id=tweet_id, defaults={
+ obj, created = Tweet.objects.update_or_create(tweet_id=tweet_id, defaults={
'user': tweet_userna... |
8a0f17eea757f2001ec9d9579a413ab852549d39 | tavenner.py | tavenner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import errno
import zipfile
import sys
import hashlib
def main():
from urllib2 import Request, urlopen, HTTPError
url_base = 'http://ethicssearch.dls.virginia.gov/ViewFormBinary.aspx?filingid='
errors = 0
i = 1
while True:
req ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import errno
import zipfile
import sys
import hashlib
output_dir = 'output'
def main():
# Make our output directory, if it doesn't exist.
if not os.path.exists(output_dir):
os.makedirs(output_dir)
from urllib2 import Request, urlopen, ... | Store output in a subdirectory | Store output in a subdirectory
| Python | mit | openva/tavenner | ---
+++
@@ -7,7 +7,13 @@
import sys
import hashlib
+output_dir = 'output'
+
def main():
+
+ # Make our output directory, if it doesn't exist.
+ if not os.path.exists(output_dir):
+ os.makedirs(output_dir)
from urllib2 import Request, urlopen, HTTPError
url_base = 'http://ethicssearch... |
d2e03bf76f585dc1025b5a94be0327284f8d5fa2 | Left_pare.py | Left_pare.py | # This macro is to remove 1 character form selected line on the left.
# Useful to clean code copied from diff file.
#
# Author: Nguyễn Hồng Quân (ng.hong.quan@gmail.com)
from xpcom import components
viewSvc = components.classes["@activestate.com/koViewService;1"]\
.getService(components.interfaces.koIViewService)
... | # This macro is to remove 1 character form selected line on the left.
# Useful to clean code copied from diff file.
#
# Author: Nguyễn Hồng Quân (ng.hong.quan@gmail.com)
from xpcom import components
viewSvc = components.classes["@activestate.com/koViewService;1"]\
.getService(components.interfaces.koIViewService)
... | Correct selecting text by length when text is Unicode. | Correct selecting text by length when text is Unicode.
| Python | mpl-2.0 | Komodo/macros,Komodo/macros | ---
+++
@@ -28,5 +28,5 @@
# Replace selection content
text = '\n'.join(lines)
sm.replaceSel(text)
-# Keep selection to allow to continue to apply this macro if use wants
-sm.setSel(start, start+len(text))
+# Keep selection to let user continue to apply this macro
+sm.setSel(start, start+len(text.encode('utf-8'))) |
0a884d3c38cb1449a6fa5c650ed06cde647de4a8 | settings/sqlite.py | settings/sqlite.py | from .base import *
import os.path
DATABASES = {
'default':
{
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(SITE_ROOT, 'dev.db'),
}
}
SESSION_COOKIE_DOMAIN = None
HAYSTACK_SOLR_URL = 'http://localhost:8983/solr'
| from .base import *
import os.path
DATABASES = {
'default':
{
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(SITE_ROOT, 'dev.db'),
}
}
SESSION_COOKIE_DOMAIN = None
HAYSTACK_SOLR_URL = 'http://localhost:8983/solr'
try:
... | Allow local settings override as well. | Allow local settings override as well.
| Python | mit | singingwolfboy/readthedocs.org,laplaceliu/readthedocs.org,kenwang76/readthedocs.org,hach-que/readthedocs.org,fujita-shintaro/readthedocs.org,rtfd/readthedocs.org,tddv/readthedocs.org,raven47git/readthedocs.org,mhils/readthedocs.org,royalwang/readthedocs.org,johncosta/private-readthedocs.org,asampat3090/readthedocs.org,... | ---
+++
@@ -13,3 +13,8 @@
SESSION_COOKIE_DOMAIN = None
HAYSTACK_SOLR_URL = 'http://localhost:8983/solr'
+try:
+ from local_settings import *
+except:
+ pass
+ |
14d170eece4e8bb105f5316fb0c6e672a3253b08 | py3flowtools/flowtools_wrapper.py | py3flowtools/flowtools_wrapper.py | # flowtools_wrapper.py
# Copyright 2014 Bo Bayles (bbayles@gmail.com)
# See http://github.com/bbayles/py3flowtools for documentation and license
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import ... | # flowtools_wrapper.py
# Copyright 2014 Bo Bayles (bbayles@gmail.com)
# See http://github.com/bbayles/py3flowtools for documentation and license
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import ... | Convert FlowToolsLog to a class | Convert FlowToolsLog to a class
| Python | mit | bbayles/py3flowtools | ---
+++
@@ -21,21 +21,40 @@
]
-def FlowToolsLog(file_path):
- with io.open(file_path, mode='rb') as flow_fd, \
- io.open(os.devnull, mode='wb') as DEVNULL:
- with subprocess.Popen(
- FLOW_EXPORT_ARGS,
- stdin=flow_fd,
- stdout=subprocess.PIPE,
- ... |
5b6bd6cacc7032bc6a830707374b1448861e5d08 | plugin.py | plugin.py | import sublime
def plugin_loaded():
# Native package causes some conflicts.
# Thanks https://github.com/SublimeText-Markdown/MarkdownEditing
disable_native_php_package()
def disable_native_php_package():
settings = sublime.load_settings('Preferences.sublime-settings')
ignored_packages = settings.g... | import sublime
def plugin_loaded():
# Native package causes some conflicts.
# Thanks https://github.com/SublimeText-Markdown/MarkdownEditing
disable_native_php_package()
def disable_native_php_package():
settings = sublime.load_settings('Preferences.sublime-settings')
ignored_packages = settings.g... | Sort ignored packages when adding native PHP package | Sort ignored packages when adding native PHP package
| Python | bsd-3-clause | gerardroche/sublime-php-grammar,gerardroche/sublime-php-grammar | ---
+++
@@ -11,5 +11,6 @@
if 'PHP' not in ignored_packages:
ignored_packages.append('PHP')
+ ignored_packages.sort()
settings.set('ignored_packages', ignored_packages)
sublime.save_settings('Preferences.sublime-settings') |
76e766998984da126de4cb6121c07690fbdeeba1 | pystil/data/graph/line.py | pystil/data/graph/line.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 by Florian Mounier, Kozea
# This file is part of pystil, licensed under a 3-clause BSD license.
"""Treat line data"""
from pystil.data.utils import make_time_serie, on, between
from pystil.db import db, count, Visit, distinct
def process_data(site,... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 by Florian Mounier, Kozea
# This file is part of pystil, licensed under a 3-clause BSD license.
"""Treat line data"""
from pystil.data.utils import make_time_serie, on, between
from pystil.db import db, count, Visit, distinct
def process_data(site,... | Fix the new/unique visits (at least!) | Fix the new/unique visits (at least!)
| Python | bsd-3-clause | Kozea/pystil,Kozea/pystil,Kozea/pystil,Kozea/pystil,Kozea/pystil | ---
+++
@@ -14,7 +14,7 @@
rq = (db.session
.query(Visit.day.label("key"),
count(distinct(Visit.uuid)).label("count")
- if criteria == 'unique' else count(1).label("count"))
+ if criteria in ('unique', 'new') else count(1).label("count"))
.fi... |
268467c5eb12e92a031d22e3e0515e9d6fc264b7 | ofgem_certificates.py | ofgem_certificates.py | #!/usr/bin/env python
# coding=utf-8
#
# Copyright 2013 david reid <zathrasorama@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
... | #!/usr/bin/env python
# coding=utf-8
#
# Copyright 2013 david reid <zathrasorama@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
... | Update the certificate script to accept month & year | Update the certificate script to accept month & year
| Python | unlicense | zathras777/pywind,zathras777/pywind | ---
+++
@@ -32,9 +32,10 @@
print "No certificates returned."
if __name__ == '__main__':
- parser = argparse.ArgumentParser(description='Get details of a station by accreditation number')
-# parser.add_argument('accreditation', action='store', help='Accreditation number to search for')
+ parser = ... |
695b3f628b56cd1dbe050f07692559ff3685290c | templatefinder/__init__.py | templatefinder/__init__.py | from __future__ import absolute_import
from .utils import *
VERSION = (0, 5,)
| from __future__ import absolute_import
# this is required for setup.py to work
try:
from .utils import *
except ImportError:
pass
VERSION = (0, 5, 1,)
| Fix setup.py for installs without Django | Fix setup.py for installs without Django
| Python | bsd-2-clause | TyMaszWeb/django-template-finder | ---
+++
@@ -1,6 +1,10 @@
from __future__ import absolute_import
-from .utils import *
+# this is required for setup.py to work
+try:
+ from .utils import *
+except ImportError:
+ pass
-VERSION = (0, 5,)
+VERSION = (0, 5, 1,) |
8d604d20562c8e90a938986976715e165aa98a53 | tests/test_rmd_to_ipynb.py | tests/test_rmd_to_ipynb.py | import nbrmd
import pytest
@pytest.mark.parametrize('nb_file', ['ioslides.Rmd', 'chunk_options.Rmd'])
def test_identity_write_read(nb_file):
"""
Test that writing the notebook with ipynb, and read again, yields identify
:param file:
:return:
"""
with open(nb_file) as fp:
rmd = fp.read(... | import nbrmd
import pytest
@pytest.mark.parametrize('nb_file', ['ioslides.Rmd', 'chunk_options.Rmd'])
def test_identity_write_read(nb_file):
"""
Test that writing the notebook with ipynb, and read again, yields identity
:param file:
:return:
"""
with open(nb_file) as fp:
rmd = fp.read(... | Fix typo identified by @tgy | Fix typo identified by @tgy
| Python | mit | mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext | ---
+++
@@ -4,7 +4,7 @@
@pytest.mark.parametrize('nb_file', ['ioslides.Rmd', 'chunk_options.Rmd'])
def test_identity_write_read(nb_file):
"""
- Test that writing the notebook with ipynb, and read again, yields identify
+ Test that writing the notebook with ipynb, and read again, yields identity
:par... |
a764e58549284b8af1b3978676b8ee121fd918e3 | thecure/levels/__init__.py | thecure/levels/__init__.py | from thecure.levels.base import *
from thecure.levels.cliff import Cliff
from thecure.levels.overworld import Overworld
def get_levels():
return [Cliff]
#return [Overworld, Cliff]
| from thecure.levels.base import *
from thecure.levels.cliff import Cliff
from thecure.levels.overworld import Overworld
def get_levels():
return [Overworld, Cliff]
| Set the overworld as the default level again. | Set the overworld as the default level again.
| Python | mit | chipx86/the-cure | ---
+++
@@ -4,5 +4,4 @@
def get_levels():
- return [Cliff]
- #return [Overworld, Cliff]
+ return [Overworld, Cliff] |
e8cfb78df42021097e54009c5b724c1d176822bc | sale_analytic_cost/__openerp__.py | sale_analytic_cost/__openerp__.py | # -*- coding: utf-8 -*-
# (c) 2015 Ainara Galdona - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Sale Analytic Cost',
"version": "8.0.1.0.0",
"license": 'AGPL-3',
"author": 'AvanzOSC,'
'Serv. Tecnol. Avanzados - Pedro M. Baeza',
'website': "http... | # -*- coding: utf-8 -*-
# (c) 2015 Ainara Galdona - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Sale Analytic Cost',
"version": "8.0.1.0.0",
"license": 'AGPL-3',
"author": 'AvanzOSC,'
'Serv. Tecnol. Avanzados - Pedro M. Baeza',
'website': "http... | Change dependency with "mrp_production_project_estimated_cost" by dependecy "mrp_production_estimated_cost". | [FIX] sale_analytic_cost: Change dependency with "mrp_production_project_estimated_cost" by dependecy "mrp_production_estimated_cost".
| Python | agpl-3.0 | Daniel-CA/odoo-addons,alfredoavanzosc/odoo-addons,mikelarre/hr-addons,Daniel-CA/odoo-addons,esthermm/odoo-addons,agaldona/odoo-addons,alfredoavanzosc/odoo-addons,esthermm/odoo-addons,agaldona/odoo-addons,agaldona/odoo-addons,esthermm/odoo-addons,Daniel-CA/odoo-addons | ---
+++
@@ -17,7 +17,7 @@
'category': 'Sales',
'depends': ['sale',
'account',
- 'mrp_production_project_estimated_cost'],
+ 'mrp_production_estimated_cost'],
'data': [],
'installable': True,
} |
9b239f3484f3ec3e03ad1fda2a76d35852f662e6 | _releng/deploy.py | _releng/deploy.py | #!/usr/bin/env python3
import os
import subprocess
PUBLIC_URL = "https://frida.re"
BUCKET_URI = "s3://frida.re"
MAX_PURGES_PER_REQUEST = 30
def main():
repo_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
urls = []
listing = subprocess.check_output([
"s3cmd",
"ls",
... | #!/usr/bin/env python3
import os
import subprocess
PUBLIC_URL = "https://frida.re"
BUCKET_URI = "s3://frida.re"
MAX_PURGES_PER_REQUEST = 30
def main():
repo_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
urls = []
listing = subprocess.check_output([
"s3cmd",
"ls",
... | Make cache purging logic a bit more thorough | Make cache purging logic a bit more thorough
| Python | mit | frida/frida-website,frida/frida-website,frida/frida-website | ---
+++
@@ -21,7 +21,7 @@
lines = listing.rstrip().split("\n")
for line in lines:
path = line[line.index(BUCKET_URI) + len(BUCKET_URI):]
- urls.append(PUBLIC_URL + path)
+ urls += compute_urls_for_path(path)
subprocess.check_call([
"s3cmd",
@@ -36,6 +36,19 @@
... |
fa42219c1e6763f3adfc1f6ede4080f769e476a6 | tests/test_mongo.py | tests/test_mongo.py | #!/usr/bin/env python
# coding=utf8
from uuid import uuid4 as uuid
import pytest
pymongo = pytest.importorskip('pymongo')
from simplekv.db.mongo import MongoStore
from basic_store import BasicStore
class TestMongoDB(BasicStore):
@pytest.fixture
def db_name(self):
return '_simplekv_test_{}'.format(u... | #!/usr/bin/env python
# coding=utf8
from uuid import uuid4 as uuid
import pytest
pymongo = pytest.importorskip('pymongo')
from simplekv.db.mongo import MongoStore
from basic_store import BasicStore
class TestMongoDB(BasicStore):
@pytest.fixture
def db_name(self):
return '_simplekv_test_{}'.format(u... | Add database table name to MongoStore tests. | Add database table name to MongoStore tests.
| Python | mit | fmarczin/simplekv,karteek/simplekv,mbr/simplekv,mbr/simplekv,fmarczin/simplekv,karteek/simplekv | ---
+++
@@ -18,5 +18,5 @@
@pytest.yield_fixture
def store(self, db_name):
conn = pymongo.MongoClient()
- yield MongoStore(conn[db_name])
+ yield MongoStore(conn[db_name], 'simplekv-tests')
conn.drop_database(self.db_name) |
af6c31d09aef686ba896b2a2c74fbb88cc7f1be0 | tests/test_utils.py | tests/test_utils.py | #!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | #!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | Add a start and end method to MockRequest | Add a start and end method to MockRequest
| Python | apache-2.0 | SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange | ---
+++
@@ -19,12 +19,42 @@
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
+ '"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
+
+
+from soc.modules import callback
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
+
+ Before using the object, start ... |
bff9e9c8c72be580bca4d82abf2d7931379f8ebf | scripts/get_services_to_deploy.py | scripts/get_services_to_deploy.py | #!/usr/bin/env python
import requests
import json
import sys
import argparse
parser = argparse.ArgumentParser('Queries Monorail to get the services and deployNotes where a list of Pull requests will be deployed')
parser.add_argument('--url', help='URL where Monorail is located')
parser.add_argument('--pr', help='List... | #!/usr/bin/env python
import requests
import json
import sys
import argparse
parser = argparse.ArgumentParser('Queries Monorail to get the services and deployNotes where a list of Pull requests will be deployed')
parser.add_argument('--url', help='URL where Monorail is located')
parser.add_argument('--pr', help='List... | Print variables for initial testing | Print variables for initial testing
| Python | mit | AudienseCo/monorail,AudienseCo/monorail | ---
+++
@@ -38,6 +38,11 @@
services=json_list['services']
deploynotes=json_list['deployNotes']
+print 'deploynotes:'
+print deploynotes
+print '\nservices:'
+print services
+
if deploynotes == 'True':
print 'There are deployNotes so we cannot continue'
exit(3) |
e3545cf444aea043fa892caeaff5a66ce893a0bb | misc/move-objects.py | misc/move-objects.py | from sys import argv
from axiom.store import Store
from entropy.store import ImmutableObject
from entropy.util import getAppStore
def moveObjects(appStore, start, limit=1000):
obj = None
for obj in appStore.query(
ImmutableObject,
ImmutableObject.storeID >= start,
limit=li... | from sys import argv
from axiom.store import Store
from entropy.store import ImmutableObject
from entropy.util import getAppStore
def moveObjects(appStore, start, limit):
obj = None
for obj in appStore.query(
ImmutableObject,
ImmutableObject.storeID >= start,
limit=limit):... | Make limit a command-line parameter too. | Make limit a command-line parameter too.
| Python | mit | fusionapp/entropy | ---
+++
@@ -5,7 +5,7 @@
from entropy.util import getAppStore
-def moveObjects(appStore, start, limit=1000):
+def moveObjects(appStore, start, limit):
obj = None
for obj in appStore.query(
ImmutableObject,
@@ -28,4 +28,5 @@
siteStore = Store(argv[1])
appStore = getAppStore(siteStore)
-a... |
b1382e380016c9034826b090540275ce2bbe3a95 | src/ggrc_basic_permissions/roles/ProgramAuditReader.py | src/ggrc_basic_permissions/roles/ProgramAuditReader.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
scope = "AuditImplied"
description = """
A user with the ProgramReader role fo... | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
scope = "AuditImplied"
description = """
A user with the ProgramReader role fo... | Allow Program Readers to view comments | Allow Program Readers to view comments
| Python | apache-2.0 | jmakov/ggrc-core,plamut/ggrc-core,NejcZupec/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,kr41/ggrc-core,NejcZupec/ggrc-core,edofic/ggrc-core,jmakov/ggrc-core,NejcZupec/ggrc-core,kr41/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,josthk... | ---
+++
@@ -11,6 +11,7 @@
permissions = {
"read": [
"Request",
+ "Comment",
"ControlAssessment",
"Issue",
"DocumentationResponse", |
8773f652a1cf78299e3dd5ba9296ca2a50143caa | aiopg/__init__.py | aiopg/__init__.py | import re
import sys
from collections import namedtuple
from .connection import connect, Connection
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info')
__version__ = '0.3.2'
version = __version__ +... | import re
import sys
from collections import namedtuple
from .connection import connect, Connection
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info')
__version__ = '0.4.0a0'
version = __version__... | Revert master version to 0.4.0a0 | Revert master version to 0.4.0a0
| Python | bsd-2-clause | eirnym/aiopg,graingert/aiopg,hyzhak/aiopg,aio-libs/aiopg,luhn/aiopg,nerandell/aiopg | ---
+++
@@ -10,7 +10,7 @@
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info')
-__version__ = '0.3.2'
+__version__ = '0.4.0a0'
version = __version__ + ' , Python ' + sys.version
|
d0e7d3578fe79432ad2b2cc62be2203d4ff36014 | examples/charts/file/cat_heatmap.py | examples/charts/file/cat_heatmap.py | from bokeh.charts import HeatMap, output_file, show
from bokeh.sampledata.unemployment1948 import data
# pandas magic
df = data[data.columns[:-2]]
df2 = df.set_index(df[df.columns[0]].astype(str))
df2.drop(df.columns[0], axis=1, inplace=True)
df3 = df2.transpose()
output_file("cat_heatmap.html")
hm = HeatMap(df3, ti... | from bokeh.charts import HeatMap, output_file, show
from bokeh.palettes import YlOrRd9 as palette
from bokeh.sampledata.unemployment1948 import data
# pandas magic
df = data[data.columns[:-1]]
df2 = df.set_index(df[df.columns[0]].astype(str))
df2.drop(df.columns[0], axis=1, inplace=True)
df3 = df2.transpose()
output_... | Use all the months of the year and tweak palette. | Use all the months of the year and tweak palette.
- Picked a continuous palette and reversed as better for the data.
| Python | bsd-3-clause | abele/bokeh,laurent-george/bokeh,azjps/bokeh,josherick/bokeh,rs2/bokeh,timsnyder/bokeh,draperjames/bokeh,matbra/bokeh,ptitjano/bokeh,DuCorey/bokeh,awanke/bokeh,akloster/bokeh,xguse/bokeh,stonebig/bokeh,KasperPRasmussen/bokeh,phobson/bokeh,stonebig/bokeh,CrazyGuo/bokeh,ericmjl/bokeh,rhiever/bokeh,caseyclements/bokeh,rox... | ---
+++
@@ -1,14 +1,16 @@
from bokeh.charts import HeatMap, output_file, show
+from bokeh.palettes import YlOrRd9 as palette
from bokeh.sampledata.unemployment1948 import data
# pandas magic
-df = data[data.columns[:-2]]
+df = data[data.columns[:-1]]
df2 = df.set_index(df[df.columns[0]].astype(str))
df2.drop(d... |
a7c5c9d27d29e14ebb2d314890b40eab318501ac | dialogos/admin.py | dialogos/admin.py | from django.contrib import admin
from dialogos.models import Comment
class CommentAdmin(admin.ModelAdmin):
list_display = ['author', 'content_type', 'public']
list_filter = ['public', 'content_type']
admin.site.register(Comment, CommentAdmin)
| from django.contrib import admin
from dialogos.models import Comment
class CommentAdmin(admin.ModelAdmin):
list_display = ["author", "content_type", "public"]
list_filter = ["public", "content_type"]
admin.site.register(Comment, CommentAdmin)
| Update style to match Pinax conventions | Update style to match Pinax conventions | Python | mit | pinax/pinax-comments,rizumu/dialogos,GeoNode/geonode-dialogos,eldarion/dialogos,georgedorn/dialogos,pinax/pinax-comments | ---
+++
@@ -1,8 +1,11 @@
from django.contrib import admin
+
from dialogos.models import Comment
+
class CommentAdmin(admin.ModelAdmin):
- list_display = ['author', 'content_type', 'public']
- list_filter = ['public', 'content_type']
+ list_display = ["author", "content_type", "public"]
+ list_filte... |
c09465f6f5d70789ca01470015985cbbdb465db9 | problem_2/solution.py | problem_2/solution.py | from timeit import timeit
def sum_even_fibonacci_numbers_1():
f1, f2, s, = 0, 1, 0,
while f2 < 4000000:
f2, f1 = f1, f1 + f2
if f2 % 2 == 0:
s += f2
return s
def sum_even_fibonacci_numbers_2():
s, a, b = 0, 1, 1
c = a + b
while c < 4000000:
s += c
a = ... | import time
def sum_even_fibonacci_numbers_1():
f1, f2, s, = 0, 1, 0,
while f2 < 4000000:
f2, f1 = f1, f1 + f2
if f2 % 2 == 0:
s += f2
return s
def sum_even_fibonacci_numbers_2():
s, a, b = 0, 1, 1
c = a + b
while c < 4000000:
s += c
a = b + c
... | Add better timing for python implementation of problem 2 | Add better timing for python implementation of problem 2
| Python | mit | mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler | ---
+++
@@ -1,4 +1,4 @@
-from timeit import timeit
+import time
def sum_even_fibonacci_numbers_1():
f1, f2, s, = 0, 1, 0,
while f2 < 4000000:
@@ -15,5 +15,11 @@
b = a + c
c = a + b
return s
-print "sum_even_fibonacci_numbers_1: {0}".format(timeit("sum_even_fibonacci_numbers_1()", "fr... |
a612a245937781e86391e5c3ec8a740f36b405ce | problems/19/Solver.py | problems/19/Solver.py | class Solver:
def solve(self, start_number):
recipient = 1
remaining = start_number
power = 1
while remaining > 1:
new_remaining = remaining // 2
remaining_was_odd = remaining % 2
power *= 2
remaining = new_remaining
if rema... | class Solver:
def __init__(self):
self.next_elves = {}
def solve(self, start_number):
recipient = 1
remaining = start_number
power = 1
while remaining > 1:
new_remaining = remaining // 2
remaining_was_odd = remaining % 2
power *= 2
... | Refactor to use linked list | Refactor to use linked list
| Python | mit | tmct/adventOfCode2016 | ---
+++
@@ -1,4 +1,7 @@
class Solver:
+ def __init__(self):
+ self.next_elves = {}
+
def solve(self, start_number):
recipient = 1
remaining = start_number
@@ -13,17 +16,25 @@
return recipient
def solve_b(self, start_number):
- elves = list(range(1, start_number... |
44191360586beeec04a4abc8a4aa262bc5ec052d | odinweb/exceptions.py | odinweb/exceptions.py | # -*- coding: utf-8 -*-
"""
Exceptions
~~~~~~~~~~
"""
from .constants import HTTPStatus
from .resources import Error
class ImmediateHttpResponse(Exception):
"""
A response that should be returned immediately.
"""
def __init__(self, resource, status=HTTPStatus.OK, headers=None):
self.resource ... | # -*- coding: utf-8 -*-
"""
Exceptions
~~~~~~~~~~
"""
from .constants import HTTPStatus
from .resources import Error
__all__ = ('ImmediateHttpResponse', 'HttpError', 'PermissionDenied')
class ImmediateHttpResponse(Exception):
"""
A response that should be returned immediately.
"""
def __init__(self,... | Refactor HttpError to use Error.from_status helper | Refactor HttpError to use Error.from_status helper
| Python | bsd-3-clause | python-odin/odinweb,python-odin/odinweb | ---
+++
@@ -6,6 +6,8 @@
"""
from .constants import HTTPStatus
from .resources import Error
+
+__all__ = ('ImmediateHttpResponse', 'HttpError', 'PermissionDenied')
class ImmediateHttpResponse(Exception):
@@ -22,10 +24,9 @@
"""
An error response that should be returned immediately.
"""
- def _... |
7ae151e277d2cb03037d40e1598b190ba4736433 | dthm4kaiako/events/views.py | dthm4kaiako/events/views.py | """Views for events application."""
from django.views import generic
from django.utils.timezone import now
from events.models import (
Event,
Location,
)
class HomeView(generic.TemplateView):
"""View for event homepage."""
template_name = 'events/home.html'
def get_context_data(self, **kwargs):... | """Views for events application."""
from django.views import generic
from django.utils.timezone import now
from events.models import (
Event,
Location,
)
class HomeView(generic.TemplateView):
"""View for event homepage."""
template_name = 'events/home.html'
def get_context_data(self, **kwargs):... | Reduce SQL queries for events homepage | Reduce SQL queries for events homepage
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | ---
+++
@@ -20,7 +20,13 @@
Dictionary of context data.
"""
context = super().get_context_data(**kwargs)
- future_events = Event.objects.filter(end__gte=now()).order_by('start')
+ future_events = Event.objects.filter(end__gte=now()).order_by('start').prefetch_related(
+ ... |
33f47fc9aff361d0cea9557e6470d505a352e5f0 | forms.py | forms.py | from flask.ext.wtf import Form
from wtforms import SelectField, BooleanField, IntegerField, TextField, \
validators
class TeamForm(Form):
number = IntegerField("Number", [validators.Required(),
validators.NumberRange(min=1, max=99999)])
name = TextField("Name", [valida... | from flask.ext.wtf import Form
from wtforms import SelectField, BooleanField, IntegerField, TextField, \
validators
from models import RobotScore
class TeamForm(Form):
number = IntegerField("Number", [validators.Required(),
validators.NumberRange(min=1, max=99999)])
na... | Validate that score doesn't already exist for a round when submitting the form | Validate that score doesn't already exist for a round when submitting the form
| Python | mit | rtfoley/scorepy,rtfoley/scorepy,rtfoley/scorepy | ---
+++
@@ -1,6 +1,7 @@
from flask.ext.wtf import Form
from wtforms import SelectField, BooleanField, IntegerField, TextField, \
validators
+from models import RobotScore
class TeamForm(Form):
@@ -22,3 +23,20 @@
cargo_plane_location = SelectField(u'Cargo plane location', choices=[('0', 'None'),
... |
08a7389e5be0d3f7a9e6c4e12b13f82da50480b1 | reference/gittaggers.py | reference/gittaggers.py | from setuptools.command.egg_info import egg_info
import subprocess
import time
class EggInfoFromGit(egg_info):
"""Tag the build with git commit timestamp.
If a build tag has already been set (e.g., "egg_info -b", building
from source package), leave it alone.
"""
def git_timestamp_tag(self):
... | from setuptools.command.egg_info import egg_info
import subprocess
import time
class EggInfoFromGit(egg_info):
"""Tag the build with git commit timestamp.
If a build tag has already been set (e.g., "egg_info -b", building
from source package), leave it alone.
"""
def git_timestamp_tag(self):
... | Fix Python packaging to use correct git log for package time/version stamps (2nd try) | Fix Python packaging to use correct git log for package time/version stamps (2nd try)
| Python | apache-2.0 | chapmanb/cwltool,brainstorm/common-workflow-language,curoverse/common-workflow-language,chapmanb/cwltool,hmenager/common-workflow-language,common-workflow-language/cwltool,foreveremain/common-workflow-language,StarvingMarvin/common-workflow-language,jeremiahsavage/cwltool,foreveremain/common-workflow-language,satra/com... | ---
+++
@@ -11,7 +11,7 @@
def git_timestamp_tag(self):
gitinfo = subprocess.check_output(
['git', 'log', '--first-parent', '--max-count=1',
- '--format=format:%ct', '..']).strip()
+ '--format=format:%ct']).strip()
return time.strftime('.%Y%m%d%H%M%S', time.g... |
834349fc6cc2f6d281f03f339dab116b897615fc | knowledge_repo/postprocessors/format_checks.py | knowledge_repo/postprocessors/format_checks.py | from ..constants import FORMAT_CHECKS
from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES
from ..postprocessor import KnowledgePostProcessor
class FormatChecks(KnowledgePostProcessor):
_registry_keys = [FORMAT_CHECKS]
def process(self, kp):
headers = kp.headers
for fie... | from ..constants import FORMAT_CHECKS
from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES
from ..postprocessor import KnowledgePostProcessor
class FormatChecks(KnowledgePostProcessor):
_registry_keys = [FORMAT_CHECKS]
def process(self, kp):
headers = kp.headers
for fie... | Refactor to avoid duplicate code | Refactor to avoid duplicate code
| Python | apache-2.0 | airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo | ---
+++
@@ -8,14 +8,13 @@
def process(self, kp):
headers = kp.headers
- for field, typ, input in HEADER_REQUIRED_FIELD_TYPES:
+ for field, typ, _ in HEADER_REQUIRED_FIELD_TYPES:
assert field in headers, \
"Required field `{field}` missing from headers."
- ... |
5d2110059731069a6a29a31d2b9f02bb2743e90b | scripts/cleanup-images.py | scripts/cleanup-images.py | #!/usr/bin/python
import os, sys
import pwd
if os.geteuid():
print >> sys.stderr, "Script must be run as root to manipulate permissions"
sys.exit(1)
from conary import dbstore
from mint import config
apacheGid = pwd.getpwnam('apache')[3]
isogenUid = pwd.getpwnam('isogen')[2]
cfg = config.MintConfig()
cfg.r... | #!/usr/bin/python
import os, sys
import pwd
if os.geteuid():
print >> sys.stderr, "Script must be run as root to manipulate permissions"
sys.exit(1)
from conary import dbstore
from mint import config
apacheGid = pwd.getpwnam('apache')[3]
isogenUid = pwd.getpwnam('isogen')[2]
cfg = config.MintConfig()
cfg.r... | Kill off another hardcoded path | Kill off another hardcoded path
| Python | apache-2.0 | sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint | ---
+++
@@ -14,13 +14,13 @@
isogenUid = pwd.getpwnam('isogen')[2]
cfg = config.MintConfig()
-cfg.read('/srv/rbuilder/rbuilder.conf')
+cfg.read(config.RBUILDER_CONFIG)
db = dbstore.connect(cfg.dbPath, cfg.dbDriver)
cu = db.cursor()
cu.execute('SELECT filename FROM ImageFiles')
imageFiles = [x[0] for x in cu.fe... |
eabc02aed1cd5a109554f48bfb82f185e392c404 | remo/base/middleware.py | remo/base/middleware.py | from django.conf import settings
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
class RegisterMiddleware(object):
"""Middleware to enforce users to complete registration.
When a user logins and has the registration_complete field in his
... | from django.conf import settings
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
class RegisterMiddleware(object):
"""Middleware to enforce users to complete registration.
When a user logins and has the registration_complete field in his
... | Add 'oidc_logout' in allowed urls. | Add 'oidc_logout' in allowed urls.
| Python | bsd-3-clause | flamingspaz/remo,akatsoulas/remo,mozilla/remo,Mte90/remo,flamingspaz/remo,akatsoulas/remo,Mte90/remo,Mte90/remo,flamingspaz/remo,mozilla/remo,akatsoulas/remo,tsmrachel/remo,tsmrachel/remo,akatsoulas/remo,tsmrachel/remo,tsmrachel/remo,mozilla/remo,flamingspaz/remo,Mte90/remo,mozilla/remo | ---
+++
@@ -22,6 +22,7 @@
allow_urls = [
reverse('oidc_authentication_init'),
reverse('oidc_authentication_callback'),
+ reverse('oidc_logout'),
reverse('profiles_edit',
kwargs={'display_name':
... |
d1afc8b673595accb854639b311bbdd49be56022 | server/LikeLines/debug.py | server/LikeLines/debug.py | """
Debug Blueprints.
"""
from flask import Blueprint, current_app, redirect, jsonify, url_for
debug_pages = Blueprint('debug', __name__)
@debug_pages.route("/clear_all")
def clear_all():
mongo = current_app.mongo
mongo.db.userSessions.remove()
mongo.db.interactionSessions.remove()
return redirect(ur... | """
Debug Blueprints.
"""
from flask import Blueprint, current_app, redirect, jsonify, url_for, request
debug_pages = Blueprint('debug', __name__)
@debug_pages.route("/clear_all", methods=['GET', 'POST'])
def clear_all():
if request.method == 'GET':
return '<form method="POST"><input type="submit" value=... | Make it harder to accidentally empty the database | Make it harder to accidentally empty the database
| Python | mit | ShinNoNoir/likelines-player,ShinNoNoir/likelines-player,ShinNoNoir/likelines-player | ---
+++
@@ -1,17 +1,20 @@
"""
Debug Blueprints.
"""
-from flask import Blueprint, current_app, redirect, jsonify, url_for
+from flask import Blueprint, current_app, redirect, jsonify, url_for, request
debug_pages = Blueprint('debug', __name__)
-@debug_pages.route("/clear_all")
+@debug_pages.route("/clear_al... |
5ab34396d4f494f884ddf98fb993bcf1b928216e | api/citations/urls.py | api/citations/urls.py | from django.conf.urls import url
from api.citations import views
urlpatterns = [
url(r'^$', views.CitationList.as_view(), name=views.CitationList.view_name),
url(r'^(?P<citation_id>\w+)/$', views.CitationDetail.as_view(), name=views.CitationDetail.view_name),
]
| from django.conf.urls import url
from api.citations import views
urlpatterns = [
url(r'^styles/$', views.CitationList.as_view(), name=views.CitationList.view_name),
url(r'^styles/(?P<citation_id>\w+)/$', views.CitationDetail.as_view(), name=views.CitationDetail.view_name),
]
| Add styles prefix to match api v1 | Add styles prefix to match api v1
| Python | apache-2.0 | mattclark/osf.io,chennan47/osf.io,rdhyee/osf.io,alexschiller/osf.io,mluo613/osf.io,HalcyonChimera/osf.io,TomBaxter/osf.io,laurenrevere/osf.io,Nesiehr/osf.io,mfraezz/osf.io,caneruguz/osf.io,crcresearch/osf.io,sloria/osf.io,adlius/osf.io,caseyrollins/osf.io,monikagrabowska/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,i... | ---
+++
@@ -3,6 +3,6 @@
from api.citations import views
urlpatterns = [
- url(r'^$', views.CitationList.as_view(), name=views.CitationList.view_name),
- url(r'^(?P<citation_id>\w+)/$', views.CitationDetail.as_view(), name=views.CitationDetail.view_name),
+ url(r'^styles/$', views.CitationList.as_view(), ... |
3059f6448e0fc2dd49ad38306f8efedc734b3aab | api/projects/tasks.py | api/projects/tasks.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
from api.settings import CeleryTasks, Intervals
from api.celery_api import app as celery_app
from experiments.tasks import build_experiment
from projects.models import ExperimentGroup
logger = logging.getLogger('p... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
from api.settings import CeleryTasks, Intervals
from api.celery_api import app as celery_app
from experiments.tasks import build_experiment
from projects.models import ExperimentGroup
logger = logging.getLogger('p... | Fix retry for experiment group | Fix retry for experiment group
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -11,7 +11,7 @@
logger = logging.getLogger('polyaxon.tasks.projects')
-@celery_app.task(name=CeleryTasks.EXPERIMENTS_START_GROUP, bind=True)
+@celery_app.task(name=CeleryTasks.EXPERIMENTS_START_GROUP, bind=True, max_retries=None)
def start_group_experiments(self, experiment_group_id):
try:
... |
10655be79d9ab65f86939d0bd085197e0e35b39d | CodeFights/knapsackLight.py | CodeFights/knapsackLight.py | #!/usr/local/bin/python
# Code Fights Knapsack Problem
def knapsackLight(value1, weight1, value2, weight2, maxW):
if weight1 + weight2 <= maxW:
return value1 + value2
else:
return max([v for v, w in zip((value1, value2), (weight1, weight2))
if w <= maxW] + [0])
def main():... | #!/usr/local/bin/python
# Code Fights Knapsack Problem
def knapsackLight(value1, weight1, value2, weight2, maxW):
if weight1 + weight2 <= maxW:
return value1 + value2
else:
return max([v for v, w in zip((value1, value2), (weight1, weight2))
if w <= maxW] + [0])
def main():... | Format Code Fights knapsack light problem | Format Code Fights knapsack light problem
| Python | mit | HKuz/Test_Code | ---
+++
@@ -12,18 +12,20 @@
def main():
tests = [
+ [10, 5, 6, 4, 8, 10],
[]
]
for t in tests:
- res = knapsackLight(t[0], t[1], t[2])
- ans = t[3]
+ res = knapsackLight(t[0], t[1], t[2], t[3], t[4])
+ ans = t[5]
if ans == res:
- prin... |
82796dfb24c3e65b669d4336948e76e2a64cf73f | LR/lr/model/node_service.py | LR/lr/model/node_service.py | #!/usr/bin/pyton
# Copyright 2011 Lockheed Martin
'''
Created on Mar 17, 2011
Base model class for learning registry data model
@author: jpoyau
'''
from base_model import createBaseModel, ModelParser, defaultCouchServer, appConfig
from pylons import *
import datetime, logging
log = logging.getLogger(__name__)... | #!/usr/bin/pyton
# Copyright 2011 Lockheed Martin
'''
Created on Mar 17, 2011
Base model class for learning registry data model
@author: jpoyau
'''
from base_model import createBaseModel, ModelParser, defaultCouchServer, appConfig
from pylons import *
import datetime, logging
log = logging.getLogger(__name__)... | Add 'distribute' to the node services | Add 'distribute' to the node services
| Python | apache-2.0 | jimklo/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningR... | ---
+++
@@ -25,6 +25,7 @@
PUBLISH='publish'
ACCESS = 'access'
BROKER = 'broker'
+ DISTRIBUTE = 'distribute'
ADMINISTRATIVE='administrative'
def __init__(self, data=None): |
dcd97762b65df37b5f7c4724892ab76bb631762f | src/havenctl/havenctl/launcher.py | src/havenctl/havenctl/launcher.py | import sys
import getopt
from ctl import HavenCtl
def print_version():
import pkg_resources # part of setuptools
version = pkg_resources.require("havenctl")[0].version
print(version)
def print_usage():
print """
Usage: havenctl [-a <remote_address> | --address=<remote_address>]
[-p <... | import sys
import getopt
from ctl import HavenCtl
def print_version():
import pkg_resources # part of setuptools
version = pkg_resources.require("havenctl")[0].version
print(version)
def print_usage():
print """
Usage: havenctl [-a <remote_address> | --address=<remote_address>]
[-p <... | Make plain repl work again. | Make plain repl work again.
| Python | apache-2.0 | fintler/tomatodb,fintler/tomatodb,fintler/tomatodb | ---
+++
@@ -15,6 +15,9 @@
"""
def execute_from_command_line():
+ address = None
+ port = 7854
+
try:
opts, args = getopt.getopt(sys.argv[1:], "a:p:hv", \
["address=", "port=", "version", "help"])
@@ -40,7 +43,8 @@
assert False, "unhandled option"
... |
7ce0478dafebb7f6c52150a3563ae4cc59d68d6e | mass_mailing_switzerland/models/mailchimp_merge_fields.py | mass_mailing_switzerland/models/mailchimp_merge_fields.py | ##############################################################################
#
# Copyright (C) 2021 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
#####################... | ##############################################################################
#
# Copyright (C) 2021 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
#####################... | FIX mailing_contact merge fields value | FIX mailing_contact merge fields value
| Python | agpl-3.0 | CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland | ---
+++
@@ -26,8 +26,8 @@
res = super(MailchimpMergeFields, partner_fields).get_value(mailing_contact)
for custom_field in contact_fields:
if custom_field.field_id and hasattr(
- self, custom_field.field_id.name):
- value = getattr(self, custom_field.fi... |
2ad16c44adb20e9ba023e873149d67068504c34c | saleor/cart/__init__.py | saleor/cart/__init__.py | from __future__ import unicode_literals
from django.utils.translation import pgettext
from satchless import cart
from satchless.item import ItemList, ClassifyingPartitioner
from ..product.models import DigitalShip
class ShippedGroup(ItemList):
'''
Group for shippable products.
'''
pass
class Digit... | from __future__ import unicode_literals
from django.utils.translation import pgettext
from satchless import cart
from satchless.item import ItemList, ClassifyingPartitioner
from ..product.models import DigitalShip
class ShippedGroup(ItemList):
'''
Group for shippable products.
'''
pass
class Digit... | Add ability to clear cart | Add ability to clear cart
| Python | bsd-3-clause | avorio/saleor,laosunhust/saleor,hongquan/saleor,maferelo/saleor,avorio/saleor,car3oon/saleor,tfroehlich82/saleor,UITools/saleor,car3oon/saleor,Drekscott/Motlaesaleor,maferelo/saleor,hongquan/saleor,josesanch/saleor,taedori81/saleor,KenMutemi/saleor,tfroehlich82/saleor,spartonia/saleor,mociepka/saleor,itbabu/saleor,UITo... | ---
+++
@@ -48,3 +48,6 @@
return pgettext(
'Shopping cart',
'Your cart (%(cart_count)s)') % {'cart_count': self.count()}
+
+ def clear(self):
+ self._state = [] |
5f9cf67c473ef7d304da067b70b56d77f71ca4fa | web/impact/impact/middleware/method_override_middleware.py | web/impact/impact/middleware/method_override_middleware.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
# METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE'
METHOD_OVERRIDE_HEADER = 'X-HTTP-Method-Override'
class MethodOverrideMiddleware(object):
def process_request(self, request):
if request.method != 'POST':
return
if METHOD_OV... | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE'
class MethodOverrideMiddleware(object):
def process_request(self, request):
if request.method != 'POST':
return
if METHOD_OVERRIDE_HEADER not in request.META:
retur... | Revert Changes To Middleware To Prevent Build Hangup | [AC-4959] Revert Changes To Middleware To Prevent Build Hangup
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api | ---
+++
@@ -1,8 +1,7 @@
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
-# METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE'
-METHOD_OVERRIDE_HEADER = 'X-HTTP-Method-Override'
+METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE'
class MethodOverrideMiddleware(object):
def process_request(se... |
42a0dd7f808b87035f8067c5d0ad4bb688632135 | ecmd-core/pyapi/init/__init__.py | ecmd-core/pyapi/init/__init__.py | # import the right SWIG module depending on Python version
from sys import version_info
from sys import path as sys_path
from os import path as os_path
if version_info[0] >= 3:
sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python3"))
from .python3 import *
else:
sys_path.insert(0, os_path.join... | # import the right SWIG module depending on Python version
from sys import version_info
from sys import path as sys_path
from os import path as os_path
if version_info[0] >= 3:
sys_path.append(os_path.join(os_path.dirname(__file__), "python3"))
from .python3 import *
else:
sys_path.append(os_path.join(os_pa... | Append version specific path to os.path rather than prepend | pyapi: Append version specific path to os.path rather than prepend
Other code might depend on os.path[0] being the path of the executed
script, and there is no need for our new path to be at the front.
| Python | apache-2.0 | open-power/eCMD,mklight/eCMD,mklight/eCMD,open-power/eCMD,mklight/eCMD,mklight/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD,mklight/eCMD | ---
+++
@@ -3,9 +3,9 @@
from sys import path as sys_path
from os import path as os_path
if version_info[0] >= 3:
- sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python3"))
+ sys_path.append(os_path.join(os_path.dirname(__file__), "python3"))
from .python3 import *
else:
- sys_path.inse... |
b03c8ebe8cc426e21b45f4de0d8d6e7176a4a647 | api/admin.py | api/admin.py | from django.contrib import admin
from api import models
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'country', )
class EventAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
list_display = ('title', 'status', 'location', 'country', 'start_date')
list_editable... | from django.contrib import admin
from api import models
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'country', )
search_fields = ['user__email', 'user__username', 'user__first_name', 'user__last_name']
class EventAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
... | Allow searching by email, username and names in user profiles | Allow searching by email, username and names in user profiles
This is needed as user profiles need to be edited for setting main
contact flag and ambassador roles.
| Python | mit | codeeu/coding-events,michelesr/coding-events,michelesr/coding-events,michelesr/coding-events,codeeu/coding-events,codeeu/coding-events,michelesr/coding-events,codeeu/coding-events,codeeu/coding-events,michelesr/coding-events | ---
+++
@@ -5,7 +5,7 @@
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'country', )
-
+ search_fields = ['user__email', 'user__username', 'user__first_name', 'user__last_name']
class EventAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)} |
eb313bcced5a71f80cff8b3314d3346a151297a9 | flickr_api/__init__.py | flickr_api/__init__.py | """
Object Oriented implementation of Flickr API.
Important notes:
- For consistency, the nameing of methods might differ from the name
in the official API. Please check the method "docstring" to know
what is the implemented method.
- For methods which expect an object "id", eith... | """
Object Oriented implementation of Flickr API.
Important notes:
- For consistency, the nameing of methods might differ from the name
in the official API. Please check the method "docstring" to know
what is the implemented method.
- For methods which expect an object "id", eith... | Put some import clauses into try/except blocks to be able to use flickr_api.tools when the list of methods is not up to date | Put some import clauses into try/except blocks to be able to use flickr_api.tools when the list of methods is not up to date
| Python | bsd-3-clause | alexis-mignon/python-flickr-api,alexis-mignon/python-flickr-api,bryndin/tornado-flickr-api | ---
+++
@@ -20,13 +20,16 @@
Date : 05/08/2011
"""
-
-from objects import *
-import objects
+try:
+ from objects import *
+ import objects
+ import upload as Upload
+ from upload import upload,replace
+except Exception, e:
+ print "Could not all modules"
+ print type(e), e
+
from a... |
c1c2503933243fe51bb14f7d63222f958178d7e7 | tfx/components/transform/executor_v2_test.py | tfx/components/transform/executor_v2_test.py | # Lint as: python3
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | # Lint as: python3
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | Remove version check now that TFX 0.25 is released. | Remove version check now that TFX 0.25 is released.
PiperOrigin-RevId: 343533114
| Python | apache-2.0 | tensorflow/tfx,tensorflow/tfx | ---
+++
@@ -19,7 +19,6 @@
import os
import tensorflow as tf
-import tensorflow_transform as tft
from tfx.components.transform import executor_test
@@ -35,6 +34,4 @@
if __name__ == '__main__':
- # TODO(b/168641322): remove once TFT post-0.25.0 released and depended on.
- if tft.__version__ > '0.25.0' a... |
eab299ce4bd3fa4734b8a3adbc805c3f5863bfc5 | fastpt/v2/util.py | fastpt/v2/util.py | import sys
from threading import local
def debug():
def pm(etype, value, tb): # pragma no cover
import pdb, traceback
try:
from IPython.ipapi import make_session; make_session()
from IPython.Debugger import Pdb
sys.stderr.write('Entering post-mortem IPDB shell\n'... | import sys
from threading import local
def debug():# pragma no cover
def pm(etype, value, tb):
import pdb, traceback
try:
from IPython.ipapi import make_session; make_session()
from IPython.Debugger import Pdb
sys.stderr.write('Entering post-mortem IPDB shell\n'... | Remove more obsolete code in v2 | Remove more obsolete code in v2
| Python | mit | moreati/kajiki,ollyc/kajiki,ollyc/kajiki,moreati/kajiki,moreati/kajiki,ollyc/kajiki | ---
+++
@@ -1,8 +1,8 @@
import sys
from threading import local
-def debug():
- def pm(etype, value, tb): # pragma no cover
+def debug():# pragma no cover
+ def pm(etype, value, tb):
import pdb, traceback
try:
from IPython.ipapi import make_session; make_session()
@@ -48,18 +4... |
1eb6f65e40fccb3cea4b35374e7ddc25dd574dfa | examples/test/test_scratchnet.py | examples/test/test_scratchnet.py | #!/usr/bin/env python
"""
Test for scratchnet.py
"""
import unittest
import pexpect
class testScratchNet( unittest.TestCase ):
opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ]
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn... | #!/usr/bin/env python
"""
Test for scratchnet.py
"""
import unittest
import pexpect
class testScratchNet( unittest.TestCase ):
opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ]
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn... | Increase scratchnet timeout to see if it's just slow. | Increase scratchnet timeout to see if it's just slow.
| Python | bsd-3-clause | mininet/mininet,mininet/mininet,mininet/mininet | ---
+++
@@ -14,7 +14,7 @@
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn( 'python -m %s' % name )
- index = p.expect( self.opts )
+ index = p.expect( self.opts, timeout=120 )
self.assertEqual( index, 0 )
def testPingKernel(... |
47c5bb272040f47bc20cde647f76b9a8e673698c | Bindings/Python/tests/test_component_interface.py | Bindings/Python/tests/test_component_interface.py | import os
import unittest
import opensim as osim
test_dir = os.path.join(os.path.dirname(os.path.abspath(osim.__file__)),
'tests')
# Silence warning messages if mesh (.vtp) files cannot be found.
osim.Model.setDebugLevel(0)
class TestComponentInterface(unittest.TestCase):
def test_printC... | import os
import unittest
import opensim as osim
test_dir = os.path.join(os.path.dirname(os.path.abspath(osim.__file__)),
'tests')
# Silence warning messages if mesh (.vtp) files cannot be found.
osim.Model.setDebugLevel(0)
class TestComponentInterface(unittest.TestCase):
def test_printC... | Add the ModelComponentSets to the number of subcomponents. | Add the ModelComponentSets to the number of subcomponents.
| Python | apache-2.0 | opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core | ---
+++
@@ -14,7 +14,7 @@
model = osim.Model(os.path.join(test_dir,
"gait10dof18musc_subject01.osim"))
num_matches = model.printComponentsMatching("_r")
- self.assertEquals(num_matches, 126)
+ self.assertEquals(num_matches, 144)
def test_attachGeometry_memory_manageme... |
c6e16cf939e74640fc8aec3475bf917214ee8ee6 | copyrightme.py | copyrightme.py | import sublime, sublime_plugin
class CopyrightmeCommand(sublime_plugin.TextCommand):
def run(self, edit, text):
region = self.view.visible_region()
if text not in self.view.substr(region):
self.view.split_by_newlines(region)
self.view.insert(edit, 0, text + '\n\n')
| import sublime, sublime_plugin
class CopyrightmeCommand(sublime_plugin.TextCommand):
def run(self, edit, text):
region = self.view.visible_region()
if text not in self.view.substr(region):
self.view.insert(edit, 0, text + '\n\n')
| Remove line splitting in view | Remove line splitting in view | Python | mit | tatarin0/CopyrightMe,tatarin0/CopyrightMe | ---
+++
@@ -5,6 +5,5 @@
region = self.view.visible_region()
if text not in self.view.substr(region):
- self.view.split_by_newlines(region)
self.view.insert(edit, 0, text + '\n\n')
|
1a242dc184adf4a3917b6c82742a667399c16ae9 | respite/middleware.py | respite/middleware.py | from django.http import QueryDict
class HttpMethodOverrideMiddleware:
"""
Facilitate for overriding the HTTP method with the X-HTTP-Method-Override
header or a '_method' HTTP POST parameter.
"""
def process_request(self, request):
if request.META.has_key('HTTP_X_HTTP_METHOD_OVERRIDE') \
... | import re
from django.http import QueryDict
class HttpMethodOverrideMiddleware:
"""
Facilitate for overriding the HTTP method with the X-HTTP-Method-Override
header or a '_method' HTTP POST parameter.
"""
def process_request(self, request):
if request.META.has_key('HTTP_X_HTTP_METHOD_OVER... | Discard the '_method' parameter on HTTP POST | Discard the '_method' parameter on HTTP POST
| Python | mit | jgorset/django-respite,jgorset/django-respite,jgorset/django-respite | ---
+++
@@ -1,3 +1,5 @@
+import re
+
from django.http import QueryDict
class HttpMethodOverrideMiddleware:
@@ -13,6 +15,9 @@
request.META.get('HTTP_X_HTTP_METHOD_OVERRIDE') or
request.POST.get('_method')
).upper()
+
+ if '_method' in request.POST:
... |
04e243aafbd08008556d83d73fbbf22e5398aab4 | telostats/stations/models.py | telostats/stations/models.py | from django.db import models
from django.utils import timezone
class Station(models.Model):
id = models.IntegerField(unique=True, primary_key=True)
name = models.CharField(u'name', max_length=100)
longitude = models.FloatField(u'longitude')
latitude = models.FloatField(u'latitude')
class Status(mode... | from django.db import models
from django.utils import timezone
class Station(models.Model):
id = models.IntegerField(unique=True, primary_key=True)
name = models.CharField(u'name', max_length=100)
longitude = models.FloatField(u'longitude')
latitude = models.FloatField(u'latitude')
def __unicode_... | Add unicode methods to Station/Status | Add unicode methods to Station/Status
| Python | bsd-3-clause | idan/telostats,idan/telostats,idan/telostats | ---
+++
@@ -8,6 +8,9 @@
longitude = models.FloatField(u'longitude')
latitude = models.FloatField(u'latitude')
+ def __unicode__(self):
+ return self.name
+
class Status(models.Model):
station = models.ForeignKey(Station)
@@ -15,3 +18,9 @@
actual_timestamp = models.DateTimeField(defa... |
bd0310663a4f646873119e6b01afe585d0ef40bb | lib/interpreters/ScssInterpreter.py | lib/interpreters/ScssInterpreter.py | import re
from os import path
from ..interpreter import *
from ..SIMode import SIMode
from ..utils import endswith
class ScssInterpreter(Interpreter):
def run(self):
self.settings = {
"extensions": [".scss"],
"remove_extensions": [".scss"],
"extra_extensions": [".jpg", ".png", ".gif", ".svg"],
... | import re
from os import path
from ..interpreter import *
from ..SIMode import SIMode
from ..utils import endswith
class ScssInterpreter(Interpreter):
def run(self):
self.settings = {
"extensions": [".scss"],
"remove_extensions": [".scss"],
"extra_extensions": [".jpg", ".png", ".gif", ".svg"],
... | Add single-quotes setting to scss | Add single-quotes setting to scss
| Python | mit | vinpac/sublime-simple-import,vini175pa/sublime-simple-import,vini175pa/sublime-simple-import,vini175pa/simple-import-js,vini175pa/simple-import-js | ---
+++
@@ -33,6 +33,9 @@
if handler_name == "file":
return "url({0})".format(statements["module"])
+ if self.getSetting("single-quotes"):
+ return "@import \'{0}\';".format(statements["module"])
+
return "@import \"{0}\";".format(statements["module"])
def getQueryObject(self, interpre... |
9219a70106ce3008e5d4a394bb0d8507d474405b | pylib/mapit/areas/management/commands/utils.py | pylib/mapit/areas/management/commands/utils.py | import sys
def save_polygons(lookup):
for shape in lookup.values():
m, poly = shape
if not poly:
continue
sys.stdout.write(".")
sys.stdout.flush()
#g = OGRGeometry(OGRGeomType('MultiPolygon'))
m.polygons.all().delete()
for p in poly:
p... | import sys
def save_polygons(lookup):
for shape in lookup.values():
m, poly = shape
if not poly:
continue
sys.stdout.write(".")
sys.stdout.flush()
#g = OGRGeometry(OGRGeomType('MultiPolygon'))
m.polygons.all().delete()
for p in poly:
p... | Work around KML -> Django import bug. | Work around KML -> Django import bug.
| Python | agpl-3.0 | chris48s/mapit,chris48s/mapit,opencorato/mapit,chris48s/mapit,opencorato/mapit,New-Bamboo/mapit,Code4SA/mapit,opencorato/mapit,Sinar/mapit,Sinar/mapit,Code4SA/mapit,Code4SA/mapit,New-Bamboo/mapit | ---
+++
@@ -16,7 +16,17 @@
else:
shapes = p
for g in shapes:
- m.polygons.create(polygon=g.wkt)
+ # XXX Using g.wkt directly when importing Norway KML works fine
+ # with Django 1.1, Postgres 8.3, PostGIS 1.3.3 but fails with
+ ... |
f3ae9106bf738fc3e86609fbf4d7ed26d4c76354 | bookmarks/database.py | bookmarks/database.py | from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from bookmarks import app
DATABASE_URL = 'postgresql://{}:{}@{}/{}'.format(
app.config['DATABASE_USERNAME'],
app.config['DATABASE_PASSWORD'],
app.config['DATA... | from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from bookmarks import app
engine = create_engine(app.config['DATABASE_URI'], convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
... | Use a DATABASE_URI config for db reference | Use a DATABASE_URI config for db reference
| Python | apache-2.0 | byanofsky/bookmarks,byanofsky/bookmarks,byanofsky/bookmarks | ---
+++
@@ -3,14 +3,7 @@
from sqlalchemy.ext.declarative import declarative_base
from bookmarks import app
-DATABASE_URL = 'postgresql://{}:{}@{}/{}'.format(
- app.config['DATABASE_USERNAME'],
- app.config['DATABASE_PASSWORD'],
- app.config['DATABASE_HOST'],
- app.config['DATABASE_NAME']
-)
-
-engine ... |
62622d78c5cd45fbbe04497de856ff5424051678 | tensorflow/models/rnn/__init__.py | tensorflow/models/rnn/__init__.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Fix doc string weirdness introduced by script | Fix doc string weirdness introduced by script
The doc string is still pretty confusing, but this is what it was before I
messed it up with my script.
Change: 114470999
| Python | apache-2.0 | sandeepdsouza93/TensorFlow-15712,alsrgv/tensorflow,annarev/tensorflow,EvenStrangest/tensorflow,chemelnucfin/tensorflow,SnakeJenny/TensorFlow,Carmezim/tensorflow,admcrae/tensorflow,cxxgtxy/tensorflow,anilmuthineni/tensorflow,benoitsteiner/tensorflow-xsmm,ppwwyyxx/tensorflow,calebfoss/tensorflow,MostafaGazar/tensorflow,h... | ---
+++
@@ -13,18 +13,11 @@
# limitations under the License.
# ==============================================================================
-"""Libraries to build Recurrent Neural Networks.
-
-This file helps simplify the import process:
-
+"""Libraries to build Recurrent Neural Networks."""
from __future__ im... |
de2ea6f02af98902bf50afbef25f51760715fc4a | ci/generate_pipeline_yml.py | ci/generate_pipeline_yml.py | #!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['2_0', '2_1', '2_2']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Template(... | #!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['2_0', '2_1', '2_2', '2_3']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Te... | Add PCF 2.3 to CI pipeline. | Add PCF 2.3 to CI pipeline.
| Python | apache-2.0 | cf-platform-eng/tile-generator,cf-platform-eng/tile-generator,cf-platform-eng/tile-generator,cf-platform-eng/tile-generator | ---
+++
@@ -3,7 +3,7 @@
import os
from jinja2 import Template
-clusters = ['2_0', '2_1', '2_2']
+clusters = ['2_0', '2_1', '2_2', '2_3']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
|
1b0fdfdc2ff49d6dfc7d239b5a9cda1ff334f20b | candidates/cache.py | candidates/cache.py | from django.core.cache import cache
def post_cache_key(mapit_area_id):
"""Form the cache key used for post data"""
return "post:{0}".format(mapit_area_id)
def invalidate_posts(post_ids):
for post_id in post_ids:
post_key = post_cache_key(post_id)
cache.delete(post_key)
def get_post_cached... | from django.core.cache import cache
def post_cache_key(mapit_area_id):
"""Form the cache key used for post data"""
return "post:{0}".format(mapit_area_id)
def person_cache_key(person_id):
"""Form the cache key used for person data"""
return "person:{0}".format(person_id)
def invalidate_posts(post_ids... | Add functions for caching person data from PopIt | Add functions for caching person data from PopIt
| Python | agpl-3.0 | mysociety/yournextrepresentative,openstate/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,openstate/yournextrepresentative,mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,Yo... | ---
+++
@@ -4,10 +4,18 @@
"""Form the cache key used for post data"""
return "post:{0}".format(mapit_area_id)
+def person_cache_key(person_id):
+ """Form the cache key used for person data"""
+ return "person:{0}".format(person_id)
+
def invalidate_posts(post_ids):
- for post_id in post_ids:
- ... |
5831fe52a4b8296bd4f0c71e5e98369d704b8fc3 | painter/urls.py | painter/urls.py | from django.conf.urls import url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
urlpatterns = [
url(r'^noreload$', views.CardDisplay.as_view(), name='card_display_noreload'),
url(r'^$', views.CardDisplayReload.as_view(), name='card_display'),
]
urlpatterns += staticf... | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^noreload$', views.CardDisplay.as_view(), name='card_display_noreload'),
url(r'^$', views.CardDisplayReload.as_view(), name='card_display'),
]
| Remove the staticfiles from the painter app URLconf. | Remove the staticfiles from the painter app URLconf.
| Python | mit | adam-thomas/imperial-painter,adam-thomas/imperial-painter,adam-incuna/imperial-painter,adam-incuna/imperial-painter | ---
+++
@@ -1,5 +1,4 @@
from django.conf.urls import url
-from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
@@ -8,5 +7,3 @@
url(r'^noreload$', views.CardDisplay.as_view(), name='card_display_noreload'),
url(r'^$', views.CardDisplayReload.as_view(), name='card_disp... |
4971f5cd840d17df237fc09dbd11cb8e265bc6e8 | quickphotos/utils.py | quickphotos/utils.py | from django.utils.timezone import make_aware, utc
from .models import Photo
def update_photos(photos):
for i in photos:
image = i.images['standard_resolution']
obj, created = Photo.objects.update_or_create(photo_id=i.id, defaults={
'user': i.user.username,
'image': image.... | from django.utils.timezone import make_aware, utc
from .models import Photo
def update_photos(photos):
obj_list = []
for i in photos:
image = i.images['standard_resolution']
obj, created = Photo.objects.update_or_create(photo_id=i.id, defaults={
'user': i.user.username,
... | Return a list of all photo objects which have been updated | Return a list of all photo objects which have been updated
| Python | bsd-3-clause | blancltd/django-quick-photos,kmlebedev/mezzanine-instagram-quickphotos | ---
+++
@@ -4,6 +4,8 @@
def update_photos(photos):
+ obj_list = []
+
for i in photos:
image = i.images['standard_resolution']
@@ -16,3 +18,7 @@
'caption': i.caption or '',
'link': i.link,
})
+
+ obj_list.append(obj)
+
+ return obj_list |
fb8fa7fedd18d751aeb7c060786377c96a8b2319 | characters/tests.py | characters/tests.py | from django.test import TestCase
from .models import Character, Team
class TeamGetAbsoluteUrl(TestCase):
def test_slug_appears_in_url(self):
slug_value = "slug-value"
team = Team()
team.slug = "dont-care"
sut = Character()
sut.slug = slug_value
sut.team = team
... | from django.test import TestCase
from .models import Character, Team
class CharacterGetAbsoluteUrl(TestCase):
def test_slug_appears_in_url(self):
slug_value = "slug-value"
team = Team()
team.slug = "dont-care"
sut = Character()
sut.slug = slug_value
sut.team = t... | Fix name - it is testing Character, not Team | Fix name - it is testing Character, not Team
| Python | mit | evanepio/dotmanca,evanepio/dotmanca,evanepio/dotmanca | ---
+++
@@ -3,7 +3,7 @@
from .models import Character, Team
-class TeamGetAbsoluteUrl(TestCase):
+class CharacterGetAbsoluteUrl(TestCase):
def test_slug_appears_in_url(self):
slug_value = "slug-value"
|
47162e68dd7662efd8f1c2463d11dc9228726523 | solar/dblayer/standalone_session_wrapper.py | solar/dblayer/standalone_session_wrapper.py | # Copyright 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | # Copyright 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | Fix session in CLI on Debian systems | Fix session in CLI on Debian systems
Change-Id: I4b1a3e45417a8d8442e097d440ebee8a09a8aaa2
| Python | apache-2.0 | openstack/solar,pigmej/solar,openstack/solar,openstack/solar,pigmej/solar,pigmej/solar | ---
+++
@@ -23,7 +23,7 @@
def create_all():
import sys
- if not sys.executable.endswith(('python', )):
+ if sys.executable.split('/')[-1] not in ['python', 'python2']:
# auto add session to only standalone python runs
return
|
fd599497011fcb94d8b5c29dc696128eafb9d603 | tests/app/test_create_app.py | tests/app/test_create_app.py | """Verifies that instance_links are being retrieved properly from LINKS. Verifies that app_data.json.j2
contains the instance link information"""
from unittest import mock
from foremast.plugin_manager import PluginManager
MANAGER = PluginManager('app', 'aws')
PLUGIN = MANAGER.load()
@mock.patch('foremast.app.aws.ba... | """Verifies that instance_links are being retrieved properly from LINKS. Verifies that app_data.json.j2
contains the instance link information"""
from unittest import mock
from foremast.plugin_manager import PluginManager
MANAGER = PluginManager('app', 'aws')
PLUGIN = MANAGER.load()
@mock.patch('foremast.app.aws.ba... | Check handling duplicate key for instance links | test: Check handling duplicate key for instance links
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast | ---
+++
@@ -24,3 +24,18 @@
instance_links = spinnaker_app.retrieve_instance_links()
assert instance_links == combined, "Instance Links are not being retrieved properly"
+
+
+@mock.patch('foremast.app.aws.base.LINKS', new={'example': 'example1', 'example': 'example2'})
+def test_duplicate_instance_links():... |
3f5867695e5b980e05f1516f2bcbd246cdc3241f | install_deps.py | install_deps.py | #!/usr/bin/env python
"""
Install the packages you have listed in the requirements file you input as
first argument.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
import fileinput
import subprocess
from pip.req import parse_requirements
... | #!/usr/bin/env python
"""
Install the packages you have listed in the requirements file you input as
first argument.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
import fileinput
import subprocess
from pip.req import parse_requirements
i... | Fix parse_requirements call for new pip version. | Fix parse_requirements call for new pip version.
| Python | bsd-3-clause | Neurita/boyle | ---
+++
@@ -12,6 +12,7 @@
import fileinput
import subprocess
from pip.req import parse_requirements
+import uuid
def get_requirements(*args):
@@ -20,7 +21,7 @@
install_deps = []
try:
for fpath in args:
- install_deps.extend([str(d.req) for d in parse_requirements(fpath)])
+ ... |
f1eae848aa48ef3891407f400410827d59d7c880 | pyservice/__init__.py | pyservice/__init__.py | """
Copyright (c) 2014, Joseph Cross.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute,... | """
Copyright (c) 2014, Joseph Cross.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute,... | Make Client, Service importable from pyservice | Make Client, Service importable from pyservice
| Python | mit | numberoverzero/pyservice | ---
+++
@@ -20,3 +20,8 @@
THE SOFTWARE.
"""
+
+from pyservice.client import Client
+from pyservice.service import Service
+
+__all__ = ["Client", "Service"] |
74d4868a0e43e5eb089d6d7a0a07545b7f829806 | main.py | main.py | from common.bounty import *
from common.peers import *
from common import settings
from time import sleep
from common.safeprint import safeprint
def main():
settings.setup()
try:
import miniupnpc
except:
settings.config['outbound'] = True
safeprint("settings are:")
safeprint(setting... | from common.bounty import *
from common.peers import *
from common import settings
from time import sleep
from common.safeprint import safeprint
def main():
settings.setup()
try:
import miniupnpc
except:
settings.config['outbound'] = True
safeprint("settings are:")
safeprint(setting... | Add delay after listener start (for testing) | Add delay after listener start (for testing) [skip ci] | Python | mit | gappleto97/Senior-Project | ---
+++
@@ -15,6 +15,7 @@
ear = listener(settings.config['port'],settings.config['outbound'])
ear.daemon = True
ear.start()
+ sleep(1)
initializePeerConnections()
if __name__ == "__main__": |
c72500abaeb1149d35fd6fcb28cb6a321b998045 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup
requirements = [
'boto3',
'pandas<0.20',
'psycopg2',
]
test_requirements = [
'pytest',
]
setup(
name='demae',
version='0.8.0',
description="",
author="Kazato Sugimoto",
author_email='kazato.sugimoto@gmail.com',
url='https://g... | #!/usr/bin/env python
from setuptools import setup
requirements = [
'boto3',
'pandas<0.20',
'psycopg2',
]
test_requirements = [
'pytest',
]
setup(
name='demae',
version='0.8.0',
description="",
author="Kazato Sugimoto",
author_email='kazato.sugimoto@gmail.com',
url='https://g... | Add source and dest to packages | Add source and dest to packages
| Python | mit | uiureo/demae | ---
+++
@@ -21,6 +21,8 @@
url='https://github.com/uiureo/demae',
packages=[
'demae',
+ 'demae.source',
+ 'demae.dest',
],
package_dir={'demae':
'demae'}, |
8465394884eea4fd6fa0eb9e45f9ec91bec57cb9 | setup.py | setup.py | import os
from setuptools import setup, find_packages
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
name='sumproduct',
version='0.0.1',
description='The sum-product algorithm. Belief propag... | import os
from setuptools import setup, find_packages
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
name='sumproduct',
version='0.0.1',
description='The sum-product algorithm. Belief propag... | Add some topics for next deploy | Add some topics for next deploy
| Python | mit | ilyakava/sumproduct | ---
+++
@@ -25,6 +25,9 @@
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
+ 'Intended Audience :: Science/Research',
+ 'Topic :: Scientific/Engineering :: Artificial Intelligence',
+ 'Topic :: Scientific/E... |
44b311eade20016f613311a98d666b2463826ad1 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
... | from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
... | Update requests requirement from <2.21,>=2.4.2 to >=2.4.2,<2.22 | Update requests requirement from <2.21,>=2.4.2 to >=2.4.2,<2.22
Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version.
- [Release notes](https://github.com/requests/requests/releases)
- [Changelog](https://github.com/requests/requests/blob/master/HISTORY.md)
- [Commi... | Python | apache-2.0 | zooniverse/panoptes-python-client | ---
+++
@@ -9,7 +9,7 @@
packages=find_packages(),
include_package_data=True,
install_requires=[
- 'requests>=2.4.2,<2.21',
+ 'requests>=2.4.2,<2.22',
'future>=0.16,<0.18',
'python-magic>=0.4,<0.5',
'redo>=1.7', |
34452461de40c35d28bfc8b2a18b6fa14ebb875d | onadata/apps/fsforms/management/commands/update_mongo_value_type.py | onadata/apps/fsforms/management/commands/update_mongo_value_type.py | from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Update value type of fs_site and fs_uuid in mongo instances to make string type to int type"
def handle(self, *args, **kwargs):
xform_instances = settings.MONGO_DB.instances
... | from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Update value type of fs_site and fs_uuid in mongo instances to make string type to int type"
def handle(self, *args, **kwargs):
xform_instances = settings.MONGO_DB.instances
... | Handle cases update mongo value type | Handle cases update mongo value type
| Python | bsd-2-clause | awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat | ---
+++
@@ -23,6 +23,8 @@
new_fs_uuid = None
elif fs_uuid == 'None':
new_fs_uuid = None
+ elif fs_uuid == 'NoneType':
+ new_fs_uuid = None
else:
new_fs_uuid = int(fs_uuid)
xform_instances.update({'_id':... |
c6b51b82fa0503a2696161374160c47297211c7c | qubs_data_api/urls.py | qubs_data_api/urls.py | from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^climate/', include('climate.urls')),
url(r'^herbarium/', include('herbarium.urls')),
url(r'^api-auth/', include('rest_framework.urls')),
url(r'^admin/', admin.site.urls),
]
| from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^', include('core.urls')),
url(r'^climate/', include('climate.urls')),
url(r'^herbarium/', include('herbarium.urls')),
url(r'^api-auth/', include('rest_framework.urls')),
url(r'^admin/', admin.site.urls... | Include Core URLS at the base URL path. | Include Core URLS at the base URL path.
| Python | apache-2.0 | qubs/data-centre,qubs/data-centre,qubs/climate-data-api,qubs/climate-data-api | ---
+++
@@ -2,6 +2,7 @@
from django.contrib import admin
urlpatterns = [
+ url(r'^', include('core.urls')),
url(r'^climate/', include('climate.urls')),
url(r'^herbarium/', include('herbarium.urls')),
url(r'^api-auth/', include('rest_framework.urls')), |
102a35d9ce74a4f29be2fc0bb34b80cb7ee4d77d | tests/helper_methods_test.py | tests/helper_methods_test.py | import os
import unittest
from config import Config
class HelperMethodsTest(unittest.TestCase):
def test_that_config_week_is_only_A_or_B(self):
"""
This test ensures that the only value set for 'WEEK'
in the envvars is A or B.
"""
config = Config()
if os.path.exis... | import os
import unittest
from config import Config
class HelperMethodsTest(unittest.TestCase):
def test_that_config_week_is_only_A_or_B(self):
"""
This test ensures that the only value set for 'WEEK'
in the envvars is A or B.
"""
config = Config()
week_options = [... | Update tests for config week | Update tests for config week
| Python | mit | andela-kanyanwu/food-bot-review | ---
+++
@@ -11,12 +11,11 @@
in the envvars is A or B.
"""
config = Config()
+ week_options = ['A', 'B']
if os.path.exists('./rtmbot.conf'):
config.load_yaml('rtmbot.conf')
-
+ self.assertIn(config['WEEK'], week_options)
else:
c... |
126d79011221da6692d70f9a9aba1f335155ab58 | us_ignite/apps/management/commands/app_load_fixtures.py | us_ignite/apps/management/commands/app_load_fixtures.py | from django.core.management.base import BaseCommand
from us_ignite.apps.models import Feature, Domain
FEATURE_LIST = (
'SDN',
'OpenFlow',
'Ultra fast',
'Speed',
'Low-latency',
'Local cloud / edge computing',
)
DOMAIN_LIST = (
'Healthcare',
'Education & Workforce',
'Energy',
'... | from django.core.management.base import BaseCommand
from us_ignite.apps.models import Feature, Domain
FEATURE_LIST = (
'SDN',
'OpenFlow',
'Ultra fast',
'Speed',
'Low-latency',
'Local cloud / edge computing',
'Advanced wireless',
'Ultra-fast/Gigabit to end-user',
'GENI/US Ignite Ra... | Update app domain initial fixtures. | Update app domain initial fixtures.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite | ---
+++
@@ -10,6 +10,10 @@
'Speed',
'Low-latency',
'Local cloud / edge computing',
+ 'Advanced wireless',
+ 'Ultra-fast/Gigabit to end-user',
+ 'GENI/US Ignite Rack',
+ 'Layer 2',
)
DOMAIN_LIST = (
@@ -17,7 +21,6 @@
'Education & Workforce',
'Energy',
'Transportation',
- ... |
0bd76b828fbd81ac85b7384174692e46e8ef3205 | devlol/urls.py | devlol/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'devlol.views.index'),
# Static Stuff
url(r'^location/$', 'devlol.views.location'),
url(r'^mail/$', 'devlol.views.mail'),
# Diary Stuff
url(r'^diary/$', ... | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'devlol.views.index'),
# Static Stuff
url(r'^location/$', 'devlol.views.location'),
url(r'^mail/$', 'devlol.views.mail'),
# Diary Stuff
url(r'^diary/$', ... | Fix rout for diary/event, argument has to be item_id | Fix rout for diary/event, argument has to be item_id
For error see here: http://devlol.at/diary/event/22/ as an example | Python | mit | DevLoL/devlol.at,DevLoL/devlol.at,DevLoL/devlol.at,DevLoL/devlol.at | ---
+++
@@ -10,7 +10,7 @@
# Diary Stuff
url(r'^diary/$', 'devlol.views.index'),
- url(r'^diary/event/(?P<event_id>[0-9]+)/$', 'diary.views.item'),
+ url(r'^diary/event/(?P<item_id>[0-9]+)/$', 'diary.views.item'),
# API Stuff
url(r'^api/events$', 'devlol.views.e... |
6e4e073b4979bbf6099d0054181f13134f8cfe73 | stash_test_case.py | stash_test_case.py | import os
import shutil
import unittest
from stash import Stash
class StashTestCase(unittest.TestCase):
"""Base class for test cases that test stash functionality.
This base class makes sure that all unit tests are executed in a sandbox
environment.
"""
PATCHES_PATH = os.path.join('test', '.patc... | import os
import shutil
import unittest
from stash import Stash
class StashTestCase(unittest.TestCase):
"""Base class for test cases that test stash functionality.
This base class makes sure that all unit tests are executed in a sandbox
environment.
"""
PATCHES_PATH = os.path.join('test', '.patc... | Remove patches in between unit tests. | Remove patches in between unit tests.
| Python | bsd-3-clause | ton/stash,ton/stash | ---
+++
@@ -36,3 +36,8 @@
# Clean up the temporary repository.
if os.path.exists(cls.REPOSITORY_URI):
shutil.rmtree(cls.REPOSITORY_URI)
+
+ def tearDown(self):
+ """Removes all stashed patches."""
+ for patch_name in os.listdir(self.PATCHES_PATH):
+ os.unlink... |
7535e8020b2d29abbe45e724f5ff4f51613d95d0 | survey/__init__.py | survey/__init__.py | import logging
LOGGER = logging.getLogger(__name__)
DEFAULT_SETTINGS = [
"CHOICES_SEPARATOR",
"USER_DID_NOT_ANSWER",
"TEX_CONFIGURATION_FILE",
"SURVEY_DEFAULT_PIE_COLOR",
"EXCEL_COMPATIBLE_CSV",
]
def set_default_settings():
try:
from django.conf import settings
from . import... | import logging
LOGGER = logging.getLogger(__name__)
DEFAULT_SETTINGS = [
"CHOICES_SEPARATOR",
"USER_DID_NOT_ANSWER",
"TEX_CONFIGURATION_FILE",
"SURVEY_DEFAULT_PIE_COLOR",
"EXCEL_COMPATIBLE_CSV",
]
def set_default_settings():
try:
from django.conf import settings
from . import... | Fix Use % formatting in logging functions | Fix Use % formatting in logging functions
| Python | agpl-3.0 | Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey | ---
+++
@@ -20,7 +20,7 @@
if setting in DEFAULT_SETTINGS:
if not hasattr(settings, setting):
setattr(settings, setting, getattr(app_settings, setting))
- LOGGER.info("Settings '{}' as the default ('{}')".format(setting, getattr(settings, setting)))
+ ... |
d4de0c4fdf205c1107b08ccba0b428125d81de1a | src/biokbase/narrative/common/url_config.py | src/biokbase/narrative/common/url_config.py | import os
import json
class Struct:
def __init__(self, **args):
self.__dict__.update(args)
def get_url(self, key):
self._dict__.get(key)
try:
nar_path = os.environ["NARRATIVEDIR"]
config_json = open(os.path.join(nar_path, "config.json")).read()
config = json.loads(config_json)
... | import os
import json
class Struct:
def __init__(self, **args):
self.__dict__.update(args)
def get_url(self, key):
self.__dict__.get(key)
try:
nar_path = os.environ["NARRATIVEDIR"]
config_json = open(os.path.join(nar_path, "config.json")).read()
config = json.loads(config_json)
... | Fix bug in new url config method | Fix bug in new url config method | Python | mit | msneddon/narrative,psnovichkov/narrative,aekazakov/narrative,msneddon/narrative,psnovichkov/narrative,psnovichkov/narrative,jmchandonia/narrative,briehl/narrative,rsutormin/narrative,aekazakov/narrative,psnovichkov/narrative,psnovichkov/narrative,briehl/narrative,nlharris/narrative,msneddon/narrative,scanon/narrative,j... | ---
+++
@@ -7,7 +7,7 @@
self.__dict__.update(args)
def get_url(self, key):
- self._dict__.get(key)
+ self.__dict__.get(key)
try:
nar_path = os.environ["NARRATIVEDIR"] |
7c9b0ac281d39cbe8b694a4cb7a4dd0c171351e0 | custom/uth/tasks.py | custom/uth/tasks.py | from custom.uth.utils import create_case, match_case, attach_images_to_case
from custom.uth.models import SonositeUpload, VscanUpload
from celery.task import task
@task
def async_create_case(upload_id):
upload_doc = SonositeUpload.get(upload_id)
files = {}
for f in upload_doc._attachments.keys():
... | from custom.uth.utils import create_case, match_case, attach_images_to_case
from custom.uth.models import SonositeUpload, VscanUpload
from celery.task import task
import io
@task
def async_create_case(upload_id):
upload_doc = SonositeUpload.get(upload_id)
files = {}
for f in upload_doc._attachments.keys(... | Fix file type for post submissions | Fix file type for post submissions
| Python | bsd-3-clause | qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,SEL-Columbia/commcare-hq,puttarajubr/commcare-hq,q... | ---
+++
@@ -1,6 +1,7 @@
from custom.uth.utils import create_case, match_case, attach_images_to_case
from custom.uth.models import SonositeUpload, VscanUpload
from celery.task import task
+import io
@task
@@ -9,7 +10,7 @@
files = {}
for f in upload_doc._attachments.keys():
- files[f] = uploa... |
7902711589cf3ce0fe492442dbfec2497fd06dc4 | build-aux/dist-docs.py | build-aux/dist-docs.py | #!/usr/bin/env python3
import os
import shutil
import subprocess
from pathlib import PurePath
references = [
'docs/json-glib/json-glib-1.0',
]
sourceroot = os.environ.get('MESON_SOURCE_ROOT')
buildroot = os.environ.get('MESON_BUILD_ROOT')
distroot = os.environ.get('MESON_DIST_ROOT')
for reference in reference... | #!/usr/bin/env python3
import os
import shutil
references = [
'doc/json-glib-1.0',
]
sourceroot = os.environ.get('MESON_SOURCE_ROOT')
buildroot = os.environ.get('MESON_BUILD_ROOT')
distroot = os.environ.get('MESON_DIST_ROOT')
for reference in references:
src_path = os.path.join(buildroot, reference)
if... | Fix the docs path in the dist script | build: Fix the docs path in the dist script
Fixes: #66
| Python | lgpl-2.1 | frida/json-glib,GNOME/json-glib,GNOME/json-glib,frida/json-glib | ---
+++
@@ -2,13 +2,10 @@
import os
import shutil
-import subprocess
-
-from pathlib import PurePath
references = [
- 'docs/json-glib/json-glib-1.0',
+ 'doc/json-glib-1.0',
]
sourceroot = os.environ.get('MESON_SOURCE_ROOT') |
ac00ef4ac08c6e47de80c33a6781d00c7b2bc943 | flask_sockets.py | flask_sockets.py | # -*- coding: utf-8 -*-
def log_request(self):
log = self.server.log
if log:
if hasattr(log, 'info'):
log.info(self.format_request() + '\n')
else:
log.write(self.format_request() + '\n')
# Monkeys are made for freedom.
try:
import gevent
from geventwebsocket.gu... | # -*- coding: utf-8 -*-
from functools import wraps
from flask import request
def log_request(self):
log = self.server.log
if log:
if hasattr(log, 'info'):
log.info(self.format_request() + '\n')
else:
log.write(self.format_request() + '\n')
# Monkeys are made for fr... | Use Flask routing to allow for variables in URL | Use Flask routing to allow for variables in URL
| Python | mit | clarkduvall/flask-sockets | ---
+++
@@ -1,4 +1,9 @@
# -*- coding: utf-8 -*-
+
+from functools import wraps
+
+from flask import request
+
def log_request(self):
log = self.server.log
@@ -21,46 +26,25 @@
if hasattr(gevent, 'pywsgi'):
gevent.pywsgi.WSGIHandler.log_request = log_request
-
-
-class SocketMiddleware(object):... |
b77174948721413de84d6037ef4e4329978978cc | taskzilla/views.py | taskzilla/views.py | from django.shortcuts import render
from .models import Task
def index(request):
tasks_list = Task.objects.filter(closed=False)
context = {'tasks_list' : tasks_list,}
return render(request, 'taskzilla/index.html', context)
def task_page(request, task_id):
task = Task.objects.get(pk=task_id)
context = {'task' :... | from django.shortcuts import render
from .models import Task
def index(request):
tasks_list = Task.objects.filter(closed=False)
context = {'tasks_list' : tasks_list,}
return render(request, 'taskzilla/index.html', context)
def task_page(request, task_id):
task = Task.objects.get(pk=task_id)
context = {'task' :... | Add comments to the Task Page | Views: Add comments to the Task Page
| Python | mit | static-code-generators/taskzilla,jailuthra/taskzilla,jailuthra/taskzilla,static-code-generators/taskzilla,static-code-generators/taskzilla,jailuthra/taskzilla | ---
+++
@@ -9,5 +9,5 @@
def task_page(request, task_id):
task = Task.objects.get(pk=task_id)
- context = {'task' : task}
+ context = {'task' : task, 'comments': task.comment_set.all()}
return render(request, 'taskzilla/task_page.html', context) |
1f13b7734b06e3c9572865734defa0b1afd4db8b | jobs_executor.py | jobs_executor.py | import subprocess
import os
import mail_handler
from datetime import datetime
from settings_handler import settings
def execJobs(jobs):
try:
for job in jobs:
if not execJob(job):
return False
print "Jobs executed"
return True
except:
print "Executed failed"
return False
finally:
output = "tmp/out... | import subprocess
import os
import mail_handler
import tempfile
from datetime import datetime
from settings_handler import settings
def execJobs(jobs):
try:
for job in jobs:
if not execJob(job):
return False
print "Jobs executed"
return True
except:
print "Executed failed"
return False
def execJob(... | Use the tempfile module to create system indipendend temporary file for the output. | Use the tempfile module to create system indipendend temporary file for the output.
closes #1
| Python | apache-2.0 | baumartig/paperboy | ---
+++
@@ -1,6 +1,7 @@
import subprocess
import os
import mail_handler
+import tempfile
from datetime import datetime
from settings_handler import settings
@@ -14,24 +15,24 @@
except:
print "Executed failed"
return False
- finally:
- output = "tmp/output.mobi"
- if os.path.isfile(output):
- os.rem... |
7ff11cc0d8183a03bb83430236b12aa70ac2f8dc | lib/allosmod/get_ss.py | lib/allosmod/get_ss.py | """Get secondary structure with DSSP."""
from __future__ import print_function, absolute_import
import optparse
import subprocess
def check_output(args, stderr=None, retcode=0, input=None, *other):
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=stderr,
stdin=subprocess.PIPE if ... | """Get secondary structure with DSSP."""
from __future__ import print_function, absolute_import
import optparse
import subprocess
def check_output(args, stderr=None, retcode=0, input=None, *other):
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=stderr,
stdin=subprocess.PIPE if ... | Return results as a generator, not in a file. | Return results as a generator, not in a file.
| Python | lgpl-2.1 | salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib | ---
+++
@@ -21,7 +21,7 @@
if "RESIDUE AA STRUCTURE" in line:
start = True
elif start and len(line) > 16 and line[11] != ' ':
- print(line[16] if line[16] != ' ' else '-')
+ yield line[16] if line[16] != ' ' else '-'
def parse_args():
usage = """%prog <PDB f... |
b0c7e61178a5eb81dc24aab9911baaeccda546ff | searchapi/__init__.py | searchapi/__init__.py | import os, logging
from flask import Flask
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
app.logger.debug("\nConfiguration\n%s\n" % app.config)
# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
sentry = Sentry(app, dsn=os.environ['SENTR... | import os, logging
from flask import Flask
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
app.logger.debug("\nConfiguration\n%s\n" % app.config)
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
# Sentry exception rep... | Add proxy fix as in lr this will run with reverse proxy | Add proxy fix as in lr this will run with reverse proxy
| Python | mit | LandRegistry/search-api-alpha,LandRegistry/search-api-alpha | ---
+++
@@ -8,6 +8,9 @@
app.logger.debug("\nConfiguration\n%s\n" % app.config)
+from werkzeug.contrib.fixers import ProxyFix
+app.wsgi_app = ProxyFix(app.wsgi_app)
+
# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
sentry = Sentry(app, dsn=os.environ['SENTRY_DSN']) |
d49118a52c15b2434a43a717476cdc7340dfc8c6 | test/test_suite.py | test/test_suite.py |
# list examples
a=['spam','eggs',100,1234]
log(a[:2]+['bacon',2*2])
log(3*a[:3]+['Boo!'])
log(a[:])
a[2]=a[2]+23
log(a)
a[0:2]=[1,12]
log(a)
a[0:2]=[]
log(a)
a[1:1]=['bletch','xyzzy']
log(a)
a[:0]=a
log(a)
a[:]=[]
log(a) |
# list examples
a=['spam','eggs',100,1234]
log(a[:2]+['bacon',2*2])
log(3*a[:3]+['Boo!'])
log(a[:])
a[2]=a[2]+23
log(a)
a[0:2]=[1,12]
log(a)
a[0:2]=[]
log(a)
a[1:1]=['bletch','xyzzy']
log(a)
a[:0]=a
log(a)
a[:]=[]
log(a)
a.extend('ab')
log(a)
a.extend([1,2,33])
log(a)
| Test suite copied from Python tutorial | Test suite copied from Python tutorial | Python | bsd-3-clause | sgzwiz/brython,sgzwiz/brython,sgzwiz/brython | ---
+++
@@ -16,3 +16,7 @@
log(a)
a[:]=[]
log(a)
+a.extend('ab')
+log(a)
+a.extend([1,2,33])
+log(a) |
eec8ddc6beb08a02577831b6f64b0455e5c1ef05 | local.py | local.py | import gntp
import Growl
class GNTPRegister(gntp.GNTPRegister):
def send(self):
print 'Sending Registration'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = self.notifications,
defaultNotifications = self.defaultNotifications,
)
growl.register()
... | import gntp
import Growl
class GNTPRegister(gntp.GNTPRegister):
def send(self):
print 'Sending Local Registration'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = self.notifications,
defaultNotifications = self.defaultNotifications,
)
growl.registe... | Disable icon temporarily and adjust the debug print statements | Disable icon temporarily and adjust the debug print statements | Python | mit | kfdm/gntp | ---
+++
@@ -3,7 +3,7 @@
class GNTPRegister(gntp.GNTPRegister):
def send(self):
- print 'Sending Registration'
+ print 'Sending Local Registration'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = self.notifications,
@@ -13,7 +13,7 @@
class GNT... |
0d3507d5eb9801b38c66fb03804e15b089fb2233 | tests/cdek_test.py | tests/cdek_test.py | # coding: utf-8
from __future__ import unicode_literals, print_function
import datetime
import unittest
import mock
from cdek import api, exceptions
@mock.patch('cdek.api.urlopen')
class CdekApiTest(unittest.TestCase):
def setUp(self):
self.reg_user = api.CdekCalc('123456', '123456')
self.unr... | # coding: utf-8
from __future__ import unicode_literals, print_function
import datetime
import unittest
import mock
from cdek import api, exceptions
@mock.patch('cdek.api.urlopen')
class CdekApiTest(unittest.TestCase):
def setUp(self):
self.reg_user = api.CdekCalc('123456', '123456')
self.unr... | Fix date for generate secure_key | Fix date for generate secure_key
| Python | mit | xtelaur/python-cdek,xtelaur/python-cdek | ---
+++
@@ -19,9 +19,9 @@
def test_valid_get_secure(self, urlopen):
self.assertEqual(self.reg_user._get_secure(
- datetime.datetime.today().date(), self.reg_user.auth_password),
- 'c5750d7c97a89aa33b8e030d4c7a4847')
+ datetime.datetime.strptime('2013-05-30', '%Y-%m-%d'... |
00fd8b13e36c5e7020b7769f6dcd1afecfb79fb3 | examples/source.py | examples/source.py | """Test client that connects and sends infinite data."""
import sys
from tulip import *
def dprint(*args):
print('source:', *args, file=sys.stderr)
class Client(Protocol):
data = b'x'*16*1024
def connection_made(self, tr):
dprint('connecting to', tr.get_extra_info('addr'))
self.tr ... | """Test client that connects and sends infinite data."""
import sys
from tulip import *
def dprint(*args):
print('source:', *args, file=sys.stderr)
class Client(Protocol):
data = b'x'*16*1024
def connection_made(self, tr):
dprint('connecting to', tr.get_extra_info('addr'))
self.tr ... | Fix logic around lost connection. | Fix logic around lost connection.
| Python | apache-2.0 | Martiusweb/asyncio,manipopopo/asyncio,jashandeep-sohi/asyncio,manipopopo/asyncio,ajdavis/asyncio,1st1/asyncio,gvanrossum/asyncio,manipopopo/asyncio,1st1/asyncio,fallen/asyncio,vxgmichel/asyncio,haypo/trollius,gvanrossum/asyncio,vxgmichel/asyncio,fallen/asyncio,ajdavis/asyncio,gsb-eng/asyncio,jashandeep-sohi/asyncio,Mar... | ---
+++
@@ -20,10 +20,12 @@
self.write_some_data()
def write_some_data(self):
+ if self.lost:
+ dprint('lost already')
+ return
dprint('writing', len(self.data), 'bytes')
self.tr.write(self.data)
- if not self.lost:
- self.loop.call_soon... |
991a376736e50ddd6622947d713f61cebb565c8d | server/server/urls.py | server/server/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'server.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'django_inventory.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^django/inventory/$', 'inventory.views.index'),
u... | Add some CRUD URLs to Django. | Add some CRUD URLs to Django.
| Python | agpl-3.0 | TomDataworks/angular-inventory,TomDataworks/angular-inventory | ---
+++
@@ -5,8 +5,12 @@
urlpatterns = patterns('',
# Examples:
- # url(r'^$', 'server.views.home', name='home'),
+ # url(r'^$', 'django_inventory.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
-
- url(r'^admin/', include(admin.site.urls)),
+ url(r'^django/inventory/$', 'i... |
4823b42b23580e0a294c1e4ddb3b5b62abf9c7bc | sf/mmck/parameters.py | sf/mmck/parameters.py | from sf.lib.orderedattrdict import OrderedAttrDict
class Parameters(OrderedAttrDict):
pass
class ParameterValues(OrderedAttrDict):
pass
class Parameter(object):
def __init__(self, default=None, label=None):
self.default = default
self.label = label
class Integer(Parameter):
def... | from collections import OrderedDict
from sf.lib.orderedattrdict import OrderedAttrDict
class Parameters(OrderedAttrDict):
pass
class ParameterValues(OrderedAttrDict):
pass
class Parameter(object):
def __init__(self, default=None, label=None):
self.default = default
self.label = label... | Add a key/value pairs parameter type | Add a key/value pairs parameter type
| Python | mit | metrasynth/solar-flares | ---
+++
@@ -1,3 +1,5 @@
+from collections import OrderedDict
+
from sf.lib.orderedattrdict import OrderedAttrDict
@@ -24,6 +26,13 @@
self.step = step
+class KeyValuePairs(Parameter):
+
+ def __init__(self, default=None, label=None):
+ default = default if default is not None else OrderedDi... |
ab83da7b6152dfdc50cf40fa328f3c3d24c13861 | emailmgr/urls.py | emailmgr/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
email_send_activation, email_activate, email_make_primary
#add an email to a User account
urlpatterns = patterns('',
url(
... | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
email_send_activation, email_activate, email_make_primary
#add an email to a User account
urlpatterns = patterns('',
url(
r'^emai... | Fix import for django 1.6 | Fix import for django 1.6 | Python | bsd-3-clause | un33k/django-emailmgr,un33k/django-emailmgr | ---
+++
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from django.conf.urls.defaults import patterns, include, url
+from django.conf.urls import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
email_send_activation, email_activate, email_make... |
aa15e9195c6e16ec000338e71051f64a692642e0 | nightreads/user_manager/forms.py | nightreads/user_manager/forms.py | from django.contrib.auth.models import User
from django import forms
class SubscribeForm(forms.Form):
email = forms.EmailField()
tags = forms.CharField()
def clean_tags(self):
tags = self.cleaned_data['tags'].split(',')
return [t.strip().lower() for t in tags]
class UnsubscribeForm(form... | from django.contrib.auth.models import User
from django.core.signing import BadSignature, SignatureExpired
from django import forms
from . import user_service
class SubscribeForm(forms.Form):
email = forms.EmailField()
tags = forms.CharField()
def clean_tags(self):
tags = self.cleaned_data['tags... | Update `ConfirmEmailForm` to use `user_service.validate_key` | Update `ConfirmEmailForm` to use `user_service.validate_key`
| Python | mit | avinassh/nightreads,avinassh/nightreads | ---
+++
@@ -1,5 +1,8 @@
from django.contrib.auth.models import User
+from django.core.signing import BadSignature, SignatureExpired
from django import forms
+
+from . import user_service
class SubscribeForm(forms.Form):
@@ -31,12 +34,16 @@
return cleaned_data
email = cleaned_data['email']... |
d3356d42aa083ecebf53bb7792a573ed2289173b | unityparser/csharp/csharp_class_body_parser.py | unityparser/csharp/csharp_class_body_parser.py | import os, sys
__file__ = os.path.normpath(os.path.abspath(__file__))
__path__ = os.path.dirname(__file__)
# print(__path__)
if __path__ not in sys.path:
sys.path.insert(0, __path__)
from csharp_element import CSharpElement
import csharp_class_method_parser
import csharp_class_member_parser
import csharp_class... | import os, sys
__file__ = os.path.normpath(os.path.abspath(__file__))
__path__ = os.path.dirname(__file__)
# print(__path__)
if __path__ not in sys.path:
sys.path.insert(0, __path__)
from csharp_element import CSharpElement
import csharp_class_method_parser
import csharp_class_member_parser
# import csharp_cla... | Comment out property parser due to commit mistake | Comment out property parser due to commit mistake
| Python | mit | adrianogil/SublimeUnityIntel | ---
+++
@@ -12,12 +12,12 @@
import csharp_class_method_parser
import csharp_class_member_parser
-import csharp_class_property_parser
+# import csharp_class_property_parser
# class_region = (token_start, token_end) of enclosure class
def parse_tokens(tokens_data, class_region, class_name, class_instance):
... |
8f226fffd17b9d89d916ad4a1c42d43afc1f0634 | minitrue/utils.py | minitrue/utils.py | """
Generically useful utilities.
"""
import urlparse
try: # pragma: no cover
from cStringIO import StringIO; StringIO
except ImportError:
from StringIO import StringIO; StringIO
class Constructor(object):
def __init__(self):
self.kw = {}
def kwarg(self, kwargName=None):
"""
... | """
Generically useful utilities.
"""
import urlparse
from twisted.internet import defer
from twisted.python import log
try: # pragma: no cover
from cStringIO import StringIO; StringIO
except ImportError:
from StringIO import StringIO; StringIO
class Constructor(object):
def __init__(self):
self... | Support for deferred-returning manglers for Combined. Added OrderedCombined that guarantees order of execution. | Support for deferred-returning manglers for Combined. Added OrderedCombined that guarantees order of execution.
| Python | isc | lvh/minitrue | ---
+++
@@ -2,6 +2,9 @@
Generically useful utilities.
"""
import urlparse
+
+from twisted.internet import defer
+from twisted.python import log
try: # pragma: no cover
from cStringIO import StringIO; StringIO
@@ -54,5 +57,13 @@
def __call__(self, *a, **kw):
+ ds = [defer.maybeDeferred(f, *a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.