commit
stringlengths
40
40
old_file
stringlengths
5
117
new_file
stringlengths
5
117
old_contents
stringlengths
0
1.93k
new_contents
stringlengths
19
3.3k
subject
stringlengths
17
320
message
stringlengths
18
3.28k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
7
42.4k
completion
stringlengths
152
6.66k
prompt
stringlengths
21
3.65k
a2e7642034bf89bf1d7d513ef155da3375482373
virtool/user_permissions.py
virtool/user_permissions.py
#: A list of the permission strings used by Virtool. PERMISSIONS = [ "add_virus", "modify_virus", "remove_virus", "modify_hmm", "add_sample", "add_host", "remove_host", "cancel_job", "remove_job", "archive_job", "rebuild_index", "modify_options", "manage_users" ]
#: A list of the permission strings used by Virtool. PERMISSIONS = [ "add_virus", "modify_virus", "remove_virus", "modify_hmm", "create_sample", "add_host", "remove_host", "cancel_job", "remove_job", "archive_job", "rebuild_index", "modify_options", "manage_users" ]
Change 'add_sample' permission to 'create_sample'
Change 'add_sample' permission to 'create_sample'
Python
mit
igboyes/virtool,igboyes/virtool,virtool/virtool,virtool/virtool
<REPLACE_OLD> "add_sample", <REPLACE_NEW> "create_sample", <REPLACE_END> <|endoftext|> #: A list of the permission strings used by Virtool. PERMISSIONS = [ "add_virus", "modify_virus", "remove_virus", "modify_hmm", "create_sample", "add_host", "remove_host", "cancel_job", "remove_job", "archive_job", "rebuild_index", "modify_options", "manage_users" ]
Change 'add_sample' permission to 'create_sample' #: A list of the permission strings used by Virtool. PERMISSIONS = [ "add_virus", "modify_virus", "remove_virus", "modify_hmm", "add_sample", "add_host", "remove_host", "cancel_job", "remove_job", "archive_job", "rebuild_index", "modify_options", "manage_users" ]
5d44a67c1e416f8024bac1cbef5f3b3516ffd42a
cms_shiny/urls.py
cms_shiny/urls.py
from django.conf.urls import patterns, url from cms_shiny.views import ShinyAppListView, ShinyAppDetailView urlpatterns = patterns('', url(r'^$', ShinyAppListView.as_view(), name='shiny_list'), url(r'^(?P<slug>[^/]+)$', ShinyAppDetailView.as_view(), name='shiny_detail'), )
from django.conf.urls import patterns, url from cms_shiny.views import ShinyAppListView, ShinyAppDetailView urlpatterns = patterns('', url(r'^$', ShinyAppListView.as_view(), name='shiny_list'), url(r'^(?P<slug>[^/]+)/$', ShinyAppDetailView.as_view(), name='shiny_detail'), )
Append trailing slash to detail URL
Append trailing slash to detail URL
Python
bsd-3-clause
mfcovington/djangocms-shiny-app,mfcovington/djangocms-shiny-app,mfcovington/djangocms-shiny-app
<REPLACE_OLD> url(r'^(?P<slug>[^/]+)$', <REPLACE_NEW> url(r'^(?P<slug>[^/]+)/$', <REPLACE_END> <|endoftext|> from django.conf.urls import patterns, url from cms_shiny.views import ShinyAppListView, ShinyAppDetailView urlpatterns = patterns('', url(r'^$', ShinyAppListView.as_view(), name='shiny_list'), url(r'^(?P<slug>[^/]+)/$', ShinyAppDetailView.as_view(), name='shiny_detail'), )
Append trailing slash to detail URL from django.conf.urls import patterns, url from cms_shiny.views import ShinyAppListView, ShinyAppDetailView urlpatterns = patterns('', url(r'^$', ShinyAppListView.as_view(), name='shiny_list'), url(r'^(?P<slug>[^/]+)$', ShinyAppDetailView.as_view(), name='shiny_detail'), )
bb26d56cbce6d7f5d12bd9a2e5c428df6bf4b1d7
fabfile.py
fabfile.py
import sys import sh from fabric import api as fab sed = sh.sed.bake('-i bak -e') TRAVIS_YAML = '.travis.yml' REPLACE_LANGUAGE = 's/language: .*/language: {}/' def is_dirty(): return "" != sh.git.status(porcelain=True).strip() def release(language, message): if is_dirty(): sys.exit("Repo must be in clean state before deploying. Please commit changes.") sed(REPLACE_LANGUAGE.format(language), TRAVIS_YAML) if is_dirty(): sh.git.add(TRAVIS_YAML) sh.git.commit(m=message) sh.git.pull(rebase=True) sh.git.push() @fab.task def release_osx(): release('objective-c', "Release OS X") @fab.task def release_linux(): release('python', "Release Linux")
import sys import sh from fabric import api as fab sed = sh.sed.bake('-i bak -e') TRAVIS_YAML = '.travis.yml' REPLACE_LANGUAGE = 's/language: .*/language: {}/' def is_dirty(): return "" != sh.git.status(porcelain=True).strip() def release(language, message): if is_dirty(): sys.exit("Repo must be in clean state before deploying. Please commit changes.") sed(REPLACE_LANGUAGE.format(language), TRAVIS_YAML) if is_dirty(): sh.git.add(TRAVIS_YAML) sh.git.commit(m=message, allow_empty=True) sh.git.pull(rebase=True) sh.git.push() @fab.task def release_osx(): release('objective-c', "Release OS X") @fab.task def release_linux(): release('python', "Release Linux")
Allow empty so we can force new build
Allow empty so we can force new build
Python
bsd-3-clause
datamicroscopes/release,jzf2101/release,datamicroscopes/release,jzf2101/release
<REPLACE_OLD> sh.git.commit(m=message) <REPLACE_NEW> sh.git.commit(m=message, allow_empty=True) <REPLACE_END> <|endoftext|> import sys import sh from fabric import api as fab sed = sh.sed.bake('-i bak -e') TRAVIS_YAML = '.travis.yml' REPLACE_LANGUAGE = 's/language: .*/language: {}/' def is_dirty(): return "" != sh.git.status(porcelain=True).strip() def release(language, message): if is_dirty(): sys.exit("Repo must be in clean state before deploying. Please commit changes.") sed(REPLACE_LANGUAGE.format(language), TRAVIS_YAML) if is_dirty(): sh.git.add(TRAVIS_YAML) sh.git.commit(m=message, allow_empty=True) sh.git.pull(rebase=True) sh.git.push() @fab.task def release_osx(): release('objective-c', "Release OS X") @fab.task def release_linux(): release('python', "Release Linux")
Allow empty so we can force new build import sys import sh from fabric import api as fab sed = sh.sed.bake('-i bak -e') TRAVIS_YAML = '.travis.yml' REPLACE_LANGUAGE = 's/language: .*/language: {}/' def is_dirty(): return "" != sh.git.status(porcelain=True).strip() def release(language, message): if is_dirty(): sys.exit("Repo must be in clean state before deploying. Please commit changes.") sed(REPLACE_LANGUAGE.format(language), TRAVIS_YAML) if is_dirty(): sh.git.add(TRAVIS_YAML) sh.git.commit(m=message) sh.git.pull(rebase=True) sh.git.push() @fab.task def release_osx(): release('objective-c', "Release OS X") @fab.task def release_linux(): release('python', "Release Linux")
064124d09973dc58a444d22aa7c47acf94f8fa81
data/bigramfreq.py
data/bigramfreq.py
import json import lxml.html from lxml.cssselect import CSSSelector import requests import sys def main(): raw = requests.get("http://norvig.com/mayzner.html") if not raw: print >>sys.stderr, "Request failed with code %d" % (raw.status_code) return 1 tree = lxml.html.fromstring(raw.text) sel = CSSSelector("td") freq = {key[:-1].lower(): float(value[:-2]) / 100 for key, value, _ in map(lambda x: x.get("title").split(), filter(lambda y: y.get("title") is not None, sel(tree)))} print json.dumps(freq) return 0 if __name__ == "__main__": sys.exit(main())
Add a script to generate JSON bigram frequencies for English
Add a script to generate JSON bigram frequencies for English
Python
apache-2.0
Kitware/clique,Kitware/clique,XDATA-Year-3/clique,XDATA-Year-3/clique,Kitware/clique,XDATA-Year-3/clique
<INSERT> import json import lxml.html from lxml.cssselect import CSSSelector import requests import sys def main(): <INSERT_END> <INSERT> raw = requests.get("http://norvig.com/mayzner.html") if not raw: print >>sys.stderr, "Request failed with code %d" % (raw.status_code) return 1 tree = lxml.html.fromstring(raw.text) sel = CSSSelector("td") freq = {key[:-1].lower(): float(value[:-2]) / 100 for key, value, _ in map(lambda x: x.get("title").split(), filter(lambda y: y.get("title") is not None, sel(tree)))} print json.dumps(freq) return 0 if __name__ == "__main__": sys.exit(main()) <INSERT_END> <|endoftext|> import json import lxml.html from lxml.cssselect import CSSSelector import requests import sys def main(): raw = requests.get("http://norvig.com/mayzner.html") if not raw: print >>sys.stderr, "Request failed with code %d" % (raw.status_code) return 1 tree = lxml.html.fromstring(raw.text) sel = CSSSelector("td") freq = {key[:-1].lower(): float(value[:-2]) / 100 for key, value, _ in map(lambda x: x.get("title").split(), filter(lambda y: y.get("title") is not None, sel(tree)))} print json.dumps(freq) return 0 if __name__ == "__main__": sys.exit(main())
Add a script to generate JSON bigram frequencies for English
a773d29d7bce78abea28209e53909ab52eee36a9
routes.py
routes.py
from flask import Flask, render_template from setup_cardsets import CardOperations co = CardOperations() app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') @app.route('/rules') def rules(): return render_template('rules.html') @app.route('/setup') def setup(): return render_template('setup.html') @app.route('/toss/<int:cardcount>') def toss(cardcount): co.cardset(cardcount) return render_template('toss.html') @app.route('/begin') def begin(): try: co.toss_result() return render_template('pages/begin.html') except Exception as detail: print detail @app.route('/game') def game(): co.update_page() co.page_no = 1 return render_template('pages/game.html') @app.route('/game/<statval>') def game_move(statval): try: completed = co.compare(int(statval)) if not completed: co.update_page() return render_template('pages/game.html') else: co.update_completion() return render_template('pages/result.html') except Exception as detail: print detail if __name__ == '__main__': app.run()
from flask import Flask, render_template, redirect from setup_cardsets import CardOperations co = CardOperations() app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') @app.route('/rules') def rules(): return render_template('rules.html') @app.route('/setup') def setup(): return render_template('setup.html') @app.route('/toss/<int:cardcount>') def toss(cardcount): co.cardset(cardcount) return render_template('toss.html') @app.route('/begin') def begin(): try: co.toss_result() return render_template('pages/begin.html') except Exception as detail: print detail @app.route('/game') def game(): co.update_page() co.page_no = 1 return render_template('pages/game.html') @app.route('/game/<statval>') def game_move(statval): try: completed = co.compare(int(statval)) if not completed: co.update_page() return render_template('pages/game.html') else: return redirect('/result') except Exception as detail: print detail @app.route('/result') def result(): co.update_completion() return render_template('pages/result.html') if __name__ == '__main__': app.run()
Use flask's redirect() method to go to result link
Use flask's redirect() method to go to result link
Python
mit
AlexMathew/tcg-ui
<REPLACE_OLD> render_template from <REPLACE_NEW> render_template, redirect from <REPLACE_END> <REPLACE_OLD> render_template('pages/game.html') else: co.update_completion() return render_template('pages/result.html') except <REPLACE_NEW> render_template('pages/game.html') else: return redirect('/result') except <REPLACE_END> <REPLACE_OLD> detail if <REPLACE_NEW> detail @app.route('/result') def result(): co.update_completion() return render_template('pages/result.html') if <REPLACE_END> <|endoftext|> from flask import Flask, render_template, redirect from setup_cardsets import CardOperations co = CardOperations() app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') @app.route('/rules') def rules(): return render_template('rules.html') @app.route('/setup') def setup(): return render_template('setup.html') @app.route('/toss/<int:cardcount>') def toss(cardcount): co.cardset(cardcount) return render_template('toss.html') @app.route('/begin') def begin(): try: co.toss_result() return render_template('pages/begin.html') except Exception as detail: print detail @app.route('/game') def game(): co.update_page() co.page_no = 1 return render_template('pages/game.html') @app.route('/game/<statval>') def game_move(statval): try: completed = co.compare(int(statval)) if not completed: co.update_page() return render_template('pages/game.html') else: return redirect('/result') except Exception as detail: print detail @app.route('/result') def result(): co.update_completion() return render_template('pages/result.html') if __name__ == '__main__': app.run()
Use flask's redirect() method to go to result link from flask import Flask, render_template from setup_cardsets import CardOperations co = CardOperations() app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') @app.route('/rules') def rules(): return render_template('rules.html') @app.route('/setup') def setup(): return render_template('setup.html') @app.route('/toss/<int:cardcount>') def toss(cardcount): co.cardset(cardcount) return render_template('toss.html') @app.route('/begin') def begin(): try: co.toss_result() return render_template('pages/begin.html') except Exception as detail: print detail @app.route('/game') def game(): co.update_page() co.page_no = 1 return render_template('pages/game.html') @app.route('/game/<statval>') def game_move(statval): try: completed = co.compare(int(statval)) if not completed: co.update_page() return render_template('pages/game.html') else: co.update_completion() return render_template('pages/result.html') except Exception as detail: print detail if __name__ == '__main__': app.run()
dc2f8342bc9b9c921086948ed10f99de9bcbc76d
client/python/setup.py
client/python/setup.py
#!/usr/bin/env python from distutils.core import setup setup(name='Spiff', version='0.1', description="API to Spaceman Spiff", author='Trever Fischer', author_email='[email protected]', url='http://github.com/synhak/spiff', py_modules=['spiff'] )
#!/usr/bin/env python from distutils.core import setup setup(name='Spiff', version='0.1', description="API to Spaceman Spiff", author='Trever Fischer', author_email='[email protected]', url='http://github.com/synhak/spiff', py_modules=['spiff'], requires=['requests'], )
Add deps for python lib
Add deps for python lib
Python
agpl-3.0
SYNHAK/spiff,SYNHAK/spiff,SYNHAK/spiff
<REPLACE_OLD> py_modules=['spiff'] ) <REPLACE_NEW> py_modules=['spiff'], requires=['requests'], ) <REPLACE_END> <|endoftext|> #!/usr/bin/env python from distutils.core import setup setup(name='Spiff', version='0.1', description="API to Spaceman Spiff", author='Trever Fischer', author_email='[email protected]', url='http://github.com/synhak/spiff', py_modules=['spiff'], requires=['requests'], )
Add deps for python lib #!/usr/bin/env python from distutils.core import setup setup(name='Spiff', version='0.1', description="API to Spaceman Spiff", author='Trever Fischer', author_email='[email protected]', url='http://github.com/synhak/spiff', py_modules=['spiff'] )
52aeb0d37aa903c0189416bbafc2a75ea41f3201
slave/skia_slave_scripts/do_skps_capture.py
slave/skia_slave_scripts/do_skps_capture.py
#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shell_utils class SKPsCapture(BuildStep): """BuildStep that captures the buildbot SKPs.""" def __init__(self, timeout=10800, **kwargs): super(SKPsCapture, self).__init__(timeout=timeout, **kwargs) def _Run(self): webpages_playback_cmd = [ 'python', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'webpages_playback.py'), '--page_sets', self._args['page_sets'], '--skia_tools', self._args['skia_tools'], '--browser_executable', self._args['browser_executable'], '--non-interactive' ] if not self._is_try: webpages_playback_cmd.append('--upload_to_gs') shell_utils.Bash(webpages_playback_cmd) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(SKPsCapture))
#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shell_utils class SKPsCapture(BuildStep): """BuildStep that captures the buildbot SKPs.""" def __init__(self, timeout=10800, **kwargs): super(SKPsCapture, self).__init__(timeout=timeout, **kwargs) def _Run(self): webpages_playback_cmd = [ 'python', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'webpages_playback.py'), '--page_sets', self._args['page_sets'], '--skia_tools', self._args['skia_tools'], '--browser_executable', self._args['browser_executable'], '--non-interactive' ] if not self._is_try: webpages_playback_cmd.append('--upload_to_gs') shell_utils.Bash(webpages_playback_cmd) # Clean up any leftover browser instances. This can happen if there are # telemetry crashes, processes are not always cleaned up appropriately by # the webpagereplay and telemetry frameworks. cleanup_cmd = [ 'pkill', '-9', '-f', self._args['browser_executable'] ] shell_utils.Bash(cleanup_cmd) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(SKPsCapture))
Clean up any left over browser processes in the RecreateSKPs buildstep.
Clean up any left over browser processes in the RecreateSKPs buildstep. BUG=skia:2055 [email protected] Review URL: https://codereview.chromium.org/140003003
Python
bsd-3-clause
google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot
<DELETE> <DELETE_END> <DELETE> <DELETE_END> <DELETE> <DELETE_END> <DELETE> <DELETE_END> <DELETE> <DELETE_END> <DELETE> <DELETE_END> <REPLACE_OLD> shell_utils.Bash(webpages_playback_cmd) if <REPLACE_NEW> shell_utils.Bash(webpages_playback_cmd) # Clean up any leftover browser instances. This can happen if there are # telemetry crashes, processes are not always cleaned up appropriately by # the webpagereplay and telemetry frameworks. cleanup_cmd = [ 'pkill', '-9', '-f', self._args['browser_executable'] ] shell_utils.Bash(cleanup_cmd) if <REPLACE_END> <|endoftext|> #!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shell_utils class SKPsCapture(BuildStep): """BuildStep that captures the buildbot SKPs.""" def __init__(self, timeout=10800, **kwargs): super(SKPsCapture, self).__init__(timeout=timeout, **kwargs) def _Run(self): webpages_playback_cmd = [ 'python', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'webpages_playback.py'), '--page_sets', self._args['page_sets'], '--skia_tools', self._args['skia_tools'], '--browser_executable', self._args['browser_executable'], '--non-interactive' ] if not self._is_try: webpages_playback_cmd.append('--upload_to_gs') shell_utils.Bash(webpages_playback_cmd) # Clean up any leftover browser instances. This can happen if there are # telemetry crashes, processes are not always cleaned up appropriately by # the webpagereplay and telemetry frameworks. cleanup_cmd = [ 'pkill', '-9', '-f', self._args['browser_executable'] ] shell_utils.Bash(cleanup_cmd) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(SKPsCapture))
Clean up any left over browser processes in the RecreateSKPs buildstep. BUG=skia:2055 [email protected] Review URL: https://codereview.chromium.org/140003003 #!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shell_utils class SKPsCapture(BuildStep): """BuildStep that captures the buildbot SKPs.""" def __init__(self, timeout=10800, **kwargs): super(SKPsCapture, self).__init__(timeout=timeout, **kwargs) def _Run(self): webpages_playback_cmd = [ 'python', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'webpages_playback.py'), '--page_sets', self._args['page_sets'], '--skia_tools', self._args['skia_tools'], '--browser_executable', self._args['browser_executable'], '--non-interactive' ] if not self._is_try: webpages_playback_cmd.append('--upload_to_gs') shell_utils.Bash(webpages_playback_cmd) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(SKPsCapture))
779d8478fd05fe50ea7dccd55e98ae82ac609d32
s3Uploader.py
s3Uploader.py
# -*- coding: utf-8 -*- import botocore import boto3 from datetime import datetime class s3Uploader(): def __init__(self, bucketName, objectName, filePath): self.__bucketName = bucketName self.__objectName = objectName self.__filePath = filePath self.__s3 = boto3.client('s3') def upload(self): if self.isExistObjectFor(): print("{name} already exist.".format(name=self.__objectName)) # Need refactoring... print("Delete {objectName}.".format(objectName=self.__objectName)) self.__s3.delete_object(Bucket=self.__bucketName, Key=self.__objectName) print("Re-Upload {objectName} to {bucketName}.".format(bucketName=self.__bucketName, objectName=self.__objectName)) self.uploadObject(self.__filePath) else: print("Upload {objectName} to {bucketName}.".format(bucketName=self.__bucketName, objectName=self.__objectName)) self.uploadObject(self.__filePath) def uploadObject(self, path): with open(path, 'rb') as fh: self.__s3.put_object(Body=fh, Bucket=self.__bucketName, Key=self.__objectName) def isExistObjectFor(self): try: self.__s3.head_object(Bucket=self.__bucketName, Key=self.__objectName) return True except botocore.exceptions.ClientError as e: print(e) return False def isExistBucketFor(self): try: response = self.__s3.head_bucket(Bucket=self.__bucketName) # response = s3.head_bucket(Bucket='test-lambda-on-java') print(response) return True except botocore.exceptions.ClientError as e: print("The {bucketName} does not found".format(bucketName=self.__bucketName)) print(e) return False
Add s3 uploader class from awsSample repository.
Add s3 uploader class from awsSample repository.
Python
mit
hondasports/Bun-chan-Bot,hondasports/Bun-chan-Bot
<REPLACE_OLD> <REPLACE_NEW> # -*- coding: utf-8 -*- import botocore import boto3 from datetime import datetime class s3Uploader(): def __init__(self, bucketName, objectName, filePath): self.__bucketName = bucketName self.__objectName = objectName self.__filePath = filePath self.__s3 = boto3.client('s3') def upload(self): if self.isExistObjectFor(): print("{name} already exist.".format(name=self.__objectName)) # Need refactoring... print("Delete {objectName}.".format(objectName=self.__objectName)) self.__s3.delete_object(Bucket=self.__bucketName, Key=self.__objectName) print("Re-Upload {objectName} to {bucketName}.".format(bucketName=self.__bucketName, objectName=self.__objectName)) self.uploadObject(self.__filePath) else: print("Upload {objectName} to {bucketName}.".format(bucketName=self.__bucketName, objectName=self.__objectName)) self.uploadObject(self.__filePath) def uploadObject(self, path): with open(path, 'rb') as fh: self.__s3.put_object(Body=fh, Bucket=self.__bucketName, Key=self.__objectName) def isExistObjectFor(self): try: self.__s3.head_object(Bucket=self.__bucketName, Key=self.__objectName) return True except botocore.exceptions.ClientError as e: print(e) return False def isExistBucketFor(self): try: response = self.__s3.head_bucket(Bucket=self.__bucketName) # response = s3.head_bucket(Bucket='test-lambda-on-java') print(response) return True except botocore.exceptions.ClientError as e: print("The {bucketName} does not found".format(bucketName=self.__bucketName)) print(e) return False <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*- import botocore import boto3 from datetime import datetime class s3Uploader(): def __init__(self, bucketName, objectName, filePath): self.__bucketName = bucketName self.__objectName = objectName self.__filePath = filePath self.__s3 = boto3.client('s3') def upload(self): if self.isExistObjectFor(): print("{name} already exist.".format(name=self.__objectName)) # Need refactoring... print("Delete {objectName}.".format(objectName=self.__objectName)) self.__s3.delete_object(Bucket=self.__bucketName, Key=self.__objectName) print("Re-Upload {objectName} to {bucketName}.".format(bucketName=self.__bucketName, objectName=self.__objectName)) self.uploadObject(self.__filePath) else: print("Upload {objectName} to {bucketName}.".format(bucketName=self.__bucketName, objectName=self.__objectName)) self.uploadObject(self.__filePath) def uploadObject(self, path): with open(path, 'rb') as fh: self.__s3.put_object(Body=fh, Bucket=self.__bucketName, Key=self.__objectName) def isExistObjectFor(self): try: self.__s3.head_object(Bucket=self.__bucketName, Key=self.__objectName) return True except botocore.exceptions.ClientError as e: print(e) return False def isExistBucketFor(self): try: response = self.__s3.head_bucket(Bucket=self.__bucketName) # response = s3.head_bucket(Bucket='test-lambda-on-java') print(response) return True except botocore.exceptions.ClientError as e: print("The {bucketName} does not found".format(bucketName=self.__bucketName)) print(e) return False
Add s3 uploader class from awsSample repository.
093c9065de9e0e08f248bbb84696bf30309bd536
examples/parallel/timer.py
examples/parallel/timer.py
import rx import concurrent.futures import time seconds = [5, 1, 2, 4, 3] def sleep(t): time.sleep(t) return t def output(result): print '%d seconds' % result with concurrent.futures.ProcessPoolExecutor(5) as executor: rx.Observable.from_(seconds).flat_map( lambda s: executor.submit(sleep, s) ).subscribe(output) # 1 seconds # 2 seconds # 3 seconds # 4 seconds # 5 seconds
from __future__ import print_function import rx import concurrent.futures import time seconds = [5, 1, 2, 4, 3] def sleep(t): time.sleep(t) return t def output(result): print('%d seconds' % result) with concurrent.futures.ProcessPoolExecutor(5) as executor: rx.Observable.from_(seconds).flat_map( lambda s: executor.submit(sleep, s) ).subscribe(output) # 1 seconds # 2 seconds # 3 seconds # 4 seconds # 5 seconds
Fix parallel example for Python 3
Fix parallel example for Python 3
Python
mit
dbrattli/RxPY,ReactiveX/RxPY,ReactiveX/RxPY
<INSERT> from __future__ <INSERT_END> <INSERT> print_function import <INSERT_END> <REPLACE_OLD> print '%d <REPLACE_NEW> print('%d <REPLACE_END> <REPLACE_OLD> result with <REPLACE_NEW> result) with <REPLACE_END> <|endoftext|> from __future__ import print_function import rx import concurrent.futures import time seconds = [5, 1, 2, 4, 3] def sleep(t): time.sleep(t) return t def output(result): print('%d seconds' % result) with concurrent.futures.ProcessPoolExecutor(5) as executor: rx.Observable.from_(seconds).flat_map( lambda s: executor.submit(sleep, s) ).subscribe(output) # 1 seconds # 2 seconds # 3 seconds # 4 seconds # 5 seconds
Fix parallel example for Python 3 import rx import concurrent.futures import time seconds = [5, 1, 2, 4, 3] def sleep(t): time.sleep(t) return t def output(result): print '%d seconds' % result with concurrent.futures.ProcessPoolExecutor(5) as executor: rx.Observable.from_(seconds).flat_map( lambda s: executor.submit(sleep, s) ).subscribe(output) # 1 seconds # 2 seconds # 3 seconds # 4 seconds # 5 seconds
3ea008feb5ebd0e4e67952267aa5e3a0c5e13e89
hoomd/operations.py
hoomd/operations.py
import hoomd.integrate class Operations: def __init__(self, simulation=None): self.simulation = simulation self._compute = list() self._auto_schedule = False self._scheduled = False def add(self, op): if isinstance(op, hoomd.integrate._integrator): self._integrator = op else: raise ValueError("Operation is not of the correct type to add to" " Operations.") @property def _operations(self): op = list() if hasattr(self, '_integrator'): op.append(self._integrator) return op @property def _sys_init(self): if self.simulation is None or self.simulation.state is None: return False else: return True def schedule(self): if not self._sys_init: raise RuntimeError("System not initialized yet") sim = self.simulation for op in self._operations: new_objs = op.attach(sim) if isinstance(op, hoomd.integrate._integrator): sim._cpp_sys.setIntegrator(op._cpp_obj) if new_objs is not None: self._compute.extend(new_objs) self._scheduled = True def _store_reader(self, reader): # TODO pass @property def scheduled(self): return self._scheduled
import hoomd.integrate class Operations: def __init__(self, simulation=None): self.simulation = simulation self._compute = list() self._auto_schedule = False self._scheduled = False def add(self, op): if isinstance(op, hoomd.integrate._integrator): self._integrator = op else: raise ValueError("Operation is not of the correct type to add to" " Operations.") @property def _operations(self): op = list() if hasattr(self, '_integrator'): op.append(self._integrator) return op @property def _sys_init(self): if self.simulation is None or self.simulation.state is None: return False else: return True def schedule(self): if not self._sys_init: raise RuntimeError("System not initialized yet") sim = self.simulation for op in self._operations: new_objs = op.attach(sim) if isinstance(op, hoomd.integrate._integrator): sim._cpp_sys.setIntegrator(op._cpp_obj) if new_objs is not None: self._compute.extend(new_objs) self._scheduled = True def _store_reader(self, reader): # TODO pass @property def scheduled(self): return self._scheduled @property def integrator(self): try: return self._integrator except AttributeError: return None
Add integrator property for Operations
Add integrator property for Operations
Python
bsd-3-clause
joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue
<REPLACE_OLD> self._scheduled <REPLACE_NEW> self._scheduled @property def integrator(self): try: return self._integrator except AttributeError: return None <REPLACE_END> <|endoftext|> import hoomd.integrate class Operations: def __init__(self, simulation=None): self.simulation = simulation self._compute = list() self._auto_schedule = False self._scheduled = False def add(self, op): if isinstance(op, hoomd.integrate._integrator): self._integrator = op else: raise ValueError("Operation is not of the correct type to add to" " Operations.") @property def _operations(self): op = list() if hasattr(self, '_integrator'): op.append(self._integrator) return op @property def _sys_init(self): if self.simulation is None or self.simulation.state is None: return False else: return True def schedule(self): if not self._sys_init: raise RuntimeError("System not initialized yet") sim = self.simulation for op in self._operations: new_objs = op.attach(sim) if isinstance(op, hoomd.integrate._integrator): sim._cpp_sys.setIntegrator(op._cpp_obj) if new_objs is not None: self._compute.extend(new_objs) self._scheduled = True def _store_reader(self, reader): # TODO pass @property def scheduled(self): return self._scheduled @property def integrator(self): try: return self._integrator except AttributeError: return None
Add integrator property for Operations import hoomd.integrate class Operations: def __init__(self, simulation=None): self.simulation = simulation self._compute = list() self._auto_schedule = False self._scheduled = False def add(self, op): if isinstance(op, hoomd.integrate._integrator): self._integrator = op else: raise ValueError("Operation is not of the correct type to add to" " Operations.") @property def _operations(self): op = list() if hasattr(self, '_integrator'): op.append(self._integrator) return op @property def _sys_init(self): if self.simulation is None or self.simulation.state is None: return False else: return True def schedule(self): if not self._sys_init: raise RuntimeError("System not initialized yet") sim = self.simulation for op in self._operations: new_objs = op.attach(sim) if isinstance(op, hoomd.integrate._integrator): sim._cpp_sys.setIntegrator(op._cpp_obj) if new_objs is not None: self._compute.extend(new_objs) self._scheduled = True def _store_reader(self, reader): # TODO pass @property def scheduled(self): return self._scheduled
f9094d47d138ecd7ece6e921b9a10a7c79eed629
setup.py
setup.py
from setuptools import setup setup( name='cmsplugin-biography', version='0.0.1', packages='cmsplugin_biography', install_requires=[ 'django-cms', 'djangocms-text-ckeditor==1.0.9', 'easy-thumbnails==1.2', ], author='Kevin Richardson', author_email='[email protected]', description='A Django CMS plugin that manages and displays biographical information', long_description=open('README.rst').read(), license='MIT', url='http://github.com/kfr2/cmsplugin-biography', include_package_data=True )
from setuptools import setup setup( name='cmsplugin-biography', version='0.0.1', packages=['cmsplugin_biography', ], install_requires=[ 'django-cms', 'djangocms-text-ckeditor==1.0.9', 'easy-thumbnails==1.2', ], author='Kevin Richardson', author_email='[email protected]', description='A Django CMS plugin that manages and displays biographical information', long_description=open('README.rst').read(), license='MIT', url='http://github.com/kfr2/cmsplugin-biography', include_package_data=True )
Convert `packages` to a list
Convert `packages` to a list
Python
mit
kfr2/cmsplugin-biography
<REPLACE_OLD> packages='cmsplugin_biography', <REPLACE_NEW> packages=['cmsplugin_biography', ], <REPLACE_END> <|endoftext|> from setuptools import setup setup( name='cmsplugin-biography', version='0.0.1', packages=['cmsplugin_biography', ], install_requires=[ 'django-cms', 'djangocms-text-ckeditor==1.0.9', 'easy-thumbnails==1.2', ], author='Kevin Richardson', author_email='[email protected]', description='A Django CMS plugin that manages and displays biographical information', long_description=open('README.rst').read(), license='MIT', url='http://github.com/kfr2/cmsplugin-biography', include_package_data=True )
Convert `packages` to a list from setuptools import setup setup( name='cmsplugin-biography', version='0.0.1', packages='cmsplugin_biography', install_requires=[ 'django-cms', 'djangocms-text-ckeditor==1.0.9', 'easy-thumbnails==1.2', ], author='Kevin Richardson', author_email='[email protected]', description='A Django CMS plugin that manages and displays biographical information', long_description=open('README.rst').read(), license='MIT', url='http://github.com/kfr2/cmsplugin-biography', include_package_data=True )
21c60fdd99e37436228cfe8e59f1b8788ea2b58b
platformio/builder/tools/pioar.py
platformio/builder/tools/pioar.py
# Copyright (C) Ivan Kravets <[email protected]> # See LICENSE for details. import atexit from os import remove from tempfile import mkstemp MAX_SOURCES_LENGTH = 8000 # Windows CLI has limit with command length to 8192 def _remove_tmpfile(path): try: remove(path) except WindowsError: pass def _huge_sources_hook(sources): if len(str(sources)) < MAX_SOURCES_LENGTH: return sources _, tmp_file = mkstemp() with open(tmp_file, "w") as f: f.write(str(sources).replace("\\", "/")) atexit.register(_remove_tmpfile, tmp_file) return "@%s" % tmp_file def exists(_): return True def generate(env): env.Replace( _huge_sources_hook=_huge_sources_hook, ARCOM=env.get("ARCOM", "").replace( "$SOURCES", "${_huge_sources_hook(SOURCES)}")) return env
# Copyright (C) Ivan Kravets <[email protected]> # See LICENSE for details. import atexit from os import remove from tempfile import mkstemp MAX_SOURCES_LENGTH = 8000 # Windows CLI has limit with command length to 8192 def _remove_tmpfile(path): try: remove(path) except WindowsError: # pylint: disable=E0602 pass def _huge_sources_hook(sources): if len(str(sources)) < MAX_SOURCES_LENGTH: return sources _, tmp_file = mkstemp() with open(tmp_file, "w") as f: f.write(str(sources).replace("\\", "/")) atexit.register(_remove_tmpfile, tmp_file) return "@%s" % tmp_file def exists(_): return True def generate(env): env.Replace( _huge_sources_hook=_huge_sources_hook, ARCOM=env.get("ARCOM", "").replace( "$SOURCES", "${_huge_sources_hook(SOURCES)}")) return env
Hide PyLint warning with undefined WindowsError exception
Hide PyLint warning with undefined WindowsError exception
Python
apache-2.0
dkuku/platformio,mseroczynski/platformio,jrobeson/platformio,bkudria/platformio,awong1900/platformio,TimJay/platformio,TimJay/platformio,jrobeson/platformio,awong1900/platformio,awong1900/platformio,mcanthony/platformio,TimJay/platformio,ZachMassia/platformio,platformio/platformio-core,TimJay/platformio,platformio/platformio-core,jrobeson/platformio,platformio/platformio,valeros/platformio,jrobeson/platformio,bkudria/platformio,TimJay/platformio,bkudria/platformio,mplewis/platformio,bkudria/platformio,eiginn/platformio,atyenoria/platformio
<REPLACE_OLD> WindowsError: <REPLACE_NEW> WindowsError: # pylint: disable=E0602 <REPLACE_END> <|endoftext|> # Copyright (C) Ivan Kravets <[email protected]> # See LICENSE for details. import atexit from os import remove from tempfile import mkstemp MAX_SOURCES_LENGTH = 8000 # Windows CLI has limit with command length to 8192 def _remove_tmpfile(path): try: remove(path) except WindowsError: # pylint: disable=E0602 pass def _huge_sources_hook(sources): if len(str(sources)) < MAX_SOURCES_LENGTH: return sources _, tmp_file = mkstemp() with open(tmp_file, "w") as f: f.write(str(sources).replace("\\", "/")) atexit.register(_remove_tmpfile, tmp_file) return "@%s" % tmp_file def exists(_): return True def generate(env): env.Replace( _huge_sources_hook=_huge_sources_hook, ARCOM=env.get("ARCOM", "").replace( "$SOURCES", "${_huge_sources_hook(SOURCES)}")) return env
Hide PyLint warning with undefined WindowsError exception # Copyright (C) Ivan Kravets <[email protected]> # See LICENSE for details. import atexit from os import remove from tempfile import mkstemp MAX_SOURCES_LENGTH = 8000 # Windows CLI has limit with command length to 8192 def _remove_tmpfile(path): try: remove(path) except WindowsError: pass def _huge_sources_hook(sources): if len(str(sources)) < MAX_SOURCES_LENGTH: return sources _, tmp_file = mkstemp() with open(tmp_file, "w") as f: f.write(str(sources).replace("\\", "/")) atexit.register(_remove_tmpfile, tmp_file) return "@%s" % tmp_file def exists(_): return True def generate(env): env.Replace( _huge_sources_hook=_huge_sources_hook, ARCOM=env.get("ARCOM", "").replace( "$SOURCES", "${_huge_sources_hook(SOURCES)}")) return env
4fa21d91ada4df904fc8fdddff608fc40c49aaee
reviewboard/accounts/urls.py
reviewboard/accounts/urls.py
from __future__ import unicode_literals from django.conf.urls import patterns, url from reviewboard.accounts.views import MyAccountView urlpatterns = patterns( "reviewboard.accounts.views", url(r'^register/$', 'account_register', {'next_url': 'dashboard'}, name="register"), url(r'^preferences/$', MyAccountView.as_view(), name="user-preferences"), ) urlpatterns += patterns( "django.contrib.auth.views", url(r'^login/$', 'login', {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$', 'logout_then_login', name='logout'), url(r'^recover/$', 'password_reset', { 'template_name': 'accounts/password_reset.html', 'email_template_name': 'accounts/password_reset_email.txt' }, name='recover'), url(r'^recover/done/$', 'password_reset_done', {'template_name': 'accounts/password_reset_done.html'}, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/password_reset_confirm.html'}, name='password-reset-confirm'), url(r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_complete.html'}), )
from __future__ import unicode_literals from django.conf.urls import patterns, url from reviewboard.accounts.views import MyAccountView urlpatterns = patterns( "reviewboard.accounts.views", url(r'^register/$', 'account_register', {'next_url': 'dashboard'}, name="register"), url(r'^preferences/$', MyAccountView.as_view(), name="user-preferences"), ) urlpatterns += patterns( "django.contrib.auth.views", url(r'^login/$', 'login', {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$', 'logout_then_login', name='logout'), url(r'^recover/$', 'password_reset', { 'template_name': 'accounts/password_reset.html', 'email_template_name': 'accounts/password_reset_email.txt' }, name='recover'), url(r'^recover/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_done.html'}, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/password_reset_confirm.html'}, name='password-reset-confirm'), url(r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_complete.html'}), )
Change 'password_reset_done' URL name to 'password_reset_complete'
Change 'password_reset_done' URL name to 'password_reset_complete' The built-in password reset views use a different name for the last page in the flow than we did before, and somehow we never noticed this until recently. Trivial fix. Fixes bug 3345.
Python
mit
reviewboard/reviewboard,custode/reviewboard,1tush/reviewboard,brennie/reviewboard,1tush/reviewboard,bkochendorfer/reviewboard,reviewboard/reviewboard,1tush/reviewboard,custode/reviewboard,chipx86/reviewboard,beol/reviewboard,reviewboard/reviewboard,1tush/reviewboard,custode/reviewboard,1tush/reviewboard,davidt/reviewboard,bkochendorfer/reviewboard,sgallagher/reviewboard,sgallagher/reviewboard,beol/reviewboard,sgallagher/reviewboard,chipx86/reviewboard,KnowNo/reviewboard,1tush/reviewboard,brennie/reviewboard,sgallagher/reviewboard,1tush/reviewboard,davidt/reviewboard,bkochendorfer/reviewboard,KnowNo/reviewboard,custode/reviewboard,beol/reviewboard,chipx86/reviewboard,beol/reviewboard,davidt/reviewboard,1tush/reviewboard,davidt/reviewboard,brennie/reviewboard,KnowNo/reviewboard,1tush/reviewboard,chipx86/reviewboard,bkochendorfer/reviewboard,KnowNo/reviewboard,brennie/reviewboard,reviewboard/reviewboard
<REPLACE_OLD> 'password_reset_done', <REPLACE_NEW> 'password_reset_complete', <REPLACE_END> <|endoftext|> from __future__ import unicode_literals from django.conf.urls import patterns, url from reviewboard.accounts.views import MyAccountView urlpatterns = patterns( "reviewboard.accounts.views", url(r'^register/$', 'account_register', {'next_url': 'dashboard'}, name="register"), url(r'^preferences/$', MyAccountView.as_view(), name="user-preferences"), ) urlpatterns += patterns( "django.contrib.auth.views", url(r'^login/$', 'login', {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$', 'logout_then_login', name='logout'), url(r'^recover/$', 'password_reset', { 'template_name': 'accounts/password_reset.html', 'email_template_name': 'accounts/password_reset_email.txt' }, name='recover'), url(r'^recover/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_done.html'}, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/password_reset_confirm.html'}, name='password-reset-confirm'), url(r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_complete.html'}), )
Change 'password_reset_done' URL name to 'password_reset_complete' The built-in password reset views use a different name for the last page in the flow than we did before, and somehow we never noticed this until recently. Trivial fix. Fixes bug 3345. from __future__ import unicode_literals from django.conf.urls import patterns, url from reviewboard.accounts.views import MyAccountView urlpatterns = patterns( "reviewboard.accounts.views", url(r'^register/$', 'account_register', {'next_url': 'dashboard'}, name="register"), url(r'^preferences/$', MyAccountView.as_view(), name="user-preferences"), ) urlpatterns += patterns( "django.contrib.auth.views", url(r'^login/$', 'login', {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$', 'logout_then_login', name='logout'), url(r'^recover/$', 'password_reset', { 'template_name': 'accounts/password_reset.html', 'email_template_name': 'accounts/password_reset_email.txt' }, name='recover'), url(r'^recover/done/$', 'password_reset_done', {'template_name': 'accounts/password_reset_done.html'}, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/password_reset_confirm.html'}, name='password-reset-confirm'), url(r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_complete.html'}), )
a4b5e6f522e3c9af502e6fbddd0dbefbae491c2e
src/server/app.py
src/server/app.py
import rumps import threading from server import CamsketchServer class CamsketchStatusBarApp(rumps.App): def __init__(self, address): super(CamsketchStatusBarApp, self).__init__("Camsketch") self.menu = [address] if __name__ == "__main__": server = CamsketchServer() threading.Thread(target=server.serve_forever).start() app = CamsketchStatusBarApp(server.address) app.run() server.shutdown()
Add status bar module to server.
Add status bar module to server.
Python
mit
pdubroy/camsketch,pdubroy/camsketch,pdubroy/camsketch,pdubroy/camsketch
<INSERT> import rumps import threading from server import CamsketchServer class CamsketchStatusBarApp(rumps.App): <INSERT_END> <INSERT> def __init__(self, address): super(CamsketchStatusBarApp, self).__init__("Camsketch") self.menu = [address] if __name__ == "__main__": server = CamsketchServer() threading.Thread(target=server.serve_forever).start() app = CamsketchStatusBarApp(server.address) app.run() server.shutdown() <INSERT_END> <|endoftext|> import rumps import threading from server import CamsketchServer class CamsketchStatusBarApp(rumps.App): def __init__(self, address): super(CamsketchStatusBarApp, self).__init__("Camsketch") self.menu = [address] if __name__ == "__main__": server = CamsketchServer() threading.Thread(target=server.serve_forever).start() app = CamsketchStatusBarApp(server.address) app.run() server.shutdown()
Add status bar module to server.
23343f0040f319f59991192636cadfd74af187af
oslo_concurrency/_i18n.py
oslo_concurrency/_i18n.py
# Copyright 2014 Mirantis Inc. # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo import i18n _translators = i18n.TranslatorFactory(domain='oslo.concurrency') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical
# Copyright 2014 Mirantis Inc. # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import oslo_i18n _translators = oslo_i18n.TranslatorFactory(domain='oslo.concurrency') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical
Drop use of namespaced oslo.i18n
Drop use of namespaced oslo.i18n Related-blueprint: drop-namespace-packages Change-Id: Ic8247cb896ba6337932d7a74618debd698584fa0
Python
apache-2.0
varunarya10/oslo.concurrency,JioCloud/oslo.concurrency
<REPLACE_OLD> License. from oslo import i18n _translators <REPLACE_NEW> License. import oslo_i18n _translators <REPLACE_END> <REPLACE_OLD> i18n.TranslatorFactory(domain='oslo.concurrency') # <REPLACE_NEW> oslo_i18n.TranslatorFactory(domain='oslo.concurrency') # <REPLACE_END> <|endoftext|> # Copyright 2014 Mirantis Inc. # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import oslo_i18n _translators = oslo_i18n.TranslatorFactory(domain='oslo.concurrency') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical
Drop use of namespaced oslo.i18n Related-blueprint: drop-namespace-packages Change-Id: Ic8247cb896ba6337932d7a74618debd698584fa0 # Copyright 2014 Mirantis Inc. # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo import i18n _translators = i18n.TranslatorFactory(domain='oslo.concurrency') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical
df0aa97de17be8b8b4d906bddf61272927009eb9
web.py
web.py
import os import requests import json from flask import Flask, jsonify, abort, make_response, request FLICKR_BASE = "http://api.flickr.com/services/rest/" app = Flask(__name__) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug=True)
import os import flickr from flask import Flask, jsonify, abort, make_response, request app = Flask(__name__) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug=True)
Add the helper to the default
Add the helper to the default
Python
mit
kyleconroy/quivr
<REPLACE_OLD> requests import json from <REPLACE_NEW> flickr from <REPLACE_END> <REPLACE_OLD> request FLICKR_BASE = "http://api.flickr.com/services/rest/" app <REPLACE_NEW> request app <REPLACE_END> <|endoftext|> import os import flickr from flask import Flask, jsonify, abort, make_response, request app = Flask(__name__) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug=True)
Add the helper to the default import os import requests import json from flask import Flask, jsonify, abort, make_response, request FLICKR_BASE = "http://api.flickr.com/services/rest/" app = Flask(__name__) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug=True)
ea7919f5e8de2d045df91fdda892757613ef3211
qregexeditor/api/quick_ref.py
qregexeditor/api/quick_ref.py
""" Contains the quick reference widget """ import re from pyqode.qt import QtWidgets from .forms import quick_ref_ui class QuickRefWidget(QtWidgets.QWidget): def __init__(self, parent=None): super(QuickRefWidget, self).__init__(parent) self.ui = quick_ref_ui.Ui_Form() self.ui.setupUi(self) self._fix_default_font_size() def _fix_default_font_size(self): # remove fixed font size to allow the user to zoom in/out using # Ctrl+Mouse Wheel # Note: Zooming into HTML documents only works if the font-size is not # set to a fixed size. # (source: http://qt-project.org/doc/qt-5/qtextedit.html) html = self.ui.textEditQuickRef.toHtml() html = re.sub('font-size:\d+pt;', '', html) self.ui.textEditQuickRef.setHtml(html)
""" Contains the quick reference widget """ import re from pyqode.qt import QtCore, QtWidgets from .forms import quick_ref_ui class QuickRefWidget(QtWidgets.QWidget): def __init__(self, parent=None): super(QuickRefWidget, self).__init__(parent) self.ui = quick_ref_ui.Ui_Form() self.ui.setupUi(self) self._fix_default_font_size() self.ui.textEditQuickRef.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) self.ui.textEditQuickRef.customContextMenuRequested.connect( self._show_context_menu) self.context_menu = self.ui.textEditQuickRef.createStandardContextMenu() self.context_menu.addSeparator() action = self.context_menu.addAction('Zoom in') action.setShortcut('Ctrl+i') action.triggered.connect(self.ui.textEditQuickRef.zoomIn) self.addAction(action) action = self.context_menu.addAction('Zoom out') action.setShortcut('Ctrl+o') self.addAction(action) action.triggered.connect(self.ui.textEditQuickRef.zoomOut) def _show_context_menu(self, pos): self.context_menu.exec_(self.ui.textEditQuickRef.mapToGlobal(pos)) def _fix_default_font_size(self): # remove fixed font size to allow the user to zoom in/out using # Ctrl+Mouse Wheel # Note: Zooming into HTML documents only works if the font-size is not # set to a fixed size. # (source: http://qt-project.org/doc/qt-5/qtextedit.html) html = self.ui.textEditQuickRef.toHtml() html = re.sub('font-size:\d+pt;', '', html) self.ui.textEditQuickRef.setHtml(html)
Add zoom in/out action to the text edit context menu
Add zoom in/out action to the text edit context menu Fix #5
Python
mit
ColinDuquesnoy/QRegexEditor
<INSERT> QtCore, <INSERT_END> <REPLACE_OLD> self._fix_default_font_size() <REPLACE_NEW> self._fix_default_font_size() self.ui.textEditQuickRef.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) self.ui.textEditQuickRef.customContextMenuRequested.connect( self._show_context_menu) self.context_menu = self.ui.textEditQuickRef.createStandardContextMenu() self.context_menu.addSeparator() action = self.context_menu.addAction('Zoom in') action.setShortcut('Ctrl+i') action.triggered.connect(self.ui.textEditQuickRef.zoomIn) self.addAction(action) action = self.context_menu.addAction('Zoom out') action.setShortcut('Ctrl+o') self.addAction(action) action.triggered.connect(self.ui.textEditQuickRef.zoomOut) def _show_context_menu(self, pos): self.context_menu.exec_(self.ui.textEditQuickRef.mapToGlobal(pos)) <REPLACE_END> <|endoftext|> """ Contains the quick reference widget """ import re from pyqode.qt import QtCore, QtWidgets from .forms import quick_ref_ui class QuickRefWidget(QtWidgets.QWidget): def __init__(self, parent=None): super(QuickRefWidget, self).__init__(parent) self.ui = quick_ref_ui.Ui_Form() self.ui.setupUi(self) self._fix_default_font_size() self.ui.textEditQuickRef.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) self.ui.textEditQuickRef.customContextMenuRequested.connect( self._show_context_menu) self.context_menu = self.ui.textEditQuickRef.createStandardContextMenu() self.context_menu.addSeparator() action = self.context_menu.addAction('Zoom in') action.setShortcut('Ctrl+i') action.triggered.connect(self.ui.textEditQuickRef.zoomIn) self.addAction(action) action = self.context_menu.addAction('Zoom out') action.setShortcut('Ctrl+o') self.addAction(action) action.triggered.connect(self.ui.textEditQuickRef.zoomOut) def _show_context_menu(self, pos): self.context_menu.exec_(self.ui.textEditQuickRef.mapToGlobal(pos)) def _fix_default_font_size(self): # remove fixed font size to allow the user to zoom in/out using # Ctrl+Mouse Wheel # Note: Zooming into HTML documents only works if the font-size is not # set to a fixed size. # (source: http://qt-project.org/doc/qt-5/qtextedit.html) html = self.ui.textEditQuickRef.toHtml() html = re.sub('font-size:\d+pt;', '', html) self.ui.textEditQuickRef.setHtml(html)
Add zoom in/out action to the text edit context menu Fix #5 """ Contains the quick reference widget """ import re from pyqode.qt import QtWidgets from .forms import quick_ref_ui class QuickRefWidget(QtWidgets.QWidget): def __init__(self, parent=None): super(QuickRefWidget, self).__init__(parent) self.ui = quick_ref_ui.Ui_Form() self.ui.setupUi(self) self._fix_default_font_size() def _fix_default_font_size(self): # remove fixed font size to allow the user to zoom in/out using # Ctrl+Mouse Wheel # Note: Zooming into HTML documents only works if the font-size is not # set to a fixed size. # (source: http://qt-project.org/doc/qt-5/qtextedit.html) html = self.ui.textEditQuickRef.toHtml() html = re.sub('font-size:\d+pt;', '', html) self.ui.textEditQuickRef.setHtml(html)
3a4e371d5d148d0171756776deffc7e5adf40197
ava/text_to_speech/__init__.py
ava/text_to_speech/__init__.py
from ..queues import QueueTtS from ..components import _BaseComponent from gtts import gTTS from playsound import playsound import os class TextToSpeech(_BaseComponent): def __init__(self): super().__init__() self.queue_tts = QueueTtS() def run(self): sentence = self.queue_tts.get() print('To say out loud : {}'.format(sentence)) # TODO change the language to match user's settings tts = gTTS(text=sentence, lang='en') tts.save("tts.mp3") playsound("tts.mp3") os.remove("tts.mp3") self.queue_tts.task_done()
from ..queues import QueueTtS from ..components import _BaseComponent from gtts import gTTS from .playsound import playsound import os class TextToSpeech(_BaseComponent): def __init__(self): super().__init__() self.queue_tts = QueueTtS() def run(self): sentence = self.queue_tts.get() print('To say out loud : {}'.format(sentence)) # TODO change the language to match user's settings tts = gTTS(text=sentence, lang='en') tts.save("tts.mp3") playsound("tts.mp3") os.remove("tts.mp3") self.queue_tts.task_done()
Add use of local playsoud.py
Add use of local playsoud.py
Python
mit
ava-project/AVA
<REPLACE_OLD> playsound <REPLACE_NEW> .playsound <REPLACE_END> <|endoftext|> from ..queues import QueueTtS from ..components import _BaseComponent from gtts import gTTS from .playsound import playsound import os class TextToSpeech(_BaseComponent): def __init__(self): super().__init__() self.queue_tts = QueueTtS() def run(self): sentence = self.queue_tts.get() print('To say out loud : {}'.format(sentence)) # TODO change the language to match user's settings tts = gTTS(text=sentence, lang='en') tts.save("tts.mp3") playsound("tts.mp3") os.remove("tts.mp3") self.queue_tts.task_done()
Add use of local playsoud.py from ..queues import QueueTtS from ..components import _BaseComponent from gtts import gTTS from playsound import playsound import os class TextToSpeech(_BaseComponent): def __init__(self): super().__init__() self.queue_tts = QueueTtS() def run(self): sentence = self.queue_tts.get() print('To say out loud : {}'.format(sentence)) # TODO change the language to match user's settings tts = gTTS(text=sentence, lang='en') tts.save("tts.mp3") playsound("tts.mp3") os.remove("tts.mp3") self.queue_tts.task_done()
7938589c950b9b36d215aa85224c931a080c104e
statsd/gauge.py
statsd/gauge.py
import statsd import decimal class Gauge(statsd.Client): '''Class to implement a statsd gauge ''' def send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :keyword value: The gauge value to send ''' assert isinstance(value, (int, long, float, decimal.Decimal)) name = self._get_name(self.name, subname) self.logger.info('%s: %s', name, value) return statsd.Client._send(self, {name: '%s|g' % value})
import statsd from . import compat class Gauge(statsd.Client): '''Class to implement a statsd gauge ''' def send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :keyword value: The gauge value to send ''' assert isinstance(value, compat.NUM_TYPES) name = self._get_name(self.name, subname) self.logger.info('%s: %s', name, value) return statsd.Client._send(self, {name: '%s|g' % value})
Use compat.NUM_TYPES due to removal of long in py3k
Use compat.NUM_TYPES due to removal of long in py3k
Python
bsd-3-clause
wolph/python-statsd
<REPLACE_OLD> statsd import decimal class <REPLACE_NEW> statsd from . import compat class <REPLACE_END> <REPLACE_OLD> (int, long, float, decimal.Decimal)) <REPLACE_NEW> compat.NUM_TYPES) <REPLACE_END> <|endoftext|> import statsd from . import compat class Gauge(statsd.Client): '''Class to implement a statsd gauge ''' def send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :keyword value: The gauge value to send ''' assert isinstance(value, compat.NUM_TYPES) name = self._get_name(self.name, subname) self.logger.info('%s: %s', name, value) return statsd.Client._send(self, {name: '%s|g' % value})
Use compat.NUM_TYPES due to removal of long in py3k import statsd import decimal class Gauge(statsd.Client): '''Class to implement a statsd gauge ''' def send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :keyword value: The gauge value to send ''' assert isinstance(value, (int, long, float, decimal.Decimal)) name = self._get_name(self.name, subname) self.logger.info('%s: %s', name, value) return statsd.Client._send(self, {name: '%s|g' % value})
c1756ab481f3bf72ab33465c8eb1d5a3e729ce4e
model_logging/migrations/0003_data_migration.py
model_logging/migrations/0003_data_migration.py
# -*- coding: utf-8 -*- from django.db import migrations app = 'model_logging' model = 'LogEntry' def move_data(apps, schema_editor): LogEntry = apps.get_model(app, model) for entry in LogEntry.objects.all(): entry.data_temp = entry.data entry.save() class Migration(migrations.Migration): dependencies = [ ('model_logging', '0002_add_new_data_field'), ] operations = [ migrations.RunPython(move_data), ]
# -*- coding: utf-8 -*- from django.db import migrations app = 'model_logging' model = 'LogEntry' def move_data(apps, schema_editor): try: from pgcrypto.fields import TextPGPPublicKeyField except ImportError: raise ImportError('Please install django-pgcrypto-fields to perform migration') LogEntry = apps.get_model(app, model) for entry in LogEntry.objects.all(): entry.data_temp = entry.data entry.save() class Migration(migrations.Migration): dependencies = [ ('model_logging', '0002_add_new_data_field'), ] operations = [ migrations.RunPython(move_data), ]
Add try, catch statement to ensure data migration can be performed.
Add try, catch statement to ensure data migration can be performed.
Python
bsd-2-clause
incuna/django-model-logging
<INSERT> try: from pgcrypto.fields import TextPGPPublicKeyField except ImportError: raise ImportError('Please install django-pgcrypto-fields to perform migration') <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*- from django.db import migrations app = 'model_logging' model = 'LogEntry' def move_data(apps, schema_editor): try: from pgcrypto.fields import TextPGPPublicKeyField except ImportError: raise ImportError('Please install django-pgcrypto-fields to perform migration') LogEntry = apps.get_model(app, model) for entry in LogEntry.objects.all(): entry.data_temp = entry.data entry.save() class Migration(migrations.Migration): dependencies = [ ('model_logging', '0002_add_new_data_field'), ] operations = [ migrations.RunPython(move_data), ]
Add try, catch statement to ensure data migration can be performed. # -*- coding: utf-8 -*- from django.db import migrations app = 'model_logging' model = 'LogEntry' def move_data(apps, schema_editor): LogEntry = apps.get_model(app, model) for entry in LogEntry.objects.all(): entry.data_temp = entry.data entry.save() class Migration(migrations.Migration): dependencies = [ ('model_logging', '0002_add_new_data_field'), ] operations = [ migrations.RunPython(move_data), ]
dbf39babaacc8c6407620b7d6d6e5cb568a99940
conf_site/proposals/migrations/0003_add_disclaimer.py
conf_site/proposals/migrations/0003_add_disclaimer.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.12 on 2017-01-19 05:30 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('proposals', '0002_add_under_represented_population_questions'), ] operations = [ migrations.AlterField( model_name='proposal', name='under_represented_population', field=models.CharField(choices=[(b'', b'----'), (b'Y', b'Yes'), (b'N', b'No'), (b'O', b'I would prefer not to answer')], default=b'', max_length=1, verbose_name=b"Do you feel that you or your talk represent a population under-represented in the Python and/or Data community? In no way will this data be used as part of your proposal. This will only be used to gather diversity statistics in order to further NumFOCUS' mission."), ), ]
Add missing migration from proposals application.
Add missing migration from proposals application. See e4b9588275dda17a70ba13fc3997b7dc20f66f57.
Python
mit
pydata/conf_site,pydata/conf_site,pydata/conf_site
<INSERT> # -*- coding: utf-8 -*- # Generated by Django 1.9.12 on 2017-01-19 05:30 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): <INSERT_END> <INSERT> dependencies = [ ('proposals', '0002_add_under_represented_population_questions'), ] operations = [ migrations.AlterField( model_name='proposal', name='under_represented_population', field=models.CharField(choices=[(b'', b'----'), (b'Y', b'Yes'), (b'N', b'No'), (b'O', b'I would prefer not to answer')], default=b'', max_length=1, verbose_name=b"Do you feel that you or your talk represent a population under-represented in the Python and/or Data community? In no way will this data be used as part of your proposal. This will only be used to gather diversity statistics in order to further NumFOCUS' mission."), ), ] <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*- # Generated by Django 1.9.12 on 2017-01-19 05:30 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('proposals', '0002_add_under_represented_population_questions'), ] operations = [ migrations.AlterField( model_name='proposal', name='under_represented_population', field=models.CharField(choices=[(b'', b'----'), (b'Y', b'Yes'), (b'N', b'No'), (b'O', b'I would prefer not to answer')], default=b'', max_length=1, verbose_name=b"Do you feel that you or your talk represent a population under-represented in the Python and/or Data community? In no way will this data be used as part of your proposal. This will only be used to gather diversity statistics in order to further NumFOCUS' mission."), ), ]
Add missing migration from proposals application. See e4b9588275dda17a70ba13fc3997b7dc20f66f57.
4aced6fea8ff8ccd087362cb237a9f00d111d0d8
corehq/apps/commtrack/management/commands/toggle_locations.py
corehq/apps/commtrack/management/commands/toggle_locations.py
from django.core.management.base import BaseCommand from corehq.apps.domain.models import Domain from corehq.feature_previews import LOCATIONS from corehq.toggles import NAMESPACE_DOMAIN from toggle.shortcuts import update_toggle_cache, namespaced_item from toggle.models import Toggle class Command(BaseCommand): def handle(self, *args, **options): domains = Domain.get_all() for domain in domains: if domain.commtrack_enabled: toggle = Toggle.get(LOCATIONS.slug) toggle_user_key = namespaced_item(domain.name, NAMESPACE_DOMAIN) if toggle_user_key not in toggle.enabled_users: toggle.enabled_users.append(toggle_user_key) toggle.save() update_toggle_cache(LOCATIONS.slug, toggle_user_key, True) if not domain.locations_enabled: domain.locations_enabled = True domain.save()
Add command to turn on locations flag
Add command to turn on locations flag
Python
bsd-3-clause
dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq
<REPLACE_OLD> <REPLACE_NEW> from django.core.management.base import BaseCommand from corehq.apps.domain.models import Domain from corehq.feature_previews import LOCATIONS from corehq.toggles import NAMESPACE_DOMAIN from toggle.shortcuts import update_toggle_cache, namespaced_item from toggle.models import Toggle class Command(BaseCommand): def handle(self, *args, **options): domains = Domain.get_all() for domain in domains: if domain.commtrack_enabled: toggle = Toggle.get(LOCATIONS.slug) toggle_user_key = namespaced_item(domain.name, NAMESPACE_DOMAIN) if toggle_user_key not in toggle.enabled_users: toggle.enabled_users.append(toggle_user_key) toggle.save() update_toggle_cache(LOCATIONS.slug, toggle_user_key, True) if not domain.locations_enabled: domain.locations_enabled = True domain.save() <REPLACE_END> <|endoftext|> from django.core.management.base import BaseCommand from corehq.apps.domain.models import Domain from corehq.feature_previews import LOCATIONS from corehq.toggles import NAMESPACE_DOMAIN from toggle.shortcuts import update_toggle_cache, namespaced_item from toggle.models import Toggle class Command(BaseCommand): def handle(self, *args, **options): domains = Domain.get_all() for domain in domains: if domain.commtrack_enabled: toggle = Toggle.get(LOCATIONS.slug) toggle_user_key = namespaced_item(domain.name, NAMESPACE_DOMAIN) if toggle_user_key not in toggle.enabled_users: toggle.enabled_users.append(toggle_user_key) toggle.save() update_toggle_cache(LOCATIONS.slug, toggle_user_key, True) if not domain.locations_enabled: domain.locations_enabled = True domain.save()
Add command to turn on locations flag
d8247d43c8026a8de39b09856a3f7beb235dc4f6
antxetamedia/multimedia/handlers.py
antxetamedia/multimedia/handlers.py
from boto.s3.connection import S3Connection from boto.exception import S3ResponseError from django.conf import settings def upload(user, passwd, bucket, metadata, key, fd): conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False) while bucket.endswith('-'): bucket = bucket[:-1] try: bucket = conn.get_bucket(bucket) except S3ResponseError: try: bucket = conn.create_bucket(bucket, headers=metadata) except (S3ResponseError, UnicodeDecodeError): bucket = conn.create_bucket(bucket) key = bucket.new_key(key) try: key.set_contents_from_file(fd) except S3ResponseError: key.set_contents_from_file(fd) return key.generate_url(0).split('?')[0]
from boto.s3.connection import S3Connection from boto.s3.bucket import Bucket from boto.exception import S3ResponseError, S3CreateError from django.conf import settings def upload(user, passwd, bucket, metadata, key, fd): conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False) while bucket.endswith('-'): bucket = bucket[:-1] try: bucket = conn.get_bucket(bucket) except S3ResponseError: try: bucket = conn.create_bucket(bucket, headers=metadata) except (S3ResponseError, UnicodeDecodeError): bucket = conn.create_bucket(bucket) except S3CreateError as e: if e.status == 409: bucket = Bucket(conn, bucket) key = bucket.new_key(key) try: key.set_contents_from_file(fd) except S3ResponseError: key.set_contents_from_file(fd) return key.generate_url(0).split('?')[0]
Handle the case where the bucket already exists
Handle the case where the bucket already exists
Python
agpl-3.0
GISAElkartea/antxetamedia,GISAElkartea/antxetamedia,GISAElkartea/antxetamedia
<INSERT> boto.s3.bucket import Bucket from <INSERT_END> <REPLACE_OLD> S3ResponseError from <REPLACE_NEW> S3ResponseError, S3CreateError from <REPLACE_END> <REPLACE_OLD> settings def <REPLACE_NEW> settings def <REPLACE_END> <REPLACE_OLD> conn.create_bucket(bucket) <REPLACE_NEW> conn.create_bucket(bucket) except S3CreateError as e: if e.status == 409: bucket = Bucket(conn, bucket) <REPLACE_END> <|endoftext|> from boto.s3.connection import S3Connection from boto.s3.bucket import Bucket from boto.exception import S3ResponseError, S3CreateError from django.conf import settings def upload(user, passwd, bucket, metadata, key, fd): conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False) while bucket.endswith('-'): bucket = bucket[:-1] try: bucket = conn.get_bucket(bucket) except S3ResponseError: try: bucket = conn.create_bucket(bucket, headers=metadata) except (S3ResponseError, UnicodeDecodeError): bucket = conn.create_bucket(bucket) except S3CreateError as e: if e.status == 409: bucket = Bucket(conn, bucket) key = bucket.new_key(key) try: key.set_contents_from_file(fd) except S3ResponseError: key.set_contents_from_file(fd) return key.generate_url(0).split('?')[0]
Handle the case where the bucket already exists from boto.s3.connection import S3Connection from boto.exception import S3ResponseError from django.conf import settings def upload(user, passwd, bucket, metadata, key, fd): conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False) while bucket.endswith('-'): bucket = bucket[:-1] try: bucket = conn.get_bucket(bucket) except S3ResponseError: try: bucket = conn.create_bucket(bucket, headers=metadata) except (S3ResponseError, UnicodeDecodeError): bucket = conn.create_bucket(bucket) key = bucket.new_key(key) try: key.set_contents_from_file(fd) except S3ResponseError: key.set_contents_from_file(fd) return key.generate_url(0).split('?')[0]
8322c776fe989d65f83beaefff5089716d0286e7
test/test_pydh.py
test/test_pydh.py
import pyDH def test_pydh_keygen(): d1 = pyDH.DiffieHellman() d2 = pyDH.DiffieHellman() d1_pubkey = d1.gen_public_key() d2_pubkey = d2.gen_public_key() d1_sharedkey = d1.gen_shared_key(d2_pubkey) d2_sharedkey = d2.gen_shared_key(d1_pubkey) assert d1_sharedkey == d2_sharedkey
import sys sys.path.append('.') import pyDH def test_pydh_keygen(): d1 = pyDH.DiffieHellman() d2 = pyDH.DiffieHellman() d1_pubkey = d1.gen_public_key() d2_pubkey = d2.gen_public_key() d1_sharedkey = d1.gen_shared_key(d2_pubkey) d2_sharedkey = d2.gen_shared_key(d1_pubkey) assert d1_sharedkey == d2_sharedkey
Add current dir to Python path
Add current dir to Python path
Python
apache-2.0
amiralis/pyDH
<INSERT> sys sys.path.append('.') import <INSERT_END> <REPLACE_OLD> d2_sharedkey <REPLACE_NEW> d2_sharedkey <REPLACE_END> <|endoftext|> import sys sys.path.append('.') import pyDH def test_pydh_keygen(): d1 = pyDH.DiffieHellman() d2 = pyDH.DiffieHellman() d1_pubkey = d1.gen_public_key() d2_pubkey = d2.gen_public_key() d1_sharedkey = d1.gen_shared_key(d2_pubkey) d2_sharedkey = d2.gen_shared_key(d1_pubkey) assert d1_sharedkey == d2_sharedkey
Add current dir to Python path import pyDH def test_pydh_keygen(): d1 = pyDH.DiffieHellman() d2 = pyDH.DiffieHellman() d1_pubkey = d1.gen_public_key() d2_pubkey = d2.gen_public_key() d1_sharedkey = d1.gen_shared_key(d2_pubkey) d2_sharedkey = d2.gen_shared_key(d1_pubkey) assert d1_sharedkey == d2_sharedkey
decc454dfb50258eaab4635379b1c18470246f62
indico/modules/events/views.py
indico/modules/events/views.py
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from MaKaC.webinterface.pages.admins import WPAdminsBase from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceDefaultDisplayBase class WPReferenceTypes(WPJinjaMixin, WPAdminsBase): template_prefix = 'events/' class WPEventDisplay(WPJinjaMixin, WPConferenceDefaultDisplayBase): template_prefix = 'events/' def _getBody(self, params): return WPJinjaMixin._getPageContent(self, params) def getCSSFiles(self): return WPConferenceDefaultDisplayBase.getCSSFiles(self) + self._asset_env['event_display_sass'].urls()
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from MaKaC.webinterface.pages.admins import WPAdminsBase from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceDefaultDisplayBase class WPReferenceTypes(WPJinjaMixin, WPAdminsBase): template_prefix = 'events/' sidemenu_option = 'reference_types' class WPEventDisplay(WPJinjaMixin, WPConferenceDefaultDisplayBase): template_prefix = 'events/' def _getBody(self, params): return WPJinjaMixin._getPageContent(self, params) def getCSSFiles(self): return WPConferenceDefaultDisplayBase.getCSSFiles(self) + self._asset_env['event_display_sass'].urls()
Fix highlighting of "External ID Types" menu entry
Fix highlighting of "External ID Types" menu entry
Python
mit
ThiefMaster/indico,pferreir/indico,mic4ael/indico,ThiefMaster/indico,DirkHoffmann/indico,ThiefMaster/indico,OmeGak/indico,mic4ael/indico,indico/indico,DirkHoffmann/indico,mvidalgarcia/indico,mvidalgarcia/indico,pferreir/indico,OmeGak/indico,OmeGak/indico,mic4ael/indico,mic4ael/indico,indico/indico,DirkHoffmann/indico,indico/indico,ThiefMaster/indico,DirkHoffmann/indico,OmeGak/indico,mvidalgarcia/indico,indico/indico,pferreir/indico,pferreir/indico,mvidalgarcia/indico
<REPLACE_OLD> 'events/' class <REPLACE_NEW> 'events/' sidemenu_option = 'reference_types' class <REPLACE_END> <|endoftext|> # This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from MaKaC.webinterface.pages.admins import WPAdminsBase from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceDefaultDisplayBase class WPReferenceTypes(WPJinjaMixin, WPAdminsBase): template_prefix = 'events/' sidemenu_option = 'reference_types' class WPEventDisplay(WPJinjaMixin, WPConferenceDefaultDisplayBase): template_prefix = 'events/' def _getBody(self, params): return WPJinjaMixin._getPageContent(self, params) def getCSSFiles(self): return WPConferenceDefaultDisplayBase.getCSSFiles(self) + self._asset_env['event_display_sass'].urls()
Fix highlighting of "External ID Types" menu entry # This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from MaKaC.webinterface.pages.admins import WPAdminsBase from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceDefaultDisplayBase class WPReferenceTypes(WPJinjaMixin, WPAdminsBase): template_prefix = 'events/' class WPEventDisplay(WPJinjaMixin, WPConferenceDefaultDisplayBase): template_prefix = 'events/' def _getBody(self, params): return WPJinjaMixin._getPageContent(self, params) def getCSSFiles(self): return WPConferenceDefaultDisplayBase.getCSSFiles(self) + self._asset_env['event_display_sass'].urls()
07bcbe76f33cb4354cb90744f46c5528169183e3
launch_pyslvs.py
launch_pyslvs.py
# -*- coding: utf-8 -*- ##Pyslvs - Dimensional Synthesis of Planar Four-bar Linkages in PyQt5 GUI. ##Copyright (C) 2016 Yuan Chang [[email protected]] from sys import exit if __name__=='__main__': try: from core.info.info import show_info, Pyslvs_Splash args = show_info() from PyQt5.QtWidgets import QApplication from core.main import MainWindow if args.fusion: QApplication.setStyle('fusion') app = QApplication(list(vars(args).values())) splash = Pyslvs_Splash() splash.show() run = MainWindow(args) run.show() splash.finish(run) exit(app.exec()) except Exception as e: if e!=SystemExit: import logging logging.basicConfig(filename='PyslvsLogFile.log', filemode='w', format='%(asctime)s | %(message)s', level=logging.INFO) logging.exception("Exception Happened.") print("Exception Happened. Please check the log file.") exit(1)
# -*- coding: utf-8 -*- ##Pyslvs - Dimensional Synthesis of Planar Four-bar Linkages in PyQt5 GUI. ##Copyright (C) 2016 Yuan Chang [[email protected]] from sys import exit if __name__=='__main__': try: from core.info.info import show_info, Pyslvs_Splash args = show_info() from PyQt5.QtWidgets import QApplication from core.main import MainWindow if args.fusion: QApplication.setStyle('fusion') app = QApplication(list(vars(args).values())) splash = Pyslvs_Splash() splash.show() run = MainWindow(args) run.show() splash.finish(run) exit(app.exec()) except Exception as e: if e!=SystemExit: import logging logging.basicConfig(filename='PyslvsLogFile.log', filemode='w', format='%(asctime)s | %(message)s', level=logging.INFO) logging.exception("Exception Happened.") print('{}\n{}'.format(type(e), e)) exit(1)
Change the Error show in command window.
Change the Error show in command window.
Python
agpl-3.0
40323230/Pyslvs-PyQt5,KmolYuan/Pyslvs-PyQt5,KmolYuan/Pyslvs-PyQt5
<REPLACE_OLD> print("Exception Happened. Please check the log file.") <REPLACE_NEW> print('{}\n{}'.format(type(e), e)) <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*- ##Pyslvs - Dimensional Synthesis of Planar Four-bar Linkages in PyQt5 GUI. ##Copyright (C) 2016 Yuan Chang [[email protected]] from sys import exit if __name__=='__main__': try: from core.info.info import show_info, Pyslvs_Splash args = show_info() from PyQt5.QtWidgets import QApplication from core.main import MainWindow if args.fusion: QApplication.setStyle('fusion') app = QApplication(list(vars(args).values())) splash = Pyslvs_Splash() splash.show() run = MainWindow(args) run.show() splash.finish(run) exit(app.exec()) except Exception as e: if e!=SystemExit: import logging logging.basicConfig(filename='PyslvsLogFile.log', filemode='w', format='%(asctime)s | %(message)s', level=logging.INFO) logging.exception("Exception Happened.") print('{}\n{}'.format(type(e), e)) exit(1)
Change the Error show in command window. # -*- coding: utf-8 -*- ##Pyslvs - Dimensional Synthesis of Planar Four-bar Linkages in PyQt5 GUI. ##Copyright (C) 2016 Yuan Chang [[email protected]] from sys import exit if __name__=='__main__': try: from core.info.info import show_info, Pyslvs_Splash args = show_info() from PyQt5.QtWidgets import QApplication from core.main import MainWindow if args.fusion: QApplication.setStyle('fusion') app = QApplication(list(vars(args).values())) splash = Pyslvs_Splash() splash.show() run = MainWindow(args) run.show() splash.finish(run) exit(app.exec()) except Exception as e: if e!=SystemExit: import logging logging.basicConfig(filename='PyslvsLogFile.log', filemode='w', format='%(asctime)s | %(message)s', level=logging.INFO) logging.exception("Exception Happened.") print("Exception Happened. Please check the log file.") exit(1)
8180c84a98bec11308afca884a4d7fed4738403b
spacy/tests/test_align.py
spacy/tests/test_align.py
import pytest from .._align import align @pytest.mark.parametrize('string1,string2,cost', [ (b'hello', b'hell', 1), (b'rat', b'cat', 1), (b'rat', b'rat', 0), (b'rat', b'catsie', 4), (b't', b'catsie', 5), ]) def test_align_costs(string1, string2, cost): output_cost, i2j, j2i, matrix = align(string1, string2) assert output_cost == cost @pytest.mark.parametrize('string1,string2,i2j', [ (b'hello', b'hell', [0,1,2,3,-1]), (b'rat', b'cat', [0,1,2]), (b'rat', b'rat', [0,1,2]), (b'rat', b'catsie', [0,1,2]), (b't', b'catsie', [2]), ]) def test_align_i2j(string1, string2, i2j): output_cost, output_i2j, j2i, matrix = align(string1, string2) assert list(output_i2j) == i2j @pytest.mark.parametrize('string1,string2,j2i', [ (b'hello', b'hell', [0,1,2,3]), (b'rat', b'cat', [0,1,2]), (b'rat', b'rat', [0,1,2]), (b'rat', b'catsie', [0,1,2, -1, -1, -1]), (b't', b'catsie', [-1, -1, 0, -1, -1, -1]), ]) def test_align_i2j(string1, string2, j2i): output_cost, output_i2j, output_j2i, matrix = align(string1, string2) assert list(output_j2i) == j2i
Add tests for new Levenshtein alignment
Add tests for new Levenshtein alignment
Python
mit
explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,honnibal/spaCy,recognai/spaCy,spacy-io/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,honnibal/spaCy,aikramer2/spaCy,spacy-io/spaCy,spacy-io/spaCy,aikramer2/spaCy,aikramer2/spaCy,honnibal/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,aikramer2/spaCy
<INSERT> import pytest from .._align import align @pytest.mark.parametrize('string1,string2,cost', [ <INSERT_END> <INSERT> (b'hello', b'hell', 1), (b'rat', b'cat', 1), (b'rat', b'rat', 0), (b'rat', b'catsie', 4), (b't', b'catsie', 5), ]) def test_align_costs(string1, string2, cost): output_cost, i2j, j2i, matrix = align(string1, string2) assert output_cost == cost @pytest.mark.parametrize('string1,string2,i2j', [ (b'hello', b'hell', [0,1,2,3,-1]), (b'rat', b'cat', [0,1,2]), (b'rat', b'rat', [0,1,2]), (b'rat', b'catsie', [0,1,2]), (b't', b'catsie', [2]), ]) def test_align_i2j(string1, string2, i2j): output_cost, output_i2j, j2i, matrix = align(string1, string2) assert list(output_i2j) == i2j @pytest.mark.parametrize('string1,string2,j2i', [ (b'hello', b'hell', [0,1,2,3]), (b'rat', b'cat', [0,1,2]), (b'rat', b'rat', [0,1,2]), (b'rat', b'catsie', [0,1,2, -1, -1, -1]), (b't', b'catsie', [-1, -1, 0, -1, -1, -1]), ]) def test_align_i2j(string1, string2, j2i): output_cost, output_i2j, output_j2i, matrix = align(string1, string2) assert list(output_j2i) == j2i <INSERT_END> <|endoftext|> import pytest from .._align import align @pytest.mark.parametrize('string1,string2,cost', [ (b'hello', b'hell', 1), (b'rat', b'cat', 1), (b'rat', b'rat', 0), (b'rat', b'catsie', 4), (b't', b'catsie', 5), ]) def test_align_costs(string1, string2, cost): output_cost, i2j, j2i, matrix = align(string1, string2) assert output_cost == cost @pytest.mark.parametrize('string1,string2,i2j', [ (b'hello', b'hell', [0,1,2,3,-1]), (b'rat', b'cat', [0,1,2]), (b'rat', b'rat', [0,1,2]), (b'rat', b'catsie', [0,1,2]), (b't', b'catsie', [2]), ]) def test_align_i2j(string1, string2, i2j): output_cost, output_i2j, j2i, matrix = align(string1, string2) assert list(output_i2j) == i2j @pytest.mark.parametrize('string1,string2,j2i', [ (b'hello', b'hell', [0,1,2,3]), (b'rat', b'cat', [0,1,2]), (b'rat', b'rat', [0,1,2]), (b'rat', b'catsie', [0,1,2, -1, -1, -1]), (b't', b'catsie', [-1, -1, 0, -1, -1, -1]), ]) def test_align_i2j(string1, string2, j2i): output_cost, output_i2j, output_j2i, matrix = align(string1, string2) assert list(output_j2i) == j2i
Add tests for new Levenshtein alignment
49e89bee4a7c5e241402766072ae60697c136ca6
guild/__init__.py
guild/__init__.py
import os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs()
import os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") if raw else [] def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs()
Fix to git status info
Fix to git status info
Python
apache-2.0
guildai/guild,guildai/guild,guildai/guild,guildai/guild
<REPLACE_OLD> raw.split("\n") def <REPLACE_NEW> raw.split("\n") if raw else [] def <REPLACE_END> <|endoftext|> import os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") if raw else [] def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs()
Fix to git status info import os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs()
d4c8b0f15cd1694b84f8dab7936571d9f9bca42f
tests/people/test_managers.py
tests/people/test_managers.py
import pytest from components.people.factories import IdolFactory from components.people.models import Idol from components.people.constants import STATUS pytestmark = pytest.mark.django_db class TestIdols: @pytest.fixture def idols(self): idols = [] [idols.append(IdolFactory(status=STATUS.active)) for i in xrange(3)] [idols.append(IdolFactory(status=STATUS.former)) for i in xrange(2)] return idols def test_active_manager(self, idols): assert len(Idol.objects.active()) == 3 def test_inactive_manager(self, idols): assert len(Idol.objects.inactive()) == 2
# -*- coding: utf-8 -*- import datetime import pytest from components.people.constants import STATUS from components.people.factories import GroupFactory, IdolFactory from components.people.models import Group, Idol pytestmark = pytest.mark.django_db class TestIdols: @pytest.fixture def status(self): idols = [] [idols.append(IdolFactory(status=STATUS.active)) for i in xrange(3)] [idols.append(IdolFactory(status=STATUS.former)) for i in xrange(2)] return idols def test_active_manager(self, status): assert len(Idol.objects.active()) == 3 def test_inactive_manager(self, status): assert len(Idol.objects.inactive()) == 2 class TestGroups: @pytest.fixture def status(self): groups = [ GroupFactory(), GroupFactory(ended=datetime.date.today() + datetime.timedelta(days=30)), GroupFactory(ended=datetime.date.today() - datetime.timedelta(days=30)) ] return groups def test_active_manager(self, status): assert len(Group.objects.active()) == 2 def test_inactive_manager(self, status): assert len(Group.objects.inactive()) == 1
Test group managers. Rename idols() => status().
Test group managers. Rename idols() => status().
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
<INSERT> # -*- coding: utf-8 -*- import datetime import pytest from components.people.constants <INSERT_END> <REPLACE_OLD> pytest from <REPLACE_NEW> STATUS from <REPLACE_END> <INSERT> GroupFactory, <INSERT_END> <REPLACE_OLD> Idol from components.people.constants import STATUS pytestmark <REPLACE_NEW> Group, Idol pytestmark <REPLACE_END> <REPLACE_OLD> idols(self): <REPLACE_NEW> status(self): <REPLACE_END> <REPLACE_OLD> idols): <REPLACE_NEW> status): <REPLACE_END> <REPLACE_OLD> idols): <REPLACE_NEW> status): <REPLACE_END> <REPLACE_OLD> 2 <REPLACE_NEW> 2 class TestGroups: @pytest.fixture def status(self): groups = [ GroupFactory(), GroupFactory(ended=datetime.date.today() + datetime.timedelta(days=30)), GroupFactory(ended=datetime.date.today() - datetime.timedelta(days=30)) ] return groups def test_active_manager(self, status): assert len(Group.objects.active()) == 2 def test_inactive_manager(self, status): assert len(Group.objects.inactive()) == 1 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*- import datetime import pytest from components.people.constants import STATUS from components.people.factories import GroupFactory, IdolFactory from components.people.models import Group, Idol pytestmark = pytest.mark.django_db class TestIdols: @pytest.fixture def status(self): idols = [] [idols.append(IdolFactory(status=STATUS.active)) for i in xrange(3)] [idols.append(IdolFactory(status=STATUS.former)) for i in xrange(2)] return idols def test_active_manager(self, status): assert len(Idol.objects.active()) == 3 def test_inactive_manager(self, status): assert len(Idol.objects.inactive()) == 2 class TestGroups: @pytest.fixture def status(self): groups = [ GroupFactory(), GroupFactory(ended=datetime.date.today() + datetime.timedelta(days=30)), GroupFactory(ended=datetime.date.today() - datetime.timedelta(days=30)) ] return groups def test_active_manager(self, status): assert len(Group.objects.active()) == 2 def test_inactive_manager(self, status): assert len(Group.objects.inactive()) == 1
Test group managers. Rename idols() => status(). import pytest from components.people.factories import IdolFactory from components.people.models import Idol from components.people.constants import STATUS pytestmark = pytest.mark.django_db class TestIdols: @pytest.fixture def idols(self): idols = [] [idols.append(IdolFactory(status=STATUS.active)) for i in xrange(3)] [idols.append(IdolFactory(status=STATUS.former)) for i in xrange(2)] return idols def test_active_manager(self, idols): assert len(Idol.objects.active()) == 3 def test_inactive_manager(self, idols): assert len(Idol.objects.inactive()) == 2
0b6cdcf91783e562d1da230e7658ba43b6ed5543
tests/test_unicode.py
tests/test_unicode.py
# coding: utf-8 import logging import os import shutil import sys import tempfile import unittest import six import fiona logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) class UnicodePathTest(unittest.TestCase): def setUp(self): tempdir = tempfile.mkdtemp() self.dir = os.path.join(tempdir, 'français') shutil.copytree('docs/data/', self.dir) def tearDown(self): shutil.rmtree(self.dir) def test_unicode_path(self): path = self.dir + '/test_uk.shp' if sys.version_info < (3,): path = path.decode('utf-8') with fiona.open(path) as c: assert len(c) == 48 def test_unicode_path_layer(self): path = self.dir layer = 'test_uk' if sys.version_info < (3,): path = path.decode('utf-8') layer = layer.decode('utf-8') with fiona.open(path, layer=layer) as c: assert len(c) == 48 def test_utf8_path(self): path = self.dir + '/test_uk.shp' if sys.version_info < (3,): with fiona.open(path) as c: assert len(c) == 48
# coding: utf-8 import logging import os import shutil import sys import tempfile import unittest import six import fiona logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) class UnicodePathTest(unittest.TestCase): def setUp(self): tempdir = tempfile.mkdtemp() self.dir = os.path.join(tempdir, 'français') shutil.copytree('docs/data/', self.dir) def tearDown(self): shutil.rmtree(os.path.dirname(self.dir)) def test_unicode_path(self): path = self.dir + '/test_uk.shp' if sys.version_info < (3,): path = path.decode('utf-8') with fiona.open(path) as c: assert len(c) == 48 def test_unicode_path_layer(self): path = self.dir layer = 'test_uk' if sys.version_info < (3,): path = path.decode('utf-8') layer = layer.decode('utf-8') with fiona.open(path, layer=layer) as c: assert len(c) == 48 def test_utf8_path(self): path = self.dir + '/test_uk.shp' if sys.version_info < (3,): with fiona.open(path) as c: assert len(c) == 48
Clean up parent temporary directory
TST: Clean up parent temporary directory
Python
bsd-3-clause
johanvdw/Fiona,rbuffat/Fiona,Toblerity/Fiona,perrygeo/Fiona,rbuffat/Fiona,Toblerity/Fiona,perrygeo/Fiona
<REPLACE_OLD> shutil.rmtree(self.dir) <REPLACE_NEW> shutil.rmtree(os.path.dirname(self.dir)) <REPLACE_END> <|endoftext|> # coding: utf-8 import logging import os import shutil import sys import tempfile import unittest import six import fiona logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) class UnicodePathTest(unittest.TestCase): def setUp(self): tempdir = tempfile.mkdtemp() self.dir = os.path.join(tempdir, 'français') shutil.copytree('docs/data/', self.dir) def tearDown(self): shutil.rmtree(os.path.dirname(self.dir)) def test_unicode_path(self): path = self.dir + '/test_uk.shp' if sys.version_info < (3,): path = path.decode('utf-8') with fiona.open(path) as c: assert len(c) == 48 def test_unicode_path_layer(self): path = self.dir layer = 'test_uk' if sys.version_info < (3,): path = path.decode('utf-8') layer = layer.decode('utf-8') with fiona.open(path, layer=layer) as c: assert len(c) == 48 def test_utf8_path(self): path = self.dir + '/test_uk.shp' if sys.version_info < (3,): with fiona.open(path) as c: assert len(c) == 48
TST: Clean up parent temporary directory # coding: utf-8 import logging import os import shutil import sys import tempfile import unittest import six import fiona logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) class UnicodePathTest(unittest.TestCase): def setUp(self): tempdir = tempfile.mkdtemp() self.dir = os.path.join(tempdir, 'français') shutil.copytree('docs/data/', self.dir) def tearDown(self): shutil.rmtree(self.dir) def test_unicode_path(self): path = self.dir + '/test_uk.shp' if sys.version_info < (3,): path = path.decode('utf-8') with fiona.open(path) as c: assert len(c) == 48 def test_unicode_path_layer(self): path = self.dir layer = 'test_uk' if sys.version_info < (3,): path = path.decode('utf-8') layer = layer.decode('utf-8') with fiona.open(path, layer=layer) as c: assert len(c) == 48 def test_utf8_path(self): path = self.dir + '/test_uk.shp' if sys.version_info < (3,): with fiona.open(path) as c: assert len(c) == 48
3450712ec629c1720b6a6af28835d95a91b8fce7
setup.py
setup.py
#!/usr/bin/python import os import re from setuptools import setup from m2r import parse_from_file import restructuredtext_lint # Parser README.md into reStructuredText format rst_readme = parse_from_file('README.md') # Validate the README, checking for errors errors = restructuredtext_lint.lint(rst_readme) # Raise an exception for any errors found if errors: print(rst_readme) raise ValueError('README.md contains errors: ', ', '.join([e.message for e in errors])) # Attempt to get version number from TravisCI environment variable version = os.environ.get('TRAVIS_TAG', default='0.0.0') # Remove leading 'v' version = re.sub('^v', '', version) setup( name='anybadge', description='Simple, flexible badge generator for project badges.', long_description=rst_readme, version=version, author='Jon Grace-Cox', author_email='[email protected]', py_modules=['anybadge', 'anybadge_server'], setup_requires=['setuptools', 'wheel'], tests_require=['unittest'], install_requires=[], data_files=[], options={ 'bdist_wheel': {'universal': True} }, url='https://github.com/jongracecox/anybadge', entry_points={ 'console_scripts': ['anybadge=anybadge:main', 'anybadge-server=anybadge_server:main'], } )
#!/usr/bin/python import os import re from setuptools import setup from m2r import parse_from_file import restructuredtext_lint # Parser README.md into reStructuredText format rst_readme = parse_from_file('README.md') # Validate the README, checking for errors errors = restructuredtext_lint.lint(rst_readme) # Raise an exception for any errors found if errors: print(rst_readme) raise ValueError('README.md contains errors: ', ', '.join([e.message for e in errors])) # Attempt to get version number from TravisCI environment variable version = os.environ.get('TRAVIS_TAG', default='0.0.0') # Remove leading 'v' version = re.sub('^v', '', version) setup( name='anybadge', description='Simple, flexible badge generator for project badges.', long_description=rst_readme, version=version, author='Jon Grace-Cox', author_email='[email protected]', py_modules=['anybadge', 'anybadge_server'], setup_requires=['setuptools', 'wheel'], tests_require=['unittest'], install_requires=[], data_files=[], options={ 'bdist_wheel': {'universal': True} }, url='https://github.com/jongracecox/anybadge', entry_points={ 'console_scripts': ['anybadge=anybadge:main', 'anybadge-server=anybadge_server:main'], }, classifiers=[ 'License :: OSI Approved :: MIT License' ] )
Use classifiers to specify the license.
Use classifiers to specify the license. Classifiers are a standard way of specifying a license, and make it easy for automated tools to properly detect the license of the package. The "license" field should only be used if the license has no corresponding Trove classifier.
Python
mit
jongracecox/anybadge,jongracecox/anybadge
<REPLACE_OLD> } ) <REPLACE_NEW> }, classifiers=[ 'License :: OSI Approved :: MIT License' ] ) <REPLACE_END> <|endoftext|> #!/usr/bin/python import os import re from setuptools import setup from m2r import parse_from_file import restructuredtext_lint # Parser README.md into reStructuredText format rst_readme = parse_from_file('README.md') # Validate the README, checking for errors errors = restructuredtext_lint.lint(rst_readme) # Raise an exception for any errors found if errors: print(rst_readme) raise ValueError('README.md contains errors: ', ', '.join([e.message for e in errors])) # Attempt to get version number from TravisCI environment variable version = os.environ.get('TRAVIS_TAG', default='0.0.0') # Remove leading 'v' version = re.sub('^v', '', version) setup( name='anybadge', description='Simple, flexible badge generator for project badges.', long_description=rst_readme, version=version, author='Jon Grace-Cox', author_email='[email protected]', py_modules=['anybadge', 'anybadge_server'], setup_requires=['setuptools', 'wheel'], tests_require=['unittest'], install_requires=[], data_files=[], options={ 'bdist_wheel': {'universal': True} }, url='https://github.com/jongracecox/anybadge', entry_points={ 'console_scripts': ['anybadge=anybadge:main', 'anybadge-server=anybadge_server:main'], }, classifiers=[ 'License :: OSI Approved :: MIT License' ] )
Use classifiers to specify the license. Classifiers are a standard way of specifying a license, and make it easy for automated tools to properly detect the license of the package. The "license" field should only be used if the license has no corresponding Trove classifier. #!/usr/bin/python import os import re from setuptools import setup from m2r import parse_from_file import restructuredtext_lint # Parser README.md into reStructuredText format rst_readme = parse_from_file('README.md') # Validate the README, checking for errors errors = restructuredtext_lint.lint(rst_readme) # Raise an exception for any errors found if errors: print(rst_readme) raise ValueError('README.md contains errors: ', ', '.join([e.message for e in errors])) # Attempt to get version number from TravisCI environment variable version = os.environ.get('TRAVIS_TAG', default='0.0.0') # Remove leading 'v' version = re.sub('^v', '', version) setup( name='anybadge', description='Simple, flexible badge generator for project badges.', long_description=rst_readme, version=version, author='Jon Grace-Cox', author_email='[email protected]', py_modules=['anybadge', 'anybadge_server'], setup_requires=['setuptools', 'wheel'], tests_require=['unittest'], install_requires=[], data_files=[], options={ 'bdist_wheel': {'universal': True} }, url='https://github.com/jongracecox/anybadge', entry_points={ 'console_scripts': ['anybadge=anybadge:main', 'anybadge-server=anybadge_server:main'], } )
0636d474764c1dd6f795ebf5c4f73e2a101ae023
correlations/server.py
correlations/server.py
#!/usr/bin/python3 from flask import Flask, jsonify, request from funds_correlations import correlations, parse_performances_from_dict import traceback app = Flask(__name__) @app.route("/correlations", methods=['POST']) def correlation_api(): req_json = request.get_json() perf_list = parse_performances_from_dict(req_json) if len(perf_list) < 2: return jsonify({ 'error': 'not enough valid data' }), 400 try: corr, min_size, limiting = correlations(perf_list) except Exception: traceback.print_exc() return jsonify({ 'error': 'Internal error' }), 500 data = { 'correlations': corr, 'min_size': min_size, 'limiting': limiting } return jsonify(data) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
#!/usr/bin/python3 from flask import Flask, jsonify, request from funds_correlations import correlations, parse_performances_from_dict import traceback app = Flask(__name__) @app.route("/correlations", methods=['POST']) def correlation_api(): try: req_json = request.get_json() valid_input = True perf_list = [] if req_json: perf_list = parse_performances_from_dict(req_json) if len(perf_list) < 2: valid_input = False else: valid_input = False if not valid_input: return jsonify({ 'error': 'not enough valid data' }), 400 corr, min_size, limiting = correlations(perf_list) data = { 'correlations': corr, 'min_size': min_size, 'limiting': limiting } return jsonify(data) except Exception: traceback.print_exc() return jsonify({ 'error': 'Internal error' }), 500 if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
Improve API robustness Case where no JSON is sent
Improve API robustness Case where no JSON is sent
Python
apache-2.0
egenerat/portfolio,egenerat/portfolio,egenerat/portfolio
<INSERT> try: <INSERT_END> <INSERT> valid_input = True <INSERT_END> <INSERT> [] if req_json: perf_list = <INSERT_END> <INSERT> <INSERT_END> <INSERT> valid_input = False else: valid_input = False if not valid_input: <INSERT_END> <INSERT> <INSERT_END> <INSERT> <INSERT_END> <DELETE> try: <DELETE_END> <INSERT> data = { 'correlations': corr, 'min_size': min_size, 'limiting': limiting } return jsonify(data) <INSERT_END> <REPLACE_OLD> 500 data = { 'correlations': corr, 'min_size': min_size, 'limiting': limiting } return jsonify(data) if <REPLACE_NEW> 500 if <REPLACE_END> <|endoftext|> #!/usr/bin/python3 from flask import Flask, jsonify, request from funds_correlations import correlations, parse_performances_from_dict import traceback app = Flask(__name__) @app.route("/correlations", methods=['POST']) def correlation_api(): try: req_json = request.get_json() valid_input = True perf_list = [] if req_json: perf_list = parse_performances_from_dict(req_json) if len(perf_list) < 2: valid_input = False else: valid_input = False if not valid_input: return jsonify({ 'error': 'not enough valid data' }), 400 corr, min_size, limiting = correlations(perf_list) data = { 'correlations': corr, 'min_size': min_size, 'limiting': limiting } return jsonify(data) except Exception: traceback.print_exc() return jsonify({ 'error': 'Internal error' }), 500 if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
Improve API robustness Case where no JSON is sent #!/usr/bin/python3 from flask import Flask, jsonify, request from funds_correlations import correlations, parse_performances_from_dict import traceback app = Flask(__name__) @app.route("/correlations", methods=['POST']) def correlation_api(): req_json = request.get_json() perf_list = parse_performances_from_dict(req_json) if len(perf_list) < 2: return jsonify({ 'error': 'not enough valid data' }), 400 try: corr, min_size, limiting = correlations(perf_list) except Exception: traceback.print_exc() return jsonify({ 'error': 'Internal error' }), 500 data = { 'correlations': corr, 'min_size': min_size, 'limiting': limiting } return jsonify(data) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
dcda634f00d2e04e1c77bca14059a9df1a1fdc5c
ghtools/command/login.py
ghtools/command/login.py
from __future__ import print_function from getpass import getpass, _raw_input import logging import sys from argh import ArghParser, arg from ghtools import cli from ghtools.api import envkey, GithubAPIClient log = logging.getLogger(__name__) parser = ArghParser() def login_if_needed(gh, scopes): if gh.logged_in: log.info("Already logged in") return print("Please log into GitHub ({0})".format(gh.nickname or "public"), file=sys.stderr) username = _raw_input("Username: ") password = getpass("Password: ") gh.login(username, password, scopes=scopes) @arg('-s', '--scope', default=None, action='append', help='GitHub auth scopes to request') @arg('github', nargs='?', help='GitHub instance nickname (e.g "enterprise")') def login(args): """ Log into a GitHub instance, and print the resulting OAuth token. """ with cli.catch_api_errors(): client = GithubAPIClient(args.github) login_if_needed(client, args.scope) oauth_token_key = envkey(client.nickname, 'oauth_token') print("export {0}='{1}'".format(oauth_token_key, client.token)) parser.set_default_command(login) def main(): parser.dispatch() if __name__ == '__main__': main()
from __future__ import print_function from getpass import getpass, _raw_input import logging import sys from argh import ArghParser, arg from ghtools import cli from ghtools.api import envkey, GithubAPIClient log = logging.getLogger(__name__) parser = ArghParser() def login_if_needed(gh, scopes): if gh.logged_in: log.info("Already logged in") return print("Please log into GitHub ({0})".format(gh.nickname or "public"), file=sys.stderr) username = _raw_input("Username: ") password = getpass("Password: ") gh.login(username, password, scopes=scopes) @arg('-s', '--scope', default=None, action='append', help='GitHub auth scopes to request') @arg('github', nargs='?', help='GitHub instance nickname (e.g "enterprise")') def login(args): """ Log into a GitHub instance, and print the resulting OAuth token. """ with cli.catch_api_errors(): client = GithubAPIClient(nickname=args.github) login_if_needed(client, args.scope) oauth_token_key = envkey(client.nickname, 'oauth_token') print("export {0}='{1}'".format(oauth_token_key, client.token)) parser.set_default_command(login) def main(): parser.dispatch() if __name__ == '__main__': main()
Fix broken GithubAPIClient constructor args
Fix broken GithubAPIClient constructor args
Python
mit
alphagov/ghtools
<REPLACE_OLD> GithubAPIClient(args.github) <REPLACE_NEW> GithubAPIClient(nickname=args.github) <REPLACE_END> <|endoftext|> from __future__ import print_function from getpass import getpass, _raw_input import logging import sys from argh import ArghParser, arg from ghtools import cli from ghtools.api import envkey, GithubAPIClient log = logging.getLogger(__name__) parser = ArghParser() def login_if_needed(gh, scopes): if gh.logged_in: log.info("Already logged in") return print("Please log into GitHub ({0})".format(gh.nickname or "public"), file=sys.stderr) username = _raw_input("Username: ") password = getpass("Password: ") gh.login(username, password, scopes=scopes) @arg('-s', '--scope', default=None, action='append', help='GitHub auth scopes to request') @arg('github', nargs='?', help='GitHub instance nickname (e.g "enterprise")') def login(args): """ Log into a GitHub instance, and print the resulting OAuth token. """ with cli.catch_api_errors(): client = GithubAPIClient(nickname=args.github) login_if_needed(client, args.scope) oauth_token_key = envkey(client.nickname, 'oauth_token') print("export {0}='{1}'".format(oauth_token_key, client.token)) parser.set_default_command(login) def main(): parser.dispatch() if __name__ == '__main__': main()
Fix broken GithubAPIClient constructor args from __future__ import print_function from getpass import getpass, _raw_input import logging import sys from argh import ArghParser, arg from ghtools import cli from ghtools.api import envkey, GithubAPIClient log = logging.getLogger(__name__) parser = ArghParser() def login_if_needed(gh, scopes): if gh.logged_in: log.info("Already logged in") return print("Please log into GitHub ({0})".format(gh.nickname or "public"), file=sys.stderr) username = _raw_input("Username: ") password = getpass("Password: ") gh.login(username, password, scopes=scopes) @arg('-s', '--scope', default=None, action='append', help='GitHub auth scopes to request') @arg('github', nargs='?', help='GitHub instance nickname (e.g "enterprise")') def login(args): """ Log into a GitHub instance, and print the resulting OAuth token. """ with cli.catch_api_errors(): client = GithubAPIClient(args.github) login_if_needed(client, args.scope) oauth_token_key = envkey(client.nickname, 'oauth_token') print("export {0}='{1}'".format(oauth_token_key, client.token)) parser.set_default_command(login) def main(): parser.dispatch() if __name__ == '__main__': main()
a355a9f76add5b7b91b31b9e8b07c4f0fbc9ce3a
docs/examples/core/ipython-get-history.py
docs/examples/core/ipython-get-history.py
#!/usr/bin/env python """Extract a session from the IPython input history. Usage: ipython-get-history.py sessionnumber [outputfile] If outputfile is not given, the relevant history is written to stdout. If outputfile has a .py extension, the translated history (without IPython's special syntax) will be extracted. Example: ./ipython-get-history.py 57 record.ipy This script is a simple demonstration of HistoryAccessor. It should be possible to build much more flexible and powerful tools to browse and pull from the history database. """ import sys import codecs from IPython.core.history import HistoryAccessor session_number = int(sys.argv[1]) if len(sys.argv) > 2: dest = open(sys.argv[2], "w") raw = not sys.argv[2].endswith('.py') else: dest = sys.stdout raw = True dest.write("# coding: utf-8\n") # Profiles other than 'default' can be specified here with a profile= argument: hist = HistoryAccessor() for session, lineno, cell in hist.get_range(session=session_number, raw=raw): # To use this in Python 3, remove the .encode() here: dest.write(cell.encode('utf-8') + '\n')
Add example script for extracting history from the database.
Add example script for extracting history from the database.
Python
bsd-3-clause
ipython/ipython,ipython/ipython
<INSERT> #!/usr/bin/env python """Extract a session from the IPython input history. Usage: <INSERT_END> <INSERT> ipython-get-history.py sessionnumber [outputfile] If outputfile is not given, the relevant history is written to stdout. If outputfile has a .py extension, the translated history (without IPython's special syntax) will be extracted. Example: ./ipython-get-history.py 57 record.ipy This script is a simple demonstration of HistoryAccessor. It should be possible to build much more flexible and powerful tools to browse and pull from the history database. """ import sys import codecs from IPython.core.history import HistoryAccessor session_number = int(sys.argv[1]) if len(sys.argv) > 2: dest = open(sys.argv[2], "w") raw = not sys.argv[2].endswith('.py') else: dest = sys.stdout raw = True dest.write("# coding: utf-8\n") # Profiles other than 'default' can be specified here with a profile= argument: hist = HistoryAccessor() for session, lineno, cell in hist.get_range(session=session_number, raw=raw): # To use this in Python 3, remove the .encode() here: dest.write(cell.encode('utf-8') + '\n') <INSERT_END> <|endoftext|> #!/usr/bin/env python """Extract a session from the IPython input history. Usage: ipython-get-history.py sessionnumber [outputfile] If outputfile is not given, the relevant history is written to stdout. If outputfile has a .py extension, the translated history (without IPython's special syntax) will be extracted. Example: ./ipython-get-history.py 57 record.ipy This script is a simple demonstration of HistoryAccessor. It should be possible to build much more flexible and powerful tools to browse and pull from the history database. """ import sys import codecs from IPython.core.history import HistoryAccessor session_number = int(sys.argv[1]) if len(sys.argv) > 2: dest = open(sys.argv[2], "w") raw = not sys.argv[2].endswith('.py') else: dest = sys.stdout raw = True dest.write("# coding: utf-8\n") # Profiles other than 'default' can be specified here with a profile= argument: hist = HistoryAccessor() for session, lineno, cell in hist.get_range(session=session_number, raw=raw): # To use this in Python 3, remove the .encode() here: dest.write(cell.encode('utf-8') + '\n')
Add example script for extracting history from the database.
85373313233dfad0183d52ba44235a5131cc0f7d
readthedocs/builds/migrations/0016_migrate_protected_versions_to_hidden.py
readthedocs/builds/migrations/0016_migrate_protected_versions_to_hidden.py
# Generated by Django 2.2.11 on 2020-03-18 18:27 from django.db import migrations def forwards_func(apps, schema_editor): """Migrate all protected versions to be hidden.""" Version = apps.get_model('builds', 'Version') Version.objects.filter(privacy_level='protected').update(hidden=True) class Migration(migrations.Migration): dependencies = [ ('builds', '0015_add_hidden_field_to_version'), ] operations = [ migrations.RunPython(forwards_func), ]
Migrate protected versions to be hidden
Migrate protected versions to be hidden
Python
mit
rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org
<INSERT> # Generated by Django 2.2.11 on 2020-03-18 18:27 from django.db import migrations def forwards_func(apps, schema_editor): <INSERT_END> <INSERT> """Migrate all protected versions to be hidden.""" Version = apps.get_model('builds', 'Version') Version.objects.filter(privacy_level='protected').update(hidden=True) class Migration(migrations.Migration): dependencies = [ ('builds', '0015_add_hidden_field_to_version'), ] operations = [ migrations.RunPython(forwards_func), ] <INSERT_END> <|endoftext|> # Generated by Django 2.2.11 on 2020-03-18 18:27 from django.db import migrations def forwards_func(apps, schema_editor): """Migrate all protected versions to be hidden.""" Version = apps.get_model('builds', 'Version') Version.objects.filter(privacy_level='protected').update(hidden=True) class Migration(migrations.Migration): dependencies = [ ('builds', '0015_add_hidden_field_to_version'), ] operations = [ migrations.RunPython(forwards_func), ]
Migrate protected versions to be hidden
1b1bc020f3e37c10072ed45271e92348a8e2fcad
pi/plot_temperature.py
pi/plot_temperature.py
import datetime import matplotlib.pyplot as pyplot import os import re import sys def main(): """Main.""" if sys.version_info.major <= 2: print('Use Python 3') return lines = [] for file_name in sorted(os.listdir('.{}temperatures'.format(os.sep))): if file_name.endswith('csv'): # Do a line at a time because some lines might be corrupted due to # power loss file_name = '.{sep}temperatures{sep}{f}'.format(sep=os.sep, f=file_name) with open(file_name) as file_: for line in file_.readlines(): if line.startswith('"') and line.endswith('\n'): lines.append(line) def parse_time(line): """Returns the time from a line.""" time_str = line.split(',')[0].replace('"', '') parts = [int(i) for i in re.split('[: -]', time_str)] return datetime.datetime(*parts) def parse_temperature(line): """Returns the temperature from a line.""" return float(line.split(',')[1][:-1]) initial_time = parse_time(lines[0]) seconds = [(parse_time(line) - initial_time).total_seconds() for line in lines] temperatures = [parse_temperature(line) for line in lines] hours = [sec / 3600. for sec in seconds] pyplot.plot(hours, temperatures) pyplot.xlabel('time (hours)') pyplot.ylabel('temperature (degrees C)') pyplot.grid(True) pyplot.show() if __name__ == '__main__': main()
Add script to plot temperatures
Add script to plot temperatures
Python
mit
bskari/eclipse-2017-hab,bskari/eclipse-2017-hab
<REPLACE_OLD> <REPLACE_NEW> import datetime import matplotlib.pyplot as pyplot import os import re import sys def main(): """Main.""" if sys.version_info.major <= 2: print('Use Python 3') return lines = [] for file_name in sorted(os.listdir('.{}temperatures'.format(os.sep))): if file_name.endswith('csv'): # Do a line at a time because some lines might be corrupted due to # power loss file_name = '.{sep}temperatures{sep}{f}'.format(sep=os.sep, f=file_name) with open(file_name) as file_: for line in file_.readlines(): if line.startswith('"') and line.endswith('\n'): lines.append(line) def parse_time(line): """Returns the time from a line.""" time_str = line.split(',')[0].replace('"', '') parts = [int(i) for i in re.split('[: -]', time_str)] return datetime.datetime(*parts) def parse_temperature(line): """Returns the temperature from a line.""" return float(line.split(',')[1][:-1]) initial_time = parse_time(lines[0]) seconds = [(parse_time(line) - initial_time).total_seconds() for line in lines] temperatures = [parse_temperature(line) for line in lines] hours = [sec / 3600. for sec in seconds] pyplot.plot(hours, temperatures) pyplot.xlabel('time (hours)') pyplot.ylabel('temperature (degrees C)') pyplot.grid(True) pyplot.show() if __name__ == '__main__': main() <REPLACE_END> <|endoftext|> import datetime import matplotlib.pyplot as pyplot import os import re import sys def main(): """Main.""" if sys.version_info.major <= 2: print('Use Python 3') return lines = [] for file_name in sorted(os.listdir('.{}temperatures'.format(os.sep))): if file_name.endswith('csv'): # Do a line at a time because some lines might be corrupted due to # power loss file_name = '.{sep}temperatures{sep}{f}'.format(sep=os.sep, f=file_name) with open(file_name) as file_: for line in file_.readlines(): if line.startswith('"') and line.endswith('\n'): lines.append(line) def parse_time(line): """Returns the time from a line.""" time_str = line.split(',')[0].replace('"', '') parts = [int(i) for i in re.split('[: -]', time_str)] return datetime.datetime(*parts) def parse_temperature(line): """Returns the temperature from a line.""" return float(line.split(',')[1][:-1]) initial_time = parse_time(lines[0]) seconds = [(parse_time(line) - initial_time).total_seconds() for line in lines] temperatures = [parse_temperature(line) for line in lines] hours = [sec / 3600. for sec in seconds] pyplot.plot(hours, temperatures) pyplot.xlabel('time (hours)') pyplot.ylabel('temperature (degrees C)') pyplot.grid(True) pyplot.show() if __name__ == '__main__': main()
Add script to plot temperatures
96fac3babb22386fd94eccc86abb5bd15c917c53
rpyc/core/__init__.py
rpyc/core/__init__.py
from rpyc.core.stream import SocketStream, PipeStream from rpyc.core.channel import Channel from rpyc.core.protocol import Connection from rpyc.core.netref import BaseNetref from rpyc.core.async import AsyncResult, AsyncResultTimeout from rpyc.core.service import Service, VoidService, SlaveService from rpyc.core.vinegar import GenericException, install_rpyc_excepthook # for .NET import platform if platform.system() == "cli": import clr # Add Reference to IronPython zlib (required for channel compression) # grab it from http://bitbucket.org/jdhardy/ironpythonzlib clr.AddReference("IronPython.Zlib") install_rpyc_excepthook()
from rpyc.core.stream import SocketStream, PipeStream from rpyc.core.channel import Channel from rpyc.core.protocol import Connection from rpyc.core.netref import BaseNetref from rpyc.core.async import AsyncResult, AsyncResultTimeout from rpyc.core.service import Service, VoidService, SlaveService from rpyc.core.vinegar import GenericException, install_rpyc_excepthook install_rpyc_excepthook()
Remove Code specific for IronPython - useless with 2.7
Remove Code specific for IronPython - useless with 2.7
Python
mit
glpatcern/rpyc,sponce/rpyc,pyq881120/rpyc,pombredanne/rpyc,geromueller/rpyc,kwlzn/rpyc,siemens/rpyc,eplaut/rpyc,gleon99/rpyc
<REPLACE_OLD> install_rpyc_excepthook # for .NET import platform if platform.system() == "cli": import clr # Add Reference to IronPython zlib (required for channel compression) # grab it from http://bitbucket.org/jdhardy/ironpythonzlib clr.AddReference("IronPython.Zlib") install_rpyc_excepthook() <REPLACE_NEW> install_rpyc_excepthook install_rpyc_excepthook() <REPLACE_END> <|endoftext|> from rpyc.core.stream import SocketStream, PipeStream from rpyc.core.channel import Channel from rpyc.core.protocol import Connection from rpyc.core.netref import BaseNetref from rpyc.core.async import AsyncResult, AsyncResultTimeout from rpyc.core.service import Service, VoidService, SlaveService from rpyc.core.vinegar import GenericException, install_rpyc_excepthook install_rpyc_excepthook()
Remove Code specific for IronPython - useless with 2.7 from rpyc.core.stream import SocketStream, PipeStream from rpyc.core.channel import Channel from rpyc.core.protocol import Connection from rpyc.core.netref import BaseNetref from rpyc.core.async import AsyncResult, AsyncResultTimeout from rpyc.core.service import Service, VoidService, SlaveService from rpyc.core.vinegar import GenericException, install_rpyc_excepthook # for .NET import platform if platform.system() == "cli": import clr # Add Reference to IronPython zlib (required for channel compression) # grab it from http://bitbucket.org/jdhardy/ironpythonzlib clr.AddReference("IronPython.Zlib") install_rpyc_excepthook()
26b0571212d6abcd65fd4d857726131d12146d85
setup.py
setup.py
from distutils.core import setup setup( name='LightMatchingEngine', version='0.1.2', author='Gavin Chan', author_email='[email protected]', packages=['lightmatchingengine'], url='http://pypi.python.org/pypi/LightMatchingEngine/', license='LICENSE.txt', description='A light matching engine.' )
from setuptools import setup setup( name='LightMatchingEngine', use_scm_version=True, setup_requires=['setuptools_scm'], author='Gavin Chan', author_email='[email protected]', packages=['lightmatchingengine'], url='http://pypi.python.org/pypi/LightMatchingEngine/', license='LICENSE.txt', description='A light matching engine.' )
Update to use scm for versioning
Update to use scm for versioning
Python
mit
gavincyi/LightMatchingEngine
<REPLACE_OLD> distutils.core <REPLACE_NEW> setuptools <REPLACE_END> <REPLACE_OLD> version='0.1.2', <REPLACE_NEW> use_scm_version=True, setup_requires=['setuptools_scm'], <REPLACE_END> <REPLACE_OLD> engine.' ) <REPLACE_NEW> engine.' ) <REPLACE_END> <|endoftext|> from setuptools import setup setup( name='LightMatchingEngine', use_scm_version=True, setup_requires=['setuptools_scm'], author='Gavin Chan', author_email='[email protected]', packages=['lightmatchingengine'], url='http://pypi.python.org/pypi/LightMatchingEngine/', license='LICENSE.txt', description='A light matching engine.' )
Update to use scm for versioning from distutils.core import setup setup( name='LightMatchingEngine', version='0.1.2', author='Gavin Chan', author_email='[email protected]', packages=['lightmatchingengine'], url='http://pypi.python.org/pypi/LightMatchingEngine/', license='LICENSE.txt', description='A light matching engine.' )
c5c77ba407e195e3cc98bb75a961fe112736fca6
homebrew/command_line.py
homebrew/command_line.py
# -*- coding: utf-8 -*- from .homebrew import HomeBrew def main(): HomeBrew().log_info()
# -*- coding: utf-8 -*- import argparse from .homebrew import HomeBrew def main(): argparse.ArgumentParser(description='Get homebrew info').parse_args() HomeBrew().log_info()
Add argparse for info on hb command
Add argparse for info on hb command
Python
isc
igroen/homebrew
<REPLACE_OLD> -*- from <REPLACE_NEW> -*- import argparse from <REPLACE_END> <INSERT> argparse.ArgumentParser(description='Get homebrew info').parse_args() <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*- import argparse from .homebrew import HomeBrew def main(): argparse.ArgumentParser(description='Get homebrew info').parse_args() HomeBrew().log_info()
Add argparse for info on hb command # -*- coding: utf-8 -*- from .homebrew import HomeBrew def main(): HomeBrew().log_info()
766735563fe327363e87a103fd70f88a896bf9a8
version.py
version.py
major = 0 minor=0 patch=22 branch="master" timestamp=1376526477.22
major = 0 minor=0 patch=23 branch="master" timestamp=1376526646.52
Tag commit for v0.0.23-master generated by gitmake.py
Tag commit for v0.0.23-master generated by gitmake.py
Python
mit
ryansturmer/gitmake
<REPLACE_OLD> 0 minor=0 patch=22 branch="master" timestamp=1376526477.22 <REPLACE_NEW> 0 minor=0 patch=23 branch="master" timestamp=1376526646.52 <REPLACE_END> <|endoftext|> major = 0 minor=0 patch=23 branch="master" timestamp=1376526646.52
Tag commit for v0.0.23-master generated by gitmake.py major = 0 minor=0 patch=22 branch="master" timestamp=1376526477.22
c8483dd1cd40db8b9628f19c9ba664165708a8ab
project/urls.py
project/urls.py
from django.conf.urls.defaults import * from django.contrib import admin from django.conf import settings admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', admin.site.urls), url(r'^publication/', include('project.publications.urls')), #url(r'^google/', include('project.google.urls')), url(r'^project/', include('project.projects.urls')), url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'), url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog'), url(r'^$', 'project.views.index'), # Media serving url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}, name='media', ), )
from django.conf.urls.defaults import * from django.contrib import admin from django.conf import settings admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', admin.site.urls), url(r'^publication/', include('project.publications.urls')), url(r'^google/', include('djangoogle.urls')), url(r'^project/', include('project.projects.urls')), url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'), url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog'), url(r'^$', 'project.views.index'), # Media serving url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}, name='media', ), )
Make photos and videos accessible
Make photos and videos accessible
Python
bsd-2-clause
anjos/website,anjos/website
<REPLACE_OLD> #url(r'^google/', include('project.google.urls')), <REPLACE_NEW> url(r'^google/', include('djangoogle.urls')), <REPLACE_END> <|endoftext|> from django.conf.urls.defaults import * from django.contrib import admin from django.conf import settings admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', admin.site.urls), url(r'^publication/', include('project.publications.urls')), url(r'^google/', include('djangoogle.urls')), url(r'^project/', include('project.projects.urls')), url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'), url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog'), url(r'^$', 'project.views.index'), # Media serving url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}, name='media', ), )
Make photos and videos accessible from django.conf.urls.defaults import * from django.contrib import admin from django.conf import settings admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', admin.site.urls), url(r'^publication/', include('project.publications.urls')), #url(r'^google/', include('project.google.urls')), url(r'^project/', include('project.projects.urls')), url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'), url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog'), url(r'^$', 'project.views.index'), # Media serving url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}, name='media', ), )
c08e6a22e589880d97b92048cfaec994c41a23d4
pylama/lint/pylama_pydocstyle.py
pylama/lint/pylama_pydocstyle.py
"""pydocstyle support.""" from pydocstyle import PEP257Checker from pylama.lint import Linter as Abstract class Linter(Abstract): """Check pydocstyle errors.""" @staticmethod def run(path, code=None, **meta): """pydocstyle code checking. :return list: List of errors. """ return [{ 'lnum': e.line, # Remove colon after error code ("D403: ..." => "D403 ..."). 'text': (e.message[0:4] + e.message[5:] if e.message[4] == ':' else e.message), 'type': 'D', 'number': e.code } for e in PEP257Checker().check_source(code, path)]
"""pydocstyle support.""" THIRD_ARG = True try: #: Import for pydocstyle 2.0.0 and newer from pydocstyle import ConventionChecker as PyDocChecker except ImportError: #: Backward compatibility for pydocstyle prior to 2.0.0 from pydocstyle import PEP257Checker as PyDocChecker THIRD_ARG = False from pylama.lint import Linter as Abstract class Linter(Abstract): """Check pydocstyle errors.""" @staticmethod def run(path, code=None, **meta): """pydocstyle code checking. :return list: List of errors. """ check_source_args = (code, path, None) if THIRD_ARG else (code, path) return [{ 'lnum': e.line, # Remove colon after error code ("D403: ..." => "D403 ..."). 'text': (e.message[0:4] + e.message[5:] if e.message[4] == ':' else e.message), 'type': 'D', 'number': e.code } for e in PyDocChecker().check_source(*check_source_args)]
Update for pydocstyle 2.0.0 compatibility
Update for pydocstyle 2.0.0 compatibility Fix klen/pylama#96 Adding the newer ignore_decorators argument. Thanks to @not-raspberry for the tip!
Python
mit
klen/pylama
<REPLACE_OLD> support.""" from <REPLACE_NEW> support.""" THIRD_ARG = True try: #: Import for pydocstyle 2.0.0 and newer from <REPLACE_END> <REPLACE_OLD> PEP257Checker from <REPLACE_NEW> ConventionChecker as PyDocChecker except ImportError: #: Backward compatibility for pydocstyle prior to 2.0.0 from pydocstyle import PEP257Checker as PyDocChecker THIRD_ARG = False from <REPLACE_END> <INSERT> check_source_args = (code, path, None) if THIRD_ARG else (code, path) <INSERT_END> <REPLACE_OLD> PEP257Checker().check_source(code, path)] <REPLACE_NEW> PyDocChecker().check_source(*check_source_args)] <REPLACE_END> <|endoftext|> """pydocstyle support.""" THIRD_ARG = True try: #: Import for pydocstyle 2.0.0 and newer from pydocstyle import ConventionChecker as PyDocChecker except ImportError: #: Backward compatibility for pydocstyle prior to 2.0.0 from pydocstyle import PEP257Checker as PyDocChecker THIRD_ARG = False from pylama.lint import Linter as Abstract class Linter(Abstract): """Check pydocstyle errors.""" @staticmethod def run(path, code=None, **meta): """pydocstyle code checking. :return list: List of errors. """ check_source_args = (code, path, None) if THIRD_ARG else (code, path) return [{ 'lnum': e.line, # Remove colon after error code ("D403: ..." => "D403 ..."). 'text': (e.message[0:4] + e.message[5:] if e.message[4] == ':' else e.message), 'type': 'D', 'number': e.code } for e in PyDocChecker().check_source(*check_source_args)]
Update for pydocstyle 2.0.0 compatibility Fix klen/pylama#96 Adding the newer ignore_decorators argument. Thanks to @not-raspberry for the tip! """pydocstyle support.""" from pydocstyle import PEP257Checker from pylama.lint import Linter as Abstract class Linter(Abstract): """Check pydocstyle errors.""" @staticmethod def run(path, code=None, **meta): """pydocstyle code checking. :return list: List of errors. """ return [{ 'lnum': e.line, # Remove colon after error code ("D403: ..." => "D403 ..."). 'text': (e.message[0:4] + e.message[5:] if e.message[4] == ':' else e.message), 'type': 'D', 'number': e.code } for e in PEP257Checker().check_source(code, path)]
daf29f52c01d83619585a1f2fa2e6f03a397e1cc
tests/test_utils.py
tests/test_utils.py
# coding: utf-8 from __future__ import absolute_import from __future__ import unicode_literals import io import os import unittest import tempfile try: from unittest import mock except ImportError: import mock from fs.archive import _utils class TestUtils(unittest.TestCase): @unittest.skipUnless(os.name == 'posix', 'POSIX platform needed') def test_writable_path(self): self.assertFalse(_utils.writable_path('/')) self.assertFalse(_utils.writable_path('/root_location')) self.assertTrue(_utils.writable_path(__file__)) def test_writable_stream(self): with tempfile.NamedTemporaryFile() as tmp: self.assertTrue(_utils.writable_stream(tmp)) with open(tmp.name) as tmp2: self.assertFalse(_utils.writable_stream(tmp2)) buff = io.BytesIO() self.assertTrue(_utils.writable_stream(buff)) buff = io.BufferedReader(buff) self.assertFalse(_utils.writable_stream(buff)) buff = mock.MagicMock() buff.write = mock.MagicMock(side_effect=IOError("not writable")) self.assertFalse(_utils.writable_stream(buff)) def test_import_from_names(self): imp = _utils.import_from_names self.assertIs(imp('os'), os) self.assertIs(imp('akjhkjhsk', 'os'), os) self.assertIs(imp('akeskjhk'), None)
# coding: utf-8 from __future__ import absolute_import from __future__ import unicode_literals import io import os import unittest import tempfile try: from unittest import mock except ImportError: import mock from fs.archive import _utils class TestUtils(unittest.TestCase): @unittest.skipUnless(os.name == 'posix', 'POSIX platform needed') def test_writable_path(self): self.assertFalse(_utils.writable_path('/')) self.assertFalse(_utils.writable_path('/root_location')) self.assertTrue(_utils.writable_path(__file__)) def test_writable_stream(self): with tempfile.NamedTemporaryFile(mode='wb+') as tmp: self.assertTrue(_utils.writable_stream(tmp)) with open(tmp.name, 'rb') as tmp2: self.assertFalse(_utils.writable_stream(tmp2)) buff = io.BytesIO() self.assertTrue(_utils.writable_stream(buff)) buff = io.BufferedReader(buff) self.assertFalse(_utils.writable_stream(buff)) buff = mock.MagicMock() buff.write = mock.MagicMock(side_effect=IOError("not writable")) self.assertFalse(_utils.writable_stream(buff)) def test_import_from_names(self): imp = _utils.import_from_names self.assertIs(imp('os'), os) self.assertIs(imp('akjhkjhsk', 'os'), os) self.assertIs(imp('akeskjhk'), None)
Fix test_writable_stream failing in Python 3.3 and 3.4
Fix test_writable_stream failing in Python 3.3 and 3.4
Python
mit
althonos/fs.archive
<REPLACE_OLD> tempfile.NamedTemporaryFile() <REPLACE_NEW> tempfile.NamedTemporaryFile(mode='wb+') <REPLACE_END> <REPLACE_OLD> open(tmp.name) <REPLACE_NEW> open(tmp.name, 'rb') <REPLACE_END> <|endoftext|> # coding: utf-8 from __future__ import absolute_import from __future__ import unicode_literals import io import os import unittest import tempfile try: from unittest import mock except ImportError: import mock from fs.archive import _utils class TestUtils(unittest.TestCase): @unittest.skipUnless(os.name == 'posix', 'POSIX platform needed') def test_writable_path(self): self.assertFalse(_utils.writable_path('/')) self.assertFalse(_utils.writable_path('/root_location')) self.assertTrue(_utils.writable_path(__file__)) def test_writable_stream(self): with tempfile.NamedTemporaryFile(mode='wb+') as tmp: self.assertTrue(_utils.writable_stream(tmp)) with open(tmp.name, 'rb') as tmp2: self.assertFalse(_utils.writable_stream(tmp2)) buff = io.BytesIO() self.assertTrue(_utils.writable_stream(buff)) buff = io.BufferedReader(buff) self.assertFalse(_utils.writable_stream(buff)) buff = mock.MagicMock() buff.write = mock.MagicMock(side_effect=IOError("not writable")) self.assertFalse(_utils.writable_stream(buff)) def test_import_from_names(self): imp = _utils.import_from_names self.assertIs(imp('os'), os) self.assertIs(imp('akjhkjhsk', 'os'), os) self.assertIs(imp('akeskjhk'), None)
Fix test_writable_stream failing in Python 3.3 and 3.4 # coding: utf-8 from __future__ import absolute_import from __future__ import unicode_literals import io import os import unittest import tempfile try: from unittest import mock except ImportError: import mock from fs.archive import _utils class TestUtils(unittest.TestCase): @unittest.skipUnless(os.name == 'posix', 'POSIX platform needed') def test_writable_path(self): self.assertFalse(_utils.writable_path('/')) self.assertFalse(_utils.writable_path('/root_location')) self.assertTrue(_utils.writable_path(__file__)) def test_writable_stream(self): with tempfile.NamedTemporaryFile() as tmp: self.assertTrue(_utils.writable_stream(tmp)) with open(tmp.name) as tmp2: self.assertFalse(_utils.writable_stream(tmp2)) buff = io.BytesIO() self.assertTrue(_utils.writable_stream(buff)) buff = io.BufferedReader(buff) self.assertFalse(_utils.writable_stream(buff)) buff = mock.MagicMock() buff.write = mock.MagicMock(side_effect=IOError("not writable")) self.assertFalse(_utils.writable_stream(buff)) def test_import_from_names(self): imp = _utils.import_from_names self.assertIs(imp('os'), os) self.assertIs(imp('akjhkjhsk', 'os'), os) self.assertIs(imp('akeskjhk'), None)
3b41e2166adde50f36f8f7ea389c80b76b83acaf
test/test_wavedrom.py
test/test_wavedrom.py
import subprocess from utils import * @all_files_in_dir('wavedrom_0') def test_wavedrom_0(datafiles): with datafiles.as_cwd(): subprocess.check_call(['python3', 'wavedrom-test.py']) @all_files_in_dir('wavedrom_1') def test_wavedrom_1(datafiles): with datafiles.as_cwd(): for s in get_simulators(): subprocess.check_call(['runSVUnit', '-s', s, '-w']) expect_testrunner_pass('run.log')
import subprocess from utils import * @all_files_in_dir('wavedrom_0') def test_wavedrom_0(datafiles): with datafiles.as_cwd(): subprocess.check_call(['python3', 'wavedrom-test.py']) @all_files_in_dir('wavedrom_1') @all_available_simulators() def test_wavedrom_1(datafiles, simulator): with datafiles.as_cwd(): subprocess.check_call(['runSVUnit', '-s', simulator, '-w']) expect_testrunner_pass('run.log')
Update wavedrom tests to get simulators via fixture
Update wavedrom tests to get simulators via fixture
Python
apache-2.0
nosnhojn/svunit-code,svunit/svunit,nosnhojn/svunit-code,svunit/svunit,svunit/svunit,nosnhojn/svunit-code
<REPLACE_OLD> 'wavedrom-test.py']) @all_files_in_dir('wavedrom_1') def test_wavedrom_1(datafiles): <REPLACE_NEW> 'wavedrom-test.py']) @all_files_in_dir('wavedrom_1') @all_available_simulators() def test_wavedrom_1(datafiles, simulator): <REPLACE_END> <DELETE> for s in get_simulators(): <DELETE_END> <REPLACE_OLD> s, <REPLACE_NEW> simulator, <REPLACE_END> <DELETE> <DELETE_END> <|endoftext|> import subprocess from utils import * @all_files_in_dir('wavedrom_0') def test_wavedrom_0(datafiles): with datafiles.as_cwd(): subprocess.check_call(['python3', 'wavedrom-test.py']) @all_files_in_dir('wavedrom_1') @all_available_simulators() def test_wavedrom_1(datafiles, simulator): with datafiles.as_cwd(): subprocess.check_call(['runSVUnit', '-s', simulator, '-w']) expect_testrunner_pass('run.log')
Update wavedrom tests to get simulators via fixture import subprocess from utils import * @all_files_in_dir('wavedrom_0') def test_wavedrom_0(datafiles): with datafiles.as_cwd(): subprocess.check_call(['python3', 'wavedrom-test.py']) @all_files_in_dir('wavedrom_1') def test_wavedrom_1(datafiles): with datafiles.as_cwd(): for s in get_simulators(): subprocess.check_call(['runSVUnit', '-s', s, '-w']) expect_testrunner_pass('run.log')
d3fdefb173b0fc3ab6a6479883a77049a4b8af16
trypython/stdlib/sys_/sys03.py
trypython/stdlib/sys_/sys03.py
""" sys モジュールについてのサンプルです. venv 環境での - sys.prefix - sys.exec_prefix - sys.base_prefix - sys.base_exec_prefix の値について. REFERENCES:: http://bit.ly/2Vun6U9 http://bit.ly/2Vuvqn6 """ import sys from trypython.common.commoncls import SampleBase from trypython.common.commonfunc import pr, hr class Sample(SampleBase): def exec(self): # -------------------------------------------- # venv で仮想環境を作り、 activate している状態だと # sys モジュールの prefixとbase_prefixの値が異なる # 状態となる。仮想環境を使っていない場合、同じ値となる. # -------------------------------------------- pr('prefix', sys.prefix) pr('exec_prefix', sys.exec_prefix) hr() pr('base_prefix', sys.base_prefix) pr('base_exec_prefix', sys.base_exec_prefix) pr('venv 利用している?', sys.prefix != sys.base_prefix) def go(): obj = Sample() obj.exec() if __name__ == '__main__': go()
Add venv利用時のsys.prefix, sys.base_prefix, sys.exec_prefix, sys.base_exec_prefix の値の違いについてのサンプル追加
Add venv利用時のsys.prefix, sys.base_prefix, sys.exec_prefix, sys.base_exec_prefix の値の違いについてのサンプル追加
Python
mit
devlights/try-python
<INSERT> """ sys モジュールについてのサンプルです. venv 環境での <INSERT_END> <INSERT> - sys.prefix - sys.exec_prefix - sys.base_prefix - sys.base_exec_prefix の値について. REFERENCES:: http://bit.ly/2Vun6U9 http://bit.ly/2Vuvqn6 """ import sys from trypython.common.commoncls import SampleBase from trypython.common.commonfunc import pr, hr class Sample(SampleBase): def exec(self): # -------------------------------------------- # venv で仮想環境を作り、 activate している状態だと # sys モジュールの prefixとbase_prefixの値が異なる # 状態となる。仮想環境を使っていない場合、同じ値となる. # -------------------------------------------- pr('prefix', sys.prefix) pr('exec_prefix', sys.exec_prefix) hr() pr('base_prefix', sys.base_prefix) pr('base_exec_prefix', sys.base_exec_prefix) pr('venv 利用している?', sys.prefix != sys.base_prefix) def go(): obj = Sample() obj.exec() if __name__ == '__main__': go() <INSERT_END> <|endoftext|> """ sys モジュールについてのサンプルです. venv 環境での - sys.prefix - sys.exec_prefix - sys.base_prefix - sys.base_exec_prefix の値について. REFERENCES:: http://bit.ly/2Vun6U9 http://bit.ly/2Vuvqn6 """ import sys from trypython.common.commoncls import SampleBase from trypython.common.commonfunc import pr, hr class Sample(SampleBase): def exec(self): # -------------------------------------------- # venv で仮想環境を作り、 activate している状態だと # sys モジュールの prefixとbase_prefixの値が異なる # 状態となる。仮想環境を使っていない場合、同じ値となる. # -------------------------------------------- pr('prefix', sys.prefix) pr('exec_prefix', sys.exec_prefix) hr() pr('base_prefix', sys.base_prefix) pr('base_exec_prefix', sys.base_exec_prefix) pr('venv 利用している?', sys.prefix != sys.base_prefix) def go(): obj = Sample() obj.exec() if __name__ == '__main__': go()
Add venv利用時のsys.prefix, sys.base_prefix, sys.exec_prefix, sys.base_exec_prefix の値の違いについてのサンプル追加
b51e0ff9407f8a609be580d8fcb9cad6cfd267d8
setup.py
setup.py
# Use setuptools if we can try: from setuptools.core import setup except ImportError: from distutils.core import setup PACKAGE = 'django-render-as' VERSION = '1.1' package_data = { 'render_as': [ 'templates/avoid_clash_with_real_app/*.html', 'templates/render_as/*.html', ], } setup( name=PACKAGE, version=VERSION, description="Template rendering indirector based on object class", packages=[ 'render_as', 'render_as/templatetags', ], package_data=package_data, license='MIT', author='James Aylett', author_email='[email protected]', install_requires=[ 'Django~=1.10', ], classifiers=[ 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
# Use setuptools if we can try: from setuptools.core import setup except ImportError: from distutils.core import setup PACKAGE = 'django-render-as' VERSION = '1.2' package_data = { 'render_as': [ 'test_templates/avoid_clash_with_real_app/*.html', 'test_templates/render_as/*.html', ], } setup( name=PACKAGE, version=VERSION, description="Template rendering indirector based on object class", packages=[ 'render_as', 'render_as/templatetags', ], package_data=package_data, license='MIT', author='James Aylett', author_email='[email protected]', install_requires=[ 'Django~=1.10', ], classifiers=[ 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
Include test templates in distributions.
Include test templates in distributions. This probably wasn't working before, although apparently I didn't notice. But then no one really runs tests for their 3PA, do they? This is v1.2.
Python
mit
jaylett/django-render-as,jaylett/django-render-as
<REPLACE_OLD> '1.1' package_data <REPLACE_NEW> '1.2' package_data <REPLACE_END> <REPLACE_OLD> 'templates/avoid_clash_with_real_app/*.html', 'templates/render_as/*.html', <REPLACE_NEW> 'test_templates/avoid_clash_with_real_app/*.html', 'test_templates/render_as/*.html', <REPLACE_END> <|endoftext|> # Use setuptools if we can try: from setuptools.core import setup except ImportError: from distutils.core import setup PACKAGE = 'django-render-as' VERSION = '1.2' package_data = { 'render_as': [ 'test_templates/avoid_clash_with_real_app/*.html', 'test_templates/render_as/*.html', ], } setup( name=PACKAGE, version=VERSION, description="Template rendering indirector based on object class", packages=[ 'render_as', 'render_as/templatetags', ], package_data=package_data, license='MIT', author='James Aylett', author_email='[email protected]', install_requires=[ 'Django~=1.10', ], classifiers=[ 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
Include test templates in distributions. This probably wasn't working before, although apparently I didn't notice. But then no one really runs tests for their 3PA, do they? This is v1.2. # Use setuptools if we can try: from setuptools.core import setup except ImportError: from distutils.core import setup PACKAGE = 'django-render-as' VERSION = '1.1' package_data = { 'render_as': [ 'templates/avoid_clash_with_real_app/*.html', 'templates/render_as/*.html', ], } setup( name=PACKAGE, version=VERSION, description="Template rendering indirector based on object class", packages=[ 'render_as', 'render_as/templatetags', ], package_data=package_data, license='MIT', author='James Aylett', author_email='[email protected]', install_requires=[ 'Django~=1.10', ], classifiers=[ 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
db32ee58b5247dbc281d5f4633f5b9c2fe704ad1
metaci/testresults/utils.py
metaci/testresults/utils.py
from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404 from metaci.build.models import Build from metaci.build.models import BuildFlow def find_buildflow(request, build_id, flow): """ given a build_id and flow name, find a single BuildFlow (ala tests/ urls patterns). """ build = get_object_or_404(Build, id=build_id) if not request.user.has_perm('plan.view_builds', build): raise PermissionDenied() query = {'build_id': build_id, 'flow': flow} if build.current_rebuild: query['rebuild_id'] = build.current_rebuild build_flow = get_object_or_404(BuildFlow, **query) return build_flow
from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404 from metaci.build.models import Build from metaci.build.models import BuildFlow def find_buildflow(request, build_id, flow): """ given a build_id and flow name, find a single BuildFlow (ala tests/ urls patterns). """ build = get_object_or_404(Build, id=build_id) if not request.user.has_perm('plan.view_builds', build.planrepo): raise PermissionDenied() query = {'build_id': build_id, 'flow': flow} if build.current_rebuild: query['rebuild_id'] = build.current_rebuild build_flow = get_object_or_404(BuildFlow, **query) return build_flow
Use PlanRepository as the object for permission check instead of Build
Use PlanRepository as the object for permission check instead of Build
Python
bsd-3-clause
SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci
<REPLACE_OLD> build): <REPLACE_NEW> build.planrepo): <REPLACE_END> <|endoftext|> from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404 from metaci.build.models import Build from metaci.build.models import BuildFlow def find_buildflow(request, build_id, flow): """ given a build_id and flow name, find a single BuildFlow (ala tests/ urls patterns). """ build = get_object_or_404(Build, id=build_id) if not request.user.has_perm('plan.view_builds', build.planrepo): raise PermissionDenied() query = {'build_id': build_id, 'flow': flow} if build.current_rebuild: query['rebuild_id'] = build.current_rebuild build_flow = get_object_or_404(BuildFlow, **query) return build_flow
Use PlanRepository as the object for permission check instead of Build from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404 from metaci.build.models import Build from metaci.build.models import BuildFlow def find_buildflow(request, build_id, flow): """ given a build_id and flow name, find a single BuildFlow (ala tests/ urls patterns). """ build = get_object_or_404(Build, id=build_id) if not request.user.has_perm('plan.view_builds', build): raise PermissionDenied() query = {'build_id': build_id, 'flow': flow} if build.current_rebuild: query['rebuild_id'] = build.current_rebuild build_flow = get_object_or_404(BuildFlow, **query) return build_flow
33448340d278da7e0653701d78cbab317893279d
AG/datasets/analyze.py
AG/datasets/analyze.py
#!/usr/bin/python import os import sys import lxml from lxml import etree import math class StatsCounter(object): prefixes = {} cur_tag = None def start( self, tag, attrib ): self.cur_tag = tag def end( self, tag ): pass #self.cur_tag = None def data( self, _data ): if self.cur_tag != "File" and self.cur_tag != "Dir": return data = _data.rstrip("/") if data == "": return dir_name = os.path.dirname( data ) if dir_name == "": return if not self.prefixes.has_key( dir_name ): self.prefixes[ dir_name ] = 0 self.prefixes[ dir_name ] += 1 def close( self ): return "closed!" if __name__ == "__main__": counter = StatsCounter() parser = etree.XMLParser( target=counter ) fd = open( sys.argv[1], "r" ) while True: buf = fd.read( 32768 ) if len(buf) == 0: break parser.feed( buf ) result = parser.close() order = counter.prefixes.keys() order.sort() size_bins = {} for path in order: count = counter.prefixes[path] print "% 15s %s" % (count, path) size_bin = int(math.log(count, 10)) if not size_bins.has_key( size_bin ): size_bins[ size_bin ] = 1 else: size_bins[ size_bin ] += 1 print "" print "sizes" max_bin = max( size_bins.keys() ) bin_fmt = r"1e%0" + str( int(math.log(max_bin, 10)) + 1 ) + "s" for size in xrange( 0, max_bin + 1 ): binsize = 0 if size_bins.has_key( size ): binsize = size_bins[size] bin_str = bin_fmt % size print "%s %s" % (bin_str, binsize)
Add a simple analysis tool to get some structural properties about an AG's specfile.
Add a simple analysis tool to get some structural properties about an AG's specfile.
Python
apache-2.0
jcnelson/syndicate,iychoi/syndicate,iychoi/syndicate,jcnelson/syndicate,iychoi/syndicate,iychoi/syndicate,iychoi/syndicate,iychoi/syndicate,iychoi/syndicate,jcnelson/syndicate,jcnelson/syndicate,jcnelson/syndicate,jcnelson/syndicate,iychoi/syndicate,jcnelson/syndicate,jcnelson/syndicate
<REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/python import os import sys import lxml from lxml import etree import math class StatsCounter(object): prefixes = {} cur_tag = None def start( self, tag, attrib ): self.cur_tag = tag def end( self, tag ): pass #self.cur_tag = None def data( self, _data ): if self.cur_tag != "File" and self.cur_tag != "Dir": return data = _data.rstrip("/") if data == "": return dir_name = os.path.dirname( data ) if dir_name == "": return if not self.prefixes.has_key( dir_name ): self.prefixes[ dir_name ] = 0 self.prefixes[ dir_name ] += 1 def close( self ): return "closed!" if __name__ == "__main__": counter = StatsCounter() parser = etree.XMLParser( target=counter ) fd = open( sys.argv[1], "r" ) while True: buf = fd.read( 32768 ) if len(buf) == 0: break parser.feed( buf ) result = parser.close() order = counter.prefixes.keys() order.sort() size_bins = {} for path in order: count = counter.prefixes[path] print "% 15s %s" % (count, path) size_bin = int(math.log(count, 10)) if not size_bins.has_key( size_bin ): size_bins[ size_bin ] = 1 else: size_bins[ size_bin ] += 1 print "" print "sizes" max_bin = max( size_bins.keys() ) bin_fmt = r"1e%0" + str( int(math.log(max_bin, 10)) + 1 ) + "s" for size in xrange( 0, max_bin + 1 ): binsize = 0 if size_bins.has_key( size ): binsize = size_bins[size] bin_str = bin_fmt % size print "%s %s" % (bin_str, binsize) <REPLACE_END> <|endoftext|> #!/usr/bin/python import os import sys import lxml from lxml import etree import math class StatsCounter(object): prefixes = {} cur_tag = None def start( self, tag, attrib ): self.cur_tag = tag def end( self, tag ): pass #self.cur_tag = None def data( self, _data ): if self.cur_tag != "File" and self.cur_tag != "Dir": return data = _data.rstrip("/") if data == "": return dir_name = os.path.dirname( data ) if dir_name == "": return if not self.prefixes.has_key( dir_name ): self.prefixes[ dir_name ] = 0 self.prefixes[ dir_name ] += 1 def close( self ): return "closed!" if __name__ == "__main__": counter = StatsCounter() parser = etree.XMLParser( target=counter ) fd = open( sys.argv[1], "r" ) while True: buf = fd.read( 32768 ) if len(buf) == 0: break parser.feed( buf ) result = parser.close() order = counter.prefixes.keys() order.sort() size_bins = {} for path in order: count = counter.prefixes[path] print "% 15s %s" % (count, path) size_bin = int(math.log(count, 10)) if not size_bins.has_key( size_bin ): size_bins[ size_bin ] = 1 else: size_bins[ size_bin ] += 1 print "" print "sizes" max_bin = max( size_bins.keys() ) bin_fmt = r"1e%0" + str( int(math.log(max_bin, 10)) + 1 ) + "s" for size in xrange( 0, max_bin + 1 ): binsize = 0 if size_bins.has_key( size ): binsize = size_bins[size] bin_str = bin_fmt % size print "%s %s" % (bin_str, binsize)
Add a simple analysis tool to get some structural properties about an AG's specfile.
50bb7a20ee055b870794607022e4e30f8842f80d
openedx/core/djangoapps/appsembler/settings/settings/devstack_lms.py
openedx/core/djangoapps/appsembler/settings/settings/devstack_lms.py
""" Settings for Appsembler on devstack/LMS. """ from os import path from openedx.core.djangoapps.appsembler.settings.settings import devstack_common def plugin_settings(settings): """ Appsembler LMS overrides for devstack. """ devstack_common.plugin_settings(settings) settings.DEBUG_TOOLBAR_PATCH_SETTINGS = False settings.SITE_ID = 1 settings.EDX_API_KEY = "test" settings.ALTERNATE_QUEUE_ENVS = ['cms'] settings.USE_S3_FOR_CUSTOMER_THEMES = False if settings.ENABLE_COMPREHENSIVE_THEMING: assert len(settings.COMPREHENSIVE_THEME_DIRS) == 1, ( 'Tahoe supports a single theme, please double check that ' 'you have only one directory in the `COMPREHENSIVE_THEME_DIRS` setting.' ) # Add the LMS-generated customer CSS files to the list # LMS-generated files looks like: `appsembler-academy.tahoe.appsembler.com.css` customer_themes_dir = path.join(settings.COMPREHENSIVE_THEME_DIRS[0], 'customer_themes') if path.isdir(customer_themes_dir): settings.STATICFILES_DIRS.insert(0, customer_themes_dir) # This is used in the appsembler_sites.middleware.RedirectMiddleware to exclude certain paths # from the redirect mechanics. settings.MAIN_SITE_REDIRECT_WHITELIST += ['/media/']
""" Settings for Appsembler on devstack/LMS. """ from os import path from openedx.core.djangoapps.appsembler.settings.settings import devstack_common def plugin_settings(settings): """ Appsembler LMS overrides for devstack. """ devstack_common.plugin_settings(settings) settings.DEBUG_TOOLBAR_PATCH_SETTINGS = False settings.SITE_ID = 1 settings.EDX_API_KEY = "test" settings.ALTERNATE_QUEUE_ENVS = ['cms'] settings.USE_S3_FOR_CUSTOMER_THEMES = False if settings.ENABLE_COMPREHENSIVE_THEMING: assert len(settings.COMPREHENSIVE_THEME_DIRS) == 1, ( 'Tahoe supports a single theme, please double check that ' 'you have only one directory in the `COMPREHENSIVE_THEME_DIRS` setting.' ) # Add the LMS-generated customer CSS files to the list # LMS-generated files looks like: `appsembler-academy.tahoe.appsembler.com.css` customer_themes_dir = path.join(settings.COMPREHENSIVE_THEME_DIRS[0], 'customer_themes') if path.isdir(customer_themes_dir): settings.STATICFILES_DIRS.insert(0, ('customer_themes', customer_themes_dir)) # This is used in the appsembler_sites.middleware.RedirectMiddleware to exclude certain paths # from the redirect mechanics. settings.MAIN_SITE_REDIRECT_WHITELIST += ['/media/']
Set the customer_themes static dir prefix for devstack (no S3) customer theme file storage to match expectation in SiteConfiguration model method
Set the customer_themes static dir prefix for devstack (no S3) customer theme file storage to match expectation in SiteConfiguration model method
Python
agpl-3.0
appsembler/edx-platform,appsembler/edx-platform,appsembler/edx-platform,appsembler/edx-platform
<REPLACE_OLD> customer_themes_dir) <REPLACE_NEW> ('customer_themes', customer_themes_dir)) <REPLACE_END> <|endoftext|> """ Settings for Appsembler on devstack/LMS. """ from os import path from openedx.core.djangoapps.appsembler.settings.settings import devstack_common def plugin_settings(settings): """ Appsembler LMS overrides for devstack. """ devstack_common.plugin_settings(settings) settings.DEBUG_TOOLBAR_PATCH_SETTINGS = False settings.SITE_ID = 1 settings.EDX_API_KEY = "test" settings.ALTERNATE_QUEUE_ENVS = ['cms'] settings.USE_S3_FOR_CUSTOMER_THEMES = False if settings.ENABLE_COMPREHENSIVE_THEMING: assert len(settings.COMPREHENSIVE_THEME_DIRS) == 1, ( 'Tahoe supports a single theme, please double check that ' 'you have only one directory in the `COMPREHENSIVE_THEME_DIRS` setting.' ) # Add the LMS-generated customer CSS files to the list # LMS-generated files looks like: `appsembler-academy.tahoe.appsembler.com.css` customer_themes_dir = path.join(settings.COMPREHENSIVE_THEME_DIRS[0], 'customer_themes') if path.isdir(customer_themes_dir): settings.STATICFILES_DIRS.insert(0, ('customer_themes', customer_themes_dir)) # This is used in the appsembler_sites.middleware.RedirectMiddleware to exclude certain paths # from the redirect mechanics. settings.MAIN_SITE_REDIRECT_WHITELIST += ['/media/']
Set the customer_themes static dir prefix for devstack (no S3) customer theme file storage to match expectation in SiteConfiguration model method """ Settings for Appsembler on devstack/LMS. """ from os import path from openedx.core.djangoapps.appsembler.settings.settings import devstack_common def plugin_settings(settings): """ Appsembler LMS overrides for devstack. """ devstack_common.plugin_settings(settings) settings.DEBUG_TOOLBAR_PATCH_SETTINGS = False settings.SITE_ID = 1 settings.EDX_API_KEY = "test" settings.ALTERNATE_QUEUE_ENVS = ['cms'] settings.USE_S3_FOR_CUSTOMER_THEMES = False if settings.ENABLE_COMPREHENSIVE_THEMING: assert len(settings.COMPREHENSIVE_THEME_DIRS) == 1, ( 'Tahoe supports a single theme, please double check that ' 'you have only one directory in the `COMPREHENSIVE_THEME_DIRS` setting.' ) # Add the LMS-generated customer CSS files to the list # LMS-generated files looks like: `appsembler-academy.tahoe.appsembler.com.css` customer_themes_dir = path.join(settings.COMPREHENSIVE_THEME_DIRS[0], 'customer_themes') if path.isdir(customer_themes_dir): settings.STATICFILES_DIRS.insert(0, customer_themes_dir) # This is used in the appsembler_sites.middleware.RedirectMiddleware to exclude certain paths # from the redirect mechanics. settings.MAIN_SITE_REDIRECT_WHITELIST += ['/media/']
2f155a48bfdae8a603148f4e593d7e49fccc7ddc
setup.py
setup.py
#!/usr/bin/env python import re from setuptools import setup, find_packages with open('rhino/__init__.py') as f: version = re.findall(r"^__version__ = '(.*)'", f.read(), re.M)[0] with open('README.rst') as f: README = f.read() setup( name='Rhino', version=version, author='Stanis Trendelenburg', author_email='[email protected]', packages=find_packages(exclude=['test*', 'example*']), url='https://github.com/trendels/rhino', license='MIT', description='A microframework for building RESTful web services', long_description=README, classifiers = [ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], install_requires=['uritemplate'], )
#!/usr/bin/env python import re from setuptools import setup, find_packages with open('rhino/__init__.py') as f: version = re.findall(r"^__version__ = '(.*)'", f.read(), re.M)[0] with open('README.rst') as f: README = f.read() setup( name='Rhino', version=version, author='Stanis Trendelenburg', author_email='[email protected]', packages=find_packages(exclude=['test*', 'example*']), url='https://github.com/trendels/rhino', license='MIT', description='A microframework for building RESTful web services', long_description=README, classifiers = [ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], )
Remove line added by mistake
Remove line added by mistake
Python
mit
trendels/rhino
<REPLACE_OLD> ], install_requires=['uritemplate'], ) <REPLACE_NEW> ], ) <REPLACE_END> <|endoftext|> #!/usr/bin/env python import re from setuptools import setup, find_packages with open('rhino/__init__.py') as f: version = re.findall(r"^__version__ = '(.*)'", f.read(), re.M)[0] with open('README.rst') as f: README = f.read() setup( name='Rhino', version=version, author='Stanis Trendelenburg', author_email='[email protected]', packages=find_packages(exclude=['test*', 'example*']), url='https://github.com/trendels/rhino', license='MIT', description='A microframework for building RESTful web services', long_description=README, classifiers = [ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], )
Remove line added by mistake #!/usr/bin/env python import re from setuptools import setup, find_packages with open('rhino/__init__.py') as f: version = re.findall(r"^__version__ = '(.*)'", f.read(), re.M)[0] with open('README.rst') as f: README = f.read() setup( name='Rhino', version=version, author='Stanis Trendelenburg', author_email='[email protected]', packages=find_packages(exclude=['test*', 'example*']), url='https://github.com/trendels/rhino', license='MIT', description='A microframework for building RESTful web services', long_description=README, classifiers = [ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], install_requires=['uritemplate'], )
df7c783937d90b74c9b477b100709ed04ac0133e
monolithe/vanilla/sphinx/conf.py
monolithe/vanilla/sphinx/conf.py
# -*- coding: utf-8 -*- import sys import os import sphinx_rtd_theme extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinxcontrib.napoleon'] add_module_names = False source_suffix = '.rst' master_doc = 'index' project = u'vspk' copyright = u'2015, Nuage Networks' version = '' release = '' exclude_patterns = ['_build', '../vsdk/autogenerates'] pygments_style = 'sphinx' html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # html_theme = "pyramid" # html_static_path = ['_static'] htmlhelp_basename = '32doc' html_logo = 'nuage-logo.png' autodoc_member_order = "groupwise" autodoc_default_flags = [] napoleon_google_docstring = True napoleon_numpy_docstring = True napoleon_include_private_with_doc = False napoleon_include_special_with_doc = True napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = True napoleon_use_rtype = True
# -*- coding: utf-8 -*- import sys import os import sphinx_rtd_theme extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon'] add_module_names = False source_suffix = '.rst' master_doc = 'index' project = u'vspk' copyright = u'2015, Nuage Networks' version = '' release = '' exclude_patterns = ['_build', '../vsdk/autogenerates'] pygments_style = 'sphinx' html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # html_theme = "pyramid" # html_static_path = ['_static'] htmlhelp_basename = '32doc' html_logo = 'nuage-logo.png' autodoc_member_order = "groupwise" autodoc_default_flags = [] napoleon_google_docstring = True napoleon_numpy_docstring = True napoleon_include_private_with_doc = False napoleon_include_special_with_doc = True napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = True napoleon_use_rtype = True
Use new import for napolean
Use new import for napolean
Python
bsd-3-clause
nuagenetworks/monolithe,little-dude/monolithe,little-dude/monolithe,nuagenetworks/monolithe,little-dude/monolithe,nuagenetworks/monolithe
<REPLACE_OLD> 'sphinxcontrib.napoleon'] add_module_names <REPLACE_NEW> 'sphinx.ext.napoleon'] add_module_names <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*- import sys import os import sphinx_rtd_theme extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon'] add_module_names = False source_suffix = '.rst' master_doc = 'index' project = u'vspk' copyright = u'2015, Nuage Networks' version = '' release = '' exclude_patterns = ['_build', '../vsdk/autogenerates'] pygments_style = 'sphinx' html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # html_theme = "pyramid" # html_static_path = ['_static'] htmlhelp_basename = '32doc' html_logo = 'nuage-logo.png' autodoc_member_order = "groupwise" autodoc_default_flags = [] napoleon_google_docstring = True napoleon_numpy_docstring = True napoleon_include_private_with_doc = False napoleon_include_special_with_doc = True napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = True napoleon_use_rtype = True
Use new import for napolean # -*- coding: utf-8 -*- import sys import os import sphinx_rtd_theme extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinxcontrib.napoleon'] add_module_names = False source_suffix = '.rst' master_doc = 'index' project = u'vspk' copyright = u'2015, Nuage Networks' version = '' release = '' exclude_patterns = ['_build', '../vsdk/autogenerates'] pygments_style = 'sphinx' html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # html_theme = "pyramid" # html_static_path = ['_static'] htmlhelp_basename = '32doc' html_logo = 'nuage-logo.png' autodoc_member_order = "groupwise" autodoc_default_flags = [] napoleon_google_docstring = True napoleon_numpy_docstring = True napoleon_include_private_with_doc = False napoleon_include_special_with_doc = True napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = True napoleon_use_rtype = True
dbb58d2898f9f9a4824ee9596e52da9eaa92cab1
examples/get_secure_user_falco_rules.py
examples/get_secure_user_falco_rules.py
#!/usr/bin/env python # # Get the sysdig secure user rules file. # import os import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdSecureClient # # Parse arguments # if len(sys.argv) != 2: print('usage: %s <sysdig-token>' % sys.argv[0]) print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] # # Instantiate the SDC client # sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com') # # Get the configuration # ok, res = sdclient.get_user_falco_rules() # # Return the result # if ok: sys.stdout.write(res[1]["userRulesFile"]["content"]) else: print(res) sys.exit(1)
#!/usr/bin/env python # # Get the sysdig secure user rules file. # import os import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdSecureClient # # Parse arguments # if len(sys.argv) != 2: print('usage: %s <sysdig-token>' % sys.argv[0]) print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] # # Instantiate the SDC client # sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com') # # Get the configuration # ok, res = sdclient.get_user_falco_rules() # # Return the result # if ok: sys.stdout.write(res["userRulesFile"]["content"]) else: print(res) sys.exit(1)
Fix legacy use of action result
Fix legacy use of action result
Python
mit
draios/python-sdc-client,draios/python-sdc-client
<REPLACE_OLD> sys.stdout.write(res[1]["userRulesFile"]["content"]) else: <REPLACE_NEW> sys.stdout.write(res["userRulesFile"]["content"]) else: <REPLACE_END> <|endoftext|> #!/usr/bin/env python # # Get the sysdig secure user rules file. # import os import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdSecureClient # # Parse arguments # if len(sys.argv) != 2: print('usage: %s <sysdig-token>' % sys.argv[0]) print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] # # Instantiate the SDC client # sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com') # # Get the configuration # ok, res = sdclient.get_user_falco_rules() # # Return the result # if ok: sys.stdout.write(res["userRulesFile"]["content"]) else: print(res) sys.exit(1)
Fix legacy use of action result #!/usr/bin/env python # # Get the sysdig secure user rules file. # import os import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdSecureClient # # Parse arguments # if len(sys.argv) != 2: print('usage: %s <sysdig-token>' % sys.argv[0]) print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] # # Instantiate the SDC client # sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com') # # Get the configuration # ok, res = sdclient.get_user_falco_rules() # # Return the result # if ok: sys.stdout.write(res[1]["userRulesFile"]["content"]) else: print(res) sys.exit(1)
a30be93bf4aeef78158898c07252fd29e0303a57
frigg/authentication/models.py
frigg/authentication/models.py
# -*- coding: utf8 -*- from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth from frigg.helpers import github class User(AbstractUser): @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return def save(self, *args, **kwargs): create = hasattr(self, 'id') super(User, self).save(*args, **kwargs) if create: self.update_repo_permissions() def update_repo_permissions(self): if self.github_token: github.update_repo_permissions(self)
# -*- coding: utf8 -*- from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth from frigg.helpers import github class User(AbstractUser): @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return def save(self, *args, **kwargs): create = not hasattr(self, 'id') super(User, self).save(*args, **kwargs) if create: self.update_repo_permissions() def update_repo_permissions(self): if self.github_token: github.update_repo_permissions(self)
Fix update permission on user
Fix update permission on user Only run it when user is created, not when it they are saved
Python
mit
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
<INSERT> not <INSERT_END> <|endoftext|> # -*- coding: utf8 -*- from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth from frigg.helpers import github class User(AbstractUser): @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return def save(self, *args, **kwargs): create = not hasattr(self, 'id') super(User, self).save(*args, **kwargs) if create: self.update_repo_permissions() def update_repo_permissions(self): if self.github_token: github.update_repo_permissions(self)
Fix update permission on user Only run it when user is created, not when it they are saved # -*- coding: utf8 -*- from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth from frigg.helpers import github class User(AbstractUser): @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return def save(self, *args, **kwargs): create = hasattr(self, 'id') super(User, self).save(*args, **kwargs) if create: self.update_repo_permissions() def update_repo_permissions(self): if self.github_token: github.update_repo_permissions(self)
3bbe539f387697137040f665958e0e0e27e6a420
tests/test_session.py
tests/test_session.py
# Local imports from uplink import session def test_base_url(uplink_builder_mock): # Setup uplink_builder_mock.base_url = "https://api.github.com" sess = session.Session(uplink_builder_mock) # Run & Verify assert uplink_builder_mock.base_url == sess.base_url def test_headers(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.headers["key"] = "value" # Verify assert uplink_builder_mock.add_hook.called assert sess.headers == {"key": "value"} def test_params(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.params["key"] = "value" # Verify uplink_builder_mock.add_hook.assert_called() assert sess.params == {"key": "value"} def test_auth(uplink_builder_mock): # Setup uplink_builder_mock.auth = ("username", "password") sess = session.Session(uplink_builder_mock) # Run & Verify assert uplink_builder_mock.auth == sess.auth def test_auth_set(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.auth = ("username", "password") # Verify assert ("username", "password") == uplink_builder_mock.auth
# Local imports from uplink import session def test_base_url(uplink_builder_mock): # Setup uplink_builder_mock.base_url = "https://api.github.com" sess = session.Session(uplink_builder_mock) # Run & Verify assert uplink_builder_mock.base_url == sess.base_url def test_headers(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.headers["key"] = "value" # Verify assert uplink_builder_mock.add_hook.called assert sess.headers == {"key": "value"} def test_params(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.params["key"] = "value" # Verify assert uplink_builder_mock.add_hook.called assert sess.params == {"key": "value"} def test_auth(uplink_builder_mock): # Setup uplink_builder_mock.auth = ("username", "password") sess = session.Session(uplink_builder_mock) # Run & Verify assert uplink_builder_mock.auth == sess.auth def test_auth_set(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.auth = ("username", "password") # Verify assert ("username", "password") == uplink_builder_mock.auth
Fix `assert_called` usage for Python 3.5 build
Fix `assert_called` usage for Python 3.5 build The `assert_called` method seems to invoke a bug caused by a type in the unittest mock module. (The bug was ultimately tracked and fix here: https://bugs.python.org/issue24656)
Python
mit
prkumar/uplink
<REPLACE_OLD> uplink_builder_mock.add_hook.assert_called() <REPLACE_NEW> assert uplink_builder_mock.add_hook.called <REPLACE_END> <|endoftext|> # Local imports from uplink import session def test_base_url(uplink_builder_mock): # Setup uplink_builder_mock.base_url = "https://api.github.com" sess = session.Session(uplink_builder_mock) # Run & Verify assert uplink_builder_mock.base_url == sess.base_url def test_headers(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.headers["key"] = "value" # Verify assert uplink_builder_mock.add_hook.called assert sess.headers == {"key": "value"} def test_params(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.params["key"] = "value" # Verify assert uplink_builder_mock.add_hook.called assert sess.params == {"key": "value"} def test_auth(uplink_builder_mock): # Setup uplink_builder_mock.auth = ("username", "password") sess = session.Session(uplink_builder_mock) # Run & Verify assert uplink_builder_mock.auth == sess.auth def test_auth_set(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.auth = ("username", "password") # Verify assert ("username", "password") == uplink_builder_mock.auth
Fix `assert_called` usage for Python 3.5 build The `assert_called` method seems to invoke a bug caused by a type in the unittest mock module. (The bug was ultimately tracked and fix here: https://bugs.python.org/issue24656) # Local imports from uplink import session def test_base_url(uplink_builder_mock): # Setup uplink_builder_mock.base_url = "https://api.github.com" sess = session.Session(uplink_builder_mock) # Run & Verify assert uplink_builder_mock.base_url == sess.base_url def test_headers(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.headers["key"] = "value" # Verify assert uplink_builder_mock.add_hook.called assert sess.headers == {"key": "value"} def test_params(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.params["key"] = "value" # Verify uplink_builder_mock.add_hook.assert_called() assert sess.params == {"key": "value"} def test_auth(uplink_builder_mock): # Setup uplink_builder_mock.auth = ("username", "password") sess = session.Session(uplink_builder_mock) # Run & Verify assert uplink_builder_mock.auth == sess.auth def test_auth_set(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.auth = ("username", "password") # Verify assert ("username", "password") == uplink_builder_mock.auth
6d91ed53a15672b1e70d74691158e9afb7162e74
src/etcd/__init__.py
src/etcd/__init__.py
import collections from client import Client class EtcdResult(collections.namedtuple( 'EtcdResult', [ 'action', 'index', 'key', 'prevValue', 'value', 'expiration', 'ttl', 'newKey'])): def __new__( cls, action=None, index=None, key=None, prevValue=None, value=None, expiration=None, ttl=None, newKey=None): return super(EtcdResult, cls).__new__( cls, action, index, key, prevValue, value, expiration, ttl, newKey) class EtcdException(Exception): """ Generic Etcd Exception. """ pass
import collections from client import Client class EtcdResult(collections.namedtuple( 'EtcdResult', [ 'action', 'index', 'key', 'prevValue', 'value', 'expiration', 'ttl', 'newKey'])): def __new__( cls, action=None, index=None, key=None, prevValue=None, value=None, expiration=None, ttl=None, newKey=None): return super(EtcdResult, cls).__new__( cls, action, index, key, prevValue, value, expiration, ttl, newKey) class EtcdException(Exception): """ Generic Etcd Exception. """ pass # Attempt to enable urllib3's SNI support, if possible # Blatantly copied from requests. try: from urllib3.contrib import pyopenssl pyopenssl.inject_into_urllib3() except ImportError: pass
Add optional support for SSL SNI
Add optional support for SSL SNI
Python
mit
dmonroy/python-etcd,ocadotechnology/python-etcd,thepwagner/python-etcd,dmonroy/python-etcd,jlamillan/python-etcd,ocadotechnology/python-etcd,aziontech/python-etcd,jplana/python-etcd,sentinelleader/python-etcd,vodik/python-etcd,projectcalico/python-etcd,j-mcnally/python-etcd,j-mcnally/python-etcd,mbrukman/python-etcd,aziontech/python-etcd,jlamillan/python-etcd,kireal/python-etcd,jplana/python-etcd,kireal/python-etcd,mbrukman/python-etcd,vodik/python-etcd,thepwagner/python-etcd,projectcalico/python-etcd,sentinelleader/python-etcd
<INSERT> pass # Attempt to enable urllib3's SNI support, if possible # Blatantly copied from requests. try: from urllib3.contrib import pyopenssl pyopenssl.inject_into_urllib3() except ImportError: <INSERT_END> <|endoftext|> import collections from client import Client class EtcdResult(collections.namedtuple( 'EtcdResult', [ 'action', 'index', 'key', 'prevValue', 'value', 'expiration', 'ttl', 'newKey'])): def __new__( cls, action=None, index=None, key=None, prevValue=None, value=None, expiration=None, ttl=None, newKey=None): return super(EtcdResult, cls).__new__( cls, action, index, key, prevValue, value, expiration, ttl, newKey) class EtcdException(Exception): """ Generic Etcd Exception. """ pass # Attempt to enable urllib3's SNI support, if possible # Blatantly copied from requests. try: from urllib3.contrib import pyopenssl pyopenssl.inject_into_urllib3() except ImportError: pass
Add optional support for SSL SNI import collections from client import Client class EtcdResult(collections.namedtuple( 'EtcdResult', [ 'action', 'index', 'key', 'prevValue', 'value', 'expiration', 'ttl', 'newKey'])): def __new__( cls, action=None, index=None, key=None, prevValue=None, value=None, expiration=None, ttl=None, newKey=None): return super(EtcdResult, cls).__new__( cls, action, index, key, prevValue, value, expiration, ttl, newKey) class EtcdException(Exception): """ Generic Etcd Exception. """ pass
056cb6d5dff67fe029a080abeaba36faee5cff60
lib/test_util.py
lib/test_util.py
from lettuce import world from tornado.escape import json_decode from tornado.httpclient import HTTPClient from newebe.settings import TORNADO_PORT client = HTTPClient() ROOT_URL = "http://localhost:%d/" % TORNADO_PORT def fetch_documents_from_url(url): ''' Retrieve newebe documents from a givent url ''' response = client.fetch(url) assert response.code == 200 assert response.headers["Content-Type"] == "application/json" world.data = json_decode(response.body) return world.data["rows"] def fetch_documents(path): fetch_documents_from_url(ROOT_URL + path)
from lettuce import world from tornado.escape import json_decode from tornado.httpclient import HTTPClient from newebe.settings import TORNADO_PORT ROOT_URL = "http://localhost:%d/" % TORNADO_PORT class NewebeClient(HTTPClient): ''' Tornado client wrapper to write POST, PUT and delete request faster. ''' def get(self, url): return HTTPClient.fetch(self, url) def post(self, url, body): return HTTPClient.fetch(self, url, method="POST", body=body) def put(self, url, body): return HTTPClient.fetch(self, url, method="PUT", body=body) def delete(self, url): return HTTPClient.fetch(self, url, method="DELETE") def fetch_documents_from_url(self, url): ''' Retrieve newebe documents from a givent url ''' response = self.get(url) assert response.code == 200 assert response.headers["Content-Type"] == "application/json" world.data = json_decode(response.body) return world.data["rows"] def fetch_documents(self, path): self.fetch_documents_from_url(ROOT_URL + path)
Make newebe HTTP client for easier requesting
Make newebe HTTP client for easier requesting
Python
agpl-3.0
gelnior/newebe,gelnior/newebe,gelnior/newebe,gelnior/newebe
<REPLACE_OLD> TORNADO_PORT client = HTTPClient() ROOT_URL <REPLACE_NEW> TORNADO_PORT ROOT_URL <REPLACE_END> <REPLACE_OLD> TORNADO_PORT def fetch_documents_from_url(url): <REPLACE_NEW> TORNADO_PORT class NewebeClient(HTTPClient): <REPLACE_END> <INSERT> Tornado client wrapper to write POST, PUT and delete request faster. ''' def get(self, url): return HTTPClient.fetch(self, url) def post(self, url, body): return HTTPClient.fetch(self, url, method="POST", body=body) def put(self, url, body): return HTTPClient.fetch(self, url, method="PUT", body=body) def delete(self, url): return HTTPClient.fetch(self, url, method="DELETE") def fetch_documents_from_url(self, url): ''' <INSERT_END> <INSERT> <INSERT_END> <INSERT> <INSERT_END> <REPLACE_OLD> client.fetch(url) <REPLACE_NEW> self.get(url) <REPLACE_END> <INSERT> <INSERT_END> <INSERT> <INSERT_END> <REPLACE_OLD> return world.data["rows"] def fetch_documents(path): fetch_documents_from_url(ROOT_URL <REPLACE_NEW> return world.data["rows"] def fetch_documents(self, path): self.fetch_documents_from_url(ROOT_URL <REPLACE_END> <REPLACE_OLD> path) <REPLACE_NEW> path) <REPLACE_END> <|endoftext|> from lettuce import world from tornado.escape import json_decode from tornado.httpclient import HTTPClient from newebe.settings import TORNADO_PORT ROOT_URL = "http://localhost:%d/" % TORNADO_PORT class NewebeClient(HTTPClient): ''' Tornado client wrapper to write POST, PUT and delete request faster. ''' def get(self, url): return HTTPClient.fetch(self, url) def post(self, url, body): return HTTPClient.fetch(self, url, method="POST", body=body) def put(self, url, body): return HTTPClient.fetch(self, url, method="PUT", body=body) def delete(self, url): return HTTPClient.fetch(self, url, method="DELETE") def fetch_documents_from_url(self, url): ''' Retrieve newebe documents from a givent url ''' response = self.get(url) assert response.code == 200 assert response.headers["Content-Type"] == "application/json" world.data = json_decode(response.body) return world.data["rows"] def fetch_documents(self, path): self.fetch_documents_from_url(ROOT_URL + path)
Make newebe HTTP client for easier requesting from lettuce import world from tornado.escape import json_decode from tornado.httpclient import HTTPClient from newebe.settings import TORNADO_PORT client = HTTPClient() ROOT_URL = "http://localhost:%d/" % TORNADO_PORT def fetch_documents_from_url(url): ''' Retrieve newebe documents from a givent url ''' response = client.fetch(url) assert response.code == 200 assert response.headers["Content-Type"] == "application/json" world.data = json_decode(response.body) return world.data["rows"] def fetch_documents(path): fetch_documents_from_url(ROOT_URL + path)
ebcc2e9d4295b1e85e43c7b7a01c69a7f28193a5
hera_mc/tests/test_utils.py
hera_mc/tests/test_utils.py
import nose.tools as nt from .. import utils def test_reraise_context(): with nt.assert_raises(ValueError) as cm: try: raise ValueError('Initial Exception message.') except ValueError: utils._reraise_context('Add some info') ex = cm.exception nt.assert_equal(ex.args[0], 'Add some info: Initial Exception message.') with nt.assert_raises(ValueError) as cm: try: raise ValueError('Initial Exception message.') except ValueError: utils._reraise_context('Add some info %s', 'and then more') ex = cm.exception nt.assert_equal(ex.args[0], 'Add some info and then more: Initial Exception message.') with nt.assert_raises(EnvironmentError) as cm: try: raise EnvironmentError(1, 'some bad problem') except EnvironmentError: utils._reraise_context('Add some info') ex = cm.exception nt.assert_equal(ex.args[1], 'Add some info: some bad problem')
Add testing for reraise function
Add testing for reraise function
Python
bsd-2-clause
HERA-Team/hera_mc,HERA-Team/hera_mc,HERA-Team/Monitor_and_Control
<REPLACE_OLD> <REPLACE_NEW> import nose.tools as nt from .. import utils def test_reraise_context(): with nt.assert_raises(ValueError) as cm: try: raise ValueError('Initial Exception message.') except ValueError: utils._reraise_context('Add some info') ex = cm.exception nt.assert_equal(ex.args[0], 'Add some info: Initial Exception message.') with nt.assert_raises(ValueError) as cm: try: raise ValueError('Initial Exception message.') except ValueError: utils._reraise_context('Add some info %s', 'and then more') ex = cm.exception nt.assert_equal(ex.args[0], 'Add some info and then more: Initial Exception message.') with nt.assert_raises(EnvironmentError) as cm: try: raise EnvironmentError(1, 'some bad problem') except EnvironmentError: utils._reraise_context('Add some info') ex = cm.exception nt.assert_equal(ex.args[1], 'Add some info: some bad problem') <REPLACE_END> <|endoftext|> import nose.tools as nt from .. import utils def test_reraise_context(): with nt.assert_raises(ValueError) as cm: try: raise ValueError('Initial Exception message.') except ValueError: utils._reraise_context('Add some info') ex = cm.exception nt.assert_equal(ex.args[0], 'Add some info: Initial Exception message.') with nt.assert_raises(ValueError) as cm: try: raise ValueError('Initial Exception message.') except ValueError: utils._reraise_context('Add some info %s', 'and then more') ex = cm.exception nt.assert_equal(ex.args[0], 'Add some info and then more: Initial Exception message.') with nt.assert_raises(EnvironmentError) as cm: try: raise EnvironmentError(1, 'some bad problem') except EnvironmentError: utils._reraise_context('Add some info') ex = cm.exception nt.assert_equal(ex.args[1], 'Add some info: some bad problem')
Add testing for reraise function
a4d5e88973a25464be26488d17ecc663cce776d7
altair/examples/world_map.py
altair/examples/world_map.py
""" World Map --------- This example shows how to create a world map using data generators for different background layers. """ # category: maps import altair as alt from vega_datasets import data # Data generators for the background sphere = alt.sphere() graticule = alt.graticule() # Source of land data source = alt.topo_feature(data.world_110m.url, 'countries') # Layering and configuring the components alt.layer( alt.Chart(sphere).mark_geoshape(fill='lightblue'), alt.Chart(graticule).mark_geoshape(stroke='white', strokeWidth=0.5), alt.Chart(source).mark_geoshape(fill='ForestGreen', stroke='black') ).project( 'naturalEarth1' ).properties(width=600, height=400).configure_view(stroke=None)
Add map example with data generators
DOC: Add map example with data generators
Python
bsd-3-clause
jakevdp/altair,altair-viz/altair
<INSERT> """ World Map --------- This example shows how to create a world map using data generators for different background layers. """ # category: maps import altair as alt from vega_datasets import data # Data generators for the background sphere = alt.sphere() graticule = alt.graticule() # Source of land data source = alt.topo_feature(data.world_110m.url, 'countries') # Layering and configuring the components alt.layer( <INSERT_END> <INSERT> alt.Chart(sphere).mark_geoshape(fill='lightblue'), alt.Chart(graticule).mark_geoshape(stroke='white', strokeWidth=0.5), alt.Chart(source).mark_geoshape(fill='ForestGreen', stroke='black') ).project( 'naturalEarth1' ).properties(width=600, height=400).configure_view(stroke=None) <INSERT_END> <|endoftext|> """ World Map --------- This example shows how to create a world map using data generators for different background layers. """ # category: maps import altair as alt from vega_datasets import data # Data generators for the background sphere = alt.sphere() graticule = alt.graticule() # Source of land data source = alt.topo_feature(data.world_110m.url, 'countries') # Layering and configuring the components alt.layer( alt.Chart(sphere).mark_geoshape(fill='lightblue'), alt.Chart(graticule).mark_geoshape(stroke='white', strokeWidth=0.5), alt.Chart(source).mark_geoshape(fill='ForestGreen', stroke='black') ).project( 'naturalEarth1' ).properties(width=600, height=400).configure_view(stroke=None)
DOC: Add map example with data generators
1f3183acbe50df32d76d1cc0cb71b4cd9afdaa79
controller/__init__.py
controller/__init__.py
# -*- coding: utf-8 -*- import sys __version__ = '0.6.0' FRAMEWORK_NAME = 'RAPyDo' # PROJECT_YAML_SPECSDIR = 'specs' COMPOSE_ENVIRONMENT_FILE = '.env' SUBMODULES_DIR = 'submodules' PLACEHOLDER = '#@$%-REPLACE-#@%$-ME-#@$%' ################## # NOTE: telling the app if testing or not # http://j.mp/2uifoza TESTING = hasattr(sys, '_called_from_test')
# -*- coding: utf-8 -*- import sys __version__ = '0.5.1' FRAMEWORK_NAME = 'RAPyDo' # PROJECT_YAML_SPECSDIR = 'specs' COMPOSE_ENVIRONMENT_FILE = '.env' SUBMODULES_DIR = 'submodules' PLACEHOLDER = '#@$%-REPLACE-#@%$-ME-#@$%' ################## # NOTE: telling the app if testing or not # http://j.mp/2uifoza TESTING = hasattr(sys, '_called_from_test')
Fix version with last package
Fix version with last package
Python
mit
rapydo/do
<REPLACE_OLD> '0.6.0' FRAMEWORK_NAME <REPLACE_NEW> '0.5.1' FRAMEWORK_NAME <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*- import sys __version__ = '0.5.1' FRAMEWORK_NAME = 'RAPyDo' # PROJECT_YAML_SPECSDIR = 'specs' COMPOSE_ENVIRONMENT_FILE = '.env' SUBMODULES_DIR = 'submodules' PLACEHOLDER = '#@$%-REPLACE-#@%$-ME-#@$%' ################## # NOTE: telling the app if testing or not # http://j.mp/2uifoza TESTING = hasattr(sys, '_called_from_test')
Fix version with last package # -*- coding: utf-8 -*- import sys __version__ = '0.6.0' FRAMEWORK_NAME = 'RAPyDo' # PROJECT_YAML_SPECSDIR = 'specs' COMPOSE_ENVIRONMENT_FILE = '.env' SUBMODULES_DIR = 'submodules' PLACEHOLDER = '#@$%-REPLACE-#@%$-ME-#@$%' ################## # NOTE: telling the app if testing or not # http://j.mp/2uifoza TESTING = hasattr(sys, '_called_from_test')
e53a1c33dd3ce5258aff384257bd218f14c8870e
setup.py
setup.py
import os import sys import setuptools from keystoneclient.openstack.common import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() requires = setup.parse_requirements() depend_links = setup.parse_dependency_links() tests_require = setup.parse_requirements(['tools/test-requires']) setuptools.setup( name="python-keystoneclient", version=setup.get_post_version('keystoneclient'), description="Client library for OpenStack Identity API (Keystone)", long_description=read('README.rst'), url='https://github.com/openstack/python-keystoneclient', license='Apache', author='Nebula Inc, based on work by Rackspace and Jacob Kaplan-Moss', author_email='[email protected]', packages=setuptools.find_packages(exclude=['tests', 'tests.*']), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: OpenStack', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], install_requires=requires, dependency_links=depend_links, cmdclass=setup.get_cmdclass(), tests_require=tests_require, test_suite="nose.collector", entry_points={ 'console_scripts': ['keystone = keystoneclient.shell:main'] } )
import os import sys import setuptools from keystoneclient.openstack.common import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() requires = setup.parse_requirements() depend_links = setup.parse_dependency_links() tests_require = setup.parse_requirements(['tools/test-requires']) setuptools.setup( name="python-keystoneclient", version=setup.get_post_version('keystoneclient'), description="Client library for OpenStack Identity API (Keystone)", long_description=read('README.rst'), url='https://github.com/openstack/python-keystoneclient', license='Apache', author='Nebula Inc, based on work by Rackspace and Jacob Kaplan-Moss', author_email='[email protected]', packages=setuptools.find_packages(exclude=['tests', 'tests.*']), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: OpenStack', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], install_requires=requires, dependency_links=depend_links, cmdclass=setup.get_cmdclass(), tests_require=tests_require, test_suite="nose.collector", entry_points={ 'console_scripts': ['keystone = keystoneclient.shell:main'] }, data_files=[('keystoneclient', ['keystoneclient/versioninfo'])], )
Add --version CLI opt and __version__ module attr
Add --version CLI opt and __version__ module attr Change-Id: I8c39a797e79429dd21c5caf093b076a4b1757de0
Python
apache-2.0
citrix-openstack-build/keystoneauth,jamielennox/keystoneauth,sileht/keystoneauth
<REPLACE_OLD> } ) <REPLACE_NEW> }, data_files=[('keystoneclient', ['keystoneclient/versioninfo'])], ) <REPLACE_END> <|endoftext|> import os import sys import setuptools from keystoneclient.openstack.common import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() requires = setup.parse_requirements() depend_links = setup.parse_dependency_links() tests_require = setup.parse_requirements(['tools/test-requires']) setuptools.setup( name="python-keystoneclient", version=setup.get_post_version('keystoneclient'), description="Client library for OpenStack Identity API (Keystone)", long_description=read('README.rst'), url='https://github.com/openstack/python-keystoneclient', license='Apache', author='Nebula Inc, based on work by Rackspace and Jacob Kaplan-Moss', author_email='[email protected]', packages=setuptools.find_packages(exclude=['tests', 'tests.*']), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: OpenStack', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], install_requires=requires, dependency_links=depend_links, cmdclass=setup.get_cmdclass(), tests_require=tests_require, test_suite="nose.collector", entry_points={ 'console_scripts': ['keystone = keystoneclient.shell:main'] }, data_files=[('keystoneclient', ['keystoneclient/versioninfo'])], )
Add --version CLI opt and __version__ module attr Change-Id: I8c39a797e79429dd21c5caf093b076a4b1757de0 import os import sys import setuptools from keystoneclient.openstack.common import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() requires = setup.parse_requirements() depend_links = setup.parse_dependency_links() tests_require = setup.parse_requirements(['tools/test-requires']) setuptools.setup( name="python-keystoneclient", version=setup.get_post_version('keystoneclient'), description="Client library for OpenStack Identity API (Keystone)", long_description=read('README.rst'), url='https://github.com/openstack/python-keystoneclient', license='Apache', author='Nebula Inc, based on work by Rackspace and Jacob Kaplan-Moss', author_email='[email protected]', packages=setuptools.find_packages(exclude=['tests', 'tests.*']), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: OpenStack', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], install_requires=requires, dependency_links=depend_links, cmdclass=setup.get_cmdclass(), tests_require=tests_require, test_suite="nose.collector", entry_points={ 'console_scripts': ['keystone = keystoneclient.shell:main'] } )
b9d1dcf614faa949975bc5296be451abd2594835
repository/presenter.py
repository/presenter.py
import logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if argv.top_n > 0 else None sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed)
import logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if top_n < 0 or top_n > len(counter): top_n = len(counter) sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed)
Fix small issue with `--top-n` command switch
Fix small issue with `--top-n` command switch
Python
mit
moacirosa/git-current-contributors,moacirosa/git-current-contributors
<REPLACE_OLD> argv.top_n if argv.top_n <REPLACE_NEW> argv.top_n if top_n < 0 or top_n <REPLACE_END> <REPLACE_OLD> 0 else None <REPLACE_NEW> len(counter): top_n = len(counter) <REPLACE_END> <|endoftext|> import logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if top_n < 0 or top_n > len(counter): top_n = len(counter) sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed)
Fix small issue with `--top-n` command switch import logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if argv.top_n > 0 else None sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed)
5344c97e7486229f9fae40bef2b73488d5aa2ffd
uchicagohvz/users/tasks.py
uchicagohvz/users/tasks.py
from celery import task from django.conf import settings from django.core import mail import smtplib @task(rate_limit=0.2) def do_sympa_update(user, listname, subscribe): if subscribe: body = "QUIET ADD %s %s %s" % (listname, user.email, user.get_full_name()) else: body = "QUIET DELETE %s %s" % (listname, user.email) email = mail.EmailMessage(subject='', body=body, from_email=settings.SYMPA_FROM_EMAIL, to=[settings.SYMPA_TO_EMAIL]) email.send() @task def smtp_localhost_send(from_addr, to_addrs, msg): server = smtplib.SMTP('localhost') server.sendmail(from_addr, to_addrs, msg) server.quit()
from celery import task from django.conf import settings from django.core import mail import smtplib @task def do_sympa_update(user, listname, subscribe): if subscribe: body = "QUIET ADD %s %s %s" % (listname, user.email, user.get_full_name()) else: body = "QUIET DELETE %s %s" % (listname, user.email) email = mail.EmailMessage(subject='', body=body, from_email=settings.SYMPA_FROM_EMAIL, to=[settings.SYMPA_TO_EMAIL]) email.send() @task def smtp_localhost_send(from_addr, to_addrs, msg): server = smtplib.SMTP('localhost') server.sendmail(from_addr, to_addrs, msg) server.quit()
Remove rate limit from do_sympa_update
Remove rate limit from do_sympa_update
Python
mit
kz26/uchicago-hvz,kz26/uchicago-hvz,kz26/uchicago-hvz
<REPLACE_OLD> smtplib @task(rate_limit=0.2) def <REPLACE_NEW> smtplib @task def <REPLACE_END> <|endoftext|> from celery import task from django.conf import settings from django.core import mail import smtplib @task def do_sympa_update(user, listname, subscribe): if subscribe: body = "QUIET ADD %s %s %s" % (listname, user.email, user.get_full_name()) else: body = "QUIET DELETE %s %s" % (listname, user.email) email = mail.EmailMessage(subject='', body=body, from_email=settings.SYMPA_FROM_EMAIL, to=[settings.SYMPA_TO_EMAIL]) email.send() @task def smtp_localhost_send(from_addr, to_addrs, msg): server = smtplib.SMTP('localhost') server.sendmail(from_addr, to_addrs, msg) server.quit()
Remove rate limit from do_sympa_update from celery import task from django.conf import settings from django.core import mail import smtplib @task(rate_limit=0.2) def do_sympa_update(user, listname, subscribe): if subscribe: body = "QUIET ADD %s %s %s" % (listname, user.email, user.get_full_name()) else: body = "QUIET DELETE %s %s" % (listname, user.email) email = mail.EmailMessage(subject='', body=body, from_email=settings.SYMPA_FROM_EMAIL, to=[settings.SYMPA_TO_EMAIL]) email.send() @task def smtp_localhost_send(from_addr, to_addrs, msg): server = smtplib.SMTP('localhost') server.sendmail(from_addr, to_addrs, msg) server.quit()
9887e5fe0253f4e44acdb438bc769313985e1080
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup setup( name="segfault", version="0.0.1", author="Sean Kelly", author_email="[email protected]", description="A library that makes the Python interpreter segfault.", license="MIT", keywords="segfault", py_modules=['segfault', 'satire'], )
#!/usr/bin/env python from setuptools import setup setup( name="segfault", version="0.0.1", author="Sean Kelly", author_email="[email protected]", description="A library that makes the Python interpreter segfault.", license="MIT", url='https://github.com/cbgbt/segfault', download_url='https://github.com/cbgbt/segfault/archive/v0.0.1.tar.gz', keywords="segfault", py_modules=['segfault', 'satire'], )
Add pypi url and download_url
Add pypi url and download_url
Python
mit
cbgbt/segfault,cbgbt/segfault
<INSERT> url='https://github.com/cbgbt/segfault', download_url='https://github.com/cbgbt/segfault/archive/v0.0.1.tar.gz', <INSERT_END> <|endoftext|> #!/usr/bin/env python from setuptools import setup setup( name="segfault", version="0.0.1", author="Sean Kelly", author_email="[email protected]", description="A library that makes the Python interpreter segfault.", license="MIT", url='https://github.com/cbgbt/segfault', download_url='https://github.com/cbgbt/segfault/archive/v0.0.1.tar.gz', keywords="segfault", py_modules=['segfault', 'satire'], )
Add pypi url and download_url #!/usr/bin/env python from setuptools import setup setup( name="segfault", version="0.0.1", author="Sean Kelly", author_email="[email protected]", description="A library that makes the Python interpreter segfault.", license="MIT", keywords="segfault", py_modules=['segfault', 'satire'], )
ae65aa843a2da11f4a237ce52de3b034826c40e8
setup.py
setup.py
#!/usr/bin/env python VERSION = "0.5.1" from setuptools import setup, find_packages classifiers = [ 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Topic :: Scientific/Engineering', 'Topic :: Text Processing :: Linguistic' ] GITHUB_URL = 'http://github.com/LuminosoInsight/luminoso-api-client-python' setup( name="luminoso-api", version=VERSION, maintainer='Luminoso Technologies, Inc.', maintainer_email='[email protected]', url=GITHUB_URL, download_url='%s/tarball/v%s' % (GITHUB_URL, VERSION), platforms=["any"], description="Python client library for communicating with the Luminoso REST API", classifiers=classifiers, packages=find_packages(), install_requires=[ 'requests >= 1.2.1, < 3.0', 'ftfy >= 3.3, < 5', ], entry_points={ 'console_scripts': [ 'lumi-upload = luminoso_api.upload:main', 'lumi-json-stream = luminoso_api.json_stream:main', ]}, )
#!/usr/bin/env python VERSION = "0.5.1" from setuptools import setup, find_packages classifiers = [ 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Topic :: Scientific/Engineering', 'Topic :: Text Processing :: Linguistic' ] GITHUB_URL = 'http://github.com/LuminosoInsight/luminoso-api-client-python' setup( name="luminoso-api", version=VERSION, maintainer='Luminoso Technologies, Inc.', maintainer_email='[email protected]', url=GITHUB_URL, download_url='%s/tarball/v%s' % (GITHUB_URL, VERSION), platforms=["any"], description="Python client library for communicating with the Luminoso REST API", classifiers=classifiers, packages=find_packages(exclude=('tests',)), install_requires=[ 'requests >= 1.2.1, < 3.0', 'ftfy >= 3.3, < 5', ], entry_points={ 'console_scripts': [ 'lumi-upload = luminoso_api.upload:main', 'lumi-json-stream = luminoso_api.json_stream:main', ]}, )
Exclude the tests directory when finding packages (for consistency and future-proofing).
Exclude the tests directory when finding packages (for consistency and future-proofing).
Python
mit
LuminosoInsight/luminoso-api-client-python
<REPLACE_OLD> packages=find_packages(), <REPLACE_NEW> packages=find_packages(exclude=('tests',)), <REPLACE_END> <|endoftext|> #!/usr/bin/env python VERSION = "0.5.1" from setuptools import setup, find_packages classifiers = [ 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Topic :: Scientific/Engineering', 'Topic :: Text Processing :: Linguistic' ] GITHUB_URL = 'http://github.com/LuminosoInsight/luminoso-api-client-python' setup( name="luminoso-api", version=VERSION, maintainer='Luminoso Technologies, Inc.', maintainer_email='[email protected]', url=GITHUB_URL, download_url='%s/tarball/v%s' % (GITHUB_URL, VERSION), platforms=["any"], description="Python client library for communicating with the Luminoso REST API", classifiers=classifiers, packages=find_packages(exclude=('tests',)), install_requires=[ 'requests >= 1.2.1, < 3.0', 'ftfy >= 3.3, < 5', ], entry_points={ 'console_scripts': [ 'lumi-upload = luminoso_api.upload:main', 'lumi-json-stream = luminoso_api.json_stream:main', ]}, )
Exclude the tests directory when finding packages (for consistency and future-proofing). #!/usr/bin/env python VERSION = "0.5.1" from setuptools import setup, find_packages classifiers = [ 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Topic :: Scientific/Engineering', 'Topic :: Text Processing :: Linguistic' ] GITHUB_URL = 'http://github.com/LuminosoInsight/luminoso-api-client-python' setup( name="luminoso-api", version=VERSION, maintainer='Luminoso Technologies, Inc.', maintainer_email='[email protected]', url=GITHUB_URL, download_url='%s/tarball/v%s' % (GITHUB_URL, VERSION), platforms=["any"], description="Python client library for communicating with the Luminoso REST API", classifiers=classifiers, packages=find_packages(), install_requires=[ 'requests >= 1.2.1, < 3.0', 'ftfy >= 3.3, < 5', ], entry_points={ 'console_scripts': [ 'lumi-upload = luminoso_api.upload:main', 'lumi-json-stream = luminoso_api.json_stream:main', ]}, )
739be6f9d80b95fc4c0918f64be8438eb04736a1
manage.py
manage.py
from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import db, create_app from app.models import User, BucketList, Item app = create_app("development") manager = Manager(app) migrate = Migrate(app, db) @manager.command def createdb(): db.create_all() print("database tables created successfully") @manager.command def dropdb(): db.drop_all() manager.add_command('db', MigrateCommand) if __name__ == "__main__": manager.run()
Add database migrations and creation script
Add database migrations and creation script
Python
mit
brayoh/bucket-list-api
<INSERT> from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import db, create_app from app.models import User, BucketList, Item app = create_app("development") manager = Manager(app) migrate = Migrate(app, db) @manager.command def createdb(): <INSERT_END> <INSERT> db.create_all() print("database tables created successfully") @manager.command def dropdb(): db.drop_all() manager.add_command('db', MigrateCommand) if __name__ == "__main__": manager.run() <INSERT_END> <|endoftext|> from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import db, create_app from app.models import User, BucketList, Item app = create_app("development") manager = Manager(app) migrate = Migrate(app, db) @manager.command def createdb(): db.create_all() print("database tables created successfully") @manager.command def dropdb(): db.drop_all() manager.add_command('db', MigrateCommand) if __name__ == "__main__": manager.run()
Add database migrations and creation script
1891469e5d3eb34efbe3c5feed1f7770e680120e
automata/nfa.py
automata/nfa.py
#!/usr/bin/env python3 import automata.automaton as automaton class NFA(automaton.Automaton): """a deterministic finite automaton""" def validate_automaton(self): """returns True if this NFA is internally consistent; raises the appropriate exception if this NFA is invalid""" for state in self.states: if state not in self.transitions: raise automaton.MissingStateError( 'state {} is missing from transition function'.format( state)) for start_state, paths in self.transitions.items(): invalid_states = set().union(*paths.values()).difference( self.states) if invalid_states: raise automaton.InvalidStateError( 'states are not valid ({})'.format( ', '.join(invalid_states))) if self.initial_state not in self.states: raise automaton.InvalidStateError( '{} is not a valid state'.format(self.initial_state)) for state in self.final_states: if state not in self.states: raise automaton.InvalidStateError( '{} is not a valid state'.format(state)) return True # TODO def validate_input(self, input_str): """returns True if the given string is accepted by this NFA; raises the appropriate exception if the string is not accepted""" return True
#!/usr/bin/env python3 import automata.automaton as automaton class NFA(automaton.Automaton): """a nondeterministic finite automaton""" def validate_automaton(self): """returns True if this NFA is internally consistent; raises the appropriate exception if this NFA is invalid""" for state in self.states: if state not in self.transitions: raise automaton.MissingStateError( 'state {} is missing from transition function'.format( state)) for start_state, paths in self.transitions.items(): invalid_states = set().union(*paths.values()).difference( self.states) if invalid_states: raise automaton.InvalidStateError( 'states are not valid ({})'.format( ', '.join(invalid_states))) if self.initial_state not in self.states: raise automaton.InvalidStateError( '{} is not a valid state'.format(self.initial_state)) for state in self.final_states: if state not in self.states: raise automaton.InvalidStateError( '{} is not a valid state'.format(state)) return True # TODO def validate_input(self, input_str): """returns True if the given string is accepted by this NFA; raises the appropriate exception if the string is not accepted""" return True
Fix incorrect docstring for NFA class
Fix incorrect docstring for NFA class
Python
mit
caleb531/automata
<REPLACE_OLD> deterministic <REPLACE_NEW> nondeterministic <REPLACE_END> <|endoftext|> #!/usr/bin/env python3 import automata.automaton as automaton class NFA(automaton.Automaton): """a nondeterministic finite automaton""" def validate_automaton(self): """returns True if this NFA is internally consistent; raises the appropriate exception if this NFA is invalid""" for state in self.states: if state not in self.transitions: raise automaton.MissingStateError( 'state {} is missing from transition function'.format( state)) for start_state, paths in self.transitions.items(): invalid_states = set().union(*paths.values()).difference( self.states) if invalid_states: raise automaton.InvalidStateError( 'states are not valid ({})'.format( ', '.join(invalid_states))) if self.initial_state not in self.states: raise automaton.InvalidStateError( '{} is not a valid state'.format(self.initial_state)) for state in self.final_states: if state not in self.states: raise automaton.InvalidStateError( '{} is not a valid state'.format(state)) return True # TODO def validate_input(self, input_str): """returns True if the given string is accepted by this NFA; raises the appropriate exception if the string is not accepted""" return True
Fix incorrect docstring for NFA class #!/usr/bin/env python3 import automata.automaton as automaton class NFA(automaton.Automaton): """a deterministic finite automaton""" def validate_automaton(self): """returns True if this NFA is internally consistent; raises the appropriate exception if this NFA is invalid""" for state in self.states: if state not in self.transitions: raise automaton.MissingStateError( 'state {} is missing from transition function'.format( state)) for start_state, paths in self.transitions.items(): invalid_states = set().union(*paths.values()).difference( self.states) if invalid_states: raise automaton.InvalidStateError( 'states are not valid ({})'.format( ', '.join(invalid_states))) if self.initial_state not in self.states: raise automaton.InvalidStateError( '{} is not a valid state'.format(self.initial_state)) for state in self.final_states: if state not in self.states: raise automaton.InvalidStateError( '{} is not a valid state'.format(state)) return True # TODO def validate_input(self, input_str): """returns True if the given string is accepted by this NFA; raises the appropriate exception if the string is not accepted""" return True
7d89303fddd12fc88fd04bcf27826c3c801b1eff
scripts/import_submissions.py
scripts/import_submissions.py
#!/usr/bin/env python # Copyright (C) 2012 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. import json from acoustid.script import run_script from acoustid.data.submission import import_queued_submissions logger = logging.getLogger(__name__) def main(script, opts, args): channel = script.redis.pubsub() channel.subscribe('channel.submissions') for message in channel.listen(): ids = json.loads(message) logger.debug('Got notified about %s new submissions', len(ids)) #conn = script.engine.connect() #import_queued_submissions(conn, limit=300, index=script.index) run_script(main)
Add a dummy script for continuous submission importing
Add a dummy script for continuous submission importing
Python
mit
lalinsky/acoustid-server,lalinsky/acoustid-server,lalinsky/acoustid-server,lalinsky/acoustid-server
<INSERT> #!/usr/bin/env python # Copyright (C) 2012 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. import json from acoustid.script import run_script from acoustid.data.submission import import_queued_submissions logger = logging.getLogger(__name__) def main(script, opts, args): <INSERT_END> <INSERT> channel = script.redis.pubsub() channel.subscribe('channel.submissions') for message in channel.listen(): ids = json.loads(message) logger.debug('Got notified about %s new submissions', len(ids)) #conn = script.engine.connect() #import_queued_submissions(conn, limit=300, index=script.index) run_script(main) <INSERT_END> <|endoftext|> #!/usr/bin/env python # Copyright (C) 2012 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. import json from acoustid.script import run_script from acoustid.data.submission import import_queued_submissions logger = logging.getLogger(__name__) def main(script, opts, args): channel = script.redis.pubsub() channel.subscribe('channel.submissions') for message in channel.listen(): ids = json.loads(message) logger.debug('Got notified about %s new submissions', len(ids)) #conn = script.engine.connect() #import_queued_submissions(conn, limit=300, index=script.index) run_script(main)
Add a dummy script for continuous submission importing
ddb91c20793d8e5e8a01e0302afeaaba76776741
setuptools/extern/six.py
setuptools/extern/six.py
""" Handle loading six package from system or from the bundled copy """ import imp _SIX_SEARCH_PATH = ['setuptools._vendor.six', 'six'] def _find_module(name, path=None): """ Alternative to `imp.find_module` that can also search in subpackages. """ parts = name.split('.') for part in parts: if path is not None: path = [path] fh, path, descr = imp.find_module(part, path) return fh, path, descr def _import_six(search_path=_SIX_SEARCH_PATH): for mod_name in search_path: try: mod_info = _find_module(mod_name) except ImportError: continue imp.load_module(__name__, *mod_info) break else: raise ImportError( "The 'six' module of minimum version {0} is required; " "normally this is bundled with this package so if you get " "this warning, consult the packager of your " "distribution.") _import_six()
""" Handle loading a package from system or from the bundled copy """ import imp _SEARCH_PATH = ['setuptools._vendor.six', 'six'] def _find_module(name, path=None): """ Alternative to `imp.find_module` that can also search in subpackages. """ parts = name.split('.') for part in parts: if path is not None: path = [path] fh, path, descr = imp.find_module(part, path) return fh, path, descr def _import_in_place(search_path=_SEARCH_PATH): for mod_name in search_path: try: mod_info = _find_module(mod_name) except ImportError: continue imp.load_module(__name__, *mod_info) break else: raise ImportError( "The '{name}' package is required; " "normally this is bundled with this package so if you get " "this warning, consult the packager of your " "distribution.".format(name=_SEARCH_PATH[-1])) _import_in_place()
Make the technique even more generic
Make the technique even more generic --HG-- branch : feature/issue-229
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
<REPLACE_OLD> six <REPLACE_NEW> a <REPLACE_END> <REPLACE_OLD> imp _SIX_SEARCH_PATH <REPLACE_NEW> imp _SEARCH_PATH <REPLACE_END> <REPLACE_OLD> _import_six(search_path=_SIX_SEARCH_PATH): <REPLACE_NEW> _import_in_place(search_path=_SEARCH_PATH): <REPLACE_END> <REPLACE_OLD> *mod_info) <REPLACE_NEW> *mod_info) <REPLACE_END> <REPLACE_OLD> 'six' module of minimum version {0} <REPLACE_NEW> '{name}' package <REPLACE_END> <REPLACE_OLD> "distribution.") _import_six() <REPLACE_NEW> "distribution.".format(name=_SEARCH_PATH[-1])) _import_in_place() <REPLACE_END> <|endoftext|> """ Handle loading a package from system or from the bundled copy """ import imp _SEARCH_PATH = ['setuptools._vendor.six', 'six'] def _find_module(name, path=None): """ Alternative to `imp.find_module` that can also search in subpackages. """ parts = name.split('.') for part in parts: if path is not None: path = [path] fh, path, descr = imp.find_module(part, path) return fh, path, descr def _import_in_place(search_path=_SEARCH_PATH): for mod_name in search_path: try: mod_info = _find_module(mod_name) except ImportError: continue imp.load_module(__name__, *mod_info) break else: raise ImportError( "The '{name}' package is required; " "normally this is bundled with this package so if you get " "this warning, consult the packager of your " "distribution.".format(name=_SEARCH_PATH[-1])) _import_in_place()
Make the technique even more generic --HG-- branch : feature/issue-229 """ Handle loading six package from system or from the bundled copy """ import imp _SIX_SEARCH_PATH = ['setuptools._vendor.six', 'six'] def _find_module(name, path=None): """ Alternative to `imp.find_module` that can also search in subpackages. """ parts = name.split('.') for part in parts: if path is not None: path = [path] fh, path, descr = imp.find_module(part, path) return fh, path, descr def _import_six(search_path=_SIX_SEARCH_PATH): for mod_name in search_path: try: mod_info = _find_module(mod_name) except ImportError: continue imp.load_module(__name__, *mod_info) break else: raise ImportError( "The 'six' module of minimum version {0} is required; " "normally this is bundled with this package so if you get " "this warning, consult the packager of your " "distribution.") _import_six()
cfee86e7e9e1e29cbdbf6d888edff1f02d733808
31-coin-sums.py
31-coin-sums.py
def coin_change(left, coins, count): if left == 0: return count if not coins: return 0 coin, *coins_left = coins return sum(coin_change(left-coin*i, coins_left, count+1) for i in range(0, left//coin)) if __name__ == '__main__': coins = [200, 100, 50, 20, 10, 5, 2, 1] total = 200 ans = coin_change(total, coins, 0)
Work on 31 coin sums
Work on 31 coin sums
Python
mit
dawran6/project-euler
<INSERT> def coin_change(left, coins, count): <INSERT_END> <INSERT> if left == 0: return count if not coins: return 0 coin, *coins_left = coins return sum(coin_change(left-coin*i, coins_left, count+1) for i in range(0, left//coin)) if __name__ == '__main__': coins = [200, 100, 50, 20, 10, 5, 2, 1] total = 200 ans = coin_change(total, coins, 0) <INSERT_END> <|endoftext|> def coin_change(left, coins, count): if left == 0: return count if not coins: return 0 coin, *coins_left = coins return sum(coin_change(left-coin*i, coins_left, count+1) for i in range(0, left//coin)) if __name__ == '__main__': coins = [200, 100, 50, 20, 10, 5, 2, 1] total = 200 ans = coin_change(total, coins, 0)
Work on 31 coin sums
802bed896c147fc6bb6dc72f62a80236bc3cd263
soccermetrics/rest/resources/personnel.py
soccermetrics/rest/resources/personnel.py
from soccermetrics.rest.resources import Resource class Personnel(Resource): """ Represents a Personnel REST resource (/personnel/<resource> endpoint). The Personnel resources let you access biographic and demographic data on all personnel involved in a football match – players, managers, and match referees. Derived from :class:`Resource`. """ def __init__(self, resource, base_uri, auth): """ Constructor of Personnel class. :param resource: Name of resource. :type resource: string :param base_uri: Base URI of API. :type base_uri: string :param auth: Authentication credential. :type auth: tuple """ super(Personnel, self).__init__(base_uri,auth) self.endpoint += "/personnel/%s" % resource
from soccermetrics.rest.resources import Resource class Personnel(Resource): """ Represents a Personnel REST resource (/personnel/<resource> endpoint). The Personnel resources let you access biographic and demographic data on the following personnel involved in a football match: * Players, * Managers, * Match referees. Derived from :class:`Resource`. """ def __init__(self, resource, base_uri, auth): """ Constructor of Personnel class. :param resource: Name of resource. :type resource: string :param base_uri: Base URI of API. :type base_uri: string :param auth: Authentication credential. :type auth: tuple """ super(Personnel, self).__init__(base_uri,auth) self.endpoint += "/personnel/%s" % resource
Remove stray non-ASCII character in docstring
Remove stray non-ASCII character in docstring
Python
mit
soccermetrics/soccermetrics-client-py
<REPLACE_OLD> all <REPLACE_NEW> the following <REPLACE_END> <REPLACE_OLD> match – players, managers, and match <REPLACE_NEW> match: * Players, * Managers, * Match <REPLACE_END> <|endoftext|> from soccermetrics.rest.resources import Resource class Personnel(Resource): """ Represents a Personnel REST resource (/personnel/<resource> endpoint). The Personnel resources let you access biographic and demographic data on the following personnel involved in a football match: * Players, * Managers, * Match referees. Derived from :class:`Resource`. """ def __init__(self, resource, base_uri, auth): """ Constructor of Personnel class. :param resource: Name of resource. :type resource: string :param base_uri: Base URI of API. :type base_uri: string :param auth: Authentication credential. :type auth: tuple """ super(Personnel, self).__init__(base_uri,auth) self.endpoint += "/personnel/%s" % resource
Remove stray non-ASCII character in docstring from soccermetrics.rest.resources import Resource class Personnel(Resource): """ Represents a Personnel REST resource (/personnel/<resource> endpoint). The Personnel resources let you access biographic and demographic data on all personnel involved in a football match – players, managers, and match referees. Derived from :class:`Resource`. """ def __init__(self, resource, base_uri, auth): """ Constructor of Personnel class. :param resource: Name of resource. :type resource: string :param base_uri: Base URI of API. :type base_uri: string :param auth: Authentication credential. :type auth: tuple """ super(Personnel, self).__init__(base_uri,auth) self.endpoint += "/personnel/%s" % resource
cc7b8f5dc95d09af619e588aea8042376be6edfc
secondhand/urls.py
secondhand/urls.py
from django.conf.urls import patterns, include, url from tastypie.api import Api from tracker.api import UserResource, TaskResource, WorkSessionResource, \ ApiTokenResource from tracker.views import SignupView # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() # tracker API. v1_api = Api(api_name='v1') v1_api.register(ApiTokenResource()) v1_api.register(UserResource()) v1_api.register(TaskResource()) v1_api.register(WorkSessionResource()) urlpatterns = patterns('', # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), url(r'^signup/', SignupView.as_view(), name='signup'), url(r'^api/', include(v1_api.urls)), )
from django.conf.urls import patterns, include, url from tastypie.api import Api from tracker.api import TaskResource, WorkSessionResource, \ ApiTokenResource, ProjectResource from tracker.views import SignupView # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() # tracker API. v1_api = Api(api_name='v1') v1_api.register(ApiTokenResource()) v1_api.register(ProjectResource()) v1_api.register(TaskResource()) v1_api.register(WorkSessionResource()) urlpatterns = patterns('', # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), url(r'^signup/', SignupView.as_view(), name='signup'), url(r'^api/', include(v1_api.urls)), )
Remove UserResource from the API and add ProjectResource.
Remove UserResource from the API and add ProjectResource.
Python
mit
GeneralMaximus/secondhand
<DELETE> UserResource, <DELETE_END> <REPLACE_OLD> ApiTokenResource from <REPLACE_NEW> ApiTokenResource, ProjectResource from <REPLACE_END> <REPLACE_OLD> Api(api_name='v1') v1_api.register(ApiTokenResource()) v1_api.register(UserResource()) v1_api.register(TaskResource()) v1_api.register(WorkSessionResource()) urlpatterns <REPLACE_NEW> Api(api_name='v1') v1_api.register(ApiTokenResource()) v1_api.register(ProjectResource()) v1_api.register(TaskResource()) v1_api.register(WorkSessionResource()) urlpatterns <REPLACE_END> <|endoftext|> from django.conf.urls import patterns, include, url from tastypie.api import Api from tracker.api import TaskResource, WorkSessionResource, \ ApiTokenResource, ProjectResource from tracker.views import SignupView # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() # tracker API. v1_api = Api(api_name='v1') v1_api.register(ApiTokenResource()) v1_api.register(ProjectResource()) v1_api.register(TaskResource()) v1_api.register(WorkSessionResource()) urlpatterns = patterns('', # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), url(r'^signup/', SignupView.as_view(), name='signup'), url(r'^api/', include(v1_api.urls)), )
Remove UserResource from the API and add ProjectResource. from django.conf.urls import patterns, include, url from tastypie.api import Api from tracker.api import UserResource, TaskResource, WorkSessionResource, \ ApiTokenResource from tracker.views import SignupView # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() # tracker API. v1_api = Api(api_name='v1') v1_api.register(ApiTokenResource()) v1_api.register(UserResource()) v1_api.register(TaskResource()) v1_api.register(WorkSessionResource()) urlpatterns = patterns('', # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), url(r'^signup/', SignupView.as_view(), name='signup'), url(r'^api/', include(v1_api.urls)), )
691e25dbc258d94a80a729924d76aa10a693c08e
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages from dreambeam import __version__ setup(name='dreamBeam', version=__version__, description='Measurement equation framework for radio interferometry.', author='Tobia D. Carozzi', author_email='[email protected]', packages=find_packages(), package_data={'dreambeam.telescopes.LOFAR': ['share/*.cc', 'share/simmos/*.cfg', 'share/alignment/*.txt', 'data/*teldat.p']}, license='ISC', classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: ISC License', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Astronomy', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Visualization' ], install_requires=[ 'numpy>=1.10', 'python-casacore', 'matplotlib>2.0', 'antpat>=0.4' ], entry_points={ 'console_scripts': [ 'pointing_jones = scripts.pointing_jones:cli_main', 'FoV_jones = scripts.FoV_jones:main' ] } )
#!/usr/bin/env python from setuptools import setup, find_packages from dreambeam import __version__ setup(name='dreamBeam', version=__version__, description='Measurement equation framework for radio interferometry.', author='Tobia D. Carozzi', author_email='[email protected]', packages=find_packages(), package_data={'dreambeam.telescopes.LOFAR': ['share/*.cc', 'share/simmos/*.cfg', 'share/alignment/*.txt', 'data/*teldat.p'], 'dreambeam': ['configs/*.txt']}, include_package_data=True, license='ISC', classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: ISC License', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Astronomy', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Visualization' ], install_requires=[ 'numpy>=1.10', 'python-casacore', 'matplotlib>2.0', 'antpat>=0.4' ], entry_points={ 'console_scripts': [ 'pointing_jones = scripts.pointing_jones:cli_main', 'FoV_jones = scripts.FoV_jones:main' ] } )
Include config files in the pip install
Include config files in the pip install
Python
isc
2baOrNot2ba/dreamBeam,2baOrNot2ba/dreamBeam
<REPLACE_OLD> 'data/*teldat.p']}, <REPLACE_NEW> 'data/*teldat.p'], 'dreambeam': ['configs/*.txt']}, include_package_data=True, <REPLACE_END> <|endoftext|> #!/usr/bin/env python from setuptools import setup, find_packages from dreambeam import __version__ setup(name='dreamBeam', version=__version__, description='Measurement equation framework for radio interferometry.', author='Tobia D. Carozzi', author_email='[email protected]', packages=find_packages(), package_data={'dreambeam.telescopes.LOFAR': ['share/*.cc', 'share/simmos/*.cfg', 'share/alignment/*.txt', 'data/*teldat.p'], 'dreambeam': ['configs/*.txt']}, include_package_data=True, license='ISC', classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: ISC License', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Astronomy', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Visualization' ], install_requires=[ 'numpy>=1.10', 'python-casacore', 'matplotlib>2.0', 'antpat>=0.4' ], entry_points={ 'console_scripts': [ 'pointing_jones = scripts.pointing_jones:cli_main', 'FoV_jones = scripts.FoV_jones:main' ] } )
Include config files in the pip install #!/usr/bin/env python from setuptools import setup, find_packages from dreambeam import __version__ setup(name='dreamBeam', version=__version__, description='Measurement equation framework for radio interferometry.', author='Tobia D. Carozzi', author_email='[email protected]', packages=find_packages(), package_data={'dreambeam.telescopes.LOFAR': ['share/*.cc', 'share/simmos/*.cfg', 'share/alignment/*.txt', 'data/*teldat.p']}, license='ISC', classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: ISC License', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Astronomy', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Visualization' ], install_requires=[ 'numpy>=1.10', 'python-casacore', 'matplotlib>2.0', 'antpat>=0.4' ], entry_points={ 'console_scripts': [ 'pointing_jones = scripts.pointing_jones:cli_main', 'FoV_jones = scripts.FoV_jones:main' ] } )
23bce5ac6a73473f6f166c674988e68af18d2b51
billing/__init__.py
billing/__init__.py
__version__ = '1.7.2' __copyright__ = 'Copyright (c) 2020, Skioo SA' __licence__ = 'MIT' __URL__ = 'https://github.com/skioo/django-customer-billing'
__version__ = '1.7.3' __copyright__ = 'Copyright (c) 2020, Skioo SA' __licence__ = 'MIT' __URL__ = 'https://github.com/skioo/django-customer-billing'
Update project version to 1.7.3
Update project version to 1.7.3
Python
mit
skioo/django-customer-billing,skioo/django-customer-billing
<REPLACE_OLD> '1.7.2' __copyright__ <REPLACE_NEW> '1.7.3' __copyright__ <REPLACE_END> <|endoftext|> __version__ = '1.7.3' __copyright__ = 'Copyright (c) 2020, Skioo SA' __licence__ = 'MIT' __URL__ = 'https://github.com/skioo/django-customer-billing'
Update project version to 1.7.3 __version__ = '1.7.2' __copyright__ = 'Copyright (c) 2020, Skioo SA' __licence__ = 'MIT' __URL__ = 'https://github.com/skioo/django-customer-billing'
2c4e64cb12efd82d24f4e451527118527bba1433
setup.py
setup.py
from setuptools import setup, find_packages import os import subprocess os.system("pip install git+https://github.com/ComparativeGenomicsToolkit/sonLib@toil") versionFile = "src/cactus/shared/version.py" if os.path.exists(versionFile): os.remove(versionFile) git_commit = subprocess.check_output('git log --pretty=oneline -n 1 -- $(pwd)', shell=True).split()[0] with open(versionFile, 'w') as versionFH: versionFH.write("cactus_commit = '%s'" % git_commit) setup( name="progressiveCactus", version="1.0", author="Benedict Paten", package_dir = {'': 'src'}, packages=find_packages(where='src'), include_package_data=True, package_data={'cactus': ['*_config.xml']}, # We use the __file__ attribute so this package isn't zip_safe. zip_safe=False, install_requires=[ 'decorator', 'subprocess32', 'psutil', 'networkx==1.11'], entry_points={ 'console_scripts': ['cactus = cactus.progressive.cactus_progressive:main']},)
from setuptools import setup, find_packages import os import subprocess os.system("pip install git+https://github.com/ComparativeGenomicsToolkit/sonLib@toil") versionFile = "src/cactus/shared/version.py" if os.path.exists(versionFile): os.remove(versionFile) git_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip() with open(versionFile, 'w') as versionFH: versionFH.write("cactus_commit = '%s'" % git_commit) setup( name="progressiveCactus", version="1.0", author="Benedict Paten", package_dir = {'': 'src'}, packages=find_packages(where='src'), include_package_data=True, package_data={'cactus': ['*_config.xml']}, # We use the __file__ attribute so this package isn't zip_safe. zip_safe=False, install_requires=[ 'decorator', 'subprocess32', 'psutil', 'networkx==1.11'], entry_points={ 'console_scripts': ['cactus = cactus.progressive.cactus_progressive:main']},)
Fix Docker image tag inconsistency after merge commits
Fix Docker image tag inconsistency after merge commits The image pushed is always given by `git rev-parse HEAD`, but the tag for the image requested from Docker was retrieved from git log. Merge commits were ignored by the latter. Now the tag is set to `git rev-parse HEAD` both on push and retrieve.
Python
mit
benedictpaten/cactus,benedictpaten/cactus,benedictpaten/cactus,benedictpaten/cactus,benedictpaten/cactus
<REPLACE_OLD> subprocess.check_output('git log --pretty=oneline -n 1 -- $(pwd)', shell=True).split()[0] with <REPLACE_NEW> subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip() with <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages import os import subprocess os.system("pip install git+https://github.com/ComparativeGenomicsToolkit/sonLib@toil") versionFile = "src/cactus/shared/version.py" if os.path.exists(versionFile): os.remove(versionFile) git_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip() with open(versionFile, 'w') as versionFH: versionFH.write("cactus_commit = '%s'" % git_commit) setup( name="progressiveCactus", version="1.0", author="Benedict Paten", package_dir = {'': 'src'}, packages=find_packages(where='src'), include_package_data=True, package_data={'cactus': ['*_config.xml']}, # We use the __file__ attribute so this package isn't zip_safe. zip_safe=False, install_requires=[ 'decorator', 'subprocess32', 'psutil', 'networkx==1.11'], entry_points={ 'console_scripts': ['cactus = cactus.progressive.cactus_progressive:main']},)
Fix Docker image tag inconsistency after merge commits The image pushed is always given by `git rev-parse HEAD`, but the tag for the image requested from Docker was retrieved from git log. Merge commits were ignored by the latter. Now the tag is set to `git rev-parse HEAD` both on push and retrieve. from setuptools import setup, find_packages import os import subprocess os.system("pip install git+https://github.com/ComparativeGenomicsToolkit/sonLib@toil") versionFile = "src/cactus/shared/version.py" if os.path.exists(versionFile): os.remove(versionFile) git_commit = subprocess.check_output('git log --pretty=oneline -n 1 -- $(pwd)', shell=True).split()[0] with open(versionFile, 'w') as versionFH: versionFH.write("cactus_commit = '%s'" % git_commit) setup( name="progressiveCactus", version="1.0", author="Benedict Paten", package_dir = {'': 'src'}, packages=find_packages(where='src'), include_package_data=True, package_data={'cactus': ['*_config.xml']}, # We use the __file__ attribute so this package isn't zip_safe. zip_safe=False, install_requires=[ 'decorator', 'subprocess32', 'psutil', 'networkx==1.11'], entry_points={ 'console_scripts': ['cactus = cactus.progressive.cactus_progressive:main']},)
229ea6b0f373aa2d37c40f794c4c17bfff231e01
mox3/fixture.py
mox3/fixture.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Hewlett-Packard Development Company, L.P. # 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import fixtures from mox3 import mox from mox3 import stubout class MoxStubout(fixtures.Fixture): """Deal with code around mox and stubout as a fixture.""" def setUp(self): super(MoxStubout, self).setUp() self.mox = mox.Mox() self.stubs = stubout.StubOutForTesting() self.addCleanup(self.mox.UnsetStubs) self.addCleanup(self.stubs.UnsetAll) self.addCleanup(self.stubs.SmartUnsetAll) self.addCleanup(self.mox.VerifyAll)
# Copyright 2013 Hewlett-Packard Development Company, L.P. # 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import fixtures from mox3 import mox from mox3 import stubout class MoxStubout(fixtures.Fixture): """Deal with code around mox and stubout as a fixture.""" def setUp(self): super(MoxStubout, self).setUp() self.mox = mox.Mox() self.stubs = stubout.StubOutForTesting() self.addCleanup(self.mox.UnsetStubs) self.addCleanup(self.stubs.UnsetAll) self.addCleanup(self.stubs.SmartUnsetAll) self.addCleanup(self.mox.VerifyAll)
Remove vim header from source files
Remove vim header from source files Change-Id: I67a1ee4e894841bee620b1012257ad72f5e31765
Python
apache-2.0
openstack/mox3
<DELETE> vim: tabstop=4 shiftwidth=4 softtabstop=4 # <DELETE_END> <|endoftext|> # Copyright 2013 Hewlett-Packard Development Company, L.P. # 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import fixtures from mox3 import mox from mox3 import stubout class MoxStubout(fixtures.Fixture): """Deal with code around mox and stubout as a fixture.""" def setUp(self): super(MoxStubout, self).setUp() self.mox = mox.Mox() self.stubs = stubout.StubOutForTesting() self.addCleanup(self.mox.UnsetStubs) self.addCleanup(self.stubs.UnsetAll) self.addCleanup(self.stubs.SmartUnsetAll) self.addCleanup(self.mox.VerifyAll)
Remove vim header from source files Change-Id: I67a1ee4e894841bee620b1012257ad72f5e31765 # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Hewlett-Packard Development Company, L.P. # 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import fixtures from mox3 import mox from mox3 import stubout class MoxStubout(fixtures.Fixture): """Deal with code around mox and stubout as a fixture.""" def setUp(self): super(MoxStubout, self).setUp() self.mox = mox.Mox() self.stubs = stubout.StubOutForTesting() self.addCleanup(self.mox.UnsetStubs) self.addCleanup(self.stubs.UnsetAll) self.addCleanup(self.stubs.SmartUnsetAll) self.addCleanup(self.mox.VerifyAll)
093702a38645853d560606446da0b078ba12d14e
eventkit_cloud/auth/admin.py
eventkit_cloud/auth/admin.py
import logging from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from rest_framework.authtoken.models import Token from eventkit_cloud.auth.models import OAuth from eventkit_cloud.jobs.models import UserLicense logger = logging.getLogger(__name__) class OAuthAdmin(admin.ModelAdmin): search_fields = ['user__username', 'identification', 'commonname', 'user_info'] list_display = ['user', 'identification', 'commonname'] def has_delete_permission(self, request, obj=None): return False def get_actions(self, request): actions = super(OAuthAdmin, self).get_actions(request) actions.pop('delete_selected', None) return actions class UserLicenseInline(admin.TabularInline): model = UserLicense extra = 0 UserAdmin.inlines = [UserLicenseInline] UserAdmin.readonly_fields += 'last_login', 'date_joined' admin.site.unregister(Token) admin.site.unregister(User) admin.site.register(User, UserAdmin) admin.site.register(OAuth, OAuthAdmin)
import logging from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from rest_framework.authtoken.models import Token from eventkit_cloud.auth.models import OAuth from eventkit_cloud.jobs.models import UserLicense logger = logging.getLogger(__name__) class OAuthAdmin(admin.ModelAdmin): search_fields = ['user__username', 'identification', 'commonname', 'user_info'] list_display = ['user', 'identification', 'commonname'] def has_delete_permission(self, request, obj=None): return False def get_actions(self, request): actions = super(OAuthAdmin, self).get_actions(request) actions.pop('delete_selected', None) return actions class OAuthInline(admin.StackedInline): model = OAuth class UserLicenseInline(admin.TabularInline): model = UserLicense extra = 0 UserAdmin.inlines = [OAuthInline, UserLicenseInline] UserAdmin.readonly_fields += 'last_login', 'date_joined' admin.site.unregister(Token) admin.site.unregister(User) admin.site.register(User, UserAdmin) admin.site.register(OAuth, OAuthAdmin)
Add OAuth class information to the UserAdmin page.
Add OAuth class information to the UserAdmin page.
Python
bsd-3-clause
terranodo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud,venicegeo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud
<REPLACE_OLD> actions class <REPLACE_NEW> actions class OAuthInline(admin.StackedInline): model = OAuth class <REPLACE_END> <REPLACE_OLD> 0 UserAdmin.inlines <REPLACE_NEW> 0 UserAdmin.inlines <REPLACE_END> <REPLACE_OLD> [UserLicenseInline] UserAdmin.readonly_fields <REPLACE_NEW> [OAuthInline, UserLicenseInline] UserAdmin.readonly_fields <REPLACE_END> <|endoftext|> import logging from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from rest_framework.authtoken.models import Token from eventkit_cloud.auth.models import OAuth from eventkit_cloud.jobs.models import UserLicense logger = logging.getLogger(__name__) class OAuthAdmin(admin.ModelAdmin): search_fields = ['user__username', 'identification', 'commonname', 'user_info'] list_display = ['user', 'identification', 'commonname'] def has_delete_permission(self, request, obj=None): return False def get_actions(self, request): actions = super(OAuthAdmin, self).get_actions(request) actions.pop('delete_selected', None) return actions class OAuthInline(admin.StackedInline): model = OAuth class UserLicenseInline(admin.TabularInline): model = UserLicense extra = 0 UserAdmin.inlines = [OAuthInline, UserLicenseInline] UserAdmin.readonly_fields += 'last_login', 'date_joined' admin.site.unregister(Token) admin.site.unregister(User) admin.site.register(User, UserAdmin) admin.site.register(OAuth, OAuthAdmin)
Add OAuth class information to the UserAdmin page. import logging from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from rest_framework.authtoken.models import Token from eventkit_cloud.auth.models import OAuth from eventkit_cloud.jobs.models import UserLicense logger = logging.getLogger(__name__) class OAuthAdmin(admin.ModelAdmin): search_fields = ['user__username', 'identification', 'commonname', 'user_info'] list_display = ['user', 'identification', 'commonname'] def has_delete_permission(self, request, obj=None): return False def get_actions(self, request): actions = super(OAuthAdmin, self).get_actions(request) actions.pop('delete_selected', None) return actions class UserLicenseInline(admin.TabularInline): model = UserLicense extra = 0 UserAdmin.inlines = [UserLicenseInline] UserAdmin.readonly_fields += 'last_login', 'date_joined' admin.site.unregister(Token) admin.site.unregister(User) admin.site.register(User, UserAdmin) admin.site.register(OAuth, OAuthAdmin)
f9b92cb7df1b5965fc14cefc423a8bbc664076b9
avena/tests/test-interp.py
avena/tests/test-interp.py
#!/usr/bin/env python from numpy import all, allclose, array, float32, max from .. import interp def test_interp2(): x = array([ [0, 1, 0], [1, 1, 1], [0, 1, 0], ], dtype=float32) y = interp._interp2(1.0, x) assert allclose(x, y) if __name__ == '__main__': pass
Add a unit test for the interp module.
Add a unit test for the interp module.
Python
isc
eliteraspberries/avena
<INSERT> #!/usr/bin/env python from numpy import all, allclose, array, float32, max from .. import interp def test_interp2(): <INSERT_END> <INSERT> x = array([ [0, 1, 0], [1, 1, 1], [0, 1, 0], ], dtype=float32) y = interp._interp2(1.0, x) assert allclose(x, y) if __name__ == '__main__': pass <INSERT_END> <|endoftext|> #!/usr/bin/env python from numpy import all, allclose, array, float32, max from .. import interp def test_interp2(): x = array([ [0, 1, 0], [1, 1, 1], [0, 1, 0], ], dtype=float32) y = interp._interp2(1.0, x) assert allclose(x, y) if __name__ == '__main__': pass
Add a unit test for the interp module.
952e681fe6aaf5fa20b2c3a83d3097f87286e98b
wagtail/search/backends/database/sqlite/utils.py
wagtail/search/backends/database/sqlite/utils.py
import sqlite3 from django.db import OperationalError def fts5_available(): # based on https://stackoverflow.com/a/36656216/1853523 if sqlite3.sqlite_version_info < (3, 19, 0): # Prior to version 3.19, SQLite doesn't support FTS5 queries with # column filters ('{column_1 column_2} : query'), which the sqlite # fulltext backend needs return False tmp_db = sqlite3.connect(':memory:') try: tmp_db.execute('CREATE VIRTUAL TABLE fts5test USING fts5 (data);') except OperationalError: return False finally: tmp_db.close() return True def fts_table_exists(): from wagtail.search.models import SQLiteFTSIndexEntry try: # ignore result of query; we are only interested in the query failing, # not the presence of index entries SQLiteFTSIndexEntry.objects.exists() except OperationalError: return False return True
import sqlite3 from django.db import OperationalError def fts5_available(): # based on https://stackoverflow.com/a/36656216/1853523 if sqlite3.sqlite_version_info < (3, 19, 0): # Prior to version 3.19, SQLite doesn't support FTS5 queries with # column filters ('{column_1 column_2} : query'), which the sqlite # fulltext backend needs return False tmp_db = sqlite3.connect(':memory:') try: tmp_db.execute('CREATE VIRTUAL TABLE fts5test USING fts5 (data);') except sqlite3.OperationalError: return False finally: tmp_db.close() return True def fts_table_exists(): from wagtail.search.models import SQLiteFTSIndexEntry try: # ignore result of query; we are only interested in the query failing, # not the presence of index entries SQLiteFTSIndexEntry.objects.exists() except OperationalError: return False return True
Fix Sqlite FTS5 compatibility check
Fix Sqlite FTS5 compatibility check As per https://github.com/wagtail/wagtail/issues/7798#issuecomment-1021544265 - the direct query against the sqlite3 library will fail with sqlite3.OperationalError, not django.db.OperationalError.
Python
bsd-3-clause
wagtail/wagtail,jnns/wagtail,wagtail/wagtail,zerolab/wagtail,wagtail/wagtail,rsalmaso/wagtail,thenewguy/wagtail,zerolab/wagtail,rsalmaso/wagtail,rsalmaso/wagtail,mixxorz/wagtail,jnns/wagtail,zerolab/wagtail,thenewguy/wagtail,jnns/wagtail,mixxorz/wagtail,jnns/wagtail,rsalmaso/wagtail,wagtail/wagtail,mixxorz/wagtail,thenewguy/wagtail,zerolab/wagtail,mixxorz/wagtail,zerolab/wagtail,wagtail/wagtail,mixxorz/wagtail,thenewguy/wagtail,thenewguy/wagtail,rsalmaso/wagtail
<REPLACE_OLD> OperationalError: <REPLACE_NEW> sqlite3.OperationalError: <REPLACE_END> <|endoftext|> import sqlite3 from django.db import OperationalError def fts5_available(): # based on https://stackoverflow.com/a/36656216/1853523 if sqlite3.sqlite_version_info < (3, 19, 0): # Prior to version 3.19, SQLite doesn't support FTS5 queries with # column filters ('{column_1 column_2} : query'), which the sqlite # fulltext backend needs return False tmp_db = sqlite3.connect(':memory:') try: tmp_db.execute('CREATE VIRTUAL TABLE fts5test USING fts5 (data);') except sqlite3.OperationalError: return False finally: tmp_db.close() return True def fts_table_exists(): from wagtail.search.models import SQLiteFTSIndexEntry try: # ignore result of query; we are only interested in the query failing, # not the presence of index entries SQLiteFTSIndexEntry.objects.exists() except OperationalError: return False return True
Fix Sqlite FTS5 compatibility check As per https://github.com/wagtail/wagtail/issues/7798#issuecomment-1021544265 - the direct query against the sqlite3 library will fail with sqlite3.OperationalError, not django.db.OperationalError. import sqlite3 from django.db import OperationalError def fts5_available(): # based on https://stackoverflow.com/a/36656216/1853523 if sqlite3.sqlite_version_info < (3, 19, 0): # Prior to version 3.19, SQLite doesn't support FTS5 queries with # column filters ('{column_1 column_2} : query'), which the sqlite # fulltext backend needs return False tmp_db = sqlite3.connect(':memory:') try: tmp_db.execute('CREATE VIRTUAL TABLE fts5test USING fts5 (data);') except OperationalError: return False finally: tmp_db.close() return True def fts_table_exists(): from wagtail.search.models import SQLiteFTSIndexEntry try: # ignore result of query; we are only interested in the query failing, # not the presence of index entries SQLiteFTSIndexEntry.objects.exists() except OperationalError: return False return True
670b896f0ef8a4feda9cbb0181364f277dc50299
miner_plotter/models.py
miner_plotter/models.py
import pymodm import slugify class DevicePlot(pymodm.MongoModel): device_name = pymodm.fields.CharField() slug = pymodm.fields.CharField() plot_title = pymodm.fields.CharField() x_label = pymodm.fields.CharField() y_label = pymodm.fields.CharField() def save(self, *args, **kwargs): if not self.pk: self.slug = slugify.slugify(self.device_name) super(DevicePlot, self).save(*args, **kwargs) class PlotPoints(pymodm.MongoModel): device_plot = pymodm.fields.ReferenceField(DevicePlot) label = pymodm.fields.CharField() points = pymodm.fields.ListField(default=[]) def save(self, *args, **kwargs): # TODO: configurable setting... if len(self.points) >= 30: self.points = self.points[30:] super(PlotPoints, self).save(*args, **kwargs)
import pymodm import slugify class DevicePlot(pymodm.MongoModel): device_name = pymodm.fields.CharField() slug = pymodm.fields.CharField() plot_title = pymodm.fields.CharField() x_label = pymodm.fields.CharField() y_label = pymodm.fields.CharField() def save(self, *args, **kwargs): if not self.pk: self.slug = slugify.slugify(self.device_name) super(DevicePlot, self).save(*args, **kwargs) class PlotPoints(pymodm.MongoModel): device_plot = pymodm.fields.ReferenceField(DevicePlot) label = pymodm.fields.CharField() points = pymodm.fields.ListField(default=[]) def save(self, *args, **kwargs): # TODO: configurable setting... if len(self.points) >= 30: self.points = self.points[-30:] super(PlotPoints, self).save(*args, **kwargs)
Fix bug to only store the 30 most recent points
Fix bug to only store the 30 most recent points
Python
mit
juannyG/miner-plotter,juannyG/miner-plotter,juannyG/miner-plotter
<REPLACE_OLD> self.points[30:] super(PlotPoints, <REPLACE_NEW> self.points[-30:] super(PlotPoints, <REPLACE_END> <|endoftext|> import pymodm import slugify class DevicePlot(pymodm.MongoModel): device_name = pymodm.fields.CharField() slug = pymodm.fields.CharField() plot_title = pymodm.fields.CharField() x_label = pymodm.fields.CharField() y_label = pymodm.fields.CharField() def save(self, *args, **kwargs): if not self.pk: self.slug = slugify.slugify(self.device_name) super(DevicePlot, self).save(*args, **kwargs) class PlotPoints(pymodm.MongoModel): device_plot = pymodm.fields.ReferenceField(DevicePlot) label = pymodm.fields.CharField() points = pymodm.fields.ListField(default=[]) def save(self, *args, **kwargs): # TODO: configurable setting... if len(self.points) >= 30: self.points = self.points[-30:] super(PlotPoints, self).save(*args, **kwargs)
Fix bug to only store the 30 most recent points import pymodm import slugify class DevicePlot(pymodm.MongoModel): device_name = pymodm.fields.CharField() slug = pymodm.fields.CharField() plot_title = pymodm.fields.CharField() x_label = pymodm.fields.CharField() y_label = pymodm.fields.CharField() def save(self, *args, **kwargs): if not self.pk: self.slug = slugify.slugify(self.device_name) super(DevicePlot, self).save(*args, **kwargs) class PlotPoints(pymodm.MongoModel): device_plot = pymodm.fields.ReferenceField(DevicePlot) label = pymodm.fields.CharField() points = pymodm.fields.ListField(default=[]) def save(self, *args, **kwargs): # TODO: configurable setting... if len(self.points) >= 30: self.points = self.points[30:] super(PlotPoints, self).save(*args, **kwargs)
1c18e61ece7f05ac5b1afd276c72a6a242e9fb66
braid/info.py
braid/info.py
from fabric.api import run, quiet from braid import succeeds, cacheInEnvironment @cacheInEnvironment def distroName(): """ Get the name of the distro. """ with quiet(): lsb = run('lsb_release --id --short', warn_only=True) if lsb.succeeded: return lsb.lower() distros = [ ('centos', '/etc/centos-release'), ('fedora', '/etc/fedora-release'), ] for distro, sentinel in distros: if succeeds('test -f {}'.format(sentinel)): return distro def distroFamily(): """ Get the family of the distro. @returns: C{'debian'} or C{'fedora'} """ families = { 'debian': ['debian', 'ubuntu'], 'fedora': ['fedora', 'centos', 'rhel'], } distro = distroName() for family, members in families.iteritems(): if distro in members: return family return 'other'
Add some tools for detecting the remote distribution.
Add some tools for detecting the remote distribution.
Python
mit
alex/braid,alex/braid
<REPLACE_OLD> <REPLACE_NEW> from fabric.api import run, quiet from braid import succeeds, cacheInEnvironment @cacheInEnvironment def distroName(): """ Get the name of the distro. """ with quiet(): lsb = run('lsb_release --id --short', warn_only=True) if lsb.succeeded: return lsb.lower() distros = [ ('centos', '/etc/centos-release'), ('fedora', '/etc/fedora-release'), ] for distro, sentinel in distros: if succeeds('test -f {}'.format(sentinel)): return distro def distroFamily(): """ Get the family of the distro. @returns: C{'debian'} or C{'fedora'} """ families = { 'debian': ['debian', 'ubuntu'], 'fedora': ['fedora', 'centos', 'rhel'], } distro = distroName() for family, members in families.iteritems(): if distro in members: return family return 'other' <REPLACE_END> <|endoftext|> from fabric.api import run, quiet from braid import succeeds, cacheInEnvironment @cacheInEnvironment def distroName(): """ Get the name of the distro. """ with quiet(): lsb = run('lsb_release --id --short', warn_only=True) if lsb.succeeded: return lsb.lower() distros = [ ('centos', '/etc/centos-release'), ('fedora', '/etc/fedora-release'), ] for distro, sentinel in distros: if succeeds('test -f {}'.format(sentinel)): return distro def distroFamily(): """ Get the family of the distro. @returns: C{'debian'} or C{'fedora'} """ families = { 'debian': ['debian', 'ubuntu'], 'fedora': ['fedora', 'centos', 'rhel'], } distro = distroName() for family, members in families.iteritems(): if distro in members: return family return 'other'
Add some tools for detecting the remote distribution.
2b0a11a1adf4167fb55f9b90fc87a8b8518a24a7
atmo/apps.py
atmo/apps.py
from django.apps import AppConfig from django.conf import settings import session_csrf class AtmoAppConfig(AppConfig): name = 'atmo' def ready(self): # The app is now ready. Include any monkey patches here. # Monkey patch CSRF to switch to session based CSRF. Session # based CSRF will prevent attacks from apps under the same # domain. If you're planning to host your app under it's own # domain you can remove session_csrf and use Django's CSRF # library. See also # https://github.com/mozilla/sugardough/issues/38 session_csrf.monkeypatch() # Under some circumstances (e.g. when calling collectstatic) # REDIS_URL is not available and we can skip the job schedule registration. if getattr(settings, 'REDIS_URL'): # This module contains references to some orm models, so it's # safer to import it here. from .schedule import register_job_schedule # Register rq scheduled jobs register_job_schedule()
from django.apps import AppConfig from django.conf import settings import session_csrf class AtmoAppConfig(AppConfig): name = 'atmo' def ready(self): # The app is now ready. Include any monkey patches here. # Monkey patch CSRF to switch to session based CSRF. Session # based CSRF will prevent attacks from apps under the same # domain. If you're planning to host your app under it's own # domain you can remove session_csrf and use Django's CSRF # library. See also # https://github.com/mozilla/sugardough/issues/38 session_csrf.monkeypatch() # Under some circumstances (e.g. when calling collectstatic) # REDIS_URL is not available and we can skip the job schedule registration. if settings.REDIS_URL.hostname: # This module contains references to some orm models, so it's # safer to import it here. from .schedule import register_job_schedule # Register rq scheduled jobs register_job_schedule()
Fix rq jobs registration check
Fix rq jobs registration check
Python
mpl-2.0
mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service
<REPLACE_OLD> getattr(settings, 'REDIS_URL'): <REPLACE_NEW> settings.REDIS_URL.hostname: <REPLACE_END> <|endoftext|> from django.apps import AppConfig from django.conf import settings import session_csrf class AtmoAppConfig(AppConfig): name = 'atmo' def ready(self): # The app is now ready. Include any monkey patches here. # Monkey patch CSRF to switch to session based CSRF. Session # based CSRF will prevent attacks from apps under the same # domain. If you're planning to host your app under it's own # domain you can remove session_csrf and use Django's CSRF # library. See also # https://github.com/mozilla/sugardough/issues/38 session_csrf.monkeypatch() # Under some circumstances (e.g. when calling collectstatic) # REDIS_URL is not available and we can skip the job schedule registration. if settings.REDIS_URL.hostname: # This module contains references to some orm models, so it's # safer to import it here. from .schedule import register_job_schedule # Register rq scheduled jobs register_job_schedule()
Fix rq jobs registration check from django.apps import AppConfig from django.conf import settings import session_csrf class AtmoAppConfig(AppConfig): name = 'atmo' def ready(self): # The app is now ready. Include any monkey patches here. # Monkey patch CSRF to switch to session based CSRF. Session # based CSRF will prevent attacks from apps under the same # domain. If you're planning to host your app under it's own # domain you can remove session_csrf and use Django's CSRF # library. See also # https://github.com/mozilla/sugardough/issues/38 session_csrf.monkeypatch() # Under some circumstances (e.g. when calling collectstatic) # REDIS_URL is not available and we can skip the job schedule registration. if getattr(settings, 'REDIS_URL'): # This module contains references to some orm models, so it's # safer to import it here. from .schedule import register_job_schedule # Register rq scheduled jobs register_job_schedule()
d6cf9df23e8c9e3b6a8d261ea79dfe16cfa1dbb1
numba/tests/test_redefine.py
numba/tests/test_redefine.py
from numba import * import unittest class TestRedefine(unittest.TestCase): def test_redefine(self): def foo(x): return x + 1 jfoo = jit(int32(int32))(foo) # Test original function self.assertTrue(jfoo(1), 2) jfoo = jit(int32(int32))(foo) # Test re-compiliation self.assertTrue(jfoo(2), 3) def foo(x): return x + 2 jfoo = jit(int32(int32))(foo) # Test redefinition self.assertTrue(jfoo(1), 3)
Add test for function re-definition
Add test for function re-definition
Python
bsd-2-clause
IntelLabs/numba,GaZ3ll3/numba,stuartarchibald/numba,pitrou/numba,seibert/numba,stefanseefeld/numba,ssarangi/numba,jriehl/numba,seibert/numba,gdementen/numba,pombredanne/numba,sklam/numba,stefanseefeld/numba,jriehl/numba,IntelLabs/numba,stefanseefeld/numba,pombredanne/numba,seibert/numba,stonebig/numba,GaZ3ll3/numba,sklam/numba,gmarkall/numba,jriehl/numba,ssarangi/numba,GaZ3ll3/numba,ssarangi/numba,numba/numba,IntelLabs/numba,stuartarchibald/numba,stuartarchibald/numba,gdementen/numba,stefanseefeld/numba,shiquanwang/numba,stonebig/numba,jriehl/numba,stonebig/numba,cpcloud/numba,sklam/numba,ssarangi/numba,pitrou/numba,pombredanne/numba,seibert/numba,pitrou/numba,cpcloud/numba,stefanseefeld/numba,IntelLabs/numba,seibert/numba,pitrou/numba,pombredanne/numba,gmarkall/numba,GaZ3ll3/numba,cpcloud/numba,sklam/numba,jriehl/numba,shiquanwang/numba,pitrou/numba,gmarkall/numba,stuartarchibald/numba,pombredanne/numba,numba/numba,numba/numba,numba/numba,gdementen/numba,stuartarchibald/numba,numba/numba,IntelLabs/numba,gdementen/numba,shiquanwang/numba,GaZ3ll3/numba,cpcloud/numba,cpcloud/numba,ssarangi/numba,gmarkall/numba,stonebig/numba,stonebig/numba,gdementen/numba,sklam/numba,gmarkall/numba
<INSERT> from numba import * import unittest class TestRedefine(unittest.TestCase): <INSERT_END> <INSERT> def test_redefine(self): def foo(x): return x + 1 jfoo = jit(int32(int32))(foo) # Test original function self.assertTrue(jfoo(1), 2) jfoo = jit(int32(int32))(foo) # Test re-compiliation self.assertTrue(jfoo(2), 3) def foo(x): return x + 2 jfoo = jit(int32(int32))(foo) # Test redefinition self.assertTrue(jfoo(1), 3) <INSERT_END> <|endoftext|> from numba import * import unittest class TestRedefine(unittest.TestCase): def test_redefine(self): def foo(x): return x + 1 jfoo = jit(int32(int32))(foo) # Test original function self.assertTrue(jfoo(1), 2) jfoo = jit(int32(int32))(foo) # Test re-compiliation self.assertTrue(jfoo(2), 3) def foo(x): return x + 2 jfoo = jit(int32(int32))(foo) # Test redefinition self.assertTrue(jfoo(1), 3)
Add test for function re-definition
f522a464e3f58a9f2ed235b48382c9db15f66029
eva/layers/residual_block.py
eva/layers/residual_block.py
from keras.layers import Convolution2D, Merge from keras.layers.advanced_activations import PReLU from keras.engine.topology import merge from eva.layers.masked_convolution2d import MaskedConvolution2D def ResidualBlock(model, filters): # 2h -> h block = Convolution2D(filters//2, 1, 1)(model) block = PReLU()(block) # h 3x3 -> h block = MaskedConvolution2D(filters//2, 3, 3, border_mode='same')(block) block = PReLU()(block) # h -> 2h block = Convolution2D(filters, 1, 1)(block) return PReLU()(Merge(mode='sum')([model, block])) def ResidualBlockList(model, filters, length): for _ in range(length): model = ResidualBlock(model, filters) return model
from keras.layers import Convolution2D, Merge from keras.layers.advanced_activations import PReLU from keras.engine.topology import merge from eva.layers.masked_convolution2d import MaskedConvolution2D def ResidualBlock(model, filters): # 2h -> h block = Convolution2D(filters//2, 1, 1)(model) block = PReLU()(block) # h 3x3 -> h block = MaskedConvolution2D(filters//2, 3, 3, border_mode='same')(block) block = PReLU()(block) # h -> 2h block = Convolution2D(filters, 1, 1)(block) return PReLU()(merge([model, block], mode='sum')) def ResidualBlockList(model, filters, length): for _ in range(length): model = ResidualBlock(model, filters) return model
Use the functional merge; just for formatting
Use the functional merge; just for formatting
Python
apache-2.0
israelg99/eva
<REPLACE_OLD> PReLU()(Merge(mode='sum')([model, block])) def <REPLACE_NEW> PReLU()(merge([model, block], mode='sum')) def <REPLACE_END> <|endoftext|> from keras.layers import Convolution2D, Merge from keras.layers.advanced_activations import PReLU from keras.engine.topology import merge from eva.layers.masked_convolution2d import MaskedConvolution2D def ResidualBlock(model, filters): # 2h -> h block = Convolution2D(filters//2, 1, 1)(model) block = PReLU()(block) # h 3x3 -> h block = MaskedConvolution2D(filters//2, 3, 3, border_mode='same')(block) block = PReLU()(block) # h -> 2h block = Convolution2D(filters, 1, 1)(block) return PReLU()(merge([model, block], mode='sum')) def ResidualBlockList(model, filters, length): for _ in range(length): model = ResidualBlock(model, filters) return model
Use the functional merge; just for formatting from keras.layers import Convolution2D, Merge from keras.layers.advanced_activations import PReLU from keras.engine.topology import merge from eva.layers.masked_convolution2d import MaskedConvolution2D def ResidualBlock(model, filters): # 2h -> h block = Convolution2D(filters//2, 1, 1)(model) block = PReLU()(block) # h 3x3 -> h block = MaskedConvolution2D(filters//2, 3, 3, border_mode='same')(block) block = PReLU()(block) # h -> 2h block = Convolution2D(filters, 1, 1)(block) return PReLU()(Merge(mode='sum')([model, block])) def ResidualBlockList(model, filters, length): for _ in range(length): model = ResidualBlock(model, filters) return model
0da81b53b521c22368899211dc851d6147e1a30d
common_components/static_renderers.py
common_components/static_renderers.py
from os.path import join, splitext, basename from bricks.staticfiles import StaticCss, StaticJs, StaticFile class _BuiltStatic(StaticFile): has_build_stage = True def __init__(self, *args): StaticFile.__init__(self, *args) self.url = self.url.rsplit('.', 1)[0] + '.' + self.target_type class Sass(_BuiltStatic): relpath = 'scss' target_type = 'css' def __call__(self): return '<link rel="stylesheet" href="{}" />'.format(self.url) class Coffee(_BuiltStatic): relpath = 'coffee' target_type = 'js' def __call__(self): return '<script src="{}"></script>'.format(self.url) class StaticLib(StaticFile): """A static asset or a directory with static assets that's needed to build other static assets but is not directly used by the page.""" has_build_stage = True def __call__(self): return '' class SassLib(StaticLib): relpath = 'scss'
from os.path import join, splitext, basename from bricks.staticfiles import StaticCss, StaticJs, StaticFile class _BuiltStatic(StaticFile): has_build_stage = True def __init__(self, *args): StaticFile.__init__(self, *args) self.url = self.url.rsplit('.', 1)[0] + '.' + self.target_type class Sass(_BuiltStatic): relpath = 'scss' target_type = 'css' class Coffee(_BuiltStatic): relpath = 'coffee' target_type = 'js' class StaticLib(StaticFile): """A static asset or a directory with static assets that's needed to build other static assets but is not directly used by the page.""" has_build_stage = True def __call__(self): return '' class SassLib(StaticLib): relpath = 'scss'
Revert "fixed rendering of Sass and Coffee"
Revert "fixed rendering of Sass and Coffee" This reverts commit b21834c9d439603f666d17aea338934bae063ef4.
Python
mpl-2.0
Zer0-/common_components
<REPLACE_OLD> 'css' def __call__(self): return '<link rel="stylesheet" href="{}" />'.format(self.url) class <REPLACE_NEW> 'css' class <REPLACE_END> <REPLACE_OLD> 'js' def __call__(self): return '<script src="{}"></script>'.format(self.url) class <REPLACE_NEW> 'js' class <REPLACE_END> <|endoftext|> from os.path import join, splitext, basename from bricks.staticfiles import StaticCss, StaticJs, StaticFile class _BuiltStatic(StaticFile): has_build_stage = True def __init__(self, *args): StaticFile.__init__(self, *args) self.url = self.url.rsplit('.', 1)[0] + '.' + self.target_type class Sass(_BuiltStatic): relpath = 'scss' target_type = 'css' class Coffee(_BuiltStatic): relpath = 'coffee' target_type = 'js' class StaticLib(StaticFile): """A static asset or a directory with static assets that's needed to build other static assets but is not directly used by the page.""" has_build_stage = True def __call__(self): return '' class SassLib(StaticLib): relpath = 'scss'
Revert "fixed rendering of Sass and Coffee" This reverts commit b21834c9d439603f666d17aea338934bae063ef4. from os.path import join, splitext, basename from bricks.staticfiles import StaticCss, StaticJs, StaticFile class _BuiltStatic(StaticFile): has_build_stage = True def __init__(self, *args): StaticFile.__init__(self, *args) self.url = self.url.rsplit('.', 1)[0] + '.' + self.target_type class Sass(_BuiltStatic): relpath = 'scss' target_type = 'css' def __call__(self): return '<link rel="stylesheet" href="{}" />'.format(self.url) class Coffee(_BuiltStatic): relpath = 'coffee' target_type = 'js' def __call__(self): return '<script src="{}"></script>'.format(self.url) class StaticLib(StaticFile): """A static asset or a directory with static assets that's needed to build other static assets but is not directly used by the page.""" has_build_stage = True def __call__(self): return '' class SassLib(StaticLib): relpath = 'scss'
5f64b609b621626e04516cac1c3313a3f948f19e
main.py
main.py
import logging import telebot import timer import bot import os logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logging.info("Begin start server.") tgBot = telebot.TeleBot(os.getenv("BOT_ID", "")) bot.getTracker(tgBot, logging)() timer.getTimer(tgBot, logging)("Timer").start() logging.info("Start polling") while True: try: tgBot.polling() except Exception as e: logging.error(e.message) # # import api # # print api.TrackerApi.getPackageInformation(3325607157191, "shentong")
import logging import telebot import timer import bot import os logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logging.info("Begin start server.") tgBot = telebot.TeleBot(os.getenv("BOT_ID", "")) bot.getTracker(tgBot, logging)() timer.getTimer(tgBot, logging)("Timer").start() logging.info("Start polling") tgBot.polling(none_stop=True)
Change While True Try to none_stop=True
Change While True Try to none_stop=True
Python
mit
ITelegramBot/PackageTrackerBot
<REPLACE_OLD> os logging.basicConfig(level=logging.DEBUG, <REPLACE_NEW> os logging.basicConfig(level=logging.INFO, <REPLACE_END> <REPLACE_OLD> polling") while True: try: tgBot.polling() except Exception as e: logging.error(e.message) # # import api # # print api.TrackerApi.getPackageInformation(3325607157191, "shentong") <REPLACE_NEW> polling") tgBot.polling(none_stop=True) <REPLACE_END> <|endoftext|> import logging import telebot import timer import bot import os logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logging.info("Begin start server.") tgBot = telebot.TeleBot(os.getenv("BOT_ID", "")) bot.getTracker(tgBot, logging)() timer.getTimer(tgBot, logging)("Timer").start() logging.info("Start polling") tgBot.polling(none_stop=True)
Change While True Try to none_stop=True import logging import telebot import timer import bot import os logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logging.info("Begin start server.") tgBot = telebot.TeleBot(os.getenv("BOT_ID", "")) bot.getTracker(tgBot, logging)() timer.getTimer(tgBot, logging)("Timer").start() logging.info("Start polling") while True: try: tgBot.polling() except Exception as e: logging.error(e.message) # # import api # # print api.TrackerApi.getPackageInformation(3325607157191, "shentong")
a4fcd6c4f628de22064ea054bac5603838b35459
councilmatic_core/migrations/0041_event_extras.py
councilmatic_core/migrations/0041_event_extras.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-05-07 16:20 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('councilmatic_core', '0040_mediaevent_meta'), ] operations = [ migrations.AddField( model_name='event', name='extras', field=django.contrib.postgres.fields.jsonb.JSONField(default=dict), ), migrations.RunSQL(''' UPDATE councilmatic_core_event SET extras = jsonb_build_object('guid', guid) WHERE guid IS NOT NULL ''', reverse_sql=''' UPDATE councilmatic_core_event SET guid = extras->'guid' WHERE extras->'guid' IS NOT NULL '''), migrations.RemoveField( model_name='event', name='guid', ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-05-07 16:20 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('councilmatic_core', '0040_mediaevent_meta'), ] operations = [ migrations.AddField( model_name='event', name='extras', field=django.contrib.postgres.fields.jsonb.JSONField(default=dict), ), migrations.RunSQL(''' UPDATE councilmatic_core_event SET extras = json_build_object('guid', guid) WHERE guid IS NOT NULL ''', reverse_sql=''' UPDATE councilmatic_core_event SET guid = extras->'guid' WHERE extras->'guid' IS NOT NULL '''), migrations.RemoveField( model_name='event', name='guid', ), ]
Use json_build_object, rather than jsonb_build_object
Use json_build_object, rather than jsonb_build_object
Python
mit
datamade/django-councilmatic,datamade/django-councilmatic,datamade/django-councilmatic,datamade/django-councilmatic
<REPLACE_OLD> jsonb_build_object('guid', <REPLACE_NEW> json_build_object('guid', <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-05-07 16:20 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('councilmatic_core', '0040_mediaevent_meta'), ] operations = [ migrations.AddField( model_name='event', name='extras', field=django.contrib.postgres.fields.jsonb.JSONField(default=dict), ), migrations.RunSQL(''' UPDATE councilmatic_core_event SET extras = json_build_object('guid', guid) WHERE guid IS NOT NULL ''', reverse_sql=''' UPDATE councilmatic_core_event SET guid = extras->'guid' WHERE extras->'guid' IS NOT NULL '''), migrations.RemoveField( model_name='event', name='guid', ), ]
Use json_build_object, rather than jsonb_build_object # -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-05-07 16:20 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('councilmatic_core', '0040_mediaevent_meta'), ] operations = [ migrations.AddField( model_name='event', name='extras', field=django.contrib.postgres.fields.jsonb.JSONField(default=dict), ), migrations.RunSQL(''' UPDATE councilmatic_core_event SET extras = jsonb_build_object('guid', guid) WHERE guid IS NOT NULL ''', reverse_sql=''' UPDATE councilmatic_core_event SET guid = extras->'guid' WHERE extras->'guid' IS NOT NULL '''), migrations.RemoveField( model_name='event', name='guid', ), ]
12a2113453eb5ec6171d52a49948ea663609afbd
gutenbrowse/util.py
gutenbrowse/util.py
import urllib as _urllib class HTTPError(IOError): def __init__(self, code, msg, headers): IOError.__init__(self, 'HTTP error', code, msg, headers) def __str__(self): return "HTTP: %d %s" % (self.args[1], self.args[2]) class MyURLOpener(_urllib.FancyURLopener): def http_error_default(self, url, fp, errcode, errmsg, headers): fp.close() raise HTTPError(errcode, errmsg, headers) _urlopener = None def myurlopen(url, data=None, proxies=None): """ As urllib.urlopen, but raises HTTPErrors on HTTP failure """ global _urlopener if proxies is not None: opener = MyURLOpener(proxies=proxies) elif not _urlopener: opener = MyURLOpener() _urlopener = opener else: opener = _urlopener if data is None: return opener.open(url) else: return opener.open(url, data) __all__ = ['myurlopen']
Add an exception-raising-on-http-error urlopen function
Add an exception-raising-on-http-error urlopen function
Python
bsd-3-clause
pv/mgutenberg,pv/mgutenberg
<INSERT> import urllib as _urllib class HTTPError(IOError): <INSERT_END> <INSERT> def __init__(self, code, msg, headers): IOError.__init__(self, 'HTTP error', code, msg, headers) def __str__(self): return "HTTP: %d %s" % (self.args[1], self.args[2]) class MyURLOpener(_urllib.FancyURLopener): def http_error_default(self, url, fp, errcode, errmsg, headers): fp.close() raise HTTPError(errcode, errmsg, headers) _urlopener = None def myurlopen(url, data=None, proxies=None): """ As urllib.urlopen, but raises HTTPErrors on HTTP failure """ global _urlopener if proxies is not None: opener = MyURLOpener(proxies=proxies) elif not _urlopener: opener = MyURLOpener() _urlopener = opener else: opener = _urlopener if data is None: return opener.open(url) else: return opener.open(url, data) __all__ = ['myurlopen'] <INSERT_END> <|endoftext|> import urllib as _urllib class HTTPError(IOError): def __init__(self, code, msg, headers): IOError.__init__(self, 'HTTP error', code, msg, headers) def __str__(self): return "HTTP: %d %s" % (self.args[1], self.args[2]) class MyURLOpener(_urllib.FancyURLopener): def http_error_default(self, url, fp, errcode, errmsg, headers): fp.close() raise HTTPError(errcode, errmsg, headers) _urlopener = None def myurlopen(url, data=None, proxies=None): """ As urllib.urlopen, but raises HTTPErrors on HTTP failure """ global _urlopener if proxies is not None: opener = MyURLOpener(proxies=proxies) elif not _urlopener: opener = MyURLOpener() _urlopener = opener else: opener = _urlopener if data is None: return opener.open(url) else: return opener.open(url, data) __all__ = ['myurlopen']
Add an exception-raising-on-http-error urlopen function
cad5087328bd462d6db8758929d212c4b34fae6c
server_ui/glue.py
server_ui/glue.py
""" Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('This election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied)
""" Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s\n') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s\n') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('\nThis election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied)
Add blank space in email message
Add blank space in email message
Python
apache-2.0
shirlei/helios-server,shirlei/helios-server,shirlei/helios-server,shirlei/helios-server,shirlei/helios-server
<REPLACE_OLD> in\n\n%(election_name)s') <REPLACE_NEW> in\n\n%(election_name)s\n') <REPLACE_END> <REPLACE_OLD> at:\n\n%(cast_url)s') <REPLACE_NEW> at:\n\n%(cast_url)s\n') <REPLACE_END> <REPLACE_OLD> _('This <REPLACE_NEW> _('\nThis <REPLACE_END> <|endoftext|> """ Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s\n') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s\n') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('\nThis election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied)
Add blank space in email message """ Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('This election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied)
b7faf879e81df86e49ec47f1bcce1d6488f743b2
medical_patient_species/tests/test_medical_patient_species.py
medical_patient_species/tests/test_medical_patient_species.py
# -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp.tests.common import TransactionCase class TestMedicalPatientSpecies(TransactionCase): def setUp(self): super(TestMedicalPatientSpecies, self).setUp() self.human = self.env.ref('medical_patient_species.human') self.dog = self.env.ref('medical_patient_species.dog') def test_create_is_person(self): ''' Tests on creation if Human, is_person is True ''' self.assertTrue( self.human.is_person, 'Should be True if Human' ) def test_create_not_is_person(self): ''' Tests on creation if not Human, is_person is False ''' self.assertFalse( self.dog.is_person, 'Should be False if not Human' )
# -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp.tests.common import TransactionCase from openerp.exceptions import Warning class TestMedicalPatientSpecies(TransactionCase): def setUp(self): super(TestMedicalPatientSpecies, self).setUp() self.human = self.env.ref('medical_patient_species.human') self.dog = self.env.ref('medical_patient_species.dog') def test_unlink_human(self): ''' Test raises Warning if unlinking human ''' with self.assertRaises(Warning): self.human.unlink()
Remove tests for is_person (default is False, human set to True in xml). Re-add test ensuring warning raised if trying to unlink Human.
[FIX] medical_patient_species: Remove tests for is_person (default is False, human set to True in xml). Re-add test ensuring warning raised if trying to unlink Human.
Python
agpl-3.0
laslabs/vertical-medical,laslabs/vertical-medical
<REPLACE_OLD> TransactionCase class <REPLACE_NEW> TransactionCase from openerp.exceptions import Warning class <REPLACE_END> <REPLACE_OLD> test_create_is_person(self): <REPLACE_NEW> test_unlink_human(self): <REPLACE_END> <REPLACE_OLD> Tests on creation <REPLACE_NEW> Test raises Warning <REPLACE_END> <REPLACE_OLD> Human, is_person is True <REPLACE_NEW> unlinking human <REPLACE_END> <REPLACE_OLD> self.assertTrue( <REPLACE_NEW> with self.assertRaises(Warning): <REPLACE_END> <REPLACE_OLD> self.human.is_person, 'Should be True if Human' ) def test_create_not_is_person(self): ''' Tests on creation if not Human, is_person is False ''' self.assertFalse( self.dog.is_person, 'Should be False if not Human' ) <REPLACE_NEW> self.human.unlink() <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp.tests.common import TransactionCase from openerp.exceptions import Warning class TestMedicalPatientSpecies(TransactionCase): def setUp(self): super(TestMedicalPatientSpecies, self).setUp() self.human = self.env.ref('medical_patient_species.human') self.dog = self.env.ref('medical_patient_species.dog') def test_unlink_human(self): ''' Test raises Warning if unlinking human ''' with self.assertRaises(Warning): self.human.unlink()
[FIX] medical_patient_species: Remove tests for is_person (default is False, human set to True in xml). Re-add test ensuring warning raised if trying to unlink Human. # -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp.tests.common import TransactionCase class TestMedicalPatientSpecies(TransactionCase): def setUp(self): super(TestMedicalPatientSpecies, self).setUp() self.human = self.env.ref('medical_patient_species.human') self.dog = self.env.ref('medical_patient_species.dog') def test_create_is_person(self): ''' Tests on creation if Human, is_person is True ''' self.assertTrue( self.human.is_person, 'Should be True if Human' ) def test_create_not_is_person(self): ''' Tests on creation if not Human, is_person is False ''' self.assertFalse( self.dog.is_person, 'Should be False if not Human' )
f87cbadbbcfc9d67aa3e5d0662236c18f23ba63b
DataBase.py
DataBase.py
''' Copyright 2015 RTeam (Edgar Kaziahmedov, Klim Kireev, Artem Yashuhin) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. '''
''' Copyright 2015 OneRTeam (Edgar Kaziahmedov, Klim Kireev, Artem Yashuhin) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. '''
Use source file with license 2
Use source file with license 2
Python
apache-2.0
proffK/CourseManager
<INSERT> <INSERT_END> <REPLACE_OLD> RTeam <REPLACE_NEW> OneRTeam <REPLACE_END> <|endoftext|> ''' Copyright 2015 OneRTeam (Edgar Kaziahmedov, Klim Kireev, Artem Yashuhin) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. '''
Use source file with license 2 ''' Copyright 2015 RTeam (Edgar Kaziahmedov, Klim Kireev, Artem Yashuhin) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. '''
c53e8aaadb35b6ca23d60bf4f4aa84812f186128
flake8_respect_noqa.py
flake8_respect_noqa.py
# -*- coding: utf-8 -*- """ Always ignore lines with '# noqa' """ __version__ = 0.1 import pep8 class RespectNoqaReport(pep8.StandardReport): def error(self, line_number, offset, text, check): if pep8.noqa(self.lines[line_number - 1]): return else: return super(RespectNoqaReport, self).error(line_number, offset, text, check) class RespectNoqa(object): name = 'flake8-respect-noqa' version = __version__ def __init__(self, *args, **kwargs): pass @classmethod def parse_options(cls, options): # The following only works with (flake8 2.4.1) if you run like "flake8 -j 1", # or put "jobs = 1" in your [flake8] config. # Otherwise, flake8 replaces this reported with it's own. # See https://gitlab.com/pycqa/flake8/issues/66 options.reporter = RespectNoqaReport options.report = RespectNoqaReport(options)
# -*- coding: utf-8 -*- """ Always ignore lines with '# noqa' """ __version__ = 0.1 import pep8 class RespectNoqaReport(pep8.StandardReport): def error(self, line_number, offset, text, check): if len(self.lines) > line_number - 1 and pep8.noqa(self.lines[line_number - 1]): return else: return super(RespectNoqaReport, self).error(line_number, offset, text, check) class RespectNoqa(object): name = 'flake8-respect-noqa' version = __version__ def __init__(self, *args, **kwargs): pass @classmethod def parse_options(cls, options): # The following only works with (flake8 2.4.1) if you run like "flake8 -j 1", # or put "jobs = 1" in your [flake8] config. # Otherwise, flake8 replaces this reported with it's own. # See https://gitlab.com/pycqa/flake8/issues/66 options.reporter = RespectNoqaReport options.report = RespectNoqaReport(options)
Fix for case when file can't be opened due to IOError or similar
Fix for case when file can't be opened due to IOError or similar
Python
mit
spookylukey/flake8-respect-noqa
<INSERT> len(self.lines) > line_number - 1 and <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*- """ Always ignore lines with '# noqa' """ __version__ = 0.1 import pep8 class RespectNoqaReport(pep8.StandardReport): def error(self, line_number, offset, text, check): if len(self.lines) > line_number - 1 and pep8.noqa(self.lines[line_number - 1]): return else: return super(RespectNoqaReport, self).error(line_number, offset, text, check) class RespectNoqa(object): name = 'flake8-respect-noqa' version = __version__ def __init__(self, *args, **kwargs): pass @classmethod def parse_options(cls, options): # The following only works with (flake8 2.4.1) if you run like "flake8 -j 1", # or put "jobs = 1" in your [flake8] config. # Otherwise, flake8 replaces this reported with it's own. # See https://gitlab.com/pycqa/flake8/issues/66 options.reporter = RespectNoqaReport options.report = RespectNoqaReport(options)
Fix for case when file can't be opened due to IOError or similar # -*- coding: utf-8 -*- """ Always ignore lines with '# noqa' """ __version__ = 0.1 import pep8 class RespectNoqaReport(pep8.StandardReport): def error(self, line_number, offset, text, check): if pep8.noqa(self.lines[line_number - 1]): return else: return super(RespectNoqaReport, self).error(line_number, offset, text, check) class RespectNoqa(object): name = 'flake8-respect-noqa' version = __version__ def __init__(self, *args, **kwargs): pass @classmethod def parse_options(cls, options): # The following only works with (flake8 2.4.1) if you run like "flake8 -j 1", # or put "jobs = 1" in your [flake8] config. # Otherwise, flake8 replaces this reported with it's own. # See https://gitlab.com/pycqa/flake8/issues/66 options.reporter = RespectNoqaReport options.report = RespectNoqaReport(options)
d5a59b79a3b3d6c2209eb9dc486a40d635aa6778
solum/builder/config.py
solum/builder/config.py
# Copyright 2014 - Rackspace Hosting # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # Pecan Application Configurations app = { 'root': 'solum.builder.controllers.root.RootController', 'modules': ['solum.builder'], 'debug': True, } # Custom Configurations must be in Python dictionary format:: # # foo = {'bar':'baz'} # # All configurations are accessible at:: # pecan.conf
# Copyright 2014 - Rackspace Hosting # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from solum.api import auth # Pecan Application Configurations app = { 'root': 'solum.builder.controllers.root.RootController', 'modules': ['solum.builder'], 'debug': True, 'hooks': [auth.AuthInformationHook()] } # Custom Configurations must be in Python dictionary format:: # # foo = {'bar':'baz'} # # All configurations are accessible at:: # pecan.conf
Add missing Auth hook to image builder
Add missing Auth hook to image builder Change-Id: I73f17c17a1f4d530c0351dacc2b10fbdcf3122e0
Python
apache-2.0
gilbertpilz/solum,stackforge/solum,gilbertpilz/solum,ed-/solum,openstack/solum,gilbertpilz/solum,openstack/solum,ed-/solum,stackforge/solum,devdattakulkarni/test-solum,gilbertpilz/solum,devdattakulkarni/test-solum,ed-/solum,ed-/solum
<REPLACE_OLD> License. # <REPLACE_NEW> License. from solum.api import auth # <REPLACE_END> <REPLACE_OLD> True, } # <REPLACE_NEW> True, 'hooks': [auth.AuthInformationHook()] } # <REPLACE_END> <|endoftext|> # Copyright 2014 - Rackspace Hosting # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from solum.api import auth # Pecan Application Configurations app = { 'root': 'solum.builder.controllers.root.RootController', 'modules': ['solum.builder'], 'debug': True, 'hooks': [auth.AuthInformationHook()] } # Custom Configurations must be in Python dictionary format:: # # foo = {'bar':'baz'} # # All configurations are accessible at:: # pecan.conf
Add missing Auth hook to image builder Change-Id: I73f17c17a1f4d530c0351dacc2b10fbdcf3122e0 # Copyright 2014 - Rackspace Hosting # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # Pecan Application Configurations app = { 'root': 'solum.builder.controllers.root.RootController', 'modules': ['solum.builder'], 'debug': True, } # Custom Configurations must be in Python dictionary format:: # # foo = {'bar':'baz'} # # All configurations are accessible at:: # pecan.conf
8882c77e6b96df7548357bce0a1c995fa2600e39
test/test_iebi.py
test/test_iebi.py
# -*- coding: utf-8 -*- import numpy as np import ibei from astropy import units import unittest temp_sun = 5762. temp_earth = 288. bandgap = 1.15 class Issues(unittest.TestCase): """ Tests output types of the calculator methods. """ def test_issue_1_devos_efficiency(self): """ Unit system needs to be specified for astropy.constants.e to work. """ try: ibei.devos_efficiency(bandgap, temp_sun, temp_earth, 1.09) except: self.fail("Unit system not initialized.")
Add tests for issues causing exceptions
Add tests for issues causing exceptions
Python
mit
jrsmith3/tec,jrsmith3/tec,jrsmith3/ibei
<INSERT> # -*- coding: utf-8 -*- import numpy as np import ibei from astropy import units import unittest temp_sun = 5762. temp_earth = 288. bandgap = 1.15 class Issues(unittest.TestCase): <INSERT_END> <INSERT> """ Tests output types of the calculator methods. """ def test_issue_1_devos_efficiency(self): """ Unit system needs to be specified for astropy.constants.e to work. """ try: ibei.devos_efficiency(bandgap, temp_sun, temp_earth, 1.09) except: self.fail("Unit system not initialized.") <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*- import numpy as np import ibei from astropy import units import unittest temp_sun = 5762. temp_earth = 288. bandgap = 1.15 class Issues(unittest.TestCase): """ Tests output types of the calculator methods. """ def test_issue_1_devos_efficiency(self): """ Unit system needs to be specified for astropy.constants.e to work. """ try: ibei.devos_efficiency(bandgap, temp_sun, temp_earth, 1.09) except: self.fail("Unit system not initialized.")
Add tests for issues causing exceptions
933fcfff7a9c63b03e13b0bb7756f0530603c556
series.py
series.py
"""Read and print an integer series.""" import sys def read_series(filename): f = open(filename, mode='rt', encoding='utf-8') series = [] for line in f: a = int(line.strip()) series.append(a) f.close() return series def main(filename): print(read_series(filename)) if __name__ == '__main__': main(sys.argv[1])
"""Read and print an integer series.""" import sys def read_series(filename): try: f = open(filename, mode='rt', encoding='utf-8') return [int(line.strip()) for line in f] finally: f.close() def main(filename): print(read_series(filename)) if __name__ == '__main__': main(sys.argv[1])
Refactor to ensure closing and also use list comprehension
Refactor to ensure closing and also use list comprehension
Python
mit
kentoj/python-fundamentals
<INSERT> try: <INSERT_END> <DELETE> series = [] <DELETE_END> <INSERT> return [int(line.strip()) <INSERT_END> <REPLACE_OLD> f: <REPLACE_NEW> f] finally: <REPLACE_END> <REPLACE_OLD> a = int(line.strip()) series.append(a) f.close() return series def <REPLACE_NEW> f.close() def <REPLACE_END> <|endoftext|> """Read and print an integer series.""" import sys def read_series(filename): try: f = open(filename, mode='rt', encoding='utf-8') return [int(line.strip()) for line in f] finally: f.close() def main(filename): print(read_series(filename)) if __name__ == '__main__': main(sys.argv[1])
Refactor to ensure closing and also use list comprehension """Read and print an integer series.""" import sys def read_series(filename): f = open(filename, mode='rt', encoding='utf-8') series = [] for line in f: a = int(line.strip()) series.append(a) f.close() return series def main(filename): print(read_series(filename)) if __name__ == '__main__': main(sys.argv[1])
920b4c2cee3ec37b115a190f5dbae0d2e56ec26a
array_split/split_plot.py
array_split/split_plot.py
""" ======================================== The :mod:`array_split.split_plot` Module ======================================== Uses :mod:`matplotlib` to plot a split. Classes and Functions ===================== .. autosummary:: :toctree: generated/ SplitPlotter - Plots a split. plot - Plots split shapes. """ from __future__ import absolute_import from .license import license as _license, copyright as _copyright, version as _version __author__ = "Shane J. Latham" __license__ = _license() __copyright__ = _copyright() __version__ = _version() class SplitPlotter(object): """ Plots a split. """ def __init__(self): """ """ pass def plot(split): """ Plots a split. """
Add skeleton for plotting split.
Add skeleton for plotting split.
Python
mit
array-split/array_split
<INSERT> """ ======================================== The :mod:`array_split.split_plot` Module ======================================== Uses :mod:`matplotlib` to plot a split. Classes and Functions ===================== .. autosummary:: <INSERT_END> <INSERT> :toctree: generated/ SplitPlotter - Plots a split. plot - Plots split shapes. """ from __future__ import absolute_import from .license import license as _license, copyright as _copyright, version as _version __author__ = "Shane J. Latham" __license__ = _license() __copyright__ = _copyright() __version__ = _version() class SplitPlotter(object): """ Plots a split. """ def __init__(self): """ """ pass def plot(split): """ Plots a split. """ <INSERT_END> <|endoftext|> """ ======================================== The :mod:`array_split.split_plot` Module ======================================== Uses :mod:`matplotlib` to plot a split. Classes and Functions ===================== .. autosummary:: :toctree: generated/ SplitPlotter - Plots a split. plot - Plots split shapes. """ from __future__ import absolute_import from .license import license as _license, copyright as _copyright, version as _version __author__ = "Shane J. Latham" __license__ = _license() __copyright__ = _copyright() __version__ = _version() class SplitPlotter(object): """ Plots a split. """ def __init__(self): """ """ pass def plot(split): """ Plots a split. """
Add skeleton for plotting split.
8c9d69b16f0c2848865a37b4a30325315f6d6735
longclaw/project_template/products/migrations/0001_initial.py
longclaw/project_template/products/migrations/0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-19 11:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import modelcluster.fields import wagtail.wagtailcore.fields class Migration(migrations.Migration): initial = True dependencies = [ ('longclawproducts', '0002_auto_20170219_0804'), ] operations = [ migrations.CreateModel( name='ProductVariant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=2, max_digits=12)), ('ref', models.CharField(max_length=32)), ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')), ('description', wagtail.wagtailcore.fields.RichTextField()), ('stock', models.IntegerField(default=0)), ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='longclawproducts.Product')), ], options={ 'abstract': False, }, ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-19 11:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import modelcluster.fields import wagtail.wagtailcore.fields class Migration(migrations.Migration): initial = True dependencies = [ ('longclawproducts', '0002_auto_20170219_0804'), ] operations = [ migrations.CreateModel( name='ProductVariant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=2, max_digits=12)), ('ref', models.CharField(max_length=32)), ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')), ('description', wagtail.wagtailcore.fields.RichTextField()), ('stock', models.IntegerField(default=0)), ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='products.Product')), ], options={ 'abstract': False, }, ), ]
Correct migration in project template
Correct migration in project template
Python
mit
JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw
<REPLACE_OLD> to='longclawproducts.Product')), <REPLACE_NEW> to='products.Product')), <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-19 11:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import modelcluster.fields import wagtail.wagtailcore.fields class Migration(migrations.Migration): initial = True dependencies = [ ('longclawproducts', '0002_auto_20170219_0804'), ] operations = [ migrations.CreateModel( name='ProductVariant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=2, max_digits=12)), ('ref', models.CharField(max_length=32)), ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')), ('description', wagtail.wagtailcore.fields.RichTextField()), ('stock', models.IntegerField(default=0)), ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='products.Product')), ], options={ 'abstract': False, }, ), ]
Correct migration in project template # -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-19 11:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import modelcluster.fields import wagtail.wagtailcore.fields class Migration(migrations.Migration): initial = True dependencies = [ ('longclawproducts', '0002_auto_20170219_0804'), ] operations = [ migrations.CreateModel( name='ProductVariant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=2, max_digits=12)), ('ref', models.CharField(max_length=32)), ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')), ('description', wagtail.wagtailcore.fields.RichTextField()), ('stock', models.IntegerField(default=0)), ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='longclawproducts.Product')), ], options={ 'abstract': False, }, ), ]
2137970240a9524990d55d711951fb7358621275
dedup_xspf.py
dedup_xspf.py
import xml.etree.ElementTree as ET from urllib.parse import unquote, urlparse import os import sys from fuzzywuzzy import process, fuzz # ImportError? pip install 'fuzzywuzzy[speedup]' import re files = [unquote(urlparse(el.text).path) for el in ET.parse(sys.argv[1]).getroot() .findall(".//*/{http://xspf.org/ns/0/}location") ] pfx = len(os.path.commonprefix(files)) trimmed = [re.search(r" - ([^_]+)", f[pfx:]).group(1) for f in files] for i, file in enumerate(files): others = trimmed[i + 1:] # Assume that similarity is commutative any = False for name, score in process.extractBests(trimmed[i], others, score_cutoff=80, scorer=fuzz.token_set_ratio): if not any: any = True print(file) print(name) if any: print("-----")
Create a little dedup script, probably not very general
Create a little dedup script, probably not very general
Python
mit
Rosuav/shed,Rosuav/shed,Rosuav/shed,Rosuav/shed,Rosuav/shed
<REPLACE_OLD> <REPLACE_NEW> import xml.etree.ElementTree as ET from urllib.parse import unquote, urlparse import os import sys from fuzzywuzzy import process, fuzz # ImportError? pip install 'fuzzywuzzy[speedup]' import re files = [unquote(urlparse(el.text).path) for el in ET.parse(sys.argv[1]).getroot() .findall(".//*/{http://xspf.org/ns/0/}location") ] pfx = len(os.path.commonprefix(files)) trimmed = [re.search(r" - ([^_]+)", f[pfx:]).group(1) for f in files] for i, file in enumerate(files): others = trimmed[i + 1:] # Assume that similarity is commutative any = False for name, score in process.extractBests(trimmed[i], others, score_cutoff=80, scorer=fuzz.token_set_ratio): if not any: any = True print(file) print(name) if any: print("-----") <REPLACE_END> <|endoftext|> import xml.etree.ElementTree as ET from urllib.parse import unquote, urlparse import os import sys from fuzzywuzzy import process, fuzz # ImportError? pip install 'fuzzywuzzy[speedup]' import re files = [unquote(urlparse(el.text).path) for el in ET.parse(sys.argv[1]).getroot() .findall(".//*/{http://xspf.org/ns/0/}location") ] pfx = len(os.path.commonprefix(files)) trimmed = [re.search(r" - ([^_]+)", f[pfx:]).group(1) for f in files] for i, file in enumerate(files): others = trimmed[i + 1:] # Assume that similarity is commutative any = False for name, score in process.extractBests(trimmed[i], others, score_cutoff=80, scorer=fuzz.token_set_ratio): if not any: any = True print(file) print(name) if any: print("-----")
Create a little dedup script, probably not very general
b0f3c0f8db69b7c4a141bd32680ed937b40d34c6
util/item_name_gen.py
util/item_name_gen.py
'''Script to help generate item names.''' def int_to_str(num, alphabet): '''Convert integer to string.''' # http://stackoverflow.com/a/1119769/1524507 if (num == 0): return alphabet[0] arr = [] base = len(alphabet) while num: rem = num % base num = num // base arr.append(alphabet[rem]) arr.reverse() return ''.join(arr) def main(): start_num = 0 end_num = 2176782335 pics_per_item = 1000 counter = start_num while True: lower = counter upper = min(counter + pics_per_item, end_num) print('picture:{0}-{1}'.format(lower, upper)) counter += 1000 if counter > end_num: break if __name__ == '__main__': main()
Add util script to generate item names.
Add util script to generate item names.
Python
unlicense
ArchiveTeam/twitpic-discovery,ArchiveTeam/twitpic-discovery
<INSERT> '''Script to help generate item names.''' def int_to_str(num, alphabet): <INSERT_END> <INSERT> '''Convert integer to string.''' # http://stackoverflow.com/a/1119769/1524507 if (num == 0): return alphabet[0] arr = [] base = len(alphabet) while num: rem = num % base num = num // base arr.append(alphabet[rem]) arr.reverse() return ''.join(arr) def main(): start_num = 0 end_num = 2176782335 pics_per_item = 1000 counter = start_num while True: lower = counter upper = min(counter + pics_per_item, end_num) print('picture:{0}-{1}'.format(lower, upper)) counter += 1000 if counter > end_num: break if __name__ == '__main__': main() <INSERT_END> <|endoftext|> '''Script to help generate item names.''' def int_to_str(num, alphabet): '''Convert integer to string.''' # http://stackoverflow.com/a/1119769/1524507 if (num == 0): return alphabet[0] arr = [] base = len(alphabet) while num: rem = num % base num = num // base arr.append(alphabet[rem]) arr.reverse() return ''.join(arr) def main(): start_num = 0 end_num = 2176782335 pics_per_item = 1000 counter = start_num while True: lower = counter upper = min(counter + pics_per_item, end_num) print('picture:{0}-{1}'.format(lower, upper)) counter += 1000 if counter > end_num: break if __name__ == '__main__': main()
Add util script to generate item names.
8858cf1f0b87026ce913a19c4e5df415409cfd79
streak-podium/read.py
streak-podium/read.py
import logging import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ Query Github API and return list of members from a Github organization. """ url = 'https://github.com/orgs/{}/members'.format(org_name) headers = {'Accept': 'application/vnd.github.ironman-preview+json'} try: r = requests.get(url, headers=headers) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get org members: [{}]'.format(url)) return [] if r.status_code == 404: print('Got 404') print(r.status_code) return [] print('response') print(r.text) return r.text def svg_data(username): """ Returns the contribution streak SVG file contents from Github for a specific username. """ url = 'https://github.com/users/{}/contributions'.format(username) try: r = requests.get(url) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get url: [{}]'.format(url)) return None return r.text
import logging import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ Query Github API and return list of members from a Github organization. """ if org_name is None: org_name = 'pulseenergy' url = 'https://github.com/orgs/{}/members'.format(org_name) headers = {'Accept': 'application/vnd.github.ironman-preview+json'} try: r = requests.get(url, headers=headers) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get org members: [{}]'.format(url)) return [] if r.status_code == 404: print('Got 404') print(r.status_code) return [] print('response') print(r.text) return r.text def svg_data(username): """ Returns the contribution streak SVG file contents from Github for a specific username. """ url = 'https://github.com/users/{}/contributions'.format(username) try: r = requests.get(url) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get url: [{}]'.format(url)) return None return r.text
Handle None for org or file with default org name
Handle None for org or file with default org name
Python
mit
supermitch/streak-podium,jollyra/hubot-commit-streak,jollyra/hubot-streak-podium,jollyra/hubot-commit-streak,supermitch/streak-podium,jollyra/hubot-streak-podium
<INSERT> if org_name is None: org_name = 'pulseenergy' <INSERT_END> <|endoftext|> import logging import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ Query Github API and return list of members from a Github organization. """ if org_name is None: org_name = 'pulseenergy' url = 'https://github.com/orgs/{}/members'.format(org_name) headers = {'Accept': 'application/vnd.github.ironman-preview+json'} try: r = requests.get(url, headers=headers) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get org members: [{}]'.format(url)) return [] if r.status_code == 404: print('Got 404') print(r.status_code) return [] print('response') print(r.text) return r.text def svg_data(username): """ Returns the contribution streak SVG file contents from Github for a specific username. """ url = 'https://github.com/users/{}/contributions'.format(username) try: r = requests.get(url) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get url: [{}]'.format(url)) return None return r.text
Handle None for org or file with default org name import logging import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ Query Github API and return list of members from a Github organization. """ url = 'https://github.com/orgs/{}/members'.format(org_name) headers = {'Accept': 'application/vnd.github.ironman-preview+json'} try: r = requests.get(url, headers=headers) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get org members: [{}]'.format(url)) return [] if r.status_code == 404: print('Got 404') print(r.status_code) return [] print('response') print(r.text) return r.text def svg_data(username): """ Returns the contribution streak SVG file contents from Github for a specific username. """ url = 'https://github.com/users/{}/contributions'.format(username) try: r = requests.get(url) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get url: [{}]'.format(url)) return None return r.text
a4142dfea882c37ab1b1db14aa6e7740ed1f0103
setup.py
setup.py
#!/usr/bin/env python """Setup script for PythonTemplateDemo.""" import setuptools from demo import __project__, __version__ try: README = open("README.rst").read() CHANGELOG = open("CHANGELOG.rst").read() except IOError: LONG_DESCRIPTION = "<file not found>" else: LONG_DESCRIPTION = README + '\n' + CHANGELOG setuptools.setup( name=__project__, version=__version__, description="A sample project templated from jacebrowning/template-python.", url='https://github.com/jacebrowning/template-python-demo', author='Jace Browning', author_email='[email protected]', packages=setuptools.find_packages(), entry_points={'console_scripts': []}, long_description=LONG_DESCRIPTION, license='MIT', classifiers=[ # TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers 'Development Status :: 1 - Planning', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=open("requirements.txt").readlines(), )
#!/usr/bin/env python """Setup script for PythonTemplateDemo.""" import setuptools from demo import __project__, __version__ try: README = open("README.rst").read() CHANGELOG = open("CHANGELOG.rst").read() except IOError: LONG_DESCRIPTION = "<placeholder>" else: LONG_DESCRIPTION = README + '\n' + CHANGELOG setuptools.setup( name=__project__, version=__version__, description="A sample project templated from jacebrowning/template-python.", url='https://github.com/jacebrowning/template-python-demo', author='Jace Browning', author_email='[email protected]', packages=setuptools.find_packages(), entry_points={'console_scripts': []}, long_description=LONG_DESCRIPTION, license='MIT', classifiers=[ # TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers 'Development Status :: 1 - Planning', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=open("requirements.txt").readlines(), )
Deploy Travis CI build 720 to GitHub
Deploy Travis CI build 720 to GitHub
Python
mit
jacebrowning/template-python-demo
<REPLACE_OLD> "<file not found>" else: <REPLACE_NEW> "<placeholder>" else: <REPLACE_END> <|endoftext|> #!/usr/bin/env python """Setup script for PythonTemplateDemo.""" import setuptools from demo import __project__, __version__ try: README = open("README.rst").read() CHANGELOG = open("CHANGELOG.rst").read() except IOError: LONG_DESCRIPTION = "<placeholder>" else: LONG_DESCRIPTION = README + '\n' + CHANGELOG setuptools.setup( name=__project__, version=__version__, description="A sample project templated from jacebrowning/template-python.", url='https://github.com/jacebrowning/template-python-demo', author='Jace Browning', author_email='[email protected]', packages=setuptools.find_packages(), entry_points={'console_scripts': []}, long_description=LONG_DESCRIPTION, license='MIT', classifiers=[ # TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers 'Development Status :: 1 - Planning', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=open("requirements.txt").readlines(), )
Deploy Travis CI build 720 to GitHub #!/usr/bin/env python """Setup script for PythonTemplateDemo.""" import setuptools from demo import __project__, __version__ try: README = open("README.rst").read() CHANGELOG = open("CHANGELOG.rst").read() except IOError: LONG_DESCRIPTION = "<file not found>" else: LONG_DESCRIPTION = README + '\n' + CHANGELOG setuptools.setup( name=__project__, version=__version__, description="A sample project templated from jacebrowning/template-python.", url='https://github.com/jacebrowning/template-python-demo', author='Jace Browning', author_email='[email protected]', packages=setuptools.find_packages(), entry_points={'console_scripts': []}, long_description=LONG_DESCRIPTION, license='MIT', classifiers=[ # TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers 'Development Status :: 1 - Planning', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=open("requirements.txt").readlines(), )