commit
stringlengths
40
40
old_file
stringlengths
4
106
new_file
stringlengths
4
106
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
2.95k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
7
43k
ndiff
stringlengths
52
3.31k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
diff
stringlengths
49
3.61k
b1b8c9b4e392d4865756ece6528e6668e2bc8975
wafw00f/plugins/expressionengine.py
wafw00f/plugins/expressionengine.py
NAME = 'Expression Engine (EllisLab)' def is_waf(self): for attack in self.attacks: r = attack(self) if r is None: return response, page = r # There are traces found where cookie is returning values like: # Set-Cookie: exp_last_query=834y8d73y94d8g983u4shn8u4shr3uh3 # Set-Cookie: exp_last_id=b342b432b1a876r8 if 'exp_last_' in response.getheader('Set-Cookie'): return True # In-page fingerprints vary a lot in different sites. Hence these are not quite reliable. if any(i in page for i in (b'Invalid GET Data', b'Invalid URI')): return True return False
NAME = 'Expression Engine (EllisLab)' def is_waf(self): for attack in self.attacks: r = attack(self) if r is None: return response, page = r # There are traces found where cookie is returning values like: # Set-Cookie: exp_last_query=834y8d73y94d8g983u4shn8u4shr3uh3 # Set-Cookie: exp_last_id=b342b432b1a876r8 if response.getheader('Set-Cookie'): if 'exp_last_' in response.getheader('Set-Cookie'): return True # In-page fingerprints vary a lot in different sites. Hence these are not quite reliable. if any(i in page for i in (b'Invalid GET Data', b'Invalid URI')): return True return False
Fix to avoid NoneType bugs
Fix to avoid NoneType bugs
Python
bsd-3-clause
EnableSecurity/wafw00f
NAME = 'Expression Engine (EllisLab)' def is_waf(self): for attack in self.attacks: r = attack(self) if r is None: return response, page = r # There are traces found where cookie is returning values like: # Set-Cookie: exp_last_query=834y8d73y94d8g983u4shn8u4shr3uh3 # Set-Cookie: exp_last_id=b342b432b1a876r8 + if response.getheader('Set-Cookie'): - if 'exp_last_' in response.getheader('Set-Cookie'): + if 'exp_last_' in response.getheader('Set-Cookie'): - return True + return True # In-page fingerprints vary a lot in different sites. Hence these are not quite reliable. if any(i in page for i in (b'Invalid GET Data', b'Invalid URI')): return True return False
Fix to avoid NoneType bugs
## Code Before: NAME = 'Expression Engine (EllisLab)' def is_waf(self): for attack in self.attacks: r = attack(self) if r is None: return response, page = r # There are traces found where cookie is returning values like: # Set-Cookie: exp_last_query=834y8d73y94d8g983u4shn8u4shr3uh3 # Set-Cookie: exp_last_id=b342b432b1a876r8 if 'exp_last_' in response.getheader('Set-Cookie'): return True # In-page fingerprints vary a lot in different sites. Hence these are not quite reliable. if any(i in page for i in (b'Invalid GET Data', b'Invalid URI')): return True return False ## Instruction: Fix to avoid NoneType bugs ## Code After: NAME = 'Expression Engine (EllisLab)' def is_waf(self): for attack in self.attacks: r = attack(self) if r is None: return response, page = r # There are traces found where cookie is returning values like: # Set-Cookie: exp_last_query=834y8d73y94d8g983u4shn8u4shr3uh3 # Set-Cookie: exp_last_id=b342b432b1a876r8 if response.getheader('Set-Cookie'): if 'exp_last_' in response.getheader('Set-Cookie'): return True # In-page fingerprints vary a lot in different sites. Hence these are not quite reliable. if any(i in page for i in (b'Invalid GET Data', b'Invalid URI')): return True return False
NAME = 'Expression Engine (EllisLab)' def is_waf(self): for attack in self.attacks: r = attack(self) if r is None: return response, page = r # There are traces found where cookie is returning values like: # Set-Cookie: exp_last_query=834y8d73y94d8g983u4shn8u4shr3uh3 # Set-Cookie: exp_last_id=b342b432b1a876r8 + if response.getheader('Set-Cookie'): - if 'exp_last_' in response.getheader('Set-Cookie'): + if 'exp_last_' in response.getheader('Set-Cookie'): ? ++++ - return True + return True ? ++++ # In-page fingerprints vary a lot in different sites. Hence these are not quite reliable. if any(i in page for i in (b'Invalid GET Data', b'Invalid URI')): return True return False
2baed20067fed71987bf7582fa9c9a5e53a63cb5
python/ql/test/experimental/library-tests/frameworks/stdlib/SafeAccessCheck.py
python/ql/test/experimental/library-tests/frameworks/stdlib/SafeAccessCheck.py
s = "taintedString" if s.startswith("tainted"): # $checks=s $branch=true pass
s = "taintedString" if s.startswith("tainted"): # $checks=s $branch=true pass sw = s.startswith # $f-:checks=s $f-:branch=true if sw("safe"): pass
Test false negative from review
Python: Test false negative from review
Python
mit
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
s = "taintedString" if s.startswith("tainted"): # $checks=s $branch=true pass + sw = s.startswith # $f-:checks=s $f-:branch=true + if sw("safe"): + pass +
Test false negative from review
## Code Before: s = "taintedString" if s.startswith("tainted"): # $checks=s $branch=true pass ## Instruction: Test false negative from review ## Code After: s = "taintedString" if s.startswith("tainted"): # $checks=s $branch=true pass sw = s.startswith # $f-:checks=s $f-:branch=true if sw("safe"): pass
s = "taintedString" if s.startswith("tainted"): # $checks=s $branch=true pass + + sw = s.startswith # $f-:checks=s $f-:branch=true + if sw("safe"): + pass
badddd6aa9533a01e07477174dc7422ee4941014
wsgi.py
wsgi.py
from newrelic import agent agent.initialize() from paste.deploy import loadapp from raven.middleware import Sentry application = loadapp('config:production.ini', relative_to='yithlibraryserver/config-templates') application = agent.WSGIApplicationWrapper(Sentry(application))
import os import os.path from newrelic import agent agent.initialize() from paste.deploy import loadapp from pyramid.paster import setup_logging from raven.middleware import Sentry from waitress import serve basedir= os.path.dirname(os.path.realpath(__file__)) conf_file = os.path.join( basedir, 'yithlibraryserver', 'config-templates', 'production.ini' ) application = loadapp('config:%s' % conf_file) application = agent.WSGIApplicationWrapper(Sentry(application)) if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) scheme = os.environ.get("SCHEME", "https") setup_logging(conf_file) serve(application, host='0.0.0.0', port=port, url_scheme=scheme)
Read the conf file using absolute paths
Read the conf file using absolute paths
Python
agpl-3.0
lorenzogil/yith-library-server,lorenzogil/yith-library-server,lorenzogil/yith-library-server
+ + import os + import os.path from newrelic import agent agent.initialize() from paste.deploy import loadapp + from pyramid.paster import setup_logging from raven.middleware import Sentry + from waitress import serve - application = loadapp('config:production.ini', - relative_to='yithlibraryserver/config-templates') + basedir= os.path.dirname(os.path.realpath(__file__)) + conf_file = os.path.join( + basedir, + 'yithlibraryserver', 'config-templates', 'production.ini' + ) + + application = loadapp('config:%s' % conf_file) application = agent.WSGIApplicationWrapper(Sentry(application)) + if __name__ == "__main__": + port = int(os.environ.get("PORT", 5000)) + scheme = os.environ.get("SCHEME", "https") + setup_logging(conf_file) + serve(application, host='0.0.0.0', port=port, url_scheme=scheme) +
Read the conf file using absolute paths
## Code Before: from newrelic import agent agent.initialize() from paste.deploy import loadapp from raven.middleware import Sentry application = loadapp('config:production.ini', relative_to='yithlibraryserver/config-templates') application = agent.WSGIApplicationWrapper(Sentry(application)) ## Instruction: Read the conf file using absolute paths ## Code After: import os import os.path from newrelic import agent agent.initialize() from paste.deploy import loadapp from pyramid.paster import setup_logging from raven.middleware import Sentry from waitress import serve basedir= os.path.dirname(os.path.realpath(__file__)) conf_file = os.path.join( basedir, 'yithlibraryserver', 'config-templates', 'production.ini' ) application = loadapp('config:%s' % conf_file) application = agent.WSGIApplicationWrapper(Sentry(application)) if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) scheme = os.environ.get("SCHEME", "https") setup_logging(conf_file) serve(application, host='0.0.0.0', port=port, url_scheme=scheme)
+ + import os + import os.path from newrelic import agent agent.initialize() from paste.deploy import loadapp + from pyramid.paster import setup_logging from raven.middleware import Sentry + from waitress import serve - application = loadapp('config:production.ini', - relative_to='yithlibraryserver/config-templates') + basedir= os.path.dirname(os.path.realpath(__file__)) + conf_file = os.path.join( + basedir, + 'yithlibraryserver', 'config-templates', 'production.ini' + ) + + application = loadapp('config:%s' % conf_file) application = agent.WSGIApplicationWrapper(Sentry(application)) + + if __name__ == "__main__": + port = int(os.environ.get("PORT", 5000)) + scheme = os.environ.get("SCHEME", "https") + setup_logging(conf_file) + serve(application, host='0.0.0.0', port=port, url_scheme=scheme)
2438efb99b85fbc76cd285792c1511e7e2813a05
zeus/api/resources/repository_tests.py
zeus/api/resources/repository_tests.py
from datetime import timedelta from sqlalchemy.sql import func from zeus.config import db from zeus.constants import Result, Status from zeus.models import Repository, TestCase, Job from zeus.utils import timezone from .base_repository import BaseRepositoryResource from ..schemas import TestCaseStatisticsSchema testcases_schema = TestCaseStatisticsSchema(many=True) class RepositoryTestsResource(BaseRepositoryResource): def get(self, repo: Repository): """ Return a list of testcases for the given repository. """ runs_failed = ( func.count(TestCase.result) .filter(TestCase.result == Result.failed) .label("runs_failed") ) query = ( db.session.query( TestCase.hash, TestCase.name, func.count(TestCase.hash).label("runs_total"), runs_failed, func.avg(TestCase.duration).label("avg_duration"), ) .join(Job, TestCase.job_id == Job.id) .filter( Job.repository_id == repo.id, Job.date_finished >= timezone.now() - timedelta(days=14), Job.status == Status.finished, TestCase.repository_id == repo.id, ) .group_by(TestCase.hash, TestCase.name) .order_by(runs_failed.desc()) ) return self.paginate_with_schema(testcases_schema, query)
from datetime import timedelta from sqlalchemy.sql import func from zeus.config import db from zeus.constants import Result, Status from zeus.models import Repository, TestCase, Job from zeus.utils import timezone from .base_repository import BaseRepositoryResource from ..schemas import TestCaseStatisticsSchema testcases_schema = TestCaseStatisticsSchema(many=True) class RepositoryTestsResource(BaseRepositoryResource): def get(self, repo: Repository): """ Return a list of testcases for the given repository. """ runs_failed = ( func.count(TestCase.result) .filter(TestCase.result == Result.failed) .label("runs_failed") ) query = ( db.session.query( TestCase.hash, TestCase.name, func.count(TestCase.hash).label("runs_total"), runs_failed, func.avg(TestCase.duration).label("avg_duration"), ) .filter( TestCase.job_id.in_( db.session.query(Job.id) .filter( Job.repository_id == repo.id, Job.date_finished >= timezone.now() - timedelta(days=14), Job.status == Status.finished, ) .subquery() ) ) .group_by(TestCase.hash, TestCase.name) .order_by(runs_failed.desc()) ) return self.paginate_with_schema(testcases_schema, query)
Simplify query plan for repo tests
ref: Simplify query plan for repo tests
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
from datetime import timedelta from sqlalchemy.sql import func from zeus.config import db from zeus.constants import Result, Status from zeus.models import Repository, TestCase, Job from zeus.utils import timezone from .base_repository import BaseRepositoryResource from ..schemas import TestCaseStatisticsSchema testcases_schema = TestCaseStatisticsSchema(many=True) class RepositoryTestsResource(BaseRepositoryResource): def get(self, repo: Repository): """ Return a list of testcases for the given repository. """ runs_failed = ( func.count(TestCase.result) .filter(TestCase.result == Result.failed) .label("runs_failed") ) query = ( db.session.query( TestCase.hash, TestCase.name, func.count(TestCase.hash).label("runs_total"), runs_failed, func.avg(TestCase.duration).label("avg_duration"), ) - .join(Job, TestCase.job_id == Job.id) .filter( + TestCase.job_id.in_( + db.session.query(Job.id) + .filter( - Job.repository_id == repo.id, + Job.repository_id == repo.id, - Job.date_finished >= timezone.now() - timedelta(days=14), + Job.date_finished >= timezone.now() - timedelta(days=14), - Job.status == Status.finished, + Job.status == Status.finished, - TestCase.repository_id == repo.id, + ) + .subquery() + ) ) .group_by(TestCase.hash, TestCase.name) .order_by(runs_failed.desc()) ) return self.paginate_with_schema(testcases_schema, query)
Simplify query plan for repo tests
## Code Before: from datetime import timedelta from sqlalchemy.sql import func from zeus.config import db from zeus.constants import Result, Status from zeus.models import Repository, TestCase, Job from zeus.utils import timezone from .base_repository import BaseRepositoryResource from ..schemas import TestCaseStatisticsSchema testcases_schema = TestCaseStatisticsSchema(many=True) class RepositoryTestsResource(BaseRepositoryResource): def get(self, repo: Repository): """ Return a list of testcases for the given repository. """ runs_failed = ( func.count(TestCase.result) .filter(TestCase.result == Result.failed) .label("runs_failed") ) query = ( db.session.query( TestCase.hash, TestCase.name, func.count(TestCase.hash).label("runs_total"), runs_failed, func.avg(TestCase.duration).label("avg_duration"), ) .join(Job, TestCase.job_id == Job.id) .filter( Job.repository_id == repo.id, Job.date_finished >= timezone.now() - timedelta(days=14), Job.status == Status.finished, TestCase.repository_id == repo.id, ) .group_by(TestCase.hash, TestCase.name) .order_by(runs_failed.desc()) ) return self.paginate_with_schema(testcases_schema, query) ## Instruction: Simplify query plan for repo tests ## Code After: from datetime import timedelta from sqlalchemy.sql import func from zeus.config import db from zeus.constants import Result, Status from zeus.models import Repository, TestCase, Job from zeus.utils import timezone from .base_repository import BaseRepositoryResource from ..schemas import TestCaseStatisticsSchema testcases_schema = TestCaseStatisticsSchema(many=True) class RepositoryTestsResource(BaseRepositoryResource): def get(self, repo: Repository): """ Return a list of testcases for the given repository. """ runs_failed = ( func.count(TestCase.result) .filter(TestCase.result == Result.failed) .label("runs_failed") ) query = ( db.session.query( TestCase.hash, TestCase.name, func.count(TestCase.hash).label("runs_total"), runs_failed, func.avg(TestCase.duration).label("avg_duration"), ) .filter( TestCase.job_id.in_( db.session.query(Job.id) .filter( Job.repository_id == repo.id, Job.date_finished >= timezone.now() - timedelta(days=14), Job.status == Status.finished, ) .subquery() ) ) .group_by(TestCase.hash, TestCase.name) .order_by(runs_failed.desc()) ) return self.paginate_with_schema(testcases_schema, query)
from datetime import timedelta from sqlalchemy.sql import func from zeus.config import db from zeus.constants import Result, Status from zeus.models import Repository, TestCase, Job from zeus.utils import timezone from .base_repository import BaseRepositoryResource from ..schemas import TestCaseStatisticsSchema testcases_schema = TestCaseStatisticsSchema(many=True) class RepositoryTestsResource(BaseRepositoryResource): def get(self, repo: Repository): """ Return a list of testcases for the given repository. """ runs_failed = ( func.count(TestCase.result) .filter(TestCase.result == Result.failed) .label("runs_failed") ) query = ( db.session.query( TestCase.hash, TestCase.name, func.count(TestCase.hash).label("runs_total"), runs_failed, func.avg(TestCase.duration).label("avg_duration"), ) - .join(Job, TestCase.job_id == Job.id) .filter( + TestCase.job_id.in_( + db.session.query(Job.id) + .filter( - Job.repository_id == repo.id, + Job.repository_id == repo.id, ? ++++++++ - Job.date_finished >= timezone.now() - timedelta(days=14), + Job.date_finished >= timezone.now() - timedelta(days=14), ? ++++++++ - Job.status == Status.finished, + Job.status == Status.finished, ? ++++++++ - TestCase.repository_id == repo.id, + ) + .subquery() + ) ) .group_by(TestCase.hash, TestCase.name) .order_by(runs_failed.desc()) ) return self.paginate_with_schema(testcases_schema, query)
2693b563a80e6906ace3f97b17e42012404b5cdc
modules/ecrans/tools.py
modules/ecrans/tools.py
"tools for lefigaro backend" # -*- coding: utf-8 -*- # Copyright(C) 2011 Julien Hebert # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with weboob. If not, see <http://www.gnu.org/licenses/>. import re def id2url(_id): "return an url from an id" regexp2 = re.compile("(\w+).([0-9]+).(.*$)") match = regexp2.match(_id) if match: return 'http://www.20minutes.fr/%s/%s/%s' % (match.group(1), match.group(2), match.group(3)) else: raise ValueError("id doesn't match") def url2id(url): "return an id from an url" regexp = re.compile("(^.*),([0-9]+)\.html$") match = regexp.match(url) if match: return match.group(2) else: raise ValueError("Can't find an id for the url") def rssid(entry): return url2id(entry.id)
"tools for lefigaro backend" # -*- coding: utf-8 -*- # Copyright(C) 2011 Julien Hebert # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with weboob. If not, see <http://www.gnu.org/licenses/>. import re def url2id(url): "return an id from an url" regexp = re.compile("(^.*),([0-9]+)\.html$") match = regexp.match(url) if match: return match.group(2) else: raise ValueError("Can't find an id for the url") def rssid(entry): return url2id(entry.id)
Remove useless function (2O minutes code in ecrans...)
Remove useless function (2O minutes code in ecrans...)
Python
agpl-3.0
nojhan/weboob-devel,nojhan/weboob-devel,yannrouillard/weboob,laurent-george/weboob,Konubinix/weboob,frankrousseau/weboob,frankrousseau/weboob,RouxRC/weboob,sputnick-dev/weboob,Boussadia/weboob,willprice/weboob,Konubinix/weboob,Boussadia/weboob,Boussadia/weboob,nojhan/weboob-devel,yannrouillard/weboob,frankrousseau/weboob,willprice/weboob,Boussadia/weboob,laurent-george/weboob,RouxRC/weboob,Konubinix/weboob,willprice/weboob,sputnick-dev/weboob,laurent-george/weboob,sputnick-dev/weboob,RouxRC/weboob,yannrouillard/weboob
"tools for lefigaro backend" # -*- coding: utf-8 -*- # Copyright(C) 2011 Julien Hebert # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with weboob. If not, see <http://www.gnu.org/licenses/>. - import re - - - def id2url(_id): - "return an url from an id" - regexp2 = re.compile("(\w+).([0-9]+).(.*$)") - match = regexp2.match(_id) - if match: - return 'http://www.20minutes.fr/%s/%s/%s' % (match.group(1), - match.group(2), - match.group(3)) - else: - raise ValueError("id doesn't match") def url2id(url): "return an id from an url" regexp = re.compile("(^.*),([0-9]+)\.html$") match = regexp.match(url) if match: return match.group(2) else: raise ValueError("Can't find an id for the url") def rssid(entry): return url2id(entry.id)
Remove useless function (2O minutes code in ecrans...)
## Code Before: "tools for lefigaro backend" # -*- coding: utf-8 -*- # Copyright(C) 2011 Julien Hebert # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with weboob. If not, see <http://www.gnu.org/licenses/>. import re def id2url(_id): "return an url from an id" regexp2 = re.compile("(\w+).([0-9]+).(.*$)") match = regexp2.match(_id) if match: return 'http://www.20minutes.fr/%s/%s/%s' % (match.group(1), match.group(2), match.group(3)) else: raise ValueError("id doesn't match") def url2id(url): "return an id from an url" regexp = re.compile("(^.*),([0-9]+)\.html$") match = regexp.match(url) if match: return match.group(2) else: raise ValueError("Can't find an id for the url") def rssid(entry): return url2id(entry.id) ## Instruction: Remove useless function (2O minutes code in ecrans...) ## Code After: "tools for lefigaro backend" # -*- coding: utf-8 -*- # Copyright(C) 2011 Julien Hebert # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with weboob. If not, see <http://www.gnu.org/licenses/>. import re def url2id(url): "return an id from an url" regexp = re.compile("(^.*),([0-9]+)\.html$") match = regexp.match(url) if match: return match.group(2) else: raise ValueError("Can't find an id for the url") def rssid(entry): return url2id(entry.id)
"tools for lefigaro backend" # -*- coding: utf-8 -*- # Copyright(C) 2011 Julien Hebert # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with weboob. If not, see <http://www.gnu.org/licenses/>. - import re - - - def id2url(_id): - "return an url from an id" - regexp2 = re.compile("(\w+).([0-9]+).(.*$)") - match = regexp2.match(_id) - if match: - return 'http://www.20minutes.fr/%s/%s/%s' % (match.group(1), - match.group(2), - match.group(3)) - else: - raise ValueError("id doesn't match") def url2id(url): "return an id from an url" regexp = re.compile("(^.*),([0-9]+)\.html$") match = regexp.match(url) if match: return match.group(2) else: raise ValueError("Can't find an id for the url") def rssid(entry): return url2id(entry.id)
020015cccceb3c2391c4764ee2ec29dfc5c461c6
__init__.py
__init__.py
from . import LayerView def getMetaData(): return { "name": "LayerView", "type": "View" } def register(app): app.getController().addView("LayerView", LayerView.LayerView())
from . import LayerView def getMetaData(): return { "name": "LayerView", "type": "View" } def register(app): return LayerView.LayerView()
Update plugin's register functions to return the object instance instead of performing the registration themselves
Update plugin's register functions to return the object instance instead of performing the registration themselves
Python
agpl-3.0
Curahelper/Cura,bq/Ultimaker-Cura,ad1217/Cura,bq/Ultimaker-Cura,senttech/Cura,lo0ol/Ultimaker-Cura,quillford/Cura,derekhe/Cura,ynotstartups/Wanhao,markwal/Cura,lo0ol/Ultimaker-Cura,senttech/Cura,DeskboxBrazil/Cura,ynotstartups/Wanhao,totalretribution/Cura,ad1217/Cura,fieldOfView/Cura,quillford/Cura,fxtentacle/Cura,derekhe/Cura,hmflash/Cura,DeskboxBrazil/Cura,fieldOfView/Cura,totalretribution/Cura,Curahelper/Cura,markwal/Cura,fxtentacle/Cura,hmflash/Cura
from . import LayerView def getMetaData(): return { "name": "LayerView", "type": "View" } def register(app): - app.getController().addView("LayerView", LayerView.LayerView()) + return LayerView.LayerView()
Update plugin's register functions to return the object instance instead of performing the registration themselves
## Code Before: from . import LayerView def getMetaData(): return { "name": "LayerView", "type": "View" } def register(app): app.getController().addView("LayerView", LayerView.LayerView()) ## Instruction: Update plugin's register functions to return the object instance instead of performing the registration themselves ## Code After: from . import LayerView def getMetaData(): return { "name": "LayerView", "type": "View" } def register(app): return LayerView.LayerView()
from . import LayerView def getMetaData(): return { "name": "LayerView", "type": "View" } def register(app): - app.getController().addView("LayerView", LayerView.LayerView()) + return LayerView.LayerView()
f943aa57d6ee462146ff0ab2a091c406d009acce
polyaxon/scheduler/spawners/templates/services/default_env_vars.py
polyaxon/scheduler/spawners/templates/services/default_env_vars.py
from django.conf import settings from scheduler.spawners.templates.env_vars import get_from_app_secret def get_service_env_vars(): return [ get_from_app_secret('POLYAXON_SECRET_KEY', 'polyaxon-secret'), get_from_app_secret('POLYAXON_INTERNAL_SECRET_TOKEN', 'polyaxon-internal-secret-token'), get_from_app_secret('POLYAXON_RABBITMQ_PASSWORD', 'rabbitmq-password', settings.POLYAXON_K8S_RABBITMQ_SECRET_NAME) ]
from django.conf import settings from libs.api import API_KEY_NAME, get_settings_api_url from scheduler.spawners.templates.env_vars import get_env_var, get_from_app_secret def get_service_env_vars(): return [ get_from_app_secret('POLYAXON_SECRET_KEY', 'polyaxon-secret'), get_from_app_secret('POLYAXON_INTERNAL_SECRET_TOKEN', 'polyaxon-internal-secret-token'), get_from_app_secret('POLYAXON_RABBITMQ_PASSWORD', 'rabbitmq-password', settings.POLYAXON_K8S_RABBITMQ_SECRET_NAME), get_env_var(name=API_KEY_NAME, value=get_settings_api_url()), ]
Add api url to default env vars
Add api url to default env vars
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
from django.conf import settings + from libs.api import API_KEY_NAME, get_settings_api_url - from scheduler.spawners.templates.env_vars import get_from_app_secret + from scheduler.spawners.templates.env_vars import get_env_var, get_from_app_secret def get_service_env_vars(): return [ get_from_app_secret('POLYAXON_SECRET_KEY', 'polyaxon-secret'), get_from_app_secret('POLYAXON_INTERNAL_SECRET_TOKEN', 'polyaxon-internal-secret-token'), get_from_app_secret('POLYAXON_RABBITMQ_PASSWORD', 'rabbitmq-password', - settings.POLYAXON_K8S_RABBITMQ_SECRET_NAME) + settings.POLYAXON_K8S_RABBITMQ_SECRET_NAME), + get_env_var(name=API_KEY_NAME, value=get_settings_api_url()), ]
Add api url to default env vars
## Code Before: from django.conf import settings from scheduler.spawners.templates.env_vars import get_from_app_secret def get_service_env_vars(): return [ get_from_app_secret('POLYAXON_SECRET_KEY', 'polyaxon-secret'), get_from_app_secret('POLYAXON_INTERNAL_SECRET_TOKEN', 'polyaxon-internal-secret-token'), get_from_app_secret('POLYAXON_RABBITMQ_PASSWORD', 'rabbitmq-password', settings.POLYAXON_K8S_RABBITMQ_SECRET_NAME) ] ## Instruction: Add api url to default env vars ## Code After: from django.conf import settings from libs.api import API_KEY_NAME, get_settings_api_url from scheduler.spawners.templates.env_vars import get_env_var, get_from_app_secret def get_service_env_vars(): return [ get_from_app_secret('POLYAXON_SECRET_KEY', 'polyaxon-secret'), get_from_app_secret('POLYAXON_INTERNAL_SECRET_TOKEN', 'polyaxon-internal-secret-token'), get_from_app_secret('POLYAXON_RABBITMQ_PASSWORD', 'rabbitmq-password', settings.POLYAXON_K8S_RABBITMQ_SECRET_NAME), get_env_var(name=API_KEY_NAME, value=get_settings_api_url()), ]
from django.conf import settings + from libs.api import API_KEY_NAME, get_settings_api_url - from scheduler.spawners.templates.env_vars import get_from_app_secret + from scheduler.spawners.templates.env_vars import get_env_var, get_from_app_secret ? +++++++++++++ def get_service_env_vars(): return [ get_from_app_secret('POLYAXON_SECRET_KEY', 'polyaxon-secret'), get_from_app_secret('POLYAXON_INTERNAL_SECRET_TOKEN', 'polyaxon-internal-secret-token'), get_from_app_secret('POLYAXON_RABBITMQ_PASSWORD', 'rabbitmq-password', - settings.POLYAXON_K8S_RABBITMQ_SECRET_NAME) + settings.POLYAXON_K8S_RABBITMQ_SECRET_NAME), ? + + get_env_var(name=API_KEY_NAME, value=get_settings_api_url()), ]
6136fc2bd2d9d191df7a9e6afd3aa9e4f110d61e
numpy/core/tests/test_print.py
numpy/core/tests/test_print.py
import numpy as np from numpy.testing import * class TestPrint(TestCase): def test_float_types(self) : """ Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.float, np.double, np.longdouble] : for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(t(x)), str(float(x))) def test_complex_types(self) : """Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.cfloat, np.cdouble, np.clongdouble] : for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(t(x)), str(complex(x))) assert_equal(str(t(x*1j)), str(complex(x*1j))) assert_equal(str(t(x + x*1j)), str(complex(x + x*1j))) if __name__ == "__main__": run_module_suite()
import numpy as np from numpy.testing import * def check_float_type(tp): for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(tp(x)), str(float(x))) def test_float_types(): """ Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.float, np.double, np.longdouble] : yield check_float_type, t def check_complex_type(tp): for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(tp(x)), str(complex(x))) assert_equal(str(tp(x*1j)), str(complex(x*1j))) assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j))) def test_complex_types(): """Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.cfloat, np.cdouble, np.clongdouble] : yield check_complex_type, t if __name__ == "__main__": run_module_suite()
Use parametric tests for format tests so that it is clearer which type is failing.
Use parametric tests for format tests so that it is clearer which type is failing.
Python
bsd-3-clause
solarjoe/numpy,NextThought/pypy-numpy,musically-ut/numpy,trankmichael/numpy,ViralLeadership/numpy,b-carter/numpy,argriffing/numpy,ogrisel/numpy,mhvk/numpy,mingwpy/numpy,b-carter/numpy,ewmoore/numpy,jakirkham/numpy,ahaldane/numpy,KaelChen/numpy,mhvk/numpy,utke1/numpy,ogrisel/numpy,skymanaditya1/numpy,rmcgibbo/numpy,embray/numpy,immerrr/numpy,ekalosak/numpy,skymanaditya1/numpy,ssanderson/numpy,pelson/numpy,abalkin/numpy,GaZ3ll3/numpy,rhythmsosad/numpy,kiwifb/numpy,numpy/numpy-refactor,nguyentu1602/numpy,maniteja123/numpy,BMJHayward/numpy,empeeu/numpy,has2k1/numpy,dwillmer/numpy,githubmlai/numpy,pyparallel/numpy,BMJHayward/numpy,seberg/numpy,Srisai85/numpy,AustereCuriosity/numpy,dwf/numpy,GrimDerp/numpy,numpy/numpy,charris/numpy,abalkin/numpy,Anwesh43/numpy,ViralLeadership/numpy,dato-code/numpy,rgommers/numpy,pizzathief/numpy,ChanderG/numpy,madphysicist/numpy,dwf/numpy,brandon-rhodes/numpy,gfyoung/numpy,groutr/numpy,numpy/numpy-refactor,CMartelLML/numpy,jonathanunderwood/numpy,rajathkumarmp/numpy,cowlicks/numpy,rhythmsosad/numpy,joferkington/numpy,joferkington/numpy,BabeNovelty/numpy,utke1/numpy,Yusa95/numpy,GrimDerp/numpy,astrofrog/numpy,charris/numpy,CMartelLML/numpy,GaZ3ll3/numpy,cjermain/numpy,ajdawson/numpy,MSeifert04/numpy,MaPePeR/numpy,has2k1/numpy,andsor/numpy,githubmlai/numpy,larsmans/numpy,matthew-brett/numpy,mindw/numpy,Dapid/numpy,nguyentu1602/numpy,gmcastil/numpy,abalkin/numpy,cjermain/numpy,rajathkumarmp/numpy,Anwesh43/numpy,mortada/numpy,sigma-random/numpy,numpy/numpy,chiffa/numpy,Dapid/numpy,mathdd/numpy,hainm/numpy,jschueller/numpy,ogrisel/numpy,brandon-rhodes/numpy,ewmoore/numpy,dwillmer/numpy,ekalosak/numpy,tacaswell/numpy,numpy/numpy-refactor,mwiebe/numpy,bertrand-l/numpy,jakirkham/numpy,endolith/numpy,embray/numpy,solarjoe/numpy,mattip/numpy,MaPePeR/numpy,mwiebe/numpy,AustereCuriosity/numpy,ESSS/numpy,matthew-brett/numpy,argriffing/numpy,nbeaver/numpy,dimasad/numpy,drasmuss/numpy,rudimeier/numpy,Eric89GXL/numpy,naritta/numpy,chatcannon/numpy,Dapid/numpy,jakirkham/numpy,AustereCuriosity/numpy,ESSS/numpy,tdsmith/numpy,rmcgibbo/numpy,pizzathief/numpy,rherault-insa/numpy,embray/numpy,seberg/numpy,rudimeier/numpy,mathdd/numpy,SunghanKim/numpy,MaPePeR/numpy,ddasilva/numpy,naritta/numpy,GrimDerp/numpy,nbeaver/numpy,numpy/numpy,drasmuss/numpy,kiwifb/numpy,mwiebe/numpy,bertrand-l/numpy,ogrisel/numpy,ahaldane/numpy,mortada/numpy,numpy/numpy-refactor,andsor/numpy,astrofrog/numpy,skwbc/numpy,MaPePeR/numpy,githubmlai/numpy,andsor/numpy,empeeu/numpy,dwillmer/numpy,CMartelLML/numpy,Srisai85/numpy,dimasad/numpy,madphysicist/numpy,cjermain/numpy,shoyer/numpy,ewmoore/numpy,drasmuss/numpy,bringingheavendown/numpy,dato-code/numpy,NextThought/pypy-numpy,Anwesh43/numpy,bmorris3/numpy,andsor/numpy,felipebetancur/numpy,mindw/numpy,mhvk/numpy,GaZ3ll3/numpy,skwbc/numpy,BMJHayward/numpy,jschueller/numpy,musically-ut/numpy,charris/numpy,matthew-brett/numpy,pelson/numpy,joferkington/numpy,seberg/numpy,jankoslavic/numpy,WillieMaddox/numpy,grlee77/numpy,Linkid/numpy,KaelChen/numpy,yiakwy/numpy,ChristopherHogan/numpy,MichaelAquilina/numpy,sigma-random/numpy,chatcannon/numpy,sinhrks/numpy,grlee77/numpy,dwillmer/numpy,SiccarPoint/numpy,gfyoung/numpy,pbrod/numpy,simongibbons/numpy,jorisvandenbossche/numpy,MSeifert04/numpy,ViralLeadership/numpy,yiakwy/numpy,njase/numpy,yiakwy/numpy,jorisvandenbossche/numpy,leifdenby/numpy,rhythmsosad/numpy,simongibbons/numpy,trankmichael/numpy,charris/numpy,brandon-rhodes/numpy,tdsmith/numpy,seberg/numpy,pdebuyl/numpy,numpy/numpy-refactor,rudimeier/numpy,anntzer/numpy,jorisvandenbossche/numpy,rajathkumarmp/numpy,musically-ut/numpy,grlee77/numpy,MSeifert04/numpy,bertrand-l/numpy,pyparallel/numpy,ajdawson/numpy,SunghanKim/numpy,KaelChen/numpy,jakirkham/numpy,chatcannon/numpy,kiwifb/numpy,pelson/numpy,Linkid/numpy,simongibbons/numpy,NextThought/pypy-numpy,madphysicist/numpy,MSeifert04/numpy,behzadnouri/numpy,shoyer/numpy,rherault-insa/numpy,WarrenWeckesser/numpy,ContinuumIO/numpy,embray/numpy,pdebuyl/numpy,kirillzhuravlev/numpy,utke1/numpy,larsmans/numpy,GrimDerp/numpy,immerrr/numpy,stefanv/numpy,dwf/numpy,sonnyhu/numpy,ewmoore/numpy,mhvk/numpy,ChanderG/numpy,hainm/numpy,SiccarPoint/numpy,jankoslavic/numpy,behzadnouri/numpy,musically-ut/numpy,mortada/numpy,pbrod/numpy,hainm/numpy,Yusa95/numpy,pizzathief/numpy,embray/numpy,leifdenby/numpy,stuarteberg/numpy,groutr/numpy,sigma-random/numpy,jankoslavic/numpy,solarjoe/numpy,moreati/numpy,pelson/numpy,immerrr/numpy,dimasad/numpy,endolith/numpy,hainm/numpy,larsmans/numpy,tynn/numpy,SunghanKim/numpy,trankmichael/numpy,nbeaver/numpy,pbrod/numpy,ChristopherHogan/numpy,ajdawson/numpy,sigma-random/numpy,dch312/numpy,tdsmith/numpy,stuarteberg/numpy,brandon-rhodes/numpy,has2k1/numpy,MichaelAquilina/numpy,mhvk/numpy,mingwpy/numpy,pelson/numpy,tynn/numpy,rgommers/numpy,felipebetancur/numpy,dato-code/numpy,rmcgibbo/numpy,WarrenWeckesser/numpy,WarrenWeckesser/numpy,rherault-insa/numpy,bringingheavendown/numpy,simongibbons/numpy,jakirkham/numpy,jorisvandenbossche/numpy,dwf/numpy,anntzer/numpy,jankoslavic/numpy,Yusa95/numpy,ajdawson/numpy,sinhrks/numpy,ogrisel/numpy,ssanderson/numpy,naritta/numpy,madphysicist/numpy,moreati/numpy,WarrenWeckesser/numpy,SunghanKim/numpy,numpy/numpy,jschueller/numpy,kirillzhuravlev/numpy,WillieMaddox/numpy,ssanderson/numpy,Eric89GXL/numpy,sinhrks/numpy,stuarteberg/numpy,SiccarPoint/numpy,endolith/numpy,tynn/numpy,maniteja123/numpy,BabeNovelty/numpy,skwbc/numpy,BabeNovelty/numpy,SiccarPoint/numpy,rudimeier/numpy,WarrenWeckesser/numpy,NextThought/pypy-numpy,trankmichael/numpy,dwf/numpy,sonnyhu/numpy,dch312/numpy,tacaswell/numpy,pbrod/numpy,ESSS/numpy,empeeu/numpy,larsmans/numpy,MSeifert04/numpy,maniteja123/numpy,bmorris3/numpy,gfyoung/numpy,mattip/numpy,jorisvandenbossche/numpy,ekalosak/numpy,moreati/numpy,pdebuyl/numpy,MichaelAquilina/numpy,kirillzhuravlev/numpy,ddasilva/numpy,Eric89GXL/numpy,matthew-brett/numpy,mortada/numpy,mathdd/numpy,empeeu/numpy,felipebetancur/numpy,Anwesh43/numpy,pdebuyl/numpy,ewmoore/numpy,bringingheavendown/numpy,behzadnouri/numpy,dato-code/numpy,astrofrog/numpy,Linkid/numpy,gmcastil/numpy,rhythmsosad/numpy,chiffa/numpy,endolith/numpy,stuarteberg/numpy,groutr/numpy,Linkid/numpy,GaZ3ll3/numpy,tacaswell/numpy,rajathkumarmp/numpy,jonathanunderwood/numpy,mindw/numpy,simongibbons/numpy,kirillzhuravlev/numpy,cowlicks/numpy,nguyentu1602/numpy,anntzer/numpy,njase/numpy,chiffa/numpy,pizzathief/numpy,shoyer/numpy,Srisai85/numpy,CMartelLML/numpy,githubmlai/numpy,WillieMaddox/numpy,ContinuumIO/numpy,ahaldane/numpy,mingwpy/numpy,madphysicist/numpy,naritta/numpy,sinhrks/numpy,KaelChen/numpy,stefanv/numpy,felipebetancur/numpy,yiakwy/numpy,cowlicks/numpy,MichaelAquilina/numpy,mindw/numpy,gmcastil/numpy,bmorris3/numpy,dch312/numpy,ahaldane/numpy,Yusa95/numpy,jonathanunderwood/numpy,grlee77/numpy,mathdd/numpy,sonnyhu/numpy,rgommers/numpy,rmcgibbo/numpy,tdsmith/numpy,astrofrog/numpy,sonnyhu/numpy,Srisai85/numpy,ahaldane/numpy,mattip/numpy,stefanv/numpy,shoyer/numpy,ChristopherHogan/numpy,ChanderG/numpy,rgommers/numpy,bmorris3/numpy,argriffing/numpy,mingwpy/numpy,pbrod/numpy,cjermain/numpy,pyparallel/numpy,anntzer/numpy,has2k1/numpy,b-carter/numpy,BMJHayward/numpy,stefanv/numpy,cowlicks/numpy,ChanderG/numpy,joferkington/numpy,skymanaditya1/numpy,dch312/numpy,BabeNovelty/numpy,matthew-brett/numpy,ddasilva/numpy,astrofrog/numpy,immerrr/numpy,jschueller/numpy,shoyer/numpy,grlee77/numpy,leifdenby/numpy,Eric89GXL/numpy,ChristopherHogan/numpy,ekalosak/numpy,stefanv/numpy,skymanaditya1/numpy,mattip/numpy,dimasad/numpy,ContinuumIO/numpy,njase/numpy,pizzathief/numpy,nguyentu1602/numpy
import numpy as np from numpy.testing import * - class TestPrint(TestCase): + def check_float_type(tp): + for x in [0, 1,-1, 1e10, 1e20] : + assert_equal(str(tp(x)), str(float(x))) - def test_float_types(self) : + def test_float_types(): - """ Check formatting. + """ Check formatting. - This is only for the str function, and only for simple types. + This is only for the str function, and only for simple types. - The precision of np.float and np.longdouble aren't the same as the + The precision of np.float and np.longdouble aren't the same as the - python float precision. + python float precision. - """ + """ - for t in [np.float, np.double, np.longdouble] : + for t in [np.float, np.double, np.longdouble] : + yield check_float_type, t - for x in [0, 1,-1, 1e10, 1e20] : - assert_equal(str(t(x)), str(float(x))) - def test_complex_types(self) : - """Check formatting. + def check_complex_type(tp): + for x in [0, 1,-1, 1e10, 1e20] : + assert_equal(str(tp(x)), str(complex(x))) + assert_equal(str(tp(x*1j)), str(complex(x*1j))) + assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j))) + def test_complex_types(): + """Check formatting. - This is only for the str function, and only for simple types. - The precision of np.float and np.longdouble aren't the same as the - python float precision. + This is only for the str function, and only for simple types. + The precision of np.float and np.longdouble aren't the same as the + python float precision. - """ - for t in [np.cfloat, np.cdouble, np.clongdouble] : - for x in [0, 1,-1, 1e10, 1e20] : - assert_equal(str(t(x)), str(complex(x))) - assert_equal(str(t(x*1j)), str(complex(x*1j))) - assert_equal(str(t(x + x*1j)), str(complex(x + x*1j))) + """ + for t in [np.cfloat, np.cdouble, np.clongdouble] : + yield check_complex_type, t if __name__ == "__main__": run_module_suite()
Use parametric tests for format tests so that it is clearer which type is failing.
## Code Before: import numpy as np from numpy.testing import * class TestPrint(TestCase): def test_float_types(self) : """ Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.float, np.double, np.longdouble] : for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(t(x)), str(float(x))) def test_complex_types(self) : """Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.cfloat, np.cdouble, np.clongdouble] : for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(t(x)), str(complex(x))) assert_equal(str(t(x*1j)), str(complex(x*1j))) assert_equal(str(t(x + x*1j)), str(complex(x + x*1j))) if __name__ == "__main__": run_module_suite() ## Instruction: Use parametric tests for format tests so that it is clearer which type is failing. ## Code After: import numpy as np from numpy.testing import * def check_float_type(tp): for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(tp(x)), str(float(x))) def test_float_types(): """ Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.float, np.double, np.longdouble] : yield check_float_type, t def check_complex_type(tp): for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(tp(x)), str(complex(x))) assert_equal(str(tp(x*1j)), str(complex(x*1j))) assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j))) def test_complex_types(): """Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.cfloat, np.cdouble, np.clongdouble] : yield check_complex_type, t if __name__ == "__main__": run_module_suite()
import numpy as np from numpy.testing import * - class TestPrint(TestCase): + def check_float_type(tp): + for x in [0, 1,-1, 1e10, 1e20] : + assert_equal(str(tp(x)), str(float(x))) - def test_float_types(self) : ? ---- ---- - + def test_float_types(): - """ Check formatting. ? ---- + """ Check formatting. - This is only for the str function, and only for simple types. ? ---- + This is only for the str function, and only for simple types. - The precision of np.float and np.longdouble aren't the same as the ? ---- + The precision of np.float and np.longdouble aren't the same as the - python float precision. ? ---- + python float precision. - """ ? ---- + """ - for t in [np.float, np.double, np.longdouble] : ? ---- + for t in [np.float, np.double, np.longdouble] : + yield check_float_type, t - for x in [0, 1,-1, 1e10, 1e20] : - assert_equal(str(t(x)), str(float(x))) - def test_complex_types(self) : - """Check formatting. + def check_complex_type(tp): + for x in [0, 1,-1, 1e10, 1e20] : + assert_equal(str(tp(x)), str(complex(x))) + assert_equal(str(tp(x*1j)), str(complex(x*1j))) + assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j))) + def test_complex_types(): + """Check formatting. - This is only for the str function, and only for simple types. - The precision of np.float and np.longdouble aren't the same as the - python float precision. + This is only for the str function, and only for simple types. + The precision of np.float and np.longdouble aren't the same as the + python float precision. - """ - for t in [np.cfloat, np.cdouble, np.clongdouble] : - for x in [0, 1,-1, 1e10, 1e20] : - assert_equal(str(t(x)), str(complex(x))) - assert_equal(str(t(x*1j)), str(complex(x*1j))) - assert_equal(str(t(x + x*1j)), str(complex(x + x*1j))) + """ + for t in [np.cfloat, np.cdouble, np.clongdouble] : + yield check_complex_type, t if __name__ == "__main__": run_module_suite()
42592f3f990ccd111244a8be90513aa4cf35f678
fireplace/cards/classic/neutral_epic.py
fireplace/cards/classic/neutral_epic.py
from ..utils import * # Big Game Hunter class EX1_005: action = [Destroy(TARGET)] # Mountain Giant class EX1_105: def cost(self, value): return value - (len(self.controller.hand) - 1) # Sea Giant class EX1_586: def cost(self, value): return value - len(self.game.board) # Blood Knight class EX1_590: def action(self): count = len(self.game.board.filter(divine_shield=True)) return [ SetTag(ALL_MINIONS, {GameTag.DIVINE_SHIELD: False}), Buff(self, "EX1_590e") * count, ] # Molten Giant class EX1_620: def cost(self, value): return value - self.controller.hero.damage # Captain's Parrot class NEW1_016: action = [ForceDraw(CONTROLLER, CONTROLLER_DECK + PIRATE)] # Hungry Crab class NEW1_017: action = [Destroy(TARGET), Buff(SELF, "NEW1_017e")] # Doomsayer class NEW1_021: events = [ OWN_TURN_BEGIN.on(Destroy(ALL_MINIONS)) ]
from ..utils import * # Big Game Hunter class EX1_005: action = [Destroy(TARGET)] # Mountain Giant class EX1_105: def cost(self, value): return value - (len(self.controller.hand) - 1) # Sea Giant class EX1_586: def cost(self, value): return value - len(self.game.board) # Blood Knight class EX1_590: action = [ Buff(SELF, "EX1_590e") * Count(ALL_MINIONS + DIVINE_SHIELD), SetTag(ALL_MINIONS, {GameTag.DIVINE_SHIELD: False}) ] # Molten Giant class EX1_620: def cost(self, value): return value - self.controller.hero.damage # Captain's Parrot class NEW1_016: action = [ForceDraw(CONTROLLER, CONTROLLER_DECK + PIRATE)] # Hungry Crab class NEW1_017: action = [Destroy(TARGET), Buff(SELF, "NEW1_017e")] # Doomsayer class NEW1_021: events = [ OWN_TURN_BEGIN.on(Destroy(ALL_MINIONS)) ]
Use Count() in Blood Knight
Use Count() in Blood Knight
Python
agpl-3.0
liujimj/fireplace,Ragowit/fireplace,jleclanche/fireplace,butozerca/fireplace,oftc-ftw/fireplace,Meerkov/fireplace,liujimj/fireplace,Meerkov/fireplace,smallnamespace/fireplace,butozerca/fireplace,NightKev/fireplace,smallnamespace/fireplace,amw2104/fireplace,oftc-ftw/fireplace,amw2104/fireplace,beheh/fireplace,Ragowit/fireplace
from ..utils import * # Big Game Hunter class EX1_005: action = [Destroy(TARGET)] # Mountain Giant class EX1_105: def cost(self, value): return value - (len(self.controller.hand) - 1) # Sea Giant class EX1_586: def cost(self, value): return value - len(self.game.board) # Blood Knight class EX1_590: + action = [ + Buff(SELF, "EX1_590e") * Count(ALL_MINIONS + DIVINE_SHIELD), - def action(self): - count = len(self.game.board.filter(divine_shield=True)) - return [ - SetTag(ALL_MINIONS, {GameTag.DIVINE_SHIELD: False}), + SetTag(ALL_MINIONS, {GameTag.DIVINE_SHIELD: False}) - Buff(self, "EX1_590e") * count, - ] + ] # Molten Giant class EX1_620: def cost(self, value): return value - self.controller.hero.damage # Captain's Parrot class NEW1_016: action = [ForceDraw(CONTROLLER, CONTROLLER_DECK + PIRATE)] # Hungry Crab class NEW1_017: action = [Destroy(TARGET), Buff(SELF, "NEW1_017e")] # Doomsayer class NEW1_021: events = [ OWN_TURN_BEGIN.on(Destroy(ALL_MINIONS)) ]
Use Count() in Blood Knight
## Code Before: from ..utils import * # Big Game Hunter class EX1_005: action = [Destroy(TARGET)] # Mountain Giant class EX1_105: def cost(self, value): return value - (len(self.controller.hand) - 1) # Sea Giant class EX1_586: def cost(self, value): return value - len(self.game.board) # Blood Knight class EX1_590: def action(self): count = len(self.game.board.filter(divine_shield=True)) return [ SetTag(ALL_MINIONS, {GameTag.DIVINE_SHIELD: False}), Buff(self, "EX1_590e") * count, ] # Molten Giant class EX1_620: def cost(self, value): return value - self.controller.hero.damage # Captain's Parrot class NEW1_016: action = [ForceDraw(CONTROLLER, CONTROLLER_DECK + PIRATE)] # Hungry Crab class NEW1_017: action = [Destroy(TARGET), Buff(SELF, "NEW1_017e")] # Doomsayer class NEW1_021: events = [ OWN_TURN_BEGIN.on(Destroy(ALL_MINIONS)) ] ## Instruction: Use Count() in Blood Knight ## Code After: from ..utils import * # Big Game Hunter class EX1_005: action = [Destroy(TARGET)] # Mountain Giant class EX1_105: def cost(self, value): return value - (len(self.controller.hand) - 1) # Sea Giant class EX1_586: def cost(self, value): return value - len(self.game.board) # Blood Knight class EX1_590: action = [ Buff(SELF, "EX1_590e") * Count(ALL_MINIONS + DIVINE_SHIELD), SetTag(ALL_MINIONS, {GameTag.DIVINE_SHIELD: False}) ] # Molten Giant class EX1_620: def cost(self, value): return value - self.controller.hero.damage # Captain's Parrot class NEW1_016: action = [ForceDraw(CONTROLLER, CONTROLLER_DECK + PIRATE)] # Hungry Crab class NEW1_017: action = [Destroy(TARGET), Buff(SELF, "NEW1_017e")] # Doomsayer class NEW1_021: events = [ OWN_TURN_BEGIN.on(Destroy(ALL_MINIONS)) ]
from ..utils import * # Big Game Hunter class EX1_005: action = [Destroy(TARGET)] # Mountain Giant class EX1_105: def cost(self, value): return value - (len(self.controller.hand) - 1) # Sea Giant class EX1_586: def cost(self, value): return value - len(self.game.board) # Blood Knight class EX1_590: + action = [ + Buff(SELF, "EX1_590e") * Count(ALL_MINIONS + DIVINE_SHIELD), - def action(self): - count = len(self.game.board.filter(divine_shield=True)) - return [ - SetTag(ALL_MINIONS, {GameTag.DIVINE_SHIELD: False}), ? - - + SetTag(ALL_MINIONS, {GameTag.DIVINE_SHIELD: False}) - Buff(self, "EX1_590e") * count, - ] ? - + ] # Molten Giant class EX1_620: def cost(self, value): return value - self.controller.hero.damage # Captain's Parrot class NEW1_016: action = [ForceDraw(CONTROLLER, CONTROLLER_DECK + PIRATE)] # Hungry Crab class NEW1_017: action = [Destroy(TARGET), Buff(SELF, "NEW1_017e")] # Doomsayer class NEW1_021: events = [ OWN_TURN_BEGIN.on(Destroy(ALL_MINIONS)) ]
b575099c0d1f23916038172d46852a264a5f5a95
bluebottle/utils/staticfiles_finders.py
bluebottle/utils/staticfiles_finders.py
from django.utils._os import safe_join import os from django.conf import settings from django.contrib.staticfiles.finders import FileSystemFinder from bluebottle.clients.models import Client class TenantStaticFilesFinder(FileSystemFinder): def find(self, path, all=False): """ Looks for files in the client static directories. static/assets/greatbarier/images/logo.jpg will translate to MULTI_TENANT_DIR/greatbarier/static/images/logo.jpg """ tenants = Client.objects.all() tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None) if not tenant_dir: return for tenant in tenants: if "{0}/".format(tenant.client_name) in path: tenant_path = path.replace('{0}/'.format(tenant.client_name), '{0}/static/'.format(tenant.client_name)) local_path = safe_join(tenant_dir, tenant_path) if os.path.exists(local_path): return local_path return
from django.utils._os import safe_join import os from django.conf import settings from django.contrib.staticfiles.finders import FileSystemFinder from bluebottle.clients.models import Client class TenantStaticFilesFinder(FileSystemFinder): def find(self, path, all=False): """ Looks for files in the client static directories. static/assets/greatbarier/images/logo.jpg will translate to MULTI_TENANT_DIR/greatbarier/static/images/logo.jpg """ tenants = Client.objects.all() tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None) if not tenant_dir: return [] for tenant in tenants: if "{0}/".format(tenant.client_name) in path: tenant_path = path.replace('{0}/'.format(tenant.client_name), '{0}/static/'.format(tenant.client_name)) local_path = safe_join(tenant_dir, tenant_path) if os.path.exists(local_path): if all: return [local_path] return local_path return []
Fix static files finder errors
Fix static files finder errors
Python
bsd-3-clause
jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle
from django.utils._os import safe_join import os from django.conf import settings from django.contrib.staticfiles.finders import FileSystemFinder from bluebottle.clients.models import Client class TenantStaticFilesFinder(FileSystemFinder): def find(self, path, all=False): """ Looks for files in the client static directories. static/assets/greatbarier/images/logo.jpg will translate to MULTI_TENANT_DIR/greatbarier/static/images/logo.jpg """ tenants = Client.objects.all() tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None) + if not tenant_dir: - return + return [] for tenant in tenants: if "{0}/".format(tenant.client_name) in path: tenant_path = path.replace('{0}/'.format(tenant.client_name), '{0}/static/'.format(tenant.client_name)) local_path = safe_join(tenant_dir, tenant_path) if os.path.exists(local_path): + if all: + return [local_path] return local_path - return + return []
Fix static files finder errors
## Code Before: from django.utils._os import safe_join import os from django.conf import settings from django.contrib.staticfiles.finders import FileSystemFinder from bluebottle.clients.models import Client class TenantStaticFilesFinder(FileSystemFinder): def find(self, path, all=False): """ Looks for files in the client static directories. static/assets/greatbarier/images/logo.jpg will translate to MULTI_TENANT_DIR/greatbarier/static/images/logo.jpg """ tenants = Client.objects.all() tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None) if not tenant_dir: return for tenant in tenants: if "{0}/".format(tenant.client_name) in path: tenant_path = path.replace('{0}/'.format(tenant.client_name), '{0}/static/'.format(tenant.client_name)) local_path = safe_join(tenant_dir, tenant_path) if os.path.exists(local_path): return local_path return ## Instruction: Fix static files finder errors ## Code After: from django.utils._os import safe_join import os from django.conf import settings from django.contrib.staticfiles.finders import FileSystemFinder from bluebottle.clients.models import Client class TenantStaticFilesFinder(FileSystemFinder): def find(self, path, all=False): """ Looks for files in the client static directories. static/assets/greatbarier/images/logo.jpg will translate to MULTI_TENANT_DIR/greatbarier/static/images/logo.jpg """ tenants = Client.objects.all() tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None) if not tenant_dir: return [] for tenant in tenants: if "{0}/".format(tenant.client_name) in path: tenant_path = path.replace('{0}/'.format(tenant.client_name), '{0}/static/'.format(tenant.client_name)) local_path = safe_join(tenant_dir, tenant_path) if os.path.exists(local_path): if all: return [local_path] return local_path return []
from django.utils._os import safe_join import os from django.conf import settings from django.contrib.staticfiles.finders import FileSystemFinder from bluebottle.clients.models import Client class TenantStaticFilesFinder(FileSystemFinder): def find(self, path, all=False): """ Looks for files in the client static directories. static/assets/greatbarier/images/logo.jpg will translate to MULTI_TENANT_DIR/greatbarier/static/images/logo.jpg """ tenants = Client.objects.all() tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None) + if not tenant_dir: - return + return [] ? +++ for tenant in tenants: if "{0}/".format(tenant.client_name) in path: tenant_path = path.replace('{0}/'.format(tenant.client_name), '{0}/static/'.format(tenant.client_name)) local_path = safe_join(tenant_dir, tenant_path) if os.path.exists(local_path): + if all: + return [local_path] return local_path - return + return [] ? +++
16b663441c0d994b02e68b8c785ec6c7a2805f03
onepercentclub/settings/payments.py
onepercentclub/settings/payments.py
from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS, DOCDATA_PAYMENT_METHODS PAYMENT_METHODS = DOCDATA_PAYMENT_METHODS VAT_RATE = 0.21
from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS PAYMENT_METHODS = ( { 'provider': 'docdata', 'id': 'docdata-ideal', 'profile': 'ideal', 'name': 'iDEAL', 'restricted_countries': ('NL', 'Netherlands'), 'supports_recurring': False, }, { 'provider': 'docdata', 'id': 'docdata-directdebit', 'profile': 'directdebit', 'name': 'Direct Debit', 'supports_recurring': True, }, { 'provider': 'docdata', 'id': 'docdata-creditcard', 'profile': 'creditcard', 'name': 'CreditCard', 'supports_recurring': False, }, # { # 'provider': 'docdata', # 'id': 'docdata-paypal', # 'profile': 'paypal', # 'name': 'Paypal', # 'supports_recurring': False, # }, ) VAT_RATE = 0.21
Disable Paypal, up Direct debit
Disable Paypal, up Direct debit
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
- from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS, DOCDATA_PAYMENT_METHODS + from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS - PAYMENT_METHODS = DOCDATA_PAYMENT_METHODS + PAYMENT_METHODS = ( + { + 'provider': 'docdata', + 'id': 'docdata-ideal', + 'profile': 'ideal', + 'name': 'iDEAL', + 'restricted_countries': ('NL', 'Netherlands'), + 'supports_recurring': False, + }, + { + 'provider': 'docdata', + 'id': 'docdata-directdebit', + 'profile': 'directdebit', + 'name': 'Direct Debit', + 'supports_recurring': True, + }, + { + 'provider': 'docdata', + 'id': 'docdata-creditcard', + 'profile': 'creditcard', + 'name': 'CreditCard', + 'supports_recurring': False, + }, + # { + # 'provider': 'docdata', + # 'id': 'docdata-paypal', + # 'profile': 'paypal', + # 'name': 'Paypal', + # 'supports_recurring': False, + # }, + ) VAT_RATE = 0.21
Disable Paypal, up Direct debit
## Code Before: from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS, DOCDATA_PAYMENT_METHODS PAYMENT_METHODS = DOCDATA_PAYMENT_METHODS VAT_RATE = 0.21 ## Instruction: Disable Paypal, up Direct debit ## Code After: from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS PAYMENT_METHODS = ( { 'provider': 'docdata', 'id': 'docdata-ideal', 'profile': 'ideal', 'name': 'iDEAL', 'restricted_countries': ('NL', 'Netherlands'), 'supports_recurring': False, }, { 'provider': 'docdata', 'id': 'docdata-directdebit', 'profile': 'directdebit', 'name': 'Direct Debit', 'supports_recurring': True, }, { 'provider': 'docdata', 'id': 'docdata-creditcard', 'profile': 'creditcard', 'name': 'CreditCard', 'supports_recurring': False, }, # { # 'provider': 'docdata', # 'id': 'docdata-paypal', # 'profile': 'paypal', # 'name': 'Paypal', # 'supports_recurring': False, # }, ) VAT_RATE = 0.21
- from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS, DOCDATA_PAYMENT_METHODS ? ------------------------- + from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS - PAYMENT_METHODS = DOCDATA_PAYMENT_METHODS + PAYMENT_METHODS = ( + { + 'provider': 'docdata', + 'id': 'docdata-ideal', + 'profile': 'ideal', + 'name': 'iDEAL', + 'restricted_countries': ('NL', 'Netherlands'), + 'supports_recurring': False, + }, + { + 'provider': 'docdata', + 'id': 'docdata-directdebit', + 'profile': 'directdebit', + 'name': 'Direct Debit', + 'supports_recurring': True, + }, + { + 'provider': 'docdata', + 'id': 'docdata-creditcard', + 'profile': 'creditcard', + 'name': 'CreditCard', + 'supports_recurring': False, + }, + # { + # 'provider': 'docdata', + # 'id': 'docdata-paypal', + # 'profile': 'paypal', + # 'name': 'Paypal', + # 'supports_recurring': False, + # }, + ) VAT_RATE = 0.21
2462595312ca7ddf38ffb6d4bcdf7515401fe7ee
tests/test_hooks.py
tests/test_hooks.py
import json from jazzband.projects.tasks import update_project_by_hook from jazzband.tasks import JazzbandSpinach def post(client, hook, data, guid="abc"): headers = {"X-GitHub-Event": hook, "X-GitHub-Delivery": guid} return client.post( "/hooks", content_type="application/json", data=json.dumps(data), headers=headers, ) def test_ping(client): rv = post(client, "ping", {}) assert b"pong" in rv.data assert rv.status_code == 200 def test_repo_transferred_hook(client, datadir, mocker): contents = (datadir / "repository.json").read_text() mocked_schedule = mocker.patch.object(JazzbandSpinach, "schedule") response = post(client, "repository", json.loads(contents)) assert response.data response_string = response.data.decode("utf-8") assert response_string.startswith("Started updating the project using hook id repo-added-") mocked_schedule.assert_called_once_with(update_project_by_hook, response_string)
import json from jazzband.projects.tasks import update_project_by_hook from jazzband.tasks import JazzbandSpinach def post(client, hook, data, guid="abc"): headers = {"X-GitHub-Event": hook, "X-GitHub-Delivery": guid} return client.post( "/hooks", content_type="application/json", data=json.dumps(data), headers=headers, ) def test_ping(client): rv = post(client, "ping", {}) assert b"pong" in rv.data assert rv.status_code == 200 def test_repo_transferred_hook(client, datadir, mocker): contents = (datadir / "repository.json").read_text() mocked_schedule = mocker.patch.object(JazzbandSpinach, "schedule") response = post(client, "repository", json.loads(contents)) assert response.data response_string = response.data.decode("utf-8") assert response_string.startswith("Started updating the project using hook id repo-added-") mocked_schedule.assert_called_once()
Fix more of the test.
Fix more of the test.
Python
mit
jazzband/website,jazzband/jazzband-site,jazzband/website,jazzband/website,jazzband/site,jazzband/jazzband-site,jazzband/website,jazzband/site
import json from jazzband.projects.tasks import update_project_by_hook from jazzband.tasks import JazzbandSpinach def post(client, hook, data, guid="abc"): headers = {"X-GitHub-Event": hook, "X-GitHub-Delivery": guid} return client.post( "/hooks", content_type="application/json", data=json.dumps(data), headers=headers, ) def test_ping(client): rv = post(client, "ping", {}) assert b"pong" in rv.data assert rv.status_code == 200 def test_repo_transferred_hook(client, datadir, mocker): contents = (datadir / "repository.json").read_text() mocked_schedule = mocker.patch.object(JazzbandSpinach, "schedule") response = post(client, "repository", json.loads(contents)) assert response.data response_string = response.data.decode("utf-8") assert response_string.startswith("Started updating the project using hook id repo-added-") - mocked_schedule.assert_called_once_with(update_project_by_hook, response_string) + mocked_schedule.assert_called_once()
Fix more of the test.
## Code Before: import json from jazzband.projects.tasks import update_project_by_hook from jazzband.tasks import JazzbandSpinach def post(client, hook, data, guid="abc"): headers = {"X-GitHub-Event": hook, "X-GitHub-Delivery": guid} return client.post( "/hooks", content_type="application/json", data=json.dumps(data), headers=headers, ) def test_ping(client): rv = post(client, "ping", {}) assert b"pong" in rv.data assert rv.status_code == 200 def test_repo_transferred_hook(client, datadir, mocker): contents = (datadir / "repository.json").read_text() mocked_schedule = mocker.patch.object(JazzbandSpinach, "schedule") response = post(client, "repository", json.loads(contents)) assert response.data response_string = response.data.decode("utf-8") assert response_string.startswith("Started updating the project using hook id repo-added-") mocked_schedule.assert_called_once_with(update_project_by_hook, response_string) ## Instruction: Fix more of the test. ## Code After: import json from jazzband.projects.tasks import update_project_by_hook from jazzband.tasks import JazzbandSpinach def post(client, hook, data, guid="abc"): headers = {"X-GitHub-Event": hook, "X-GitHub-Delivery": guid} return client.post( "/hooks", content_type="application/json", data=json.dumps(data), headers=headers, ) def test_ping(client): rv = post(client, "ping", {}) assert b"pong" in rv.data assert rv.status_code == 200 def test_repo_transferred_hook(client, datadir, mocker): contents = (datadir / "repository.json").read_text() mocked_schedule = mocker.patch.object(JazzbandSpinach, "schedule") response = post(client, "repository", json.loads(contents)) assert response.data response_string = response.data.decode("utf-8") assert response_string.startswith("Started updating the project using hook id repo-added-") mocked_schedule.assert_called_once()
import json from jazzband.projects.tasks import update_project_by_hook from jazzband.tasks import JazzbandSpinach def post(client, hook, data, guid="abc"): headers = {"X-GitHub-Event": hook, "X-GitHub-Delivery": guid} return client.post( "/hooks", content_type="application/json", data=json.dumps(data), headers=headers, ) def test_ping(client): rv = post(client, "ping", {}) assert b"pong" in rv.data assert rv.status_code == 200 def test_repo_transferred_hook(client, datadir, mocker): contents = (datadir / "repository.json").read_text() mocked_schedule = mocker.patch.object(JazzbandSpinach, "schedule") response = post(client, "repository", json.loads(contents)) assert response.data response_string = response.data.decode("utf-8") assert response_string.startswith("Started updating the project using hook id repo-added-") - mocked_schedule.assert_called_once_with(update_project_by_hook, response_string) + mocked_schedule.assert_called_once()
f042f6c9799d70edb41ae9495adf8bb78ed23e13
elections/ar_elections_2015/settings.py
elections/ar_elections_2015/settings.py
ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015)' MAPIT_BASE_URL = 'http://argentina.mapit.staging.mysociety.org/' SITE_OWNER = 'YoQuieroSaber' COPYRIGHT_HOLDER = 'YoQuieroSaber'
ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015|parlamentarios-mercosur-regional-paso-2015|parlamentarios-mercosur-unico-paso-2015)' MAPIT_BASE_URL = 'http://argentina.mapit.staging.mysociety.org/' SITE_OWNER = 'YoQuieroSaber' COPYRIGHT_HOLDER = 'YoQuieroSaber'
Add some missing election slugs to Argentina's ELECTION_RE
AR: Add some missing election slugs to Argentina's ELECTION_RE
Python
agpl-3.0
mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,datamade/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit
- ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015)' + ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015|parlamentarios-mercosur-regional-paso-2015|parlamentarios-mercosur-unico-paso-2015)' MAPIT_BASE_URL = 'http://argentina.mapit.staging.mysociety.org/' SITE_OWNER = 'YoQuieroSaber' COPYRIGHT_HOLDER = 'YoQuieroSaber'
Add some missing election slugs to Argentina's ELECTION_RE
## Code Before: ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015)' MAPIT_BASE_URL = 'http://argentina.mapit.staging.mysociety.org/' SITE_OWNER = 'YoQuieroSaber' COPYRIGHT_HOLDER = 'YoQuieroSaber' ## Instruction: Add some missing election slugs to Argentina's ELECTION_RE ## Code After: ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015|parlamentarios-mercosur-regional-paso-2015|parlamentarios-mercosur-unico-paso-2015)' MAPIT_BASE_URL = 'http://argentina.mapit.staging.mysociety.org/' SITE_OWNER = 'YoQuieroSaber' COPYRIGHT_HOLDER = 'YoQuieroSaber'
- ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015)' + ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015|parlamentarios-mercosur-regional-paso-2015|parlamentarios-mercosur-unico-paso-2015)' ? +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ MAPIT_BASE_URL = 'http://argentina.mapit.staging.mysociety.org/' SITE_OWNER = 'YoQuieroSaber' COPYRIGHT_HOLDER = 'YoQuieroSaber'
002be05d8bb07e610613b1ba6f24c904691c9f03
tests/conftest.py
tests/conftest.py
import os import pytest from tests.utils import VuforiaServerCredentials @pytest.fixture() def vuforia_server_credentials() -> VuforiaServerCredentials: """ Return VWS credentials from environment variables. """ credentials = VuforiaServerCredentials( database_name=os.environ['VUFORIA_TARGET_MANAGER_DATABASE_NAME'], access_key=os.environ['VUFORIA_SERVER_ACCESS_KEY'], secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'], ) # type: VuforiaServerCredentials return credentials
import os import pytest from tests.utils import VuforiaServerCredentials @pytest.fixture() def vuforia_server_credentials() -> VuforiaServerCredentials: """ Return VWS credentials from environment variables. """ credentials = VuforiaServerCredentials( database_name=os.environ['VUFORIA_TARGET_MANAGER_DATABASE_NAME'], access_key=os.environ['VUFORIA_SERVER_ACCESS_KEY'], secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'], ) # type: VuforiaServerCredentials return credentials @pytest.fixture() def vuforia_inactive_server_credentials() -> VuforiaServerCredentials: """ Return VWS credentials for an inactive project from environment variables. """ credentials = VuforiaServerCredentials( database_name=os.environ['VUFORIA_TARGET_MANAGER_DATABASE_NAME'], access_key=os.environ['VUFORIA_SERVER_ACCESS_KEY'], secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'], ) # type: VuforiaServerCredentials return credentials
Create credentials fixture for inactive project
Create credentials fixture for inactive project
Python
mit
adamtheturtle/vws-python,adamtheturtle/vws-python
import os import pytest from tests.utils import VuforiaServerCredentials @pytest.fixture() def vuforia_server_credentials() -> VuforiaServerCredentials: """ Return VWS credentials from environment variables. """ credentials = VuforiaServerCredentials( database_name=os.environ['VUFORIA_TARGET_MANAGER_DATABASE_NAME'], access_key=os.environ['VUFORIA_SERVER_ACCESS_KEY'], secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'], ) # type: VuforiaServerCredentials return credentials + + @pytest.fixture() + def vuforia_inactive_server_credentials() -> VuforiaServerCredentials: + """ + Return VWS credentials for an inactive project from environment variables. + """ + credentials = VuforiaServerCredentials( + database_name=os.environ['VUFORIA_TARGET_MANAGER_DATABASE_NAME'], + access_key=os.environ['VUFORIA_SERVER_ACCESS_KEY'], + secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'], + ) # type: VuforiaServerCredentials + return credentials +
Create credentials fixture for inactive project
## Code Before: import os import pytest from tests.utils import VuforiaServerCredentials @pytest.fixture() def vuforia_server_credentials() -> VuforiaServerCredentials: """ Return VWS credentials from environment variables. """ credentials = VuforiaServerCredentials( database_name=os.environ['VUFORIA_TARGET_MANAGER_DATABASE_NAME'], access_key=os.environ['VUFORIA_SERVER_ACCESS_KEY'], secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'], ) # type: VuforiaServerCredentials return credentials ## Instruction: Create credentials fixture for inactive project ## Code After: import os import pytest from tests.utils import VuforiaServerCredentials @pytest.fixture() def vuforia_server_credentials() -> VuforiaServerCredentials: """ Return VWS credentials from environment variables. """ credentials = VuforiaServerCredentials( database_name=os.environ['VUFORIA_TARGET_MANAGER_DATABASE_NAME'], access_key=os.environ['VUFORIA_SERVER_ACCESS_KEY'], secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'], ) # type: VuforiaServerCredentials return credentials @pytest.fixture() def vuforia_inactive_server_credentials() -> VuforiaServerCredentials: """ Return VWS credentials for an inactive project from environment variables. """ credentials = VuforiaServerCredentials( database_name=os.environ['VUFORIA_TARGET_MANAGER_DATABASE_NAME'], access_key=os.environ['VUFORIA_SERVER_ACCESS_KEY'], secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'], ) # type: VuforiaServerCredentials return credentials
import os import pytest from tests.utils import VuforiaServerCredentials @pytest.fixture() def vuforia_server_credentials() -> VuforiaServerCredentials: """ Return VWS credentials from environment variables. """ credentials = VuforiaServerCredentials( database_name=os.environ['VUFORIA_TARGET_MANAGER_DATABASE_NAME'], access_key=os.environ['VUFORIA_SERVER_ACCESS_KEY'], secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'], ) # type: VuforiaServerCredentials return credentials + + + @pytest.fixture() + def vuforia_inactive_server_credentials() -> VuforiaServerCredentials: + """ + Return VWS credentials for an inactive project from environment variables. + """ + credentials = VuforiaServerCredentials( + database_name=os.environ['VUFORIA_TARGET_MANAGER_DATABASE_NAME'], + access_key=os.environ['VUFORIA_SERVER_ACCESS_KEY'], + secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'], + ) # type: VuforiaServerCredentials + return credentials
c5c77ba407e195e3cc98bb75a961fe112736fca6
homebrew/command_line.py
homebrew/command_line.py
from .homebrew import HomeBrew def main(): HomeBrew().log_info()
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
+ 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
## Code Before: from .homebrew import HomeBrew def main(): HomeBrew().log_info() ## Instruction: Add argparse for info on hb command ## Code After: import argparse from .homebrew import HomeBrew def main(): argparse.ArgumentParser(description='Get homebrew info').parse_args() HomeBrew().log_info()
+ import argparse + from .homebrew import HomeBrew def main(): + argparse.ArgumentParser(description='Get homebrew info').parse_args() HomeBrew().log_info()
6e8e84fad2036b7df32376b617c97cb1a2144e94
shopping_app/utils/helpers.py
shopping_app/utils/helpers.py
import os import random import string from datetime import date, datetime def random_name(): return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)]) def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError("Type %s not serializable" % type(obj)) def secret_key_gen(): filepath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + '/secret.ini' generated_key = ''.join([random.SystemRandom().choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(50)]) with open(filepath, 'w') as secret_file: secret_file.write( '[SECRET_KEY]\nKEY= %(key)s' % dict(key=generated_key) ) print('Find your secret key at %(path)s' % dict(path=filepath))
import os import random import string from datetime import date, datetime def random_name(): return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)]) def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError("Type %s not serializable" % type(obj)) def secret_key_gen(): filepath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + '/secret.txt' generated_key = ''.join([random.SystemRandom().choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(50)]) with open(filepath, 'w') as secret_file: secret_file.write( '%(key)s' % dict(key=generated_key) ) print('Find your secret key at %(path)s' % dict(path=filepath))
Update secret file from to
Update secret file from to
Python
mit
gr1d99/shopping-list,gr1d99/shopping-list,gr1d99/shopping-list
import os import random import string from datetime import date, datetime def random_name(): return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)]) def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError("Type %s not serializable" % type(obj)) def secret_key_gen(): - filepath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + '/secret.ini' + filepath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + '/secret.txt' generated_key = ''.join([random.SystemRandom().choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(50)]) with open(filepath, 'w') as secret_file: secret_file.write( - '[SECRET_KEY]\nKEY= %(key)s' % dict(key=generated_key) + '%(key)s' % dict(key=generated_key) ) print('Find your secret key at %(path)s' % dict(path=filepath))
Update secret file from to
## Code Before: import os import random import string from datetime import date, datetime def random_name(): return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)]) def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError("Type %s not serializable" % type(obj)) def secret_key_gen(): filepath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + '/secret.ini' generated_key = ''.join([random.SystemRandom().choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(50)]) with open(filepath, 'w') as secret_file: secret_file.write( '[SECRET_KEY]\nKEY= %(key)s' % dict(key=generated_key) ) print('Find your secret key at %(path)s' % dict(path=filepath)) ## Instruction: Update secret file from to ## Code After: import os import random import string from datetime import date, datetime def random_name(): return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)]) def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError("Type %s not serializable" % type(obj)) def secret_key_gen(): filepath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + '/secret.txt' generated_key = ''.join([random.SystemRandom().choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(50)]) with open(filepath, 'w') as secret_file: secret_file.write( '%(key)s' % dict(key=generated_key) ) print('Find your secret key at %(path)s' % dict(path=filepath))
import os import random import string from datetime import date, datetime def random_name(): return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)]) def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError("Type %s not serializable" % type(obj)) def secret_key_gen(): - filepath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + '/secret.ini' ? ^^^ + filepath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + '/secret.txt' ? ^^^ generated_key = ''.join([random.SystemRandom().choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(50)]) with open(filepath, 'w') as secret_file: secret_file.write( - '[SECRET_KEY]\nKEY= %(key)s' % dict(key=generated_key) ? ------------------- + '%(key)s' % dict(key=generated_key) ) print('Find your secret key at %(path)s' % dict(path=filepath))
fd4bc228c978019a7251fefe2c92899a16b8f95d
demosys/scene/shaders.py
demosys/scene/shaders.py
from pyrr import Matrix33 class MeshShader: def __init__(self, shader): self.shader = shader def draw(self, mesh, proj_mat, view_mat): """Minimal draw function. Should be overridden""" mesh.vao.bind(self.shader) self.shader.uniform_mat4("m_proj", proj_mat) self.shader.uniform_mat4("m_mv", view_mat) mesh.vao.draw() def apply(self, mesh): """ Determine if this MeshShader should be applied to the mesh Can return self or some MeshShader instance to support dynamic MeshShader creation """ raise NotImplementedError("apply is not implemented. Please override the MeshShader method") def create_normal_matrix(self, modelview): """ Convert to mat3 and return inverse transpose. These are normally needed when dealing with normals in shaders. :param modelview: The modelview matrix :return: Normal matrix """ normal_m = Matrix33.from_matrix44(modelview) normal_m = normal_m.inverse normal_m = normal_m.transpose() return normal_m
from pyrr import Matrix33 class MeshShader: def __init__(self, shader, **kwargs): self.shader = shader def draw(self, mesh, proj_mat, view_mat): """Minimal draw function. Should be overridden""" mesh.vao.bind(self.shader) self.shader.uniform_mat4("m_proj", proj_mat) self.shader.uniform_mat4("m_mv", view_mat) mesh.vao.draw() def apply(self, mesh): """ Determine if this MeshShader should be applied to the mesh Can return self or some MeshShader instance to support dynamic MeshShader creation """ raise NotImplementedError("apply is not implemented. Please override the MeshShader method") def create_normal_matrix(self, modelview): """ Convert to mat3 and return inverse transpose. These are normally needed when dealing with normals in shaders. :param modelview: The modelview matrix :return: Normal matrix """ normal_m = Matrix33.from_matrix44(modelview) normal_m = normal_m.inverse normal_m = normal_m.transpose() return normal_m
Allow sending kwars to mesh shader
Allow sending kwars to mesh shader
Python
isc
Contraz/demosys-py
from pyrr import Matrix33 class MeshShader: - def __init__(self, shader): + def __init__(self, shader, **kwargs): self.shader = shader def draw(self, mesh, proj_mat, view_mat): """Minimal draw function. Should be overridden""" mesh.vao.bind(self.shader) self.shader.uniform_mat4("m_proj", proj_mat) self.shader.uniform_mat4("m_mv", view_mat) mesh.vao.draw() def apply(self, mesh): """ Determine if this MeshShader should be applied to the mesh Can return self or some MeshShader instance to support dynamic MeshShader creation """ raise NotImplementedError("apply is not implemented. Please override the MeshShader method") def create_normal_matrix(self, modelview): """ Convert to mat3 and return inverse transpose. These are normally needed when dealing with normals in shaders. :param modelview: The modelview matrix :return: Normal matrix """ normal_m = Matrix33.from_matrix44(modelview) normal_m = normal_m.inverse normal_m = normal_m.transpose() return normal_m
Allow sending kwars to mesh shader
## Code Before: from pyrr import Matrix33 class MeshShader: def __init__(self, shader): self.shader = shader def draw(self, mesh, proj_mat, view_mat): """Minimal draw function. Should be overridden""" mesh.vao.bind(self.shader) self.shader.uniform_mat4("m_proj", proj_mat) self.shader.uniform_mat4("m_mv", view_mat) mesh.vao.draw() def apply(self, mesh): """ Determine if this MeshShader should be applied to the mesh Can return self or some MeshShader instance to support dynamic MeshShader creation """ raise NotImplementedError("apply is not implemented. Please override the MeshShader method") def create_normal_matrix(self, modelview): """ Convert to mat3 and return inverse transpose. These are normally needed when dealing with normals in shaders. :param modelview: The modelview matrix :return: Normal matrix """ normal_m = Matrix33.from_matrix44(modelview) normal_m = normal_m.inverse normal_m = normal_m.transpose() return normal_m ## Instruction: Allow sending kwars to mesh shader ## Code After: from pyrr import Matrix33 class MeshShader: def __init__(self, shader, **kwargs): self.shader = shader def draw(self, mesh, proj_mat, view_mat): """Minimal draw function. Should be overridden""" mesh.vao.bind(self.shader) self.shader.uniform_mat4("m_proj", proj_mat) self.shader.uniform_mat4("m_mv", view_mat) mesh.vao.draw() def apply(self, mesh): """ Determine if this MeshShader should be applied to the mesh Can return self or some MeshShader instance to support dynamic MeshShader creation """ raise NotImplementedError("apply is not implemented. Please override the MeshShader method") def create_normal_matrix(self, modelview): """ Convert to mat3 and return inverse transpose. These are normally needed when dealing with normals in shaders. :param modelview: The modelview matrix :return: Normal matrix """ normal_m = Matrix33.from_matrix44(modelview) normal_m = normal_m.inverse normal_m = normal_m.transpose() return normal_m
from pyrr import Matrix33 class MeshShader: - def __init__(self, shader): + def __init__(self, shader, **kwargs): ? ++++++++++ self.shader = shader def draw(self, mesh, proj_mat, view_mat): """Minimal draw function. Should be overridden""" mesh.vao.bind(self.shader) self.shader.uniform_mat4("m_proj", proj_mat) self.shader.uniform_mat4("m_mv", view_mat) mesh.vao.draw() def apply(self, mesh): """ Determine if this MeshShader should be applied to the mesh Can return self or some MeshShader instance to support dynamic MeshShader creation """ raise NotImplementedError("apply is not implemented. Please override the MeshShader method") def create_normal_matrix(self, modelview): """ Convert to mat3 and return inverse transpose. These are normally needed when dealing with normals in shaders. :param modelview: The modelview matrix :return: Normal matrix """ normal_m = Matrix33.from_matrix44(modelview) normal_m = normal_m.inverse normal_m = normal_m.transpose() return normal_m
1782b15b244597d56bff18c465237c7e1f3ab482
wikked/commands/users.py
wikked/commands/users.py
import logging import getpass from wikked.bcryptfallback import generate_password_hash from wikked.commands.base import WikkedCommand, register_command logger = logging.getLogger(__name__) @register_command class UsersCommand(WikkedCommand): def __init__(self): super(UsersCommand, self).__init__() self.name = 'users' self.description = "Lists users of this wiki." def setupParser(self, parser): pass def run(self, ctx): logger.info("Users:") for user in ctx.wiki.auth.getUsers(): logger.info(" - " + user.username) @register_command class NewUserCommand(WikkedCommand): def __init__(self): super(NewUserCommand, self).__init__() self.name = 'newuser' self.description = ( "Generates the entry for a new user so you can " "copy/paste it in your `.wikirc`.") def setupParser(self, parser): parser.add_argument('username', nargs=1) parser.add_argument('password', nargs='?') def run(self, ctx): username = ctx.args.username password = ctx.args.password or getpass.getpass('Password: ') password = generate_password_hash(password) logger.info("%s = %s" % (username[0], password))
import logging import getpass from wikked.bcryptfallback import generate_password_hash from wikked.commands.base import WikkedCommand, register_command logger = logging.getLogger(__name__) @register_command class UsersCommand(WikkedCommand): def __init__(self): super(UsersCommand, self).__init__() self.name = 'users' self.description = "Lists users of this wiki." def setupParser(self, parser): pass def run(self, ctx): logger.info("Users:") for user in ctx.wiki.auth.getUsers(): logger.info(" - " + user.username) @register_command class NewUserCommand(WikkedCommand): def __init__(self): super(NewUserCommand, self).__init__() self.name = 'newuser' self.description = ( "Generates the entry for a new user so you can " "copy/paste it in your `.wikirc`.") def setupParser(self, parser): parser.add_argument('username', nargs=1) parser.add_argument('password', nargs='?') def run(self, ctx): username = ctx.args.username password = ctx.args.password or getpass.getpass('Password: ') password = generate_password_hash(password) logger.info("%s = %s" % (username[0], password)) logger.info("") logger.info("(copy this into your .wikirc file)")
Add some explanation as to what to do with the output.
newuser: Add some explanation as to what to do with the output.
Python
apache-2.0
ludovicchabant/Wikked,ludovicchabant/Wikked,ludovicchabant/Wikked
import logging import getpass from wikked.bcryptfallback import generate_password_hash from wikked.commands.base import WikkedCommand, register_command logger = logging.getLogger(__name__) @register_command class UsersCommand(WikkedCommand): def __init__(self): super(UsersCommand, self).__init__() self.name = 'users' self.description = "Lists users of this wiki." def setupParser(self, parser): pass def run(self, ctx): logger.info("Users:") for user in ctx.wiki.auth.getUsers(): logger.info(" - " + user.username) @register_command class NewUserCommand(WikkedCommand): def __init__(self): super(NewUserCommand, self).__init__() self.name = 'newuser' self.description = ( "Generates the entry for a new user so you can " "copy/paste it in your `.wikirc`.") def setupParser(self, parser): parser.add_argument('username', nargs=1) parser.add_argument('password', nargs='?') def run(self, ctx): username = ctx.args.username password = ctx.args.password or getpass.getpass('Password: ') password = generate_password_hash(password) logger.info("%s = %s" % (username[0], password)) + logger.info("") + logger.info("(copy this into your .wikirc file)")
Add some explanation as to what to do with the output.
## Code Before: import logging import getpass from wikked.bcryptfallback import generate_password_hash from wikked.commands.base import WikkedCommand, register_command logger = logging.getLogger(__name__) @register_command class UsersCommand(WikkedCommand): def __init__(self): super(UsersCommand, self).__init__() self.name = 'users' self.description = "Lists users of this wiki." def setupParser(self, parser): pass def run(self, ctx): logger.info("Users:") for user in ctx.wiki.auth.getUsers(): logger.info(" - " + user.username) @register_command class NewUserCommand(WikkedCommand): def __init__(self): super(NewUserCommand, self).__init__() self.name = 'newuser' self.description = ( "Generates the entry for a new user so you can " "copy/paste it in your `.wikirc`.") def setupParser(self, parser): parser.add_argument('username', nargs=1) parser.add_argument('password', nargs='?') def run(self, ctx): username = ctx.args.username password = ctx.args.password or getpass.getpass('Password: ') password = generate_password_hash(password) logger.info("%s = %s" % (username[0], password)) ## Instruction: Add some explanation as to what to do with the output. ## Code After: import logging import getpass from wikked.bcryptfallback import generate_password_hash from wikked.commands.base import WikkedCommand, register_command logger = logging.getLogger(__name__) @register_command class UsersCommand(WikkedCommand): def __init__(self): super(UsersCommand, self).__init__() self.name = 'users' self.description = "Lists users of this wiki." def setupParser(self, parser): pass def run(self, ctx): logger.info("Users:") for user in ctx.wiki.auth.getUsers(): logger.info(" - " + user.username) @register_command class NewUserCommand(WikkedCommand): def __init__(self): super(NewUserCommand, self).__init__() self.name = 'newuser' self.description = ( "Generates the entry for a new user so you can " "copy/paste it in your `.wikirc`.") def setupParser(self, parser): parser.add_argument('username', nargs=1) parser.add_argument('password', nargs='?') def run(self, ctx): username = ctx.args.username password = ctx.args.password or getpass.getpass('Password: ') password = generate_password_hash(password) logger.info("%s = %s" % (username[0], password)) logger.info("") logger.info("(copy this into your .wikirc file)")
import logging import getpass from wikked.bcryptfallback import generate_password_hash from wikked.commands.base import WikkedCommand, register_command logger = logging.getLogger(__name__) @register_command class UsersCommand(WikkedCommand): def __init__(self): super(UsersCommand, self).__init__() self.name = 'users' self.description = "Lists users of this wiki." def setupParser(self, parser): pass def run(self, ctx): logger.info("Users:") for user in ctx.wiki.auth.getUsers(): logger.info(" - " + user.username) @register_command class NewUserCommand(WikkedCommand): def __init__(self): super(NewUserCommand, self).__init__() self.name = 'newuser' self.description = ( "Generates the entry for a new user so you can " "copy/paste it in your `.wikirc`.") def setupParser(self, parser): parser.add_argument('username', nargs=1) parser.add_argument('password', nargs='?') def run(self, ctx): username = ctx.args.username password = ctx.args.password or getpass.getpass('Password: ') password = generate_password_hash(password) logger.info("%s = %s" % (username[0], password)) + logger.info("") + logger.info("(copy this into your .wikirc file)")
6a5c9ccf0bd2582cf42577712309b8fd6e912966
blo/__init__.py
blo/__init__.py
import configparser from blo.BloArticle import BloArticle from blo.DBControl import DBControl class Blo: def __init__(self, config_file_path): config = configparser.ConfigParser() config.read(config_file_path) self._db_file_path = config['DB']['DB_PATH'] self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'] self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'] # create tables self._db_control = DBControl(self._db_file_path) self._db_control.create_tables() self._db_control.close_connect() def insert_article(self, file_path): self._db_control = DBControl(self._db_file_path) article = BloArticle(self._template_dir) article.load_from_file(file_path) self._db_control.insert_article(article, self._default_template_file) self._db_control.close_connect()
import configparser from blo.BloArticle import BloArticle from blo.DBControl import DBControl class Blo: def __init__(self, config_file_path): config = configparser.ConfigParser() config.read(config_file_path) self._db_file_path = config['DB']['DB_PATH'].replace('"', '') self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '') self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '') # create tables self._db_control = DBControl(self._db_file_path) self._db_control.create_tables() self._db_control.close_connect() def insert_article(self, file_path): self._db_control = DBControl(self._db_file_path) article = BloArticle(self._template_dir) article.load_from_file(file_path) self._db_control.insert_article(article, self._default_template_file) self._db_control.close_connect()
Add replace double quotation mark from configuration file parameters.
Add replace double quotation mark from configuration file parameters.
Python
mit
10nin/blo,10nin/blo
import configparser from blo.BloArticle import BloArticle from blo.DBControl import DBControl class Blo: def __init__(self, config_file_path): config = configparser.ConfigParser() config.read(config_file_path) - self._db_file_path = config['DB']['DB_PATH'] + self._db_file_path = config['DB']['DB_PATH'].replace('"', '') - self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'] + self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '') - self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'] + self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '') # create tables self._db_control = DBControl(self._db_file_path) self._db_control.create_tables() self._db_control.close_connect() def insert_article(self, file_path): self._db_control = DBControl(self._db_file_path) article = BloArticle(self._template_dir) article.load_from_file(file_path) self._db_control.insert_article(article, self._default_template_file) self._db_control.close_connect()
Add replace double quotation mark from configuration file parameters.
## Code Before: import configparser from blo.BloArticle import BloArticle from blo.DBControl import DBControl class Blo: def __init__(self, config_file_path): config = configparser.ConfigParser() config.read(config_file_path) self._db_file_path = config['DB']['DB_PATH'] self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'] self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'] # create tables self._db_control = DBControl(self._db_file_path) self._db_control.create_tables() self._db_control.close_connect() def insert_article(self, file_path): self._db_control = DBControl(self._db_file_path) article = BloArticle(self._template_dir) article.load_from_file(file_path) self._db_control.insert_article(article, self._default_template_file) self._db_control.close_connect() ## Instruction: Add replace double quotation mark from configuration file parameters. ## Code After: import configparser from blo.BloArticle import BloArticle from blo.DBControl import DBControl class Blo: def __init__(self, config_file_path): config = configparser.ConfigParser() config.read(config_file_path) self._db_file_path = config['DB']['DB_PATH'].replace('"', '') self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '') self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '') # create tables self._db_control = DBControl(self._db_file_path) self._db_control.create_tables() self._db_control.close_connect() def insert_article(self, file_path): self._db_control = DBControl(self._db_file_path) article = BloArticle(self._template_dir) article.load_from_file(file_path) self._db_control.insert_article(article, self._default_template_file) self._db_control.close_connect()
import configparser from blo.BloArticle import BloArticle from blo.DBControl import DBControl class Blo: def __init__(self, config_file_path): config = configparser.ConfigParser() config.read(config_file_path) - self._db_file_path = config['DB']['DB_PATH'] + self._db_file_path = config['DB']['DB_PATH'].replace('"', '') ? +++++++++++++++++ - self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'] + self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '') ? +++++++++++++++++ - self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'] + self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '') ? +++++++++++++++++ # create tables self._db_control = DBControl(self._db_file_path) self._db_control.create_tables() self._db_control.close_connect() def insert_article(self, file_path): self._db_control = DBControl(self._db_file_path) article = BloArticle(self._template_dir) article.load_from_file(file_path) self._db_control.insert_article(article, self._default_template_file) self._db_control.close_connect()
9bf1f19eefc48dbced4b6ea1cc5258518d14bceb
app/utils/http.py
app/utils/http.py
import aiofiles import aiohttp import aiohttp.client_exceptions from aiopath import AsyncPath from sanic.log import logger EXCEPTIONS = ( aiohttp.client_exceptions.ClientConnectionError, aiohttp.client_exceptions.InvalidURL, aiohttp.client_exceptions.TooManyRedirects, AssertionError, UnicodeError, ) async def download(url: str, path: AsyncPath) -> bool: async with aiohttp.ClientSession() as session: try: async with session.get(url) as response: if response.status == 200: f = await aiofiles.open(path, mode="wb") # type: ignore await f.write(await response.read()) await f.close() return True logger.error(f"{response.status} response from {url}") except EXCEPTIONS as e: message = str(e).strip("() ") logger.error(f"Invalid response from {url}: {message}") return False
import asyncio import aiofiles import aiohttp import aiohttp.client_exceptions from aiopath import AsyncPath from sanic.log import logger EXCEPTIONS = ( aiohttp.client_exceptions.ClientConnectionError, aiohttp.client_exceptions.InvalidURL, aiohttp.client_exceptions.TooManyRedirects, AssertionError, asyncio.TimeoutError, UnicodeError, ) async def download(url: str, path: AsyncPath) -> bool: async with aiohttp.ClientSession() as session: try: async with session.get(url, timeout=10) as response: if response.status == 200: f = await aiofiles.open(path, mode="wb") # type: ignore await f.write(await response.read()) await f.close() return True logger.error(f"{response.status} response from {url}") except EXCEPTIONS as e: message = str(e).strip("() ") or e.__class__.__name__ logger.error(f"Invalid response from {url}: {message}") return False
Add timeout to downloading custom background images
Add timeout to downloading custom background images
Python
mit
jacebrowning/memegen,jacebrowning/memegen
+ import asyncio + import aiofiles import aiohttp import aiohttp.client_exceptions from aiopath import AsyncPath from sanic.log import logger EXCEPTIONS = ( aiohttp.client_exceptions.ClientConnectionError, aiohttp.client_exceptions.InvalidURL, aiohttp.client_exceptions.TooManyRedirects, AssertionError, + asyncio.TimeoutError, UnicodeError, ) async def download(url: str, path: AsyncPath) -> bool: async with aiohttp.ClientSession() as session: try: - async with session.get(url) as response: + async with session.get(url, timeout=10) as response: if response.status == 200: f = await aiofiles.open(path, mode="wb") # type: ignore await f.write(await response.read()) await f.close() return True logger.error(f"{response.status} response from {url}") except EXCEPTIONS as e: - message = str(e).strip("() ") + message = str(e).strip("() ") or e.__class__.__name__ logger.error(f"Invalid response from {url}: {message}") return False
Add timeout to downloading custom background images
## Code Before: import aiofiles import aiohttp import aiohttp.client_exceptions from aiopath import AsyncPath from sanic.log import logger EXCEPTIONS = ( aiohttp.client_exceptions.ClientConnectionError, aiohttp.client_exceptions.InvalidURL, aiohttp.client_exceptions.TooManyRedirects, AssertionError, UnicodeError, ) async def download(url: str, path: AsyncPath) -> bool: async with aiohttp.ClientSession() as session: try: async with session.get(url) as response: if response.status == 200: f = await aiofiles.open(path, mode="wb") # type: ignore await f.write(await response.read()) await f.close() return True logger.error(f"{response.status} response from {url}") except EXCEPTIONS as e: message = str(e).strip("() ") logger.error(f"Invalid response from {url}: {message}") return False ## Instruction: Add timeout to downloading custom background images ## Code After: import asyncio import aiofiles import aiohttp import aiohttp.client_exceptions from aiopath import AsyncPath from sanic.log import logger EXCEPTIONS = ( aiohttp.client_exceptions.ClientConnectionError, aiohttp.client_exceptions.InvalidURL, aiohttp.client_exceptions.TooManyRedirects, AssertionError, asyncio.TimeoutError, UnicodeError, ) async def download(url: str, path: AsyncPath) -> bool: async with aiohttp.ClientSession() as session: try: async with session.get(url, timeout=10) as response: if response.status == 200: f = await aiofiles.open(path, mode="wb") # type: ignore await f.write(await response.read()) await f.close() return True logger.error(f"{response.status} response from {url}") except EXCEPTIONS as e: message = str(e).strip("() ") or e.__class__.__name__ logger.error(f"Invalid response from {url}: {message}") return False
+ import asyncio + import aiofiles import aiohttp import aiohttp.client_exceptions from aiopath import AsyncPath from sanic.log import logger EXCEPTIONS = ( aiohttp.client_exceptions.ClientConnectionError, aiohttp.client_exceptions.InvalidURL, aiohttp.client_exceptions.TooManyRedirects, AssertionError, + asyncio.TimeoutError, UnicodeError, ) async def download(url: str, path: AsyncPath) -> bool: async with aiohttp.ClientSession() as session: try: - async with session.get(url) as response: + async with session.get(url, timeout=10) as response: ? ++++++++++++ if response.status == 200: f = await aiofiles.open(path, mode="wb") # type: ignore await f.write(await response.read()) await f.close() return True logger.error(f"{response.status} response from {url}") except EXCEPTIONS as e: - message = str(e).strip("() ") + message = str(e).strip("() ") or e.__class__.__name__ ? ++++++++++++++++++++++++ logger.error(f"Invalid response from {url}: {message}") return False
6464028097b13b5d03969c20bae56f9f70acbbd1
saleor/cart/middleware.py
saleor/cart/middleware.py
from __future__ import unicode_literals from . import SessionCart, CART_SESSION_KEY class CartMiddleware(object): ''' Saves the cart instance into the django session. ''' def process_request(self, request): try: cart_data = request.session[CART_SESSION_KEY] cart = SessionCart.from_storage(cart_data) except KeyError: cart = SessionCart() setattr(request, 'cart', cart) def process_response(self, request, response): if hasattr(request, 'cart'): request.session[CART_SESSION_KEY] = request.cart.for_storage() return response
from __future__ import unicode_literals from . import SessionCart, CART_SESSION_KEY class CartMiddleware(object): ''' Saves the cart instance into the django session. ''' def process_request(self, request): try: cart_data = request.session[CART_SESSION_KEY] cart = SessionCart.from_storage(cart_data) except KeyError: cart = SessionCart() setattr(request, 'cart', cart) def process_response(self, request, response): if hasattr(request, 'cart') and request.cart.modified: request.session[CART_SESSION_KEY] = request.cart.for_storage() return response
Store cart in session only when it was modified
Store cart in session only when it was modified
Python
bsd-3-clause
HyperManTT/ECommerceSaleor,taedori81/saleor,car3oon/saleor,UITools/saleor,rodrigozn/CW-Shop,mociepka/saleor,spartonia/saleor,UITools/saleor,arth-co/saleor,UITools/saleor,paweltin/saleor,hongquan/saleor,Drekscott/Motlaesaleor,UITools/saleor,avorio/saleor,josesanch/saleor,tfroehlich82/saleor,maferelo/saleor,spartonia/saleor,dashmug/saleor,taedori81/saleor,HyperManTT/ECommerceSaleor,Drekscott/Motlaesaleor,UITools/saleor,jreigel/saleor,josesanch/saleor,dashmug/saleor,maferelo/saleor,paweltin/saleor,arth-co/saleor,Drekscott/Motlaesaleor,KenMutemi/saleor,car3oon/saleor,mociepka/saleor,taedori81/saleor,dashmug/saleor,laosunhust/saleor,taedori81/saleor,jreigel/saleor,josesanch/saleor,itbabu/saleor,hongquan/saleor,rchav/vinerack,laosunhust/saleor,paweltin/saleor,HyperManTT/ECommerceSaleor,KenMutemi/saleor,avorio/saleor,rchav/vinerack,arth-co/saleor,hongquan/saleor,arth-co/saleor,mociepka/saleor,jreigel/saleor,laosunhust/saleor,spartonia/saleor,Drekscott/Motlaesaleor,itbabu/saleor,tfroehlich82/saleor,rodrigozn/CW-Shop,KenMutemi/saleor,paweltin/saleor,maferelo/saleor,rchav/vinerack,avorio/saleor,spartonia/saleor,tfroehlich82/saleor,itbabu/saleor,rodrigozn/CW-Shop,laosunhust/saleor,avorio/saleor,car3oon/saleor
from __future__ import unicode_literals from . import SessionCart, CART_SESSION_KEY class CartMiddleware(object): ''' Saves the cart instance into the django session. ''' def process_request(self, request): try: cart_data = request.session[CART_SESSION_KEY] cart = SessionCart.from_storage(cart_data) except KeyError: cart = SessionCart() setattr(request, 'cart', cart) def process_response(self, request, response): - if hasattr(request, 'cart'): + if hasattr(request, 'cart') and request.cart.modified: request.session[CART_SESSION_KEY] = request.cart.for_storage() return response
Store cart in session only when it was modified
## Code Before: from __future__ import unicode_literals from . import SessionCart, CART_SESSION_KEY class CartMiddleware(object): ''' Saves the cart instance into the django session. ''' def process_request(self, request): try: cart_data = request.session[CART_SESSION_KEY] cart = SessionCart.from_storage(cart_data) except KeyError: cart = SessionCart() setattr(request, 'cart', cart) def process_response(self, request, response): if hasattr(request, 'cart'): request.session[CART_SESSION_KEY] = request.cart.for_storage() return response ## Instruction: Store cart in session only when it was modified ## Code After: from __future__ import unicode_literals from . import SessionCart, CART_SESSION_KEY class CartMiddleware(object): ''' Saves the cart instance into the django session. ''' def process_request(self, request): try: cart_data = request.session[CART_SESSION_KEY] cart = SessionCart.from_storage(cart_data) except KeyError: cart = SessionCart() setattr(request, 'cart', cart) def process_response(self, request, response): if hasattr(request, 'cart') and request.cart.modified: request.session[CART_SESSION_KEY] = request.cart.for_storage() return response
from __future__ import unicode_literals from . import SessionCart, CART_SESSION_KEY class CartMiddleware(object): ''' Saves the cart instance into the django session. ''' def process_request(self, request): try: cart_data = request.session[CART_SESSION_KEY] cart = SessionCart.from_storage(cart_data) except KeyError: cart = SessionCart() setattr(request, 'cart', cart) def process_response(self, request, response): - if hasattr(request, 'cart'): + if hasattr(request, 'cart') and request.cart.modified: request.session[CART_SESSION_KEY] = request.cart.for_storage() return response
3760005cec3174b14d3f0ee20327e1b8de9ce800
ffflash/lib/container.py
ffflash/lib/container.py
from os import path from ffflash import RELEASE, log, now, timeout from ffflash.lib.clock import epoch_repr from ffflash.lib.data import merge_dicts from ffflash.lib.files import read_json_file, write_json_file class Container: def __init__(self, spec, filename): self._spec = spec self._location = path.abspath(filename) self.data = read_json_file(self._location, fallback={}) self._info() def _info(self, info={}): self.data['_info'] = self.data.get('_info', {}) self.data['_info']['generator'] = RELEASE self.data['_info']['access'] = self.data['_info'].get('access', {}) if not self.data['_info']['access'].get('first', False): self.data['_info']['access']['first'] = now self.data['_info']['access']['last'] = now self.data['_info']['access']['overall'] = epoch_repr( abs(now - self.data['_info']['access']['first']), ms=True ) self.data['_info']['access']['scrub'] = timeout if info: self.data['_info'] = merge_dicts(self.data['_info'], info) def save(self, info={}): self._info(info) if write_json_file(self._location, self.data): log.info('{} saved {}'.format(self._spec, self._location))
from os import path from ffflash import RELEASE, log, now, timeout from ffflash.lib.clock import epoch_repr from ffflash.lib.data import Element from ffflash.lib.files import read_json_file, write_json_file class Container: def __init__(self, spec, filename): self._spec = spec self._location = path.abspath(filename) content = read_json_file(self._location, fallback={}) self.info = Element(content.get('_info', {})) self.data = Element(content.get(self._spec, {})) def _info(self): self.info.generator = RELEASE if not self.info.access.first: self.info.access.first = now self.info.access.last = now self.info.access.overall = epoch_repr( abs(now - self.info.access.first), ms=True ) self.info.access.scrub = timeout def save(self): self._info() content = { '_info': self.info, self._spec: self.data } if write_json_file(self._location, content): log.info('{} saved {}'.format(self._spec, self._location))
Rewrite Container to dump/load two Elements (data,_info) into json file
Rewrite Container to dump/load two Elements (data,_info) into json file
Python
bsd-3-clause
spookey/ffflash,spookey/ffflash
from os import path from ffflash import RELEASE, log, now, timeout from ffflash.lib.clock import epoch_repr - from ffflash.lib.data import merge_dicts + from ffflash.lib.data import Element from ffflash.lib.files import read_json_file, write_json_file class Container: def __init__(self, spec, filename): self._spec = spec self._location = path.abspath(filename) - self.data = read_json_file(self._location, fallback={}) + content = read_json_file(self._location, fallback={}) + + self.info = Element(content.get('_info', {})) + self.data = Element(content.get(self._spec, {})) + + def _info(self): + self.info.generator = RELEASE + + if not self.info.access.first: + self.info.access.first = now + self.info.access.last = now + self.info.access.overall = epoch_repr( + abs(now - self.info.access.first), ms=True + ) + self.info.access.scrub = timeout + + def save(self): self._info() + content = { + '_info': self.info, + self._spec: self.data - - def _info(self, info={}): - self.data['_info'] = self.data.get('_info', {}) - self.data['_info']['generator'] = RELEASE - - self.data['_info']['access'] = self.data['_info'].get('access', {}) - if not self.data['_info']['access'].get('first', False): - self.data['_info']['access']['first'] = now - self.data['_info']['access']['last'] = now - self.data['_info']['access']['overall'] = epoch_repr( - abs(now - self.data['_info']['access']['first']), - ms=True - ) + } - self.data['_info']['access']['scrub'] = timeout - - if info: - self.data['_info'] = merge_dicts(self.data['_info'], info) - - def save(self, info={}): - self._info(info) - if write_json_file(self._location, self.data): + if write_json_file(self._location, content): log.info('{} saved {}'.format(self._spec, self._location))
Rewrite Container to dump/load two Elements (data,_info) into json file
## Code Before: from os import path from ffflash import RELEASE, log, now, timeout from ffflash.lib.clock import epoch_repr from ffflash.lib.data import merge_dicts from ffflash.lib.files import read_json_file, write_json_file class Container: def __init__(self, spec, filename): self._spec = spec self._location = path.abspath(filename) self.data = read_json_file(self._location, fallback={}) self._info() def _info(self, info={}): self.data['_info'] = self.data.get('_info', {}) self.data['_info']['generator'] = RELEASE self.data['_info']['access'] = self.data['_info'].get('access', {}) if not self.data['_info']['access'].get('first', False): self.data['_info']['access']['first'] = now self.data['_info']['access']['last'] = now self.data['_info']['access']['overall'] = epoch_repr( abs(now - self.data['_info']['access']['first']), ms=True ) self.data['_info']['access']['scrub'] = timeout if info: self.data['_info'] = merge_dicts(self.data['_info'], info) def save(self, info={}): self._info(info) if write_json_file(self._location, self.data): log.info('{} saved {}'.format(self._spec, self._location)) ## Instruction: Rewrite Container to dump/load two Elements (data,_info) into json file ## Code After: from os import path from ffflash import RELEASE, log, now, timeout from ffflash.lib.clock import epoch_repr from ffflash.lib.data import Element from ffflash.lib.files import read_json_file, write_json_file class Container: def __init__(self, spec, filename): self._spec = spec self._location = path.abspath(filename) content = read_json_file(self._location, fallback={}) self.info = Element(content.get('_info', {})) self.data = Element(content.get(self._spec, {})) def _info(self): self.info.generator = RELEASE if not self.info.access.first: self.info.access.first = now self.info.access.last = now self.info.access.overall = epoch_repr( abs(now - self.info.access.first), ms=True ) self.info.access.scrub = timeout def save(self): self._info() content = { '_info': self.info, self._spec: self.data } if write_json_file(self._location, content): log.info('{} saved {}'.format(self._spec, self._location))
from os import path from ffflash import RELEASE, log, now, timeout from ffflash.lib.clock import epoch_repr - from ffflash.lib.data import merge_dicts ? ^^^^^^^ - + from ffflash.lib.data import Element ? +++ ^ from ffflash.lib.files import read_json_file, write_json_file class Container: def __init__(self, spec, filename): self._spec = spec self._location = path.abspath(filename) - self.data = read_json_file(self._location, fallback={}) + content = read_json_file(self._location, fallback={}) + + self.info = Element(content.get('_info', {})) + self.data = Element(content.get(self._spec, {})) + + def _info(self): + self.info.generator = RELEASE + + if not self.info.access.first: + self.info.access.first = now + self.info.access.last = now + self.info.access.overall = epoch_repr( + abs(now - self.info.access.first), ms=True + ) + self.info.access.scrub = timeout + + def save(self): self._info() + content = { + '_info': self.info, + self._spec: self.data - - def _info(self, info={}): - self.data['_info'] = self.data.get('_info', {}) - self.data['_info']['generator'] = RELEASE - - self.data['_info']['access'] = self.data['_info'].get('access', {}) - if not self.data['_info']['access'].get('first', False): - self.data['_info']['access']['first'] = now - self.data['_info']['access']['last'] = now - self.data['_info']['access']['overall'] = epoch_repr( - abs(now - self.data['_info']['access']['first']), - ms=True - ) ? ^ + } ? ^ - self.data['_info']['access']['scrub'] = timeout - - if info: - self.data['_info'] = merge_dicts(self.data['_info'], info) - - def save(self, info={}): - self._info(info) - if write_json_file(self._location, self.data): ? ^ ^^^^^ - + if write_json_file(self._location, content): ? ^^^^ ^ log.info('{} saved {}'.format(self._spec, self._location))
fba405a083b29b08dc3994821ae4ca2feb0e6c49
py3status/modules/taskwarrior.py
py3status/modules/taskwarrior.py
# import your useful libs here from time import time from subprocess import check_output import json import shlex class Py3status: """ """ # available configuration parameters cache_timeout = 5 def taskWarrior(self, i3s_output_list, i3s_config): command = 'task start.before:tomorrow status:pending export' taskwarrior_output = check_output(shlex.split(command)) tasks_json = json.loads('[' + taskwarrior_output.decode('utf-8') + ']') def describeTask(taskObj): return str(taskObj['id']) + ' ' + taskObj['description'] result = ', '.join(map(describeTask, tasks_json)) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response if __name__ == "__main__": """ Test this module by calling it directly. """ from time import sleep x = Py3status() config = { 'color_bad': '#FF0000', 'color_degraded': '#FFFF00', 'color_good': '#00FF00' } while True: print(x.taskWarrior([], config)) sleep(1)
# import your useful libs here from time import time from subprocess import check_output import json import shlex class Py3status: """ """ # available configuration parameters cache_timeout = 5 def taskWarrior(self, i3s_output_list, i3s_config): command = 'task start.before:tomorrow status:pending export' taskwarrior_output = check_output(shlex.split(command)) tasks_json = json.loads(taskwarrior_output.decode('utf-8')) def describeTask(taskObj): return str(taskObj['id']) + ' ' + taskObj['description'] result = ', '.join(map(describeTask, tasks_json)) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response if __name__ == "__main__": """ Test this module by calling it directly. """ from time import sleep x = Py3status() config = { 'color_bad': '#FF0000', 'color_degraded': '#FFFF00', 'color_good': '#00FF00' } while True: print(x.taskWarrior([], config)) sleep(1)
Fix parsing of taskWarrior's output
Fix parsing of taskWarrior's output I don't know for older versions, but the latest stable release already have '[' and ']' when doing an export. This lead to raising an exception because it makes a nested list and you try to access it using a string rather than an integer
Python
bsd-3-clause
valdur55/py3status,ultrabug/py3status,Shir0kamii/py3status,tobes/py3status,Spirotot/py3status,docwalter/py3status,Andrwe/py3status,guiniol/py3status,alexoneill/py3status,ultrabug/py3status,guiniol/py3status,tobes/py3status,ultrabug/py3status,Andrwe/py3status,valdur55/py3status,vvoland/py3status,hburg1234/py3status,valdur55/py3status
# import your useful libs here from time import time from subprocess import check_output import json import shlex class Py3status: """ """ # available configuration parameters cache_timeout = 5 def taskWarrior(self, i3s_output_list, i3s_config): command = 'task start.before:tomorrow status:pending export' taskwarrior_output = check_output(shlex.split(command)) - tasks_json = json.loads('[' + taskwarrior_output.decode('utf-8') + ']') + tasks_json = json.loads(taskwarrior_output.decode('utf-8')) def describeTask(taskObj): return str(taskObj['id']) + ' ' + taskObj['description'] result = ', '.join(map(describeTask, tasks_json)) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response if __name__ == "__main__": """ Test this module by calling it directly. """ from time import sleep x = Py3status() config = { 'color_bad': '#FF0000', 'color_degraded': '#FFFF00', 'color_good': '#00FF00' } while True: print(x.taskWarrior([], config)) sleep(1)
Fix parsing of taskWarrior's output
## Code Before: # import your useful libs here from time import time from subprocess import check_output import json import shlex class Py3status: """ """ # available configuration parameters cache_timeout = 5 def taskWarrior(self, i3s_output_list, i3s_config): command = 'task start.before:tomorrow status:pending export' taskwarrior_output = check_output(shlex.split(command)) tasks_json = json.loads('[' + taskwarrior_output.decode('utf-8') + ']') def describeTask(taskObj): return str(taskObj['id']) + ' ' + taskObj['description'] result = ', '.join(map(describeTask, tasks_json)) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response if __name__ == "__main__": """ Test this module by calling it directly. """ from time import sleep x = Py3status() config = { 'color_bad': '#FF0000', 'color_degraded': '#FFFF00', 'color_good': '#00FF00' } while True: print(x.taskWarrior([], config)) sleep(1) ## Instruction: Fix parsing of taskWarrior's output ## Code After: # import your useful libs here from time import time from subprocess import check_output import json import shlex class Py3status: """ """ # available configuration parameters cache_timeout = 5 def taskWarrior(self, i3s_output_list, i3s_config): command = 'task start.before:tomorrow status:pending export' taskwarrior_output = check_output(shlex.split(command)) tasks_json = json.loads(taskwarrior_output.decode('utf-8')) def describeTask(taskObj): return str(taskObj['id']) + ' ' + taskObj['description'] result = ', '.join(map(describeTask, tasks_json)) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response if __name__ == "__main__": """ Test this module by calling it directly. """ from time import sleep x = Py3status() config = { 'color_bad': '#FF0000', 'color_degraded': '#FFFF00', 'color_good': '#00FF00' } while True: print(x.taskWarrior([], config)) sleep(1)
# import your useful libs here from time import time from subprocess import check_output import json import shlex class Py3status: """ """ # available configuration parameters cache_timeout = 5 def taskWarrior(self, i3s_output_list, i3s_config): command = 'task start.before:tomorrow status:pending export' taskwarrior_output = check_output(shlex.split(command)) - tasks_json = json.loads('[' + taskwarrior_output.decode('utf-8') + ']') ? ------ ------ + tasks_json = json.loads(taskwarrior_output.decode('utf-8')) def describeTask(taskObj): return str(taskObj['id']) + ' ' + taskObj['description'] result = ', '.join(map(describeTask, tasks_json)) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response if __name__ == "__main__": """ Test this module by calling it directly. """ from time import sleep x = Py3status() config = { 'color_bad': '#FF0000', 'color_degraded': '#FFFF00', 'color_good': '#00FF00' } while True: print(x.taskWarrior([], config)) sleep(1)
668440b16916651b85b4a4a507214cee721906a8
scanpointgenerator/__init__.py
scanpointgenerator/__init__.py
from point import Point # noqa from generator import Generator # noqa from arraygenerator import ArrayGenerator # noqa from compoundgenerator import CompoundGenerator # noqa from linegenerator import LineGenerator # noqa from lissajousgenerator import LissajousGenerator # noqa from randomoffsetgenerator import RandomOffsetGenerator # noqa from spiralgenerator import SpiralGenerator # noqa from plotgenerator import plot_generator # noqa
from scanpointgenerator.point import Point # noqa from scanpointgenerator.generator import Generator # noqa from scanpointgenerator.arraygenerator import ArrayGenerator # noqa from scanpointgenerator.compoundgenerator import CompoundGenerator # noqa from scanpointgenerator.linegenerator import LineGenerator # noqa from scanpointgenerator.lissajousgenerator import LissajousGenerator # noqa from scanpointgenerator.randomoffsetgenerator import RandomOffsetGenerator # noqa from scanpointgenerator.spiralgenerator import SpiralGenerator # noqa from scanpointgenerator.plotgenerator import plot_generator # noqa
Add absolute imports in init
Add absolute imports in init
Python
apache-2.0
dls-controls/scanpointgenerator
- from point import Point # noqa + from scanpointgenerator.point import Point # noqa - from generator import Generator # noqa + from scanpointgenerator.generator import Generator # noqa - from arraygenerator import ArrayGenerator # noqa + from scanpointgenerator.arraygenerator import ArrayGenerator # noqa - from compoundgenerator import CompoundGenerator # noqa + from scanpointgenerator.compoundgenerator import CompoundGenerator # noqa - from linegenerator import LineGenerator # noqa + from scanpointgenerator.linegenerator import LineGenerator # noqa - from lissajousgenerator import LissajousGenerator # noqa + from scanpointgenerator.lissajousgenerator import LissajousGenerator # noqa - from randomoffsetgenerator import RandomOffsetGenerator # noqa + from scanpointgenerator.randomoffsetgenerator import RandomOffsetGenerator # noqa - from spiralgenerator import SpiralGenerator # noqa + from scanpointgenerator.spiralgenerator import SpiralGenerator # noqa - from plotgenerator import plot_generator # noqa + from scanpointgenerator.plotgenerator import plot_generator # noqa
Add absolute imports in init
## Code Before: from point import Point # noqa from generator import Generator # noqa from arraygenerator import ArrayGenerator # noqa from compoundgenerator import CompoundGenerator # noqa from linegenerator import LineGenerator # noqa from lissajousgenerator import LissajousGenerator # noqa from randomoffsetgenerator import RandomOffsetGenerator # noqa from spiralgenerator import SpiralGenerator # noqa from plotgenerator import plot_generator # noqa ## Instruction: Add absolute imports in init ## Code After: from scanpointgenerator.point import Point # noqa from scanpointgenerator.generator import Generator # noqa from scanpointgenerator.arraygenerator import ArrayGenerator # noqa from scanpointgenerator.compoundgenerator import CompoundGenerator # noqa from scanpointgenerator.linegenerator import LineGenerator # noqa from scanpointgenerator.lissajousgenerator import LissajousGenerator # noqa from scanpointgenerator.randomoffsetgenerator import RandomOffsetGenerator # noqa from scanpointgenerator.spiralgenerator import SpiralGenerator # noqa from scanpointgenerator.plotgenerator import plot_generator # noqa
- from point import Point # noqa + from scanpointgenerator.point import Point # noqa ? +++++++++++++++++++ - from generator import Generator # noqa + from scanpointgenerator.generator import Generator # noqa ? +++++++++++++++++++ - from arraygenerator import ArrayGenerator # noqa + from scanpointgenerator.arraygenerator import ArrayGenerator # noqa ? +++++++++++++++++++ - from compoundgenerator import CompoundGenerator # noqa + from scanpointgenerator.compoundgenerator import CompoundGenerator # noqa ? +++++++++++++++++++ - from linegenerator import LineGenerator # noqa + from scanpointgenerator.linegenerator import LineGenerator # noqa ? +++++++++++++++++++ - from lissajousgenerator import LissajousGenerator # noqa + from scanpointgenerator.lissajousgenerator import LissajousGenerator # noqa ? +++++++++++++++++++ - from randomoffsetgenerator import RandomOffsetGenerator # noqa + from scanpointgenerator.randomoffsetgenerator import RandomOffsetGenerator # noqa ? +++++++++++++++++++ - from spiralgenerator import SpiralGenerator # noqa + from scanpointgenerator.spiralgenerator import SpiralGenerator # noqa ? +++++++++++++++++++ - from plotgenerator import plot_generator # noqa + from scanpointgenerator.plotgenerator import plot_generator # noqa ? +++++++++++++++++++
f7dd16abcab5d5e0134083267f21672de8e3d5e1
hc/front/context_processors.py
hc/front/context_processors.py
from django.conf import settings def branding(request): return { "site_name": settings.SITE_NAME, "site_root": settings.SITE_ROOT, "site_logo_url": settings.SITE_LOGO_URL, }
from django.conf import settings def branding(request): return { "site_name": settings.SITE_NAME, "site_logo_url": settings.SITE_LOGO_URL, }
Remove site_root from template context, it's never used
Remove site_root from template context, it's never used
Python
bsd-3-clause
iphoting/healthchecks,iphoting/healthchecks,healthchecks/healthchecks,healthchecks/healthchecks,healthchecks/healthchecks,iphoting/healthchecks,healthchecks/healthchecks,iphoting/healthchecks
from django.conf import settings def branding(request): return { "site_name": settings.SITE_NAME, - "site_root": settings.SITE_ROOT, "site_logo_url": settings.SITE_LOGO_URL, }
Remove site_root from template context, it's never used
## Code Before: from django.conf import settings def branding(request): return { "site_name": settings.SITE_NAME, "site_root": settings.SITE_ROOT, "site_logo_url": settings.SITE_LOGO_URL, } ## Instruction: Remove site_root from template context, it's never used ## Code After: from django.conf import settings def branding(request): return { "site_name": settings.SITE_NAME, "site_logo_url": settings.SITE_LOGO_URL, }
from django.conf import settings def branding(request): return { "site_name": settings.SITE_NAME, - "site_root": settings.SITE_ROOT, "site_logo_url": settings.SITE_LOGO_URL, }
30a173da5850a457393cfdf47b7c0db303cdd2e9
tests/test_utils.py
tests/test_utils.py
from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2')
from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai.core.nonexistingimport') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2')
Test importing of module with unexisting target inside
Test importing of module with unexisting target inside There's a coverage case where a module exists, but what's inside it isn't covered.
Python
mit
cihai/cihai-python,cihai/cihai,cihai/cihai
from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): + utils.import_string('cihai.core.nonexistingimport') + + with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2')
Test importing of module with unexisting target inside
## Code Before: from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2') ## Instruction: Test importing of module with unexisting target inside ## Code After: from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai.core.nonexistingimport') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2')
from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): + utils.import_string('cihai.core.nonexistingimport') + + with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2')
7a3c4eed8888c8c2befc94020bebbfc18e1d6156
src/redis_client.py
src/redis_client.py
import txredisapi as redis from twisted.internet import defer, reactor import config connection = None @defer.inlineCallbacks def run_redis_client(on_started): pony = yield redis.makeConnection(config.redis['host'], config.redis['port'], config.redis['db'], poolsize = 8, reconnect = True, isLazy = True) global connection connection = pony on_started()
import txredisapi as redis from twisted.internet import defer, reactor import config connection = None def run_redis_client(on_started): df = redis.makeConnection(config.redis['host'], config.redis['port'], config.redis['db'], poolsize = 8, reconnect = True, isLazy = False) def done(pony): global connection connection = pony on_started() df.addCallback(done)
Fix the Redis client connection to actually work
Fix the Redis client connection to actually work It previously lied.
Python
mit
prophile/compd,prophile/compd
import txredisapi as redis from twisted.internet import defer, reactor import config connection = None - @defer.inlineCallbacks def run_redis_client(on_started): - pony = yield redis.makeConnection(config.redis['host'], + df = redis.makeConnection(config.redis['host'], - config.redis['port'], + config.redis['port'], - config.redis['db'], + config.redis['db'], - poolsize = 8, + poolsize = 8, - reconnect = True, + reconnect = True, - isLazy = True) + isLazy = False) + def done(pony): - global connection + global connection - connection = pony + connection = pony - on_started() + on_started() + df.addCallback(done)
Fix the Redis client connection to actually work
## Code Before: import txredisapi as redis from twisted.internet import defer, reactor import config connection = None @defer.inlineCallbacks def run_redis_client(on_started): pony = yield redis.makeConnection(config.redis['host'], config.redis['port'], config.redis['db'], poolsize = 8, reconnect = True, isLazy = True) global connection connection = pony on_started() ## Instruction: Fix the Redis client connection to actually work ## Code After: import txredisapi as redis from twisted.internet import defer, reactor import config connection = None def run_redis_client(on_started): df = redis.makeConnection(config.redis['host'], config.redis['port'], config.redis['db'], poolsize = 8, reconnect = True, isLazy = False) def done(pony): global connection connection = pony on_started() df.addCallback(done)
import txredisapi as redis from twisted.internet import defer, reactor import config connection = None - @defer.inlineCallbacks def run_redis_client(on_started): - pony = yield redis.makeConnection(config.redis['host'], ? ^^^^ ------ + df = redis.makeConnection(config.redis['host'], ? ^^ - config.redis['port'], ? -------- + config.redis['port'], - config.redis['db'], ? -------- + config.redis['db'], - poolsize = 8, ? -------- + poolsize = 8, - reconnect = True, ? -------- + reconnect = True, - isLazy = True) ? -------- ^^^ + isLazy = False) ? ^^^^ + def done(pony): - global connection + global connection ? ++++ - connection = pony + connection = pony ? ++++ - on_started() + on_started() ? ++++ + df.addCallback(done)
7bd606d40372d874f49016ea381270e34c7c7d58
database/initialize.py
database/initialize.py
""" Just the SQL Alchemy ORM tutorial """ import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String engine = create_engine('sqlite:///:memory:', echo=True) Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) password = Column(String) def __repr__(self): return "<User(name='%s', fullname='%s', password='%s')>" % ( self.name, self.fullname, self.password ) if __name__ == "__main__": Base.metadata.create_all(engine)
""" Just the SQL Alchemy ORM tutorial """ import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///:memory:', echo=True) Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) password = Column(String) def __repr__(self): return "<User(name='%s', fullname='%s', password='%s')>" % ( self.name, self.fullname, self.password ) if __name__ == "__main__": Base.metadata.create_all(engine) ed_user = User(name='ed', fullname='Ed Jones', password='edspassword') Session = sessionmaker(bind=engine) session = Session() session.add(ed_user) our_user = session.query(User).filter_by(name='ed').first() print(our_user)
Insert a user into a table
Insert a user into a table
Python
mit
b-ritter/python-notes,b-ritter/python-notes
""" Just the SQL Alchemy ORM tutorial """ import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String + from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///:memory:', echo=True) Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) password = Column(String) def __repr__(self): return "<User(name='%s', fullname='%s', password='%s')>" % ( self.name, self.fullname, self.password ) if __name__ == "__main__": Base.metadata.create_all(engine) + ed_user = User(name='ed', fullname='Ed Jones', password='edspassword') + Session = sessionmaker(bind=engine) + session = Session() + session.add(ed_user) + our_user = session.query(User).filter_by(name='ed').first() + print(our_user)
Insert a user into a table
## Code Before: """ Just the SQL Alchemy ORM tutorial """ import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String engine = create_engine('sqlite:///:memory:', echo=True) Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) password = Column(String) def __repr__(self): return "<User(name='%s', fullname='%s', password='%s')>" % ( self.name, self.fullname, self.password ) if __name__ == "__main__": Base.metadata.create_all(engine) ## Instruction: Insert a user into a table ## Code After: """ Just the SQL Alchemy ORM tutorial """ import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///:memory:', echo=True) Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) password = Column(String) def __repr__(self): return "<User(name='%s', fullname='%s', password='%s')>" % ( self.name, self.fullname, self.password ) if __name__ == "__main__": Base.metadata.create_all(engine) ed_user = User(name='ed', fullname='Ed Jones', password='edspassword') Session = sessionmaker(bind=engine) session = Session() session.add(ed_user) our_user = session.query(User).filter_by(name='ed').first() print(our_user)
""" Just the SQL Alchemy ORM tutorial """ import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String + from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///:memory:', echo=True) Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) password = Column(String) def __repr__(self): return "<User(name='%s', fullname='%s', password='%s')>" % ( self.name, self.fullname, self.password ) if __name__ == "__main__": Base.metadata.create_all(engine) + ed_user = User(name='ed', fullname='Ed Jones', password='edspassword') + Session = sessionmaker(bind=engine) + session = Session() + session.add(ed_user) + our_user = session.query(User).filter_by(name='ed').first() + print(our_user)
848d783bd988e0cdf31b690f17837ac02e77b43a
pypodio2/client.py
pypodio2/client.py
from . import areas class FailedRequest(Exception): def __init__(self, error): self.error = error def __str__(self): return repr(self.error) class Client(object): """ The Podio API client. Callers should use the factory method OAuthClient to create instances. """ def __init__(self, transport): self.transport = transport def __getattr__(self, name): new_trans = self.transport area = getattr(areas, name) return area(new_trans)
from . import areas class FailedRequest(Exception): def __init__(self, error): self.error = error def __str__(self): return repr(self.error) class Client(object): """ The Podio API client. Callers should use the factory method OAuthClient to create instances. """ def __init__(self, transport): self.transport = transport def __getattr__(self, name): new_trans = self.transport area = getattr(areas, name) return area(new_trans) def __dir__(self): """ Should return list of attribute names. Since __getattr__ looks in areas, we simply list the content of the areas module """ return dir(areas)
Add __dir__ method to Client in order to allow autocompletion in interactive terminals, etc.
Add __dir__ method to Client in order to allow autocompletion in interactive terminals, etc.
Python
mit
podio/podio-py
from . import areas class FailedRequest(Exception): def __init__(self, error): self.error = error def __str__(self): return repr(self.error) class Client(object): """ The Podio API client. Callers should use the factory method OAuthClient to create instances. """ def __init__(self, transport): self.transport = transport def __getattr__(self, name): new_trans = self.transport area = getattr(areas, name) return area(new_trans) + def __dir__(self): + """ + Should return list of attribute names. + Since __getattr__ looks in areas, we simply list the content of the areas module + """ + return dir(areas) +
Add __dir__ method to Client in order to allow autocompletion in interactive terminals, etc.
## Code Before: from . import areas class FailedRequest(Exception): def __init__(self, error): self.error = error def __str__(self): return repr(self.error) class Client(object): """ The Podio API client. Callers should use the factory method OAuthClient to create instances. """ def __init__(self, transport): self.transport = transport def __getattr__(self, name): new_trans = self.transport area = getattr(areas, name) return area(new_trans) ## Instruction: Add __dir__ method to Client in order to allow autocompletion in interactive terminals, etc. ## Code After: from . import areas class FailedRequest(Exception): def __init__(self, error): self.error = error def __str__(self): return repr(self.error) class Client(object): """ The Podio API client. Callers should use the factory method OAuthClient to create instances. """ def __init__(self, transport): self.transport = transport def __getattr__(self, name): new_trans = self.transport area = getattr(areas, name) return area(new_trans) def __dir__(self): """ Should return list of attribute names. Since __getattr__ looks in areas, we simply list the content of the areas module """ return dir(areas)
from . import areas class FailedRequest(Exception): def __init__(self, error): self.error = error def __str__(self): return repr(self.error) class Client(object): """ The Podio API client. Callers should use the factory method OAuthClient to create instances. """ def __init__(self, transport): self.transport = transport def __getattr__(self, name): new_trans = self.transport area = getattr(areas, name) return area(new_trans) + + def __dir__(self): + """ + Should return list of attribute names. + Since __getattr__ looks in areas, we simply list the content of the areas module + """ + return dir(areas)
502e01be7fdf427e3fbbf03887bbb323d8c74d43
src/pi/pushrpc.py
src/pi/pushrpc.py
"""Pusher intergration for messages from the cloud.""" import json import logging import Queue import sys from common import creds from pusherclient import Pusher class PushRPC(object): """Wrapper for pusher integration.""" def __init__(self): self._queue = Queue.Queue() self._pusher = Pusher(creds.pusher_key) self._pusher.connection.bind('pusher:connection_established', self._connect_handler) self._pusher.connect() def _connect_handler(self, _): channel = self._pusher.subscribe('test') channel.bind('event', self._callback_handler) def _callback_handler(self, data): """Callback for when messages are recieved from pusher.""" try: data = json.loads(data) except ValueError: logging.error('Error parsing message', exc_info=sys.exc_info()) return self._queue.put(data) def events(self): while True: yield self._queue.get(block=True)
"""Pusher intergration for messages from the cloud.""" import json import logging import Queue import sys from common import creds from pusherclient import Pusher class PushRPC(object): """Wrapper for pusher integration.""" def __init__(self): self._queue = Queue.Queue() self._pusher = Pusher(creds.pusher_key) self._pusher.connection.bind('pusher:connection_established', self._connect_handler) self._pusher.connect() def _connect_handler(self, _): channel = self._pusher.subscribe('test') channel.bind('event', self._callback_handler) def _callback_handler(self, data): """Callback for when messages are recieved from pusher.""" try: data = json.loads(data) except ValueError: logging.error('Error parsing message', exc_info=sys.exc_info()) return self._queue.put(data) def events(self): while True: # if we specify a timeout, queues become keyboard interruptable try: yield self._queue.get(block=True, timeout=1000) except Queue.Empty: pass
Make the script respond to ctrl-c
Make the script respond to ctrl-c
Python
mit
tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation
"""Pusher intergration for messages from the cloud.""" import json import logging import Queue import sys from common import creds from pusherclient import Pusher class PushRPC(object): """Wrapper for pusher integration.""" def __init__(self): self._queue = Queue.Queue() self._pusher = Pusher(creds.pusher_key) self._pusher.connection.bind('pusher:connection_established', self._connect_handler) self._pusher.connect() def _connect_handler(self, _): channel = self._pusher.subscribe('test') channel.bind('event', self._callback_handler) def _callback_handler(self, data): """Callback for when messages are recieved from pusher.""" try: data = json.loads(data) except ValueError: logging.error('Error parsing message', exc_info=sys.exc_info()) return self._queue.put(data) def events(self): while True: + # if we specify a timeout, queues become keyboard interruptable + try: - yield self._queue.get(block=True) + yield self._queue.get(block=True, timeout=1000) + except Queue.Empty: + pass
Make the script respond to ctrl-c
## Code Before: """Pusher intergration for messages from the cloud.""" import json import logging import Queue import sys from common import creds from pusherclient import Pusher class PushRPC(object): """Wrapper for pusher integration.""" def __init__(self): self._queue = Queue.Queue() self._pusher = Pusher(creds.pusher_key) self._pusher.connection.bind('pusher:connection_established', self._connect_handler) self._pusher.connect() def _connect_handler(self, _): channel = self._pusher.subscribe('test') channel.bind('event', self._callback_handler) def _callback_handler(self, data): """Callback for when messages are recieved from pusher.""" try: data = json.loads(data) except ValueError: logging.error('Error parsing message', exc_info=sys.exc_info()) return self._queue.put(data) def events(self): while True: yield self._queue.get(block=True) ## Instruction: Make the script respond to ctrl-c ## Code After: """Pusher intergration for messages from the cloud.""" import json import logging import Queue import sys from common import creds from pusherclient import Pusher class PushRPC(object): """Wrapper for pusher integration.""" def __init__(self): self._queue = Queue.Queue() self._pusher = Pusher(creds.pusher_key) self._pusher.connection.bind('pusher:connection_established', self._connect_handler) self._pusher.connect() def _connect_handler(self, _): channel = self._pusher.subscribe('test') channel.bind('event', self._callback_handler) def _callback_handler(self, data): """Callback for when messages are recieved from pusher.""" try: data = json.loads(data) except ValueError: logging.error('Error parsing message', exc_info=sys.exc_info()) return self._queue.put(data) def events(self): while True: # if we specify a timeout, queues become keyboard interruptable try: yield self._queue.get(block=True, timeout=1000) except Queue.Empty: pass
"""Pusher intergration for messages from the cloud.""" import json import logging import Queue import sys from common import creds from pusherclient import Pusher class PushRPC(object): """Wrapper for pusher integration.""" def __init__(self): self._queue = Queue.Queue() self._pusher = Pusher(creds.pusher_key) self._pusher.connection.bind('pusher:connection_established', self._connect_handler) self._pusher.connect() def _connect_handler(self, _): channel = self._pusher.subscribe('test') channel.bind('event', self._callback_handler) def _callback_handler(self, data): """Callback for when messages are recieved from pusher.""" try: data = json.loads(data) except ValueError: logging.error('Error parsing message', exc_info=sys.exc_info()) return self._queue.put(data) def events(self): while True: + # if we specify a timeout, queues become keyboard interruptable + try: - yield self._queue.get(block=True) + yield self._queue.get(block=True, timeout=1000) ? ++ ++++++++++++++ + except Queue.Empty: + pass
4c33e921d8ad6d1a69b0d198e8ea71b64339973a
us_ignite/common/tests/context_processors_tests.py
us_ignite/common/tests/context_processors_tests.py
from nose.tools import eq_ from django.test import TestCase from us_ignite.common.tests import utils from us_ignite.common import context_processors class TestSettingsAvailableContextProcessor(TestCase): def test_settings_are_available(self): request = utils.get_request('get', '/') context = context_processors.settings_available(request) eq_(sorted(context.keys()), sorted(['SITE_URL', 'IS_PRODUCTION', 'ACCOUNT_ACTIVATION_DAYS']))
from nose.tools import eq_ from django.test import TestCase from us_ignite.common.tests import utils from us_ignite.common import context_processors class TestSettingsAvailableContextProcessor(TestCase): def test_settings_are_available(self): request = utils.get_request('get', '/') context = context_processors.settings_available(request) eq_(sorted(context.keys()), sorted(['ACCOUNT_ACTIVATION_DAYS', 'GOOGLE_ANALYTICS_ID', 'IS_PRODUCTION', 'SITE_URL']))
Update common context processors tests.
Update common context processors tests.
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
from nose.tools import eq_ from django.test import TestCase from us_ignite.common.tests import utils from us_ignite.common import context_processors class TestSettingsAvailableContextProcessor(TestCase): def test_settings_are_available(self): request = utils.get_request('get', '/') context = context_processors.settings_available(request) eq_(sorted(context.keys()), - sorted(['SITE_URL', 'IS_PRODUCTION', 'ACCOUNT_ACTIVATION_DAYS'])) + sorted(['ACCOUNT_ACTIVATION_DAYS', 'GOOGLE_ANALYTICS_ID', + 'IS_PRODUCTION', 'SITE_URL']))
Update common context processors tests.
## Code Before: from nose.tools import eq_ from django.test import TestCase from us_ignite.common.tests import utils from us_ignite.common import context_processors class TestSettingsAvailableContextProcessor(TestCase): def test_settings_are_available(self): request = utils.get_request('get', '/') context = context_processors.settings_available(request) eq_(sorted(context.keys()), sorted(['SITE_URL', 'IS_PRODUCTION', 'ACCOUNT_ACTIVATION_DAYS'])) ## Instruction: Update common context processors tests. ## Code After: from nose.tools import eq_ from django.test import TestCase from us_ignite.common.tests import utils from us_ignite.common import context_processors class TestSettingsAvailableContextProcessor(TestCase): def test_settings_are_available(self): request = utils.get_request('get', '/') context = context_processors.settings_available(request) eq_(sorted(context.keys()), sorted(['ACCOUNT_ACTIVATION_DAYS', 'GOOGLE_ANALYTICS_ID', 'IS_PRODUCTION', 'SITE_URL']))
from nose.tools import eq_ from django.test import TestCase from us_ignite.common.tests import utils from us_ignite.common import context_processors class TestSettingsAvailableContextProcessor(TestCase): def test_settings_are_available(self): request = utils.get_request('get', '/') context = context_processors.settings_available(request) eq_(sorted(context.keys()), - sorted(['SITE_URL', 'IS_PRODUCTION', 'ACCOUNT_ACTIVATION_DAYS'])) + sorted(['ACCOUNT_ACTIVATION_DAYS', 'GOOGLE_ANALYTICS_ID', + 'IS_PRODUCTION', 'SITE_URL']))
6aa8db30afba817ff9b5653480d6f735f09d9c3a
ladder.py
ladder.py
class Player: def __init__(self, name, rank): self.name = name self.rank = rank def __repr__(self): return '<{:s}(name={:s}, rank={:d})>'.format(self.__class__.__name__, self.name, self.rank) def __str__(self): rank_str = '' if self.rank < 0: rank_str = '{:d}K'.format(-self.rank) else: rank_str = '{:d}D'.format(self.rank) return '{:s} {:s}'.format(self.name, rank_str) class Ladder: def __init__(self, standings): self.standings = standings def __str__(self): the_string = 'Ladder standings:' position = 1 for player in self.standings: the_string += '\n {:d}. {:s}'.format(position, str(player)) position += 1 return the_string if __name__ == '__main__': ladder = Ladder([Player('Andrew', -1), Player('Walther', 5), Player('Milan', -6)]) print(ladder)
class Player: def __init__(self, name, rank): self.name = name self.rank = rank def __repr__(self): return '<{:s}(name={:s}, rank={:d})>'.format(self.__class__.__name__, self.name, self.rank) def __str__(self): rank_str = '' if self.rank < 0: rank_str = '{:d}K'.format(-self.rank) else: rank_str = '{:d}D'.format(self.rank) return '{:s} {:s}'.format(self.name, rank_str) class Ladder: def __init__(self, standings): self.standings = standings def __str__(self): the_string = 'Ladder standings:' position = 1 for player in self.standings: the_string += '\n {:d}. {:s}'.format(position, str(player)) position += 1 return the_string def players(self): return set(self.standings) def match_valid(self, player_one, player_two): if not {player_one, player_two} < self.players(): return False return True if __name__ == '__main__': ladder = Ladder([Player('Andrew', -1), Player('Walther', 5), Player('Milan', -6)]) print(ladder)
Add players, match_valid to Ladder
Add players, match_valid to Ladder -Add rudimentary players() method that creates a set -Add match_valid() method that *only* checks that players are in the ladder standings
Python
agpl-3.0
massgo/mgaladder,hndrewaall/mgaladder,massgo/mgaladder,massgo/mgaladder,hndrewaall/mgaladder,hndrewaall/mgaladder
class Player: def __init__(self, name, rank): self.name = name self.rank = rank def __repr__(self): return '<{:s}(name={:s}, rank={:d})>'.format(self.__class__.__name__, self.name, self.rank) - def __str__(self): rank_str = '' if self.rank < 0: rank_str = '{:d}K'.format(-self.rank) else: rank_str = '{:d}D'.format(self.rank) - return '{:s} {:s}'.format(self.name, rank_str) class Ladder: def __init__(self, standings): self.standings = standings def __str__(self): the_string = 'Ladder standings:' position = 1 for player in self.standings: the_string += '\n {:d}. {:s}'.format(position, str(player)) position += 1 return the_string + def players(self): + return set(self.standings) + + def match_valid(self, player_one, player_two): + if not {player_one, player_two} < self.players(): + return False + return True if __name__ == '__main__': ladder = Ladder([Player('Andrew', -1), Player('Walther', 5), Player('Milan', -6)]) print(ladder)
Add players, match_valid to Ladder
## Code Before: class Player: def __init__(self, name, rank): self.name = name self.rank = rank def __repr__(self): return '<{:s}(name={:s}, rank={:d})>'.format(self.__class__.__name__, self.name, self.rank) def __str__(self): rank_str = '' if self.rank < 0: rank_str = '{:d}K'.format(-self.rank) else: rank_str = '{:d}D'.format(self.rank) return '{:s} {:s}'.format(self.name, rank_str) class Ladder: def __init__(self, standings): self.standings = standings def __str__(self): the_string = 'Ladder standings:' position = 1 for player in self.standings: the_string += '\n {:d}. {:s}'.format(position, str(player)) position += 1 return the_string if __name__ == '__main__': ladder = Ladder([Player('Andrew', -1), Player('Walther', 5), Player('Milan', -6)]) print(ladder) ## Instruction: Add players, match_valid to Ladder ## Code After: class Player: def __init__(self, name, rank): self.name = name self.rank = rank def __repr__(self): return '<{:s}(name={:s}, rank={:d})>'.format(self.__class__.__name__, self.name, self.rank) def __str__(self): rank_str = '' if self.rank < 0: rank_str = '{:d}K'.format(-self.rank) else: rank_str = '{:d}D'.format(self.rank) return '{:s} {:s}'.format(self.name, rank_str) class Ladder: def __init__(self, standings): self.standings = standings def __str__(self): the_string = 'Ladder standings:' position = 1 for player in self.standings: the_string += '\n {:d}. {:s}'.format(position, str(player)) position += 1 return the_string def players(self): return set(self.standings) def match_valid(self, player_one, player_two): if not {player_one, player_two} < self.players(): return False return True if __name__ == '__main__': ladder = Ladder([Player('Andrew', -1), Player('Walther', 5), Player('Milan', -6)]) print(ladder)
class Player: def __init__(self, name, rank): self.name = name self.rank = rank def __repr__(self): return '<{:s}(name={:s}, rank={:d})>'.format(self.__class__.__name__, self.name, self.rank) - def __str__(self): rank_str = '' if self.rank < 0: rank_str = '{:d}K'.format(-self.rank) else: rank_str = '{:d}D'.format(self.rank) - return '{:s} {:s}'.format(self.name, rank_str) class Ladder: def __init__(self, standings): self.standings = standings def __str__(self): the_string = 'Ladder standings:' position = 1 for player in self.standings: the_string += '\n {:d}. {:s}'.format(position, str(player)) position += 1 return the_string + def players(self): + return set(self.standings) + + def match_valid(self, player_one, player_two): + if not {player_one, player_two} < self.players(): + return False + return True if __name__ == '__main__': ladder = Ladder([Player('Andrew', -1), Player('Walther', 5), Player('Milan', -6)]) print(ladder)
b5aacae66d4395a3c507c661144b21f9b2838a0f
utils/dakota_utils.py
utils/dakota_utils.py
import numpy as np def get_names(dat_file): ''' Reads the header from Dakota tabular graphics file. Returns a list of variable names. ''' fp = open(dat_file, 'r') return fp.readline().split() def get_data(dat_file): ''' Reads the data from Dakota tabular graphics file. Returns a numpy array. ''' return np.loadtxt(dat_file, skiprows=1, unpack=True) def read_tabular(dat_file): ''' Reads a Dakota tabular graphics file. Returns a dict with variable names and a numpy array with data. ''' names = get_names(dat_file) data = get_data(dat_file) return {'names':names, 'data':data}
import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt def get_names(dat_file): ''' Reads the header from Dakota tabular graphics file. Returns a list of variable names. ''' fp = open(dat_file, 'r') return fp.readline().split() def get_data(dat_file): ''' Reads the data from Dakota tabular graphics file. Returns a numpy array. ''' return np.loadtxt(dat_file, skiprows=1, unpack=True) def read_tabular(dat_file): ''' Reads a Dakota tabular graphics file. Returns a dict with variable names and a numpy array with data. ''' names = get_names(dat_file) data = get_data(dat_file) return {'names':names, 'data':data} def plot_tabular_2d(tab_data, column_index=-1): ''' Surface plot. ''' x = tab_data.get('data')[1,] y = tab_data.get('data')[2,] z = tab_data.get('data')[column_index,] m = len(set(x)) n = len(set(y)) X = x.reshape(m,n) Y = y.reshape(m,n) Z = z.reshape(m,n) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(X, Y, Z, rstride=1, cstride=1) ax.set_xlabel(tab_data.get('names')[1]) ax.set_ylabel(tab_data.get('names')[2]) ax.set_zlabel(tab_data.get('names')[column_index]) plt.show(block=False)
Add routine to make surface plot from Dakota output
Add routine to make surface plot from Dakota output
Python
mit
mdpiper/dakota-experiments,mdpiper/dakota-experiments,mdpiper/dakota-experiments,mcflugen/dakota-experiments,mcflugen/dakota-experiments
import numpy as np + from mpl_toolkits.mplot3d import Axes3D + import matplotlib.pyplot as plt def get_names(dat_file): ''' Reads the header from Dakota tabular graphics file. Returns a list of variable names. ''' fp = open(dat_file, 'r') return fp.readline().split() def get_data(dat_file): ''' Reads the data from Dakota tabular graphics file. Returns a numpy array. - ''' + ''' return np.loadtxt(dat_file, skiprows=1, unpack=True) def read_tabular(dat_file): ''' Reads a Dakota tabular graphics file. Returns a dict with variable names and a numpy array with data. ''' names = get_names(dat_file) data = get_data(dat_file) return {'names':names, 'data':data} + def plot_tabular_2d(tab_data, column_index=-1): + ''' + Surface plot. + ''' + x = tab_data.get('data')[1,] + y = tab_data.get('data')[2,] + z = tab_data.get('data')[column_index,] + + m = len(set(x)) + n = len(set(y)) + + X = x.reshape(m,n) + Y = y.reshape(m,n) + Z = z.reshape(m,n) + + fig = plt.figure() + ax = fig.add_subplot(111, projection='3d') + ax.plot_surface(X, Y, Z, rstride=1, cstride=1) + ax.set_xlabel(tab_data.get('names')[1]) + ax.set_ylabel(tab_data.get('names')[2]) + ax.set_zlabel(tab_data.get('names')[column_index]) + plt.show(block=False) +
Add routine to make surface plot from Dakota output
## Code Before: import numpy as np def get_names(dat_file): ''' Reads the header from Dakota tabular graphics file. Returns a list of variable names. ''' fp = open(dat_file, 'r') return fp.readline().split() def get_data(dat_file): ''' Reads the data from Dakota tabular graphics file. Returns a numpy array. ''' return np.loadtxt(dat_file, skiprows=1, unpack=True) def read_tabular(dat_file): ''' Reads a Dakota tabular graphics file. Returns a dict with variable names and a numpy array with data. ''' names = get_names(dat_file) data = get_data(dat_file) return {'names':names, 'data':data} ## Instruction: Add routine to make surface plot from Dakota output ## Code After: import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt def get_names(dat_file): ''' Reads the header from Dakota tabular graphics file. Returns a list of variable names. ''' fp = open(dat_file, 'r') return fp.readline().split() def get_data(dat_file): ''' Reads the data from Dakota tabular graphics file. Returns a numpy array. ''' return np.loadtxt(dat_file, skiprows=1, unpack=True) def read_tabular(dat_file): ''' Reads a Dakota tabular graphics file. Returns a dict with variable names and a numpy array with data. ''' names = get_names(dat_file) data = get_data(dat_file) return {'names':names, 'data':data} def plot_tabular_2d(tab_data, column_index=-1): ''' Surface plot. ''' x = tab_data.get('data')[1,] y = tab_data.get('data')[2,] z = tab_data.get('data')[column_index,] m = len(set(x)) n = len(set(y)) X = x.reshape(m,n) Y = y.reshape(m,n) Z = z.reshape(m,n) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(X, Y, Z, rstride=1, cstride=1) ax.set_xlabel(tab_data.get('names')[1]) ax.set_ylabel(tab_data.get('names')[2]) ax.set_zlabel(tab_data.get('names')[column_index]) plt.show(block=False)
import numpy as np + from mpl_toolkits.mplot3d import Axes3D + import matplotlib.pyplot as plt def get_names(dat_file): ''' Reads the header from Dakota tabular graphics file. Returns a list of variable names. ''' fp = open(dat_file, 'r') return fp.readline().split() def get_data(dat_file): ''' Reads the data from Dakota tabular graphics file. Returns a numpy array. - ''' ? ---- + ''' return np.loadtxt(dat_file, skiprows=1, unpack=True) def read_tabular(dat_file): ''' Reads a Dakota tabular graphics file. Returns a dict with variable names and a numpy array with data. ''' names = get_names(dat_file) data = get_data(dat_file) return {'names':names, 'data':data} + + def plot_tabular_2d(tab_data, column_index=-1): + ''' + Surface plot. + ''' + x = tab_data.get('data')[1,] + y = tab_data.get('data')[2,] + z = tab_data.get('data')[column_index,] + + m = len(set(x)) + n = len(set(y)) + + X = x.reshape(m,n) + Y = y.reshape(m,n) + Z = z.reshape(m,n) + + fig = plt.figure() + ax = fig.add_subplot(111, projection='3d') + ax.plot_surface(X, Y, Z, rstride=1, cstride=1) + ax.set_xlabel(tab_data.get('names')[1]) + ax.set_ylabel(tab_data.get('names')[2]) + ax.set_zlabel(tab_data.get('names')[column_index]) + plt.show(block=False)
cf16c64e378f64d2267f75444c568aed895f940c
setup.py
setup.py
import platform, sys from distutils.core import setup from distextend import * packages, package_data = findPackages("countershape") setup( name = "countershape", version = "0.1", description = "A framework for rendering static documentation.", author = "Nullcube Pty Ltd", author_email = "aldo@nullcube.com", url = "http://dev.nullcube.com", packages = packages, package_data = package_data, scripts = ["cshape"], )
import platform, sys from distutils.core import setup from distextend import * packages, package_data = findPackages("countershape") setup( name = "countershape", version = "0.1", description = "A framework for rendering static documentation.", author = "Nullcube Pty Ltd", author_email = "aldo@nullcube.com", url = "http://dev.nullcube.com", packages = packages, package_data = package_data, scripts = ["cshape", "csblog"], )
Add csblog to installed scripts.
Add csblog to installed scripts.
Python
mit
mhils/countershape,samtaufa/countershape,cortesi/countershape,cortesi/countershape,samtaufa/countershape,mhils/countershape
import platform, sys from distutils.core import setup from distextend import * packages, package_data = findPackages("countershape") setup( name = "countershape", version = "0.1", description = "A framework for rendering static documentation.", author = "Nullcube Pty Ltd", author_email = "aldo@nullcube.com", url = "http://dev.nullcube.com", packages = packages, package_data = package_data, - scripts = ["cshape"], + scripts = ["cshape", "csblog"], )
Add csblog to installed scripts.
## Code Before: import platform, sys from distutils.core import setup from distextend import * packages, package_data = findPackages("countershape") setup( name = "countershape", version = "0.1", description = "A framework for rendering static documentation.", author = "Nullcube Pty Ltd", author_email = "aldo@nullcube.com", url = "http://dev.nullcube.com", packages = packages, package_data = package_data, scripts = ["cshape"], ) ## Instruction: Add csblog to installed scripts. ## Code After: import platform, sys from distutils.core import setup from distextend import * packages, package_data = findPackages("countershape") setup( name = "countershape", version = "0.1", description = "A framework for rendering static documentation.", author = "Nullcube Pty Ltd", author_email = "aldo@nullcube.com", url = "http://dev.nullcube.com", packages = packages, package_data = package_data, scripts = ["cshape", "csblog"], )
import platform, sys from distutils.core import setup from distextend import * packages, package_data = findPackages("countershape") setup( name = "countershape", version = "0.1", description = "A framework for rendering static documentation.", author = "Nullcube Pty Ltd", author_email = "aldo@nullcube.com", url = "http://dev.nullcube.com", packages = packages, package_data = package_data, - scripts = ["cshape"], + scripts = ["cshape", "csblog"], ? ++++++++++ )
5ebcb9a666f03439bb075ac5961d2230ea649371
dockci/api/exceptions.py
dockci/api/exceptions.py
""" Exceptions relating to API issues """ from werkzeug.exceptions import HTTPException class BaseActionException(HTTPException): """ An HTTP exception for when an action can't be performed """ response = None def __init__(self, action=None): super(BaseActionException, self).__init__() if action is not None: self.action = action @property def description(self): """ Description of the action that couldn't be performed """ return self.message_fs % self.action class OnlyMeError(BaseActionException): """ Raised when a user tries an action on another user that can only be performed on themselves """ code = 401 action = "do this" message_fs = "Can not %s for another user" class WrongAuthMethodError(BaseActionException): """ Raised when user authenticated with an invalid auth method """ code = 400 action = "another method" message_fs = "Must authenticate with %s" class WrappedException(HTTPException): """ Wraps an exception in HTTPException so that it can have a status code """ response = None def __init__(self, ex): super(WrappedException, self).__init__() self.description = str(ex) class WrappedTokenError(WrappedException): """ Wrapper for the JWT TokenError to return HTTP 400 """ code = 400 class WrappedValueError(WrappedException): """ Wrapper for the ValueError to return HTTP 400 """ code = 400
""" Exceptions relating to API issues """ from werkzeug.exceptions import HTTPException class BaseActionExceptionMixin(HTTPException): """ An HTTP exception for when an action can't be performed """ response = None def __init__(self, action=None): super(BaseActionExceptionMixin, self).__init__() if action is not None: self.action = action @property def description(self): """ Description of the action that couldn't be performed """ return self.message_fs % self.action class OnlyMeError(BaseActionExceptionMixin): """ Raised when a user tries an action on another user that can only be performed on themselves """ code = 401 action = "do this" message_fs = "Can not %s for another user" class WrongAuthMethodError(BaseActionExceptionMixin): """ Raised when user authenticated with an invalid auth method """ code = 400 action = "another method" message_fs = "Must authenticate with %s" class WrappedException(HTTPException): """ Wraps an exception in HTTPException so that it can have a status code """ response = None def __init__(self, ex): super(WrappedException, self).__init__() self.description = str(ex) class WrappedTokenError(WrappedException): """ Wrapper for the JWT TokenError to return HTTP 400 """ code = 400 class WrappedValueError(WrappedException): """ Wrapper for the ValueError to return HTTP 400 """ code = 400
Make BaseActionException mixin for pylint
Make BaseActionException mixin for pylint
Python
isc
RickyCook/DockCI,sprucedev/DockCI,sprucedev/DockCI-Agent,sprucedev/DockCI,sprucedev/DockCI,sprucedev/DockCI,RickyCook/DockCI,RickyCook/DockCI,RickyCook/DockCI,sprucedev/DockCI-Agent
""" Exceptions relating to API issues """ from werkzeug.exceptions import HTTPException - class BaseActionException(HTTPException): + class BaseActionExceptionMixin(HTTPException): """ An HTTP exception for when an action can't be performed """ response = None def __init__(self, action=None): - super(BaseActionException, self).__init__() + super(BaseActionExceptionMixin, self).__init__() if action is not None: self.action = action @property def description(self): """ Description of the action that couldn't be performed """ return self.message_fs % self.action - class OnlyMeError(BaseActionException): + class OnlyMeError(BaseActionExceptionMixin): """ Raised when a user tries an action on another user that can only be performed on themselves """ code = 401 action = "do this" message_fs = "Can not %s for another user" - class WrongAuthMethodError(BaseActionException): + class WrongAuthMethodError(BaseActionExceptionMixin): """ Raised when user authenticated with an invalid auth method """ code = 400 action = "another method" message_fs = "Must authenticate with %s" class WrappedException(HTTPException): """ Wraps an exception in HTTPException so that it can have a status code """ response = None def __init__(self, ex): super(WrappedException, self).__init__() self.description = str(ex) class WrappedTokenError(WrappedException): """ Wrapper for the JWT TokenError to return HTTP 400 """ code = 400 class WrappedValueError(WrappedException): """ Wrapper for the ValueError to return HTTP 400 """ code = 400
Make BaseActionException mixin for pylint
## Code Before: """ Exceptions relating to API issues """ from werkzeug.exceptions import HTTPException class BaseActionException(HTTPException): """ An HTTP exception for when an action can't be performed """ response = None def __init__(self, action=None): super(BaseActionException, self).__init__() if action is not None: self.action = action @property def description(self): """ Description of the action that couldn't be performed """ return self.message_fs % self.action class OnlyMeError(BaseActionException): """ Raised when a user tries an action on another user that can only be performed on themselves """ code = 401 action = "do this" message_fs = "Can not %s for another user" class WrongAuthMethodError(BaseActionException): """ Raised when user authenticated with an invalid auth method """ code = 400 action = "another method" message_fs = "Must authenticate with %s" class WrappedException(HTTPException): """ Wraps an exception in HTTPException so that it can have a status code """ response = None def __init__(self, ex): super(WrappedException, self).__init__() self.description = str(ex) class WrappedTokenError(WrappedException): """ Wrapper for the JWT TokenError to return HTTP 400 """ code = 400 class WrappedValueError(WrappedException): """ Wrapper for the ValueError to return HTTP 400 """ code = 400 ## Instruction: Make BaseActionException mixin for pylint ## Code After: """ Exceptions relating to API issues """ from werkzeug.exceptions import HTTPException class BaseActionExceptionMixin(HTTPException): """ An HTTP exception for when an action can't be performed """ response = None def __init__(self, action=None): super(BaseActionExceptionMixin, self).__init__() if action is not None: self.action = action @property def description(self): """ Description of the action that couldn't be performed """ return self.message_fs % self.action class OnlyMeError(BaseActionExceptionMixin): """ Raised when a user tries an action on another user that can only be performed on themselves """ code = 401 action = "do this" message_fs = "Can not %s for another user" class WrongAuthMethodError(BaseActionExceptionMixin): """ Raised when user authenticated with an invalid auth method """ code = 400 action = "another method" message_fs = "Must authenticate with %s" class WrappedException(HTTPException): """ Wraps an exception in HTTPException so that it can have a status code """ response = None def __init__(self, ex): super(WrappedException, self).__init__() self.description = str(ex) class WrappedTokenError(WrappedException): """ Wrapper for the JWT TokenError to return HTTP 400 """ code = 400 class WrappedValueError(WrappedException): """ Wrapper for the ValueError to return HTTP 400 """ code = 400
""" Exceptions relating to API issues """ from werkzeug.exceptions import HTTPException - class BaseActionException(HTTPException): + class BaseActionExceptionMixin(HTTPException): ? +++++ """ An HTTP exception for when an action can't be performed """ response = None def __init__(self, action=None): - super(BaseActionException, self).__init__() + super(BaseActionExceptionMixin, self).__init__() ? +++++ if action is not None: self.action = action @property def description(self): """ Description of the action that couldn't be performed """ return self.message_fs % self.action - class OnlyMeError(BaseActionException): + class OnlyMeError(BaseActionExceptionMixin): ? +++++ """ Raised when a user tries an action on another user that can only be performed on themselves """ code = 401 action = "do this" message_fs = "Can not %s for another user" - class WrongAuthMethodError(BaseActionException): + class WrongAuthMethodError(BaseActionExceptionMixin): ? +++++ """ Raised when user authenticated with an invalid auth method """ code = 400 action = "another method" message_fs = "Must authenticate with %s" class WrappedException(HTTPException): """ Wraps an exception in HTTPException so that it can have a status code """ response = None def __init__(self, ex): super(WrappedException, self).__init__() self.description = str(ex) class WrappedTokenError(WrappedException): """ Wrapper for the JWT TokenError to return HTTP 400 """ code = 400 class WrappedValueError(WrappedException): """ Wrapper for the ValueError to return HTTP 400 """ code = 400
ea57d89c1acc82a473a648f1c53430fadc27f7b2
opps/polls/__init__.py
opps/polls/__init__.py
VERSION = (0, 1, 4) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Poll App for Opps CMS" __author__ = u"Bruno Cezar Rocha" __credits__ = [] __email__ = u"rochacbruno@gmail.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS"
VERSION = (0, 1, 4) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Poll App for Opps CMS" __author__ = u"Bruno Cezar Rocha" __credits__ = [] __email__ = u"rochacbruno@gmail.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, Opps Projects"
Fix Copyright application, YACOWS to Opps Projects
Fix Copyright application, YACOWS to Opps Projects
Python
mit
opps/opps-polls,opps/opps-polls
VERSION = (0, 1, 4) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Poll App for Opps CMS" __author__ = u"Bruno Cezar Rocha" __credits__ = [] __email__ = u"rochacbruno@gmail.com" __license__ = u"MIT License" - __copyright__ = u"Copyright 2013, YACOWS" + __copyright__ = u"Copyright 2013, Opps Projects"
Fix Copyright application, YACOWS to Opps Projects
## Code Before: VERSION = (0, 1, 4) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Poll App for Opps CMS" __author__ = u"Bruno Cezar Rocha" __credits__ = [] __email__ = u"rochacbruno@gmail.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS" ## Instruction: Fix Copyright application, YACOWS to Opps Projects ## Code After: VERSION = (0, 1, 4) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Poll App for Opps CMS" __author__ = u"Bruno Cezar Rocha" __credits__ = [] __email__ = u"rochacbruno@gmail.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, Opps Projects"
VERSION = (0, 1, 4) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Poll App for Opps CMS" __author__ = u"Bruno Cezar Rocha" __credits__ = [] __email__ = u"rochacbruno@gmail.com" __license__ = u"MIT License" - __copyright__ = u"Copyright 2013, YACOWS" ? --- ^^ + __copyright__ = u"Copyright 2013, Opps Projects" ? ^^^^^^^^^^^^
c7512104dce2e9ca83e8400b399b4f77113f9368
packs/travisci/actions/lib/action.py
packs/travisci/actions/lib/action.py
import requests from st2actions.runners.pythonrunner import Action API_URL = 'https://api.travis-ci.org' HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json' CONTENT_TYPE = 'application/json' class TravisCI(Action): def _get_auth_headers(self): headers = {} headers['Authorization'] = self.config['Authorization'] headers['Content-Type'] = self.config['Content-Type'] return headers def _perform_request(self, path, method, data=None, requires_auth=False): url = API_URL + path if method == "GET": if requires_auth: headers = self._get_auth_headers() else: headers = {} response = requests.get(url, headers=headers) elif method == 'POST': headers = self._get_auth_headers() response = requests.post(url, headers=headers) elif method == 'PUT': headers = self._get_auth_headers() response = requests.put(url, data=data, headers=headers) return response
import httplib import requests from st2actions.runners.pythonrunner import Action API_URL = 'https://api.travis-ci.org' HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json' CONTENT_TYPE = 'application/json' class TravisCI(Action): def _get_auth_headers(self): headers = {} headers['Authorization'] = self.config['Authorization'] headers['Content-Type'] = self.config['Content-Type'] return headers def _perform_request(self, path, method, data=None, requires_auth=False): url = API_URL + path if method == "GET": if requires_auth: headers = self._get_auth_headers() else: headers = {} response = requests.get(url, headers=headers) elif method == 'POST': headers = self._get_auth_headers() response = requests.post(url, headers=headers) elif method == 'PUT': headers = self._get_auth_headers() response = requests.put(url, data=data, headers=headers) if response.status_code in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: msg = ('Invalid or missing Travis CI auth token. Make sure you have' 'specified valid token in the config file') raise Exception(msg) return response
Throw on invalid / missing credentials.
Throw on invalid / missing credentials.
Python
apache-2.0
pidah/st2contrib,lmEshoo/st2contrib,psychopenguin/st2contrib,psychopenguin/st2contrib,armab/st2contrib,StackStorm/st2contrib,tonybaloney/st2contrib,pidah/st2contrib,pearsontechnology/st2contrib,tonybaloney/st2contrib,StackStorm/st2contrib,pearsontechnology/st2contrib,pidah/st2contrib,armab/st2contrib,armab/st2contrib,StackStorm/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,lmEshoo/st2contrib,pearsontechnology/st2contrib,digideskio/st2contrib,digideskio/st2contrib
+ import httplib + import requests from st2actions.runners.pythonrunner import Action API_URL = 'https://api.travis-ci.org' HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json' CONTENT_TYPE = 'application/json' class TravisCI(Action): def _get_auth_headers(self): headers = {} headers['Authorization'] = self.config['Authorization'] headers['Content-Type'] = self.config['Content-Type'] return headers def _perform_request(self, path, method, data=None, requires_auth=False): url = API_URL + path if method == "GET": if requires_auth: headers = self._get_auth_headers() else: headers = {} response = requests.get(url, headers=headers) elif method == 'POST': headers = self._get_auth_headers() response = requests.post(url, headers=headers) elif method == 'PUT': headers = self._get_auth_headers() response = requests.put(url, data=data, headers=headers) + if response.status_code in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: + msg = ('Invalid or missing Travis CI auth token. Make sure you have' + 'specified valid token in the config file') + raise Exception(msg) + return response
Throw on invalid / missing credentials.
## Code Before: import requests from st2actions.runners.pythonrunner import Action API_URL = 'https://api.travis-ci.org' HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json' CONTENT_TYPE = 'application/json' class TravisCI(Action): def _get_auth_headers(self): headers = {} headers['Authorization'] = self.config['Authorization'] headers['Content-Type'] = self.config['Content-Type'] return headers def _perform_request(self, path, method, data=None, requires_auth=False): url = API_URL + path if method == "GET": if requires_auth: headers = self._get_auth_headers() else: headers = {} response = requests.get(url, headers=headers) elif method == 'POST': headers = self._get_auth_headers() response = requests.post(url, headers=headers) elif method == 'PUT': headers = self._get_auth_headers() response = requests.put(url, data=data, headers=headers) return response ## Instruction: Throw on invalid / missing credentials. ## Code After: import httplib import requests from st2actions.runners.pythonrunner import Action API_URL = 'https://api.travis-ci.org' HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json' CONTENT_TYPE = 'application/json' class TravisCI(Action): def _get_auth_headers(self): headers = {} headers['Authorization'] = self.config['Authorization'] headers['Content-Type'] = self.config['Content-Type'] return headers def _perform_request(self, path, method, data=None, requires_auth=False): url = API_URL + path if method == "GET": if requires_auth: headers = self._get_auth_headers() else: headers = {} response = requests.get(url, headers=headers) elif method == 'POST': headers = self._get_auth_headers() response = requests.post(url, headers=headers) elif method == 'PUT': headers = self._get_auth_headers() response = requests.put(url, data=data, headers=headers) if response.status_code in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: msg = ('Invalid or missing Travis CI auth token. Make sure you have' 'specified valid token in the config file') raise Exception(msg) return response
+ import httplib + import requests from st2actions.runners.pythonrunner import Action API_URL = 'https://api.travis-ci.org' HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json' CONTENT_TYPE = 'application/json' class TravisCI(Action): def _get_auth_headers(self): headers = {} headers['Authorization'] = self.config['Authorization'] headers['Content-Type'] = self.config['Content-Type'] return headers def _perform_request(self, path, method, data=None, requires_auth=False): url = API_URL + path if method == "GET": if requires_auth: headers = self._get_auth_headers() else: headers = {} response = requests.get(url, headers=headers) elif method == 'POST': headers = self._get_auth_headers() response = requests.post(url, headers=headers) elif method == 'PUT': headers = self._get_auth_headers() response = requests.put(url, data=data, headers=headers) + if response.status_code in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: + msg = ('Invalid or missing Travis CI auth token. Make sure you have' + 'specified valid token in the config file') + raise Exception(msg) + return response
c3762443859ada75687e5a62d576fe8140a42a7c
tests/test_csv2iati.py
tests/test_csv2iati.py
import pytest from web_test_base import * class TestCSV2IATI(WebTestBase): requests_to_load = { 'CSV2IATI Homepage': { 'url': 'http://csv2iati.iatistandard.org/' } } def test_contains_links(self, loaded_request): """ Test that each page contains links to the defined URLs. """ result = utility.get_links_from_page(loaded_request) assert "http://iatistandard.org" in result @pytest.mark.parametrize("target_request", ["CSV2IATI Homepage"]) def test_login_form_presence(self, target_request): """ Test that there is a valid login form on the CSV2IATI Homepage. """ req = self.loaded_request_from_test_name(target_request) form_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form' form_action_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/@action' input_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/dl/dd/input' forms = utility.locate_xpath_result(req, form_xpath) form_action = utility.locate_xpath_result(req, form_action_xpath) form_inputs = utility.locate_xpath_result(req, input_xpath) assert len(forms) == 1 assert form_action == ['/login'] assert len(form_inputs) == 3
import pytest from web_test_base import * class TestCSV2IATI(WebTestBase): requests_to_load = { 'CSV2IATI Homepage': { 'url': 'http://csv2iati.iatistandard.org/' } }
Remove redundant csv2iati test now site has been decommissioned
Remove redundant csv2iati test now site has been decommissioned
Python
mit
IATI/IATI-Website-Tests
import pytest from web_test_base import * class TestCSV2IATI(WebTestBase): requests_to_load = { 'CSV2IATI Homepage': { 'url': 'http://csv2iati.iatistandard.org/' } } - def test_contains_links(self, loaded_request): - """ - Test that each page contains links to the defined URLs. - """ - result = utility.get_links_from_page(loaded_request) - - assert "http://iatistandard.org" in result - - @pytest.mark.parametrize("target_request", ["CSV2IATI Homepage"]) - def test_login_form_presence(self, target_request): - """ - Test that there is a valid login form on the CSV2IATI Homepage. - """ - req = self.loaded_request_from_test_name(target_request) - form_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form' - form_action_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/@action' - input_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/dl/dd/input' - - forms = utility.locate_xpath_result(req, form_xpath) - form_action = utility.locate_xpath_result(req, form_action_xpath) - form_inputs = utility.locate_xpath_result(req, input_xpath) - - assert len(forms) == 1 - assert form_action == ['/login'] - assert len(form_inputs) == 3 -
Remove redundant csv2iati test now site has been decommissioned
## Code Before: import pytest from web_test_base import * class TestCSV2IATI(WebTestBase): requests_to_load = { 'CSV2IATI Homepage': { 'url': 'http://csv2iati.iatistandard.org/' } } def test_contains_links(self, loaded_request): """ Test that each page contains links to the defined URLs. """ result = utility.get_links_from_page(loaded_request) assert "http://iatistandard.org" in result @pytest.mark.parametrize("target_request", ["CSV2IATI Homepage"]) def test_login_form_presence(self, target_request): """ Test that there is a valid login form on the CSV2IATI Homepage. """ req = self.loaded_request_from_test_name(target_request) form_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form' form_action_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/@action' input_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/dl/dd/input' forms = utility.locate_xpath_result(req, form_xpath) form_action = utility.locate_xpath_result(req, form_action_xpath) form_inputs = utility.locate_xpath_result(req, input_xpath) assert len(forms) == 1 assert form_action == ['/login'] assert len(form_inputs) == 3 ## Instruction: Remove redundant csv2iati test now site has been decommissioned ## Code After: import pytest from web_test_base import * class TestCSV2IATI(WebTestBase): requests_to_load = { 'CSV2IATI Homepage': { 'url': 'http://csv2iati.iatistandard.org/' } }
import pytest from web_test_base import * class TestCSV2IATI(WebTestBase): requests_to_load = { 'CSV2IATI Homepage': { 'url': 'http://csv2iati.iatistandard.org/' } } - - def test_contains_links(self, loaded_request): - """ - Test that each page contains links to the defined URLs. - """ - result = utility.get_links_from_page(loaded_request) - - assert "http://iatistandard.org" in result - - @pytest.mark.parametrize("target_request", ["CSV2IATI Homepage"]) - def test_login_form_presence(self, target_request): - """ - Test that there is a valid login form on the CSV2IATI Homepage. - """ - req = self.loaded_request_from_test_name(target_request) - form_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form' - form_action_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/@action' - input_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/dl/dd/input' - - forms = utility.locate_xpath_result(req, form_xpath) - form_action = utility.locate_xpath_result(req, form_action_xpath) - form_inputs = utility.locate_xpath_result(req, input_xpath) - - assert len(forms) == 1 - assert form_action == ['/login'] - assert len(form_inputs) == 3
7b939076fba1bb11d0ded504bcf10da457b3d092
scripts/add_identifiers_to_existing_preprints.py
scripts/add_identifiers_to_existing_preprints.py
import logging import time from website.app import init_app from website.identifiers.utils import get_top_level_domain, request_identifiers_from_ezid logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def add_identifiers_to_preprints(): from osf.models import PreprintService preprints_without_identifiers = PreprintService.objects.filter(identifiers__isnull=True) logger.info('About to add identifiers to {} preprints.'.format(preprints_without_identifiers.count())) for preprint in preprints_without_identifiers: logger.info('Saving identifier for preprint {} from source {}'.format(preprint._id, preprint.provider.name)) ezid_response = request_identifiers_from_ezid(preprint) preprint.set_preprint_identifiers(ezid_response) preprint.save() doi = preprint.get_identifier('doi') subdomain = get_top_level_domain(preprint.provider.external_url) assert subdomain.upper() in doi.value assert preprint._id.upper() in doi.value logger.info('Created DOI {} for Preprint from service {}'.format(doi.value, preprint.provider.name)) time.sleep(1) logger.info('Finished Adding identifiers to {} preprints.'.format(preprints_without_identifiers.count())) if __name__ == '__main__': init_app(routes=False) add_identifiers_to_preprints()
import logging import time from website.app import init_app from website.identifiers.utils import request_identifiers_from_ezid logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def add_identifiers_to_preprints(): from osf.models import PreprintService preprints_without_identifiers = PreprintService.objects.filter(identifiers__isnull=True) logger.info('About to add identifiers to {} preprints.'.format(preprints_without_identifiers.count())) for preprint in preprints_without_identifiers: logger.info('Saving identifier for preprint {} from source {}'.format(preprint._id, preprint.provider.name)) ezid_response = request_identifiers_from_ezid(preprint) preprint.set_preprint_identifiers(ezid_response) preprint.save() doi = preprint.get_identifier('doi') assert preprint._id.upper() in doi.value logger.info('Created DOI {} for Preprint with guid {} from service {}'.format(doi.value, preprint._id, preprint.provider.name)) time.sleep(1) logger.info('Finished Adding identifiers to {} preprints.'.format(preprints_without_identifiers.count())) if __name__ == '__main__': init_app(routes=False) add_identifiers_to_preprints()
Remove check for domain in DOI
Remove check for domain in DOI
Python
apache-2.0
mattclark/osf.io,crcresearch/osf.io,aaxelb/osf.io,saradbowman/osf.io,adlius/osf.io,mattclark/osf.io,laurenrevere/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,leb2dg/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io,sloria/osf.io,mfraezz/osf.io,chrisseto/osf.io,pattisdr/osf.io,sloria/osf.io,adlius/osf.io,felliott/osf.io,cslzchen/osf.io,laurenrevere/osf.io,crcresearch/osf.io,saradbowman/osf.io,sloria/osf.io,felliott/osf.io,binoculars/osf.io,caneruguz/osf.io,pattisdr/osf.io,Johnetordoff/osf.io,TomBaxter/osf.io,icereval/osf.io,CenterForOpenScience/osf.io,chrisseto/osf.io,chennan47/osf.io,HalcyonChimera/osf.io,mfraezz/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,caseyrollins/osf.io,crcresearch/osf.io,adlius/osf.io,erinspace/osf.io,aaxelb/osf.io,baylee-d/osf.io,icereval/osf.io,cwisecarver/osf.io,HalcyonChimera/osf.io,caseyrollins/osf.io,Johnetordoff/osf.io,icereval/osf.io,chennan47/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,cwisecarver/osf.io,caneruguz/osf.io,cslzchen/osf.io,mfraezz/osf.io,baylee-d/osf.io,brianjgeiger/osf.io,leb2dg/osf.io,felliott/osf.io,TomBaxter/osf.io,TomBaxter/osf.io,HalcyonChimera/osf.io,caseyrollins/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,binoculars/osf.io,chennan47/osf.io,erinspace/osf.io,caneruguz/osf.io,brianjgeiger/osf.io,pattisdr/osf.io,caneruguz/osf.io,chrisseto/osf.io,leb2dg/osf.io,Johnetordoff/osf.io,binoculars/osf.io,cwisecarver/osf.io,brianjgeiger/osf.io,erinspace/osf.io,mattclark/osf.io,baylee-d/osf.io,chrisseto/osf.io,laurenrevere/osf.io,cwisecarver/osf.io,felliott/osf.io,cslzchen/osf.io,leb2dg/osf.io
import logging import time from website.app import init_app - from website.identifiers.utils import get_top_level_domain, request_identifiers_from_ezid + from website.identifiers.utils import request_identifiers_from_ezid logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def add_identifiers_to_preprints(): from osf.models import PreprintService preprints_without_identifiers = PreprintService.objects.filter(identifiers__isnull=True) logger.info('About to add identifiers to {} preprints.'.format(preprints_without_identifiers.count())) for preprint in preprints_without_identifiers: logger.info('Saving identifier for preprint {} from source {}'.format(preprint._id, preprint.provider.name)) ezid_response = request_identifiers_from_ezid(preprint) preprint.set_preprint_identifiers(ezid_response) preprint.save() doi = preprint.get_identifier('doi') - subdomain = get_top_level_domain(preprint.provider.external_url) - assert subdomain.upper() in doi.value assert preprint._id.upper() in doi.value - logger.info('Created DOI {} for Preprint from service {}'.format(doi.value, preprint.provider.name)) + logger.info('Created DOI {} for Preprint with guid {} from service {}'.format(doi.value, preprint._id, preprint.provider.name)) time.sleep(1) logger.info('Finished Adding identifiers to {} preprints.'.format(preprints_without_identifiers.count())) if __name__ == '__main__': init_app(routes=False) add_identifiers_to_preprints()
Remove check for domain in DOI
## Code Before: import logging import time from website.app import init_app from website.identifiers.utils import get_top_level_domain, request_identifiers_from_ezid logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def add_identifiers_to_preprints(): from osf.models import PreprintService preprints_without_identifiers = PreprintService.objects.filter(identifiers__isnull=True) logger.info('About to add identifiers to {} preprints.'.format(preprints_without_identifiers.count())) for preprint in preprints_without_identifiers: logger.info('Saving identifier for preprint {} from source {}'.format(preprint._id, preprint.provider.name)) ezid_response = request_identifiers_from_ezid(preprint) preprint.set_preprint_identifiers(ezid_response) preprint.save() doi = preprint.get_identifier('doi') subdomain = get_top_level_domain(preprint.provider.external_url) assert subdomain.upper() in doi.value assert preprint._id.upper() in doi.value logger.info('Created DOI {} for Preprint from service {}'.format(doi.value, preprint.provider.name)) time.sleep(1) logger.info('Finished Adding identifiers to {} preprints.'.format(preprints_without_identifiers.count())) if __name__ == '__main__': init_app(routes=False) add_identifiers_to_preprints() ## Instruction: Remove check for domain in DOI ## Code After: import logging import time from website.app import init_app from website.identifiers.utils import request_identifiers_from_ezid logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def add_identifiers_to_preprints(): from osf.models import PreprintService preprints_without_identifiers = PreprintService.objects.filter(identifiers__isnull=True) logger.info('About to add identifiers to {} preprints.'.format(preprints_without_identifiers.count())) for preprint in preprints_without_identifiers: logger.info('Saving identifier for preprint {} from source {}'.format(preprint._id, preprint.provider.name)) ezid_response = request_identifiers_from_ezid(preprint) preprint.set_preprint_identifiers(ezid_response) preprint.save() doi = preprint.get_identifier('doi') assert preprint._id.upper() in doi.value logger.info('Created DOI {} for Preprint with guid {} from service {}'.format(doi.value, preprint._id, preprint.provider.name)) time.sleep(1) logger.info('Finished Adding identifiers to {} preprints.'.format(preprints_without_identifiers.count())) if __name__ == '__main__': init_app(routes=False) add_identifiers_to_preprints()
import logging import time from website.app import init_app - from website.identifiers.utils import get_top_level_domain, request_identifiers_from_ezid ? ---------------------- + from website.identifiers.utils import request_identifiers_from_ezid logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def add_identifiers_to_preprints(): from osf.models import PreprintService preprints_without_identifiers = PreprintService.objects.filter(identifiers__isnull=True) logger.info('About to add identifiers to {} preprints.'.format(preprints_without_identifiers.count())) for preprint in preprints_without_identifiers: logger.info('Saving identifier for preprint {} from source {}'.format(preprint._id, preprint.provider.name)) ezid_response = request_identifiers_from_ezid(preprint) preprint.set_preprint_identifiers(ezid_response) preprint.save() doi = preprint.get_identifier('doi') - subdomain = get_top_level_domain(preprint.provider.external_url) - assert subdomain.upper() in doi.value assert preprint._id.upper() in doi.value - logger.info('Created DOI {} for Preprint from service {}'.format(doi.value, preprint.provider.name)) + logger.info('Created DOI {} for Preprint with guid {} from service {}'.format(doi.value, preprint._id, preprint.provider.name)) ? +++++++++++++ ++++++++++++++ time.sleep(1) logger.info('Finished Adding identifiers to {} preprints.'.format(preprints_without_identifiers.count())) if __name__ == '__main__': init_app(routes=False) add_identifiers_to_preprints()
da466b391470333492a56395569812653ed6658f
compose/cli/__init__.py
compose/cli/__init__.py
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import subprocess import sys # Attempt to detect https://github.com/docker/compose/issues/4344 try: # We don't try importing pip because it messes with package imports # on some Linux distros (Ubuntu, Fedora) # https://github.com/docker/compose/issues/4425 # https://github.com/docker/compose/issues/4481 # https://github.com/pypa/pip/blob/master/pip/_vendor/__init__.py s_cmd = subprocess.Popen( ['pip', 'freeze'], stderr=subprocess.PIPE, stdout=subprocess.PIPE ) packages = s_cmd.communicate()[0].splitlines() dockerpy_installed = len( list(filter(lambda p: p.startswith(b'docker-py=='), packages)) ) > 0 if dockerpy_installed: from .colors import red print( red('ERROR:'), "Dependency conflict: an older version of the 'docker-py' package " "is polluting the namespace. " "Run the following command to remedy the issue:\n" "pip uninstall docker docker-py; pip install docker", file=sys.stderr ) sys.exit(1) except OSError: # pip command is not available, which indicates it's probably the binary # distribution of Compose which is not affected pass
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import subprocess import sys # Attempt to detect https://github.com/docker/compose/issues/4344 try: # We don't try importing pip because it messes with package imports # on some Linux distros (Ubuntu, Fedora) # https://github.com/docker/compose/issues/4425 # https://github.com/docker/compose/issues/4481 # https://github.com/pypa/pip/blob/master/pip/_vendor/__init__.py s_cmd = subprocess.Popen( ['pip', 'freeze'], stderr=subprocess.PIPE, stdout=subprocess.PIPE ) packages = s_cmd.communicate()[0].splitlines() dockerpy_installed = len( list(filter(lambda p: p.startswith(b'docker-py=='), packages)) ) > 0 if dockerpy_installed: from .colors import yellow print( yellow('WARNING:'), "Dependency conflict: an older version of the 'docker-py' package " "may be polluting the namespace. " "If you're experiencing crashes, run the following command to remedy the issue:\n" "pip uninstall docker-py; pip uninstall docker; pip install docker", file=sys.stderr ) except OSError: # pip command is not available, which indicates it's probably the binary # distribution of Compose which is not affected pass
Change docker-py dependency error to a warning, update fix command
Change docker-py dependency error to a warning, update fix command Signed-off-by: Joffrey F <2e95f49799afcec0080c0aeb8813776d949e0768@docker.com>
Python
apache-2.0
thaJeztah/compose,shin-/compose,vdemeester/compose,sdurrheimer/compose,sdurrheimer/compose,schmunk42/compose,hoogenm/compose,jrabbit/compose,dnephin/compose,dnephin/compose,schmunk42/compose,swoopla/compose,funkyfuture/docker-compose,shin-/compose,thaJeztah/compose,hoogenm/compose,funkyfuture/docker-compose,jrabbit/compose,swoopla/compose,vdemeester/compose
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import subprocess import sys # Attempt to detect https://github.com/docker/compose/issues/4344 try: # We don't try importing pip because it messes with package imports # on some Linux distros (Ubuntu, Fedora) # https://github.com/docker/compose/issues/4425 # https://github.com/docker/compose/issues/4481 # https://github.com/pypa/pip/blob/master/pip/_vendor/__init__.py s_cmd = subprocess.Popen( ['pip', 'freeze'], stderr=subprocess.PIPE, stdout=subprocess.PIPE ) packages = s_cmd.communicate()[0].splitlines() dockerpy_installed = len( list(filter(lambda p: p.startswith(b'docker-py=='), packages)) ) > 0 if dockerpy_installed: - from .colors import red + from .colors import yellow print( - red('ERROR:'), + yellow('WARNING:'), "Dependency conflict: an older version of the 'docker-py' package " - "is polluting the namespace. " + "may be polluting the namespace. " - "Run the following command to remedy the issue:\n" + "If you're experiencing crashes, run the following command to remedy the issue:\n" - "pip uninstall docker docker-py; pip install docker", + "pip uninstall docker-py; pip uninstall docker; pip install docker", file=sys.stderr ) - sys.exit(1) except OSError: # pip command is not available, which indicates it's probably the binary # distribution of Compose which is not affected pass
Change docker-py dependency error to a warning, update fix command
## Code Before: from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import subprocess import sys # Attempt to detect https://github.com/docker/compose/issues/4344 try: # We don't try importing pip because it messes with package imports # on some Linux distros (Ubuntu, Fedora) # https://github.com/docker/compose/issues/4425 # https://github.com/docker/compose/issues/4481 # https://github.com/pypa/pip/blob/master/pip/_vendor/__init__.py s_cmd = subprocess.Popen( ['pip', 'freeze'], stderr=subprocess.PIPE, stdout=subprocess.PIPE ) packages = s_cmd.communicate()[0].splitlines() dockerpy_installed = len( list(filter(lambda p: p.startswith(b'docker-py=='), packages)) ) > 0 if dockerpy_installed: from .colors import red print( red('ERROR:'), "Dependency conflict: an older version of the 'docker-py' package " "is polluting the namespace. " "Run the following command to remedy the issue:\n" "pip uninstall docker docker-py; pip install docker", file=sys.stderr ) sys.exit(1) except OSError: # pip command is not available, which indicates it's probably the binary # distribution of Compose which is not affected pass ## Instruction: Change docker-py dependency error to a warning, update fix command ## Code After: from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import subprocess import sys # Attempt to detect https://github.com/docker/compose/issues/4344 try: # We don't try importing pip because it messes with package imports # on some Linux distros (Ubuntu, Fedora) # https://github.com/docker/compose/issues/4425 # https://github.com/docker/compose/issues/4481 # https://github.com/pypa/pip/blob/master/pip/_vendor/__init__.py s_cmd = subprocess.Popen( ['pip', 'freeze'], stderr=subprocess.PIPE, stdout=subprocess.PIPE ) packages = s_cmd.communicate()[0].splitlines() dockerpy_installed = len( list(filter(lambda p: p.startswith(b'docker-py=='), packages)) ) > 0 if dockerpy_installed: from .colors import yellow print( yellow('WARNING:'), "Dependency conflict: an older version of the 'docker-py' package " "may be polluting the namespace. " "If you're experiencing crashes, run the following command to remedy the issue:\n" "pip uninstall docker-py; pip uninstall docker; pip install docker", file=sys.stderr ) except OSError: # pip command is not available, which indicates it's probably the binary # distribution of Compose which is not affected pass
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import subprocess import sys # Attempt to detect https://github.com/docker/compose/issues/4344 try: # We don't try importing pip because it messes with package imports # on some Linux distros (Ubuntu, Fedora) # https://github.com/docker/compose/issues/4425 # https://github.com/docker/compose/issues/4481 # https://github.com/pypa/pip/blob/master/pip/_vendor/__init__.py s_cmd = subprocess.Popen( ['pip', 'freeze'], stderr=subprocess.PIPE, stdout=subprocess.PIPE ) packages = s_cmd.communicate()[0].splitlines() dockerpy_installed = len( list(filter(lambda p: p.startswith(b'docker-py=='), packages)) ) > 0 if dockerpy_installed: - from .colors import red ? ^ ^ + from .colors import yellow ? ^ ^^^^ print( - red('ERROR:'), + yellow('WARNING:'), "Dependency conflict: an older version of the 'docker-py' package " - "is polluting the namespace. " ? ^^ + "may be polluting the namespace. " ? ^^^^^^ - "Run the following command to remedy the issue:\n" ? ^ + "If you're experiencing crashes, run the following command to remedy the issue:\n" ? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - "pip uninstall docker docker-py; pip install docker", ? --- + "pip uninstall docker-py; pip uninstall docker; pip install docker", ? ++++++++++++++++++ file=sys.stderr ) - sys.exit(1) except OSError: # pip command is not available, which indicates it's probably the binary # distribution of Compose which is not affected pass
d4033694f7686fe1ad48a185ae740c4d966d40d8
classes/dnsresolver.py
classes/dnsresolver.py
import dns import dns.resolver import dns.rdatatype from typing import Union, List class DNSResolver(dns.resolver.Resolver): def __init__(self, filename='/etc/resolv.conf', configure=False, nameservers: Union[str, List[str]] = None): # Run the dns.resolver.Resolver superclass init call to configure # the object. Then, depending on the value in configure argument, # do something with the nameservers argument, which is unique to this # class object instead. super(DNSResolver, self).__init__(filename, configure) if not configure: if isinstance(nameservers, str): self.nameservers = [nameservers] elif isinstance(nameservers, list): self.nameservers = nameservers else: self.nameservers = ['8.8.8.8, 8.8.4.4'] def dns_resolve(domain: str, resolver: DNSResolver = DNSResolver(configure=True)) -> list: addrs = [] for answer in resolver.query(domain, 'A').response.answer: for item in answer: addrs.append(item.address) for answer in resolver.query(domain, 'AAAA').response.answer: for item in answer: addrs.append(item.address) return addrs
import dns import dns.resolver import dns.rdatatype from typing import Union, List class DNSResolver(dns.resolver.Resolver): def __init__(self, filename='/etc/resolv.conf', configure=False, nameservers: Union[str, List[str]] = None): # Run the dns.resolver.Resolver superclass init call to configure # the object. Then, depending on the value in configure argument, # do something with the nameservers argument, which is unique to this # class object instead. super(DNSResolver, self).__init__(filename, configure) if not configure: if isinstance(nameservers, str): self.nameservers = [nameservers] elif isinstance(nameservers, list): self.nameservers = nameservers else: self.nameservers = ['8.8.8.8, 8.8.4.4'] def dns_resolve(domain: str, resolver: DNSResolver = DNSResolver(configure=True)) -> list: addrs = [] try: for answer in resolver.query(domain, 'A').response.answer: for item in answer: if item.rdtype == dns.rdatatype.A: addrs.append(item.address) except dns.resolver.NoAnswer: pass try: for answer in resolver.query(domain, 'AAAA').response.answer: for item in answer: if item.rdtype == dns.rdatatype.AAAA: addrs.append(item.address) except dns.resolver.NoAnswer: pass return addrs
Implement rdatatype-aware and NoAnswer-aware DNS handling
Implement rdatatype-aware and NoAnswer-aware DNS handling This will work for CNAME entries because CNAMEs hit by A or AAAA lookups behave like `dig` does - they will trigger a second resultset for the CNAME entry in order to return the IP address. This also is amended to handle a "NoAnswer" response - i.e. if there are no IPv4 or IPv6 addresses for a given CNAME or records lookup. The list will therefore have all the CNAME-resolved IP addresses as independent strings.
Python
apache-2.0
Charcoal-SE/SmokeDetector,Charcoal-SE/SmokeDetector
import dns import dns.resolver import dns.rdatatype from typing import Union, List class DNSResolver(dns.resolver.Resolver): def __init__(self, filename='/etc/resolv.conf', configure=False, nameservers: Union[str, List[str]] = None): # Run the dns.resolver.Resolver superclass init call to configure # the object. Then, depending on the value in configure argument, # do something with the nameservers argument, which is unique to this # class object instead. super(DNSResolver, self).__init__(filename, configure) if not configure: if isinstance(nameservers, str): self.nameservers = [nameservers] elif isinstance(nameservers, list): self.nameservers = nameservers else: self.nameservers = ['8.8.8.8, 8.8.4.4'] def dns_resolve(domain: str, resolver: DNSResolver = DNSResolver(configure=True)) -> list: addrs = [] + try: - for answer in resolver.query(domain, 'A').response.answer: + for answer in resolver.query(domain, 'A').response.answer: - for item in answer: + for item in answer: + if item.rdtype == dns.rdatatype.A: - addrs.append(item.address) + addrs.append(item.address) + except dns.resolver.NoAnswer: + pass + try: - for answer in resolver.query(domain, 'AAAA').response.answer: + for answer in resolver.query(domain, 'AAAA').response.answer: - for item in answer: + for item in answer: + if item.rdtype == dns.rdatatype.AAAA: - addrs.append(item.address) + addrs.append(item.address) + except dns.resolver.NoAnswer: + pass return addrs
Implement rdatatype-aware and NoAnswer-aware DNS handling
## Code Before: import dns import dns.resolver import dns.rdatatype from typing import Union, List class DNSResolver(dns.resolver.Resolver): def __init__(self, filename='/etc/resolv.conf', configure=False, nameservers: Union[str, List[str]] = None): # Run the dns.resolver.Resolver superclass init call to configure # the object. Then, depending on the value in configure argument, # do something with the nameservers argument, which is unique to this # class object instead. super(DNSResolver, self).__init__(filename, configure) if not configure: if isinstance(nameservers, str): self.nameservers = [nameservers] elif isinstance(nameservers, list): self.nameservers = nameservers else: self.nameservers = ['8.8.8.8, 8.8.4.4'] def dns_resolve(domain: str, resolver: DNSResolver = DNSResolver(configure=True)) -> list: addrs = [] for answer in resolver.query(domain, 'A').response.answer: for item in answer: addrs.append(item.address) for answer in resolver.query(domain, 'AAAA').response.answer: for item in answer: addrs.append(item.address) return addrs ## Instruction: Implement rdatatype-aware and NoAnswer-aware DNS handling ## Code After: import dns import dns.resolver import dns.rdatatype from typing import Union, List class DNSResolver(dns.resolver.Resolver): def __init__(self, filename='/etc/resolv.conf', configure=False, nameservers: Union[str, List[str]] = None): # Run the dns.resolver.Resolver superclass init call to configure # the object. Then, depending on the value in configure argument, # do something with the nameservers argument, which is unique to this # class object instead. super(DNSResolver, self).__init__(filename, configure) if not configure: if isinstance(nameservers, str): self.nameservers = [nameservers] elif isinstance(nameservers, list): self.nameservers = nameservers else: self.nameservers = ['8.8.8.8, 8.8.4.4'] def dns_resolve(domain: str, resolver: DNSResolver = DNSResolver(configure=True)) -> list: addrs = [] try: for answer in resolver.query(domain, 'A').response.answer: for item in answer: if item.rdtype == dns.rdatatype.A: addrs.append(item.address) except dns.resolver.NoAnswer: pass try: for answer in resolver.query(domain, 'AAAA').response.answer: for item in answer: if item.rdtype == dns.rdatatype.AAAA: addrs.append(item.address) except dns.resolver.NoAnswer: pass return addrs
import dns import dns.resolver import dns.rdatatype from typing import Union, List class DNSResolver(dns.resolver.Resolver): def __init__(self, filename='/etc/resolv.conf', configure=False, nameservers: Union[str, List[str]] = None): # Run the dns.resolver.Resolver superclass init call to configure # the object. Then, depending on the value in configure argument, # do something with the nameservers argument, which is unique to this # class object instead. super(DNSResolver, self).__init__(filename, configure) if not configure: if isinstance(nameservers, str): self.nameservers = [nameservers] elif isinstance(nameservers, list): self.nameservers = nameservers else: self.nameservers = ['8.8.8.8, 8.8.4.4'] def dns_resolve(domain: str, resolver: DNSResolver = DNSResolver(configure=True)) -> list: addrs = [] + try: - for answer in resolver.query(domain, 'A').response.answer: + for answer in resolver.query(domain, 'A').response.answer: ? ++++ - for item in answer: + for item in answer: ? ++++ + if item.rdtype == dns.rdatatype.A: - addrs.append(item.address) + addrs.append(item.address) ? ++++++++ + except dns.resolver.NoAnswer: + pass + try: - for answer in resolver.query(domain, 'AAAA').response.answer: + for answer in resolver.query(domain, 'AAAA').response.answer: ? ++++ - for item in answer: + for item in answer: ? ++++ + if item.rdtype == dns.rdatatype.AAAA: - addrs.append(item.address) + addrs.append(item.address) ? ++++++++ + except dns.resolver.NoAnswer: + pass return addrs
e081646028e4f3283fb9c7278fed89c3e42cc4d3
server/tests/api/test_user_api.py
server/tests/api/test_user_api.py
import json from tests.helpers import FlaskTestCase, fixtures class TestUserAPI(FlaskTestCase): @fixtures('base.json') def test_get_empty_users(self): """Test GET /api/users endpoint with no data""" response = self.test_client.get('/api/users') assert response.status_code is 200 def test_get_one_user(self): """Test GET /api/users endpoint with a single user""" def test_get_multiple_users(self): """Test GET /api/users endpoint with multple users""" def test_get_no_user_by_id(self): """Test GET /api/users/(int:id) for missing user""" def test_user_by_id(self): """Test GET /api/users(int:id) for existing user""" @fixtures('base.json') def test_post_user(self): data = { 'name': 'Giancarlo Anemone', 'username': 'ganemone', 'email': 'ganemone@gmail.com', 'password': 'password', 'confirm': 'password' } response = self.app.post( '/api/users', data=json.dumps(data) ) assert response.status_code is 201
import json from tests.helpers import FlaskTestCase, fixtures class TestUserAPI(FlaskTestCase): @fixtures('base.json') def test_get_empty_users(self): """Test GET /api/users endpoint with no data""" response, data = self.api_request('get', '/api/users') assert data['num_results'] is 0 assert response.status_code is 200 @fixtures('single_user.json') def test_get_one_user(self): """Test GET /api/users endpoint with a single user""" response, data = self.api_request('get', '/api/users') assert data['num_results'] is 1 assert response.status_code is 200 @fixtures('many_users.json') def test_get_multiple_users(self): """Test GET /api/users endpoint with multple users""" @fixtures('many_users.json') def test_get_no_user_by_id(self): """Test GET /api/users/(int:id) for missing user""" @fixtures('many_users.json') def test_user_by_id(self): """Test GET /api/users(int:id) for existing user""" @fixtures('base.json') def test_post_user(self): data = { 'name': 'Giancarlo Anemone', 'username': 'ganemone', 'email': 'ganemone@gmail.com', 'password': 'password', 'confirm': 'password' } response = self.app.post( '/api/users', data=json.dumps(data) ) assert response.status_code is 201
Implement tests for getting empty users list and single user list
Implement tests for getting empty users list and single user list
Python
mit
ganemone/ontheside,ganemone/ontheside,ganemone/ontheside
import json from tests.helpers import FlaskTestCase, fixtures class TestUserAPI(FlaskTestCase): @fixtures('base.json') def test_get_empty_users(self): """Test GET /api/users endpoint with no data""" - response = self.test_client.get('/api/users') + response, data = self.api_request('get', '/api/users') + assert data['num_results'] is 0 assert response.status_code is 200 + @fixtures('single_user.json') def test_get_one_user(self): """Test GET /api/users endpoint with a single user""" + response, data = self.api_request('get', '/api/users') + assert data['num_results'] is 1 + assert response.status_code is 200 + @fixtures('many_users.json') def test_get_multiple_users(self): """Test GET /api/users endpoint with multple users""" + @fixtures('many_users.json') def test_get_no_user_by_id(self): """Test GET /api/users/(int:id) for missing user""" + @fixtures('many_users.json') def test_user_by_id(self): """Test GET /api/users(int:id) for existing user""" @fixtures('base.json') def test_post_user(self): data = { 'name': 'Giancarlo Anemone', 'username': 'ganemone', 'email': 'ganemone@gmail.com', 'password': 'password', 'confirm': 'password' } response = self.app.post( '/api/users', data=json.dumps(data) ) assert response.status_code is 201
Implement tests for getting empty users list and single user list
## Code Before: import json from tests.helpers import FlaskTestCase, fixtures class TestUserAPI(FlaskTestCase): @fixtures('base.json') def test_get_empty_users(self): """Test GET /api/users endpoint with no data""" response = self.test_client.get('/api/users') assert response.status_code is 200 def test_get_one_user(self): """Test GET /api/users endpoint with a single user""" def test_get_multiple_users(self): """Test GET /api/users endpoint with multple users""" def test_get_no_user_by_id(self): """Test GET /api/users/(int:id) for missing user""" def test_user_by_id(self): """Test GET /api/users(int:id) for existing user""" @fixtures('base.json') def test_post_user(self): data = { 'name': 'Giancarlo Anemone', 'username': 'ganemone', 'email': 'ganemone@gmail.com', 'password': 'password', 'confirm': 'password' } response = self.app.post( '/api/users', data=json.dumps(data) ) assert response.status_code is 201 ## Instruction: Implement tests for getting empty users list and single user list ## Code After: import json from tests.helpers import FlaskTestCase, fixtures class TestUserAPI(FlaskTestCase): @fixtures('base.json') def test_get_empty_users(self): """Test GET /api/users endpoint with no data""" response, data = self.api_request('get', '/api/users') assert data['num_results'] is 0 assert response.status_code is 200 @fixtures('single_user.json') def test_get_one_user(self): """Test GET /api/users endpoint with a single user""" response, data = self.api_request('get', '/api/users') assert data['num_results'] is 1 assert response.status_code is 200 @fixtures('many_users.json') def test_get_multiple_users(self): """Test GET /api/users endpoint with multple users""" @fixtures('many_users.json') def test_get_no_user_by_id(self): """Test GET /api/users/(int:id) for missing user""" @fixtures('many_users.json') def test_user_by_id(self): """Test GET /api/users(int:id) for existing user""" @fixtures('base.json') def test_post_user(self): data = { 'name': 'Giancarlo Anemone', 'username': 'ganemone', 'email': 'ganemone@gmail.com', 'password': 'password', 'confirm': 'password' } response = self.app.post( '/api/users', data=json.dumps(data) ) assert response.status_code is 201
import json from tests.helpers import FlaskTestCase, fixtures class TestUserAPI(FlaskTestCase): @fixtures('base.json') def test_get_empty_users(self): """Test GET /api/users endpoint with no data""" - response = self.test_client.get('/api/users') + response, data = self.api_request('get', '/api/users') + assert data['num_results'] is 0 assert response.status_code is 200 + @fixtures('single_user.json') def test_get_one_user(self): """Test GET /api/users endpoint with a single user""" + response, data = self.api_request('get', '/api/users') + assert data['num_results'] is 1 + assert response.status_code is 200 + @fixtures('many_users.json') def test_get_multiple_users(self): """Test GET /api/users endpoint with multple users""" + @fixtures('many_users.json') def test_get_no_user_by_id(self): """Test GET /api/users/(int:id) for missing user""" + @fixtures('many_users.json') def test_user_by_id(self): """Test GET /api/users(int:id) for existing user""" @fixtures('base.json') def test_post_user(self): data = { 'name': 'Giancarlo Anemone', 'username': 'ganemone', 'email': 'ganemone@gmail.com', 'password': 'password', 'confirm': 'password' } response = self.app.post( '/api/users', data=json.dumps(data) ) assert response.status_code is 201
f3875b1d9aed5f847b11846a27f7652e4c548b6c
modules/karma.py
modules/karma.py
import discord from modules.botModule import BotModule class Karma(BotModule): name = 'karma' description = 'Monitors messages for reactions and adds karma accordingly.' help_text = 'This module has no callable functions' trigger_string = '!reddit' listen_for_reaction = True async def parse_command(self, message, client): pass async def on_reaction(self, reaction, client): print("karma_action triggered") msg = "I saw that!" + reaction.message.author.name + reaction.emoji await client.send_message(reaction.message.channel, msg)
import discord from modules.botModule import BotModule class Karma(BotModule): name = 'karma' description = 'Monitors messages for reactions and adds karma accordingly.' help_text = 'This module has no callable functions' trigger_string = '!reddit' module_db = 'karma.json' module_version = '0.1.0' listen_for_reaction = True async def parse_command(self, message, client): pass async def on_reaction(self, reaction, client): target_user = self.module_db.Query() if self.module_db.get(target_user.userid == reaction.message.author.id) == None: self.module_db.insert({'userid': reaction.message.author.id, 'karma': 1}) msg = 'New entry for ' + reaction.message.author.id + ' added.' await client.send_message(reaction.message.channel, msg) else: new_karma = self.module_db.get(target_user.userid == reaction.message.author.id)['karma'] + 1 self.module_db.update({'karma': new_karma}, target_user.userid == reaction.message.author.id) msg = 'Karma for ' + reaction.message.author.id + ' updated to ' + new_karma await client.send_message(reaction.message.channel, msg) #msg = "I saw that!" + reaction.message.author.name + reaction.emoji #await client.send_message(reaction.message.channel, msg)
Add logic and code for database operations (untested)
Add logic and code for database operations (untested)
Python
mit
suclearnub/scubot
import discord from modules.botModule import BotModule class Karma(BotModule): name = 'karma' description = 'Monitors messages for reactions and adds karma accordingly.' help_text = 'This module has no callable functions' trigger_string = '!reddit' + module_db = 'karma.json' + + module_version = '0.1.0' + listen_for_reaction = True async def parse_command(self, message, client): pass async def on_reaction(self, reaction, client): - print("karma_action triggered") - msg = "I saw that!" + reaction.message.author.name + reaction.emoji - await client.send_message(reaction.message.channel, msg) + target_user = self.module_db.Query() + if self.module_db.get(target_user.userid == reaction.message.author.id) == None: + self.module_db.insert({'userid': reaction.message.author.id, 'karma': 1}) + msg = 'New entry for ' + reaction.message.author.id + ' added.' + await client.send_message(reaction.message.channel, msg) + else: + new_karma = self.module_db.get(target_user.userid == reaction.message.author.id)['karma'] + 1 + self.module_db.update({'karma': new_karma}, target_user.userid == reaction.message.author.id) + + msg = 'Karma for ' + reaction.message.author.id + ' updated to ' + new_karma + await client.send_message(reaction.message.channel, msg) + + #msg = "I saw that!" + reaction.message.author.name + reaction.emoji + #await client.send_message(reaction.message.channel, msg) +
Add logic and code for database operations (untested)
## Code Before: import discord from modules.botModule import BotModule class Karma(BotModule): name = 'karma' description = 'Monitors messages for reactions and adds karma accordingly.' help_text = 'This module has no callable functions' trigger_string = '!reddit' listen_for_reaction = True async def parse_command(self, message, client): pass async def on_reaction(self, reaction, client): print("karma_action triggered") msg = "I saw that!" + reaction.message.author.name + reaction.emoji await client.send_message(reaction.message.channel, msg) ## Instruction: Add logic and code for database operations (untested) ## Code After: import discord from modules.botModule import BotModule class Karma(BotModule): name = 'karma' description = 'Monitors messages for reactions and adds karma accordingly.' help_text = 'This module has no callable functions' trigger_string = '!reddit' module_db = 'karma.json' module_version = '0.1.0' listen_for_reaction = True async def parse_command(self, message, client): pass async def on_reaction(self, reaction, client): target_user = self.module_db.Query() if self.module_db.get(target_user.userid == reaction.message.author.id) == None: self.module_db.insert({'userid': reaction.message.author.id, 'karma': 1}) msg = 'New entry for ' + reaction.message.author.id + ' added.' await client.send_message(reaction.message.channel, msg) else: new_karma = self.module_db.get(target_user.userid == reaction.message.author.id)['karma'] + 1 self.module_db.update({'karma': new_karma}, target_user.userid == reaction.message.author.id) msg = 'Karma for ' + reaction.message.author.id + ' updated to ' + new_karma await client.send_message(reaction.message.channel, msg) #msg = "I saw that!" + reaction.message.author.name + reaction.emoji #await client.send_message(reaction.message.channel, msg)
import discord from modules.botModule import BotModule class Karma(BotModule): name = 'karma' description = 'Monitors messages for reactions and adds karma accordingly.' help_text = 'This module has no callable functions' trigger_string = '!reddit' + module_db = 'karma.json' + + module_version = '0.1.0' + listen_for_reaction = True async def parse_command(self, message, client): pass async def on_reaction(self, reaction, client): - print("karma_action triggered") + target_user = self.module_db.Query() + if self.module_db.get(target_user.userid == reaction.message.author.id) == None: + self.module_db.insert({'userid': reaction.message.author.id, 'karma': 1}) + + msg = 'New entry for ' + reaction.message.author.id + ' added.' + await client.send_message(reaction.message.channel, msg) + else: + new_karma = self.module_db.get(target_user.userid == reaction.message.author.id)['karma'] + 1 + self.module_db.update({'karma': new_karma}, target_user.userid == reaction.message.author.id) + + msg = 'Karma for ' + reaction.message.author.id + ' updated to ' + new_karma + await client.send_message(reaction.message.channel, msg) + - msg = "I saw that!" + reaction.message.author.name + reaction.emoji + #msg = "I saw that!" + reaction.message.author.name + reaction.emoji ? + - await client.send_message(reaction.message.channel, msg) + #await client.send_message(reaction.message.channel, msg) ? +
60a90722fbd5fc047fee5e9f7377f03e11f6a654
examples/root_finding/test_funcs.py
examples/root_finding/test_funcs.py
import math def f1(x): """ Test function 1 """ return x*x*x - math.pi*x + math.e/100
import numpy as npy def f1(x): """ Test function 1 """ return x*x*x - npy.pi*x + npy.e/100 def f2(x): """ Test function 2 """ return -1.13 + npy.tanh(x-2) + 4*npy.exp(-x)*npy.sin((1/8.)*x**3) \ *x + .1*npy.exp((1/35.)*x)
Use numpy instead of math to allow vectorization
Use numpy instead of math to allow vectorization
Python
bsd-3-clause
robclewley/fovea,akuefler/fovea
- import math + import numpy as npy def f1(x): """ Test function 1 """ - return x*x*x - math.pi*x + math.e/100 + return x*x*x - npy.pi*x + npy.e/100 + def f2(x): + """ + Test function 2 + """ + return -1.13 + npy.tanh(x-2) + 4*npy.exp(-x)*npy.sin((1/8.)*x**3) \ + *x + .1*npy.exp((1/35.)*x)
Use numpy instead of math to allow vectorization
## Code Before: import math def f1(x): """ Test function 1 """ return x*x*x - math.pi*x + math.e/100 ## Instruction: Use numpy instead of math to allow vectorization ## Code After: import numpy as npy def f1(x): """ Test function 1 """ return x*x*x - npy.pi*x + npy.e/100 def f2(x): """ Test function 2 """ return -1.13 + npy.tanh(x-2) + 4*npy.exp(-x)*npy.sin((1/8.)*x**3) \ *x + .1*npy.exp((1/35.)*x)
- import math + import numpy as npy def f1(x): """ Test function 1 """ - return x*x*x - math.pi*x + math.e/100 ? ^^^^ ^^^^ + return x*x*x - npy.pi*x + npy.e/100 ? ^^^ ^^^ + + def f2(x): + """ + Test function 2 + """ + return -1.13 + npy.tanh(x-2) + 4*npy.exp(-x)*npy.sin((1/8.)*x**3) \ + *x + .1*npy.exp((1/35.)*x)
e3d3c17988fee0a9f616cf4c0f0dc67a5a60fb34
Constants.py
Constants.py
CTCP_DELIMITER = chr(1) MAX_MESSAGE_LENGTH = 450 #Officially 512 including the newline characters, but let's be on the safe side CHANNEL_PREFIXES = "#&!+.~" #All the characters that could possibly indicate something is a channel name (usually just '#' though) #Since a grey separator is often used to separate parts of a message, provide an easy way to get one GREY_SEPARATOR = u' \x0314|\x0f ' #'\x03' is the 'color' control char, 14 is grey, and '\x0f' is the 'reset' character ending any decoration IRC_NUMERIC_TO_NAME = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "412": "ERR_NOTEXTTOSEND", "433": "ERR_NICKNAMEINUSE"}
CTCP_DELIMITER = chr(1) MAX_MESSAGE_LENGTH = 450 #Officially 512 including the newline characters, but let's be on the safe side CHANNEL_PREFIXES = "#&!+.~" #All the characters that could possibly indicate something is a channel name (usually just '#' though) #Since a grey separator is often used to separate parts of a message, provide an easy way to get one GREY_SEPARATOR = u' \x0314|\x0f ' #'\x03' is the 'color' control char, 14 is grey, and '\x0f' is the 'reset' character ending any decoration IRC_NUMERIC_TO_NAME = {"001": "RPL_WELCOME", "002": "RPL_YOURHOST", "003": "RPL_CREATED", "004": "RPL_MYINFO", "005": "RPL_ISUPPORT", "251": "RPL_LUSERCLIENT", "252": "RPL_LUSEROP", "253": "RPL_LUSERUNKNOWN", "254": "RPL_LUSERCHANNELS", "255": "RPL_LUSERME", "265": "RPL_LOCALUSERS", "266": "RPL_GLOBALUSERS", "315": "RPL_ENDOFWHO", "332": "RPL_TOPIC", "333": "RPL_TOPICWHOTIME", "352": "RPL_WHOREPLY", "353": "RPL_NAMREPLY", "366": "RPL_ENDOFNAMES", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "412": "ERR_NOTEXTTOSEND", "433": "ERR_NICKNAMEINUSE"}
Expand IRC numerics to name list
Expand IRC numerics to name list
Python
mit
Didero/DideRobot
CTCP_DELIMITER = chr(1) MAX_MESSAGE_LENGTH = 450 #Officially 512 including the newline characters, but let's be on the safe side CHANNEL_PREFIXES = "#&!+.~" #All the characters that could possibly indicate something is a channel name (usually just '#' though) #Since a grey separator is often used to separate parts of a message, provide an easy way to get one GREY_SEPARATOR = u' \x0314|\x0f ' #'\x03' is the 'color' control char, 14 is grey, and '\x0f' is the 'reset' character ending any decoration - IRC_NUMERIC_TO_NAME = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", + IRC_NUMERIC_TO_NAME = {"001": "RPL_WELCOME", "002": "RPL_YOURHOST", "003": "RPL_CREATED", "004": "RPL_MYINFO", "005": "RPL_ISUPPORT", + "251": "RPL_LUSERCLIENT", "252": "RPL_LUSEROP", "253": "RPL_LUSERUNKNOWN", "254": "RPL_LUSERCHANNELS", "255": "RPL_LUSERME", + "265": "RPL_LOCALUSERS", "266": "RPL_GLOBALUSERS", "315": "RPL_ENDOFWHO", "332": "RPL_TOPIC", "333": "RPL_TOPICWHOTIME", + "352": "RPL_WHOREPLY", "353": "RPL_NAMREPLY", "366": "RPL_ENDOFNAMES", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "412": "ERR_NOTEXTTOSEND", "433": "ERR_NICKNAMEINUSE"}
Expand IRC numerics to name list
## Code Before: CTCP_DELIMITER = chr(1) MAX_MESSAGE_LENGTH = 450 #Officially 512 including the newline characters, but let's be on the safe side CHANNEL_PREFIXES = "#&!+.~" #All the characters that could possibly indicate something is a channel name (usually just '#' though) #Since a grey separator is often used to separate parts of a message, provide an easy way to get one GREY_SEPARATOR = u' \x0314|\x0f ' #'\x03' is the 'color' control char, 14 is grey, and '\x0f' is the 'reset' character ending any decoration IRC_NUMERIC_TO_NAME = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "412": "ERR_NOTEXTTOSEND", "433": "ERR_NICKNAMEINUSE"} ## Instruction: Expand IRC numerics to name list ## Code After: CTCP_DELIMITER = chr(1) MAX_MESSAGE_LENGTH = 450 #Officially 512 including the newline characters, but let's be on the safe side CHANNEL_PREFIXES = "#&!+.~" #All the characters that could possibly indicate something is a channel name (usually just '#' though) #Since a grey separator is often used to separate parts of a message, provide an easy way to get one GREY_SEPARATOR = u' \x0314|\x0f ' #'\x03' is the 'color' control char, 14 is grey, and '\x0f' is the 'reset' character ending any decoration IRC_NUMERIC_TO_NAME = {"001": "RPL_WELCOME", "002": "RPL_YOURHOST", "003": "RPL_CREATED", "004": "RPL_MYINFO", "005": "RPL_ISUPPORT", "251": "RPL_LUSERCLIENT", "252": "RPL_LUSEROP", "253": "RPL_LUSERUNKNOWN", "254": "RPL_LUSERCHANNELS", "255": "RPL_LUSERME", "265": "RPL_LOCALUSERS", "266": "RPL_GLOBALUSERS", "315": "RPL_ENDOFWHO", "332": "RPL_TOPIC", "333": "RPL_TOPICWHOTIME", "352": "RPL_WHOREPLY", "353": "RPL_NAMREPLY", "366": "RPL_ENDOFNAMES", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "412": "ERR_NOTEXTTOSEND", "433": "ERR_NICKNAMEINUSE"}
CTCP_DELIMITER = chr(1) MAX_MESSAGE_LENGTH = 450 #Officially 512 including the newline characters, but let's be on the safe side CHANNEL_PREFIXES = "#&!+.~" #All the characters that could possibly indicate something is a channel name (usually just '#' though) #Since a grey separator is often used to separate parts of a message, provide an easy way to get one GREY_SEPARATOR = u' \x0314|\x0f ' #'\x03' is the 'color' control char, 14 is grey, and '\x0f' is the 'reset' character ending any decoration - IRC_NUMERIC_TO_NAME = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", + IRC_NUMERIC_TO_NAME = {"001": "RPL_WELCOME", "002": "RPL_YOURHOST", "003": "RPL_CREATED", "004": "RPL_MYINFO", "005": "RPL_ISUPPORT", + "251": "RPL_LUSERCLIENT", "252": "RPL_LUSEROP", "253": "RPL_LUSERUNKNOWN", "254": "RPL_LUSERCHANNELS", "255": "RPL_LUSERME", + "265": "RPL_LOCALUSERS", "266": "RPL_GLOBALUSERS", "315": "RPL_ENDOFWHO", "332": "RPL_TOPIC", "333": "RPL_TOPICWHOTIME", + "352": "RPL_WHOREPLY", "353": "RPL_NAMREPLY", "366": "RPL_ENDOFNAMES", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "412": "ERR_NOTEXTTOSEND", "433": "ERR_NICKNAMEINUSE"}
07ef73f98e85919863af43f9c50bde85a143660d
conf_site/reviews/admin.py
conf_site/reviews/admin.py
from django.contrib import admin from conf_site.reviews.models import ( ProposalFeedback, ProposalNotification, ProposalResult, ProposalVote, ) class ProposalInline(admin.StackedInline): model = ProposalNotification.proposals.through @admin.register(ProposalFeedback) class ProposalFeedbackAdmin(admin.ModelAdmin): list_display = ("proposal", "author", "comment", "date_created") @admin.register(ProposalNotification) class ProposalNotificationAdmin(admin.ModelAdmin): exclude = ("proposals",) inlines = [ProposalInline] list_display = ("subject", "body", "date_sent") @admin.register(ProposalResult) class ProposalResultAdmin(admin.ModelAdmin): list_display = ("proposal", "status") @admin.register(ProposalVote) class ProposalVoteAdmin(admin.ModelAdmin): list_display = ("proposal", "voter", "score", "comment") list_filter = ("score",)
from django.contrib import admin from conf_site.reviews.models import ( ProposalFeedback, ProposalNotification, ProposalResult, ProposalVote, ) class ProposalInline(admin.StackedInline): model = ProposalNotification.proposals.through @admin.register(ProposalFeedback) class ProposalFeedbackAdmin(admin.ModelAdmin): list_display = ("proposal", "author", "comment", "date_created") @admin.register(ProposalNotification) class ProposalNotificationAdmin(admin.ModelAdmin): exclude = ("proposals",) inlines = [ProposalInline] list_display = ("subject", "body", "date_sent") @admin.register(ProposalResult) class ProposalResultAdmin(admin.ModelAdmin): list_display = ("proposal", "status") @admin.register(ProposalVote) class ProposalVoteAdmin(admin.ModelAdmin): list_display = ("proposal", "voter", "score", "comment") list_filter = ["score", "voter"]
Enable filtering ProposalVotes by reviewer.
Enable filtering ProposalVotes by reviewer.
Python
mit
pydata/conf_site,pydata/conf_site,pydata/conf_site
from django.contrib import admin from conf_site.reviews.models import ( ProposalFeedback, ProposalNotification, ProposalResult, ProposalVote, ) class ProposalInline(admin.StackedInline): model = ProposalNotification.proposals.through @admin.register(ProposalFeedback) class ProposalFeedbackAdmin(admin.ModelAdmin): list_display = ("proposal", "author", "comment", "date_created") @admin.register(ProposalNotification) class ProposalNotificationAdmin(admin.ModelAdmin): exclude = ("proposals",) inlines = [ProposalInline] list_display = ("subject", "body", "date_sent") @admin.register(ProposalResult) class ProposalResultAdmin(admin.ModelAdmin): list_display = ("proposal", "status") @admin.register(ProposalVote) class ProposalVoteAdmin(admin.ModelAdmin): list_display = ("proposal", "voter", "score", "comment") - list_filter = ("score",) + list_filter = ["score", "voter"]
Enable filtering ProposalVotes by reviewer.
## Code Before: from django.contrib import admin from conf_site.reviews.models import ( ProposalFeedback, ProposalNotification, ProposalResult, ProposalVote, ) class ProposalInline(admin.StackedInline): model = ProposalNotification.proposals.through @admin.register(ProposalFeedback) class ProposalFeedbackAdmin(admin.ModelAdmin): list_display = ("proposal", "author", "comment", "date_created") @admin.register(ProposalNotification) class ProposalNotificationAdmin(admin.ModelAdmin): exclude = ("proposals",) inlines = [ProposalInline] list_display = ("subject", "body", "date_sent") @admin.register(ProposalResult) class ProposalResultAdmin(admin.ModelAdmin): list_display = ("proposal", "status") @admin.register(ProposalVote) class ProposalVoteAdmin(admin.ModelAdmin): list_display = ("proposal", "voter", "score", "comment") list_filter = ("score",) ## Instruction: Enable filtering ProposalVotes by reviewer. ## Code After: from django.contrib import admin from conf_site.reviews.models import ( ProposalFeedback, ProposalNotification, ProposalResult, ProposalVote, ) class ProposalInline(admin.StackedInline): model = ProposalNotification.proposals.through @admin.register(ProposalFeedback) class ProposalFeedbackAdmin(admin.ModelAdmin): list_display = ("proposal", "author", "comment", "date_created") @admin.register(ProposalNotification) class ProposalNotificationAdmin(admin.ModelAdmin): exclude = ("proposals",) inlines = [ProposalInline] list_display = ("subject", "body", "date_sent") @admin.register(ProposalResult) class ProposalResultAdmin(admin.ModelAdmin): list_display = ("proposal", "status") @admin.register(ProposalVote) class ProposalVoteAdmin(admin.ModelAdmin): list_display = ("proposal", "voter", "score", "comment") list_filter = ["score", "voter"]
from django.contrib import admin from conf_site.reviews.models import ( ProposalFeedback, ProposalNotification, ProposalResult, ProposalVote, ) class ProposalInline(admin.StackedInline): model = ProposalNotification.proposals.through @admin.register(ProposalFeedback) class ProposalFeedbackAdmin(admin.ModelAdmin): list_display = ("proposal", "author", "comment", "date_created") @admin.register(ProposalNotification) class ProposalNotificationAdmin(admin.ModelAdmin): exclude = ("proposals",) inlines = [ProposalInline] list_display = ("subject", "body", "date_sent") @admin.register(ProposalResult) class ProposalResultAdmin(admin.ModelAdmin): list_display = ("proposal", "status") @admin.register(ProposalVote) class ProposalVoteAdmin(admin.ModelAdmin): list_display = ("proposal", "voter", "score", "comment") - list_filter = ("score",) ? ^ ^ + list_filter = ["score", "voter"] ? ^ ^^^^^^^^^
08bffa5f6df497f28fe3481fe80b517628b0f1a3
tmdb3/cache_engine.py
tmdb3/cache_engine.py
class Engines( object ): def __init__(self): self._engines = {} def register(self, engine): self._engines[engine.__name__] = engine self._engines[engine.name] = engine def __getitem__(self, key): return self._engines[key] Engines = Engines() class CacheEngineType( type ): """ Cache Engine Metaclass that registers new engines against the cache for named selection and use. """ def __init__(mcs, name, bases, attrs): super(CacheEngineType, mcs).__init__(name, bases, attrs) if name != 'CacheEngine': # skip base class Engines.register(mcs) class CacheEngine( object ): __metaclass__ = CacheEngineType name = 'unspecified' def __init__(self, parent): self.parent = parent def configure(self): raise RuntimeError def get(self, key): raise RuntimeError def put(self, key, value, lifetime): raise RuntimeError def expire(self, key): raise RuntimeError
class Engines( object ): def __init__(self): self._engines = {} def register(self, engine): self._engines[engine.__name__] = engine self._engines[engine.name] = engine def __getitem__(self, key): return self._engines[key] def __contains__(self, key): return self._engines.__contains__(key) Engines = Engines() class CacheEngineType( type ): """ Cache Engine Metaclass that registers new engines against the cache for named selection and use. """ def __init__(mcs, name, bases, attrs): super(CacheEngineType, mcs).__init__(name, bases, attrs) if name != 'CacheEngine': # skip base class Engines.register(mcs) class CacheEngine( object ): __metaclass__ = CacheEngineType name = 'unspecified' def __init__(self, parent): self.parent = parent def configure(self): raise RuntimeError def get(self, key): raise RuntimeError def put(self, key, value, lifetime): raise RuntimeError def expire(self, key): raise RuntimeError
Add __contains__ for proper lookup in cache Engines class.
Add __contains__ for proper lookup in cache Engines class.
Python
bsd-3-clause
wagnerrp/pytmdb3,naveenvhegde/pytmdb3
class Engines( object ): def __init__(self): self._engines = {} def register(self, engine): self._engines[engine.__name__] = engine self._engines[engine.name] = engine def __getitem__(self, key): return self._engines[key] + def __contains__(self, key): + return self._engines.__contains__(key) Engines = Engines() class CacheEngineType( type ): """ Cache Engine Metaclass that registers new engines against the cache for named selection and use. """ def __init__(mcs, name, bases, attrs): super(CacheEngineType, mcs).__init__(name, bases, attrs) if name != 'CacheEngine': # skip base class Engines.register(mcs) class CacheEngine( object ): __metaclass__ = CacheEngineType name = 'unspecified' def __init__(self, parent): self.parent = parent def configure(self): raise RuntimeError def get(self, key): raise RuntimeError def put(self, key, value, lifetime): raise RuntimeError def expire(self, key): raise RuntimeError
Add __contains__ for proper lookup in cache Engines class.
## Code Before: class Engines( object ): def __init__(self): self._engines = {} def register(self, engine): self._engines[engine.__name__] = engine self._engines[engine.name] = engine def __getitem__(self, key): return self._engines[key] Engines = Engines() class CacheEngineType( type ): """ Cache Engine Metaclass that registers new engines against the cache for named selection and use. """ def __init__(mcs, name, bases, attrs): super(CacheEngineType, mcs).__init__(name, bases, attrs) if name != 'CacheEngine': # skip base class Engines.register(mcs) class CacheEngine( object ): __metaclass__ = CacheEngineType name = 'unspecified' def __init__(self, parent): self.parent = parent def configure(self): raise RuntimeError def get(self, key): raise RuntimeError def put(self, key, value, lifetime): raise RuntimeError def expire(self, key): raise RuntimeError ## Instruction: Add __contains__ for proper lookup in cache Engines class. ## Code After: class Engines( object ): def __init__(self): self._engines = {} def register(self, engine): self._engines[engine.__name__] = engine self._engines[engine.name] = engine def __getitem__(self, key): return self._engines[key] def __contains__(self, key): return self._engines.__contains__(key) Engines = Engines() class CacheEngineType( type ): """ Cache Engine Metaclass that registers new engines against the cache for named selection and use. """ def __init__(mcs, name, bases, attrs): super(CacheEngineType, mcs).__init__(name, bases, attrs) if name != 'CacheEngine': # skip base class Engines.register(mcs) class CacheEngine( object ): __metaclass__ = CacheEngineType name = 'unspecified' def __init__(self, parent): self.parent = parent def configure(self): raise RuntimeError def get(self, key): raise RuntimeError def put(self, key, value, lifetime): raise RuntimeError def expire(self, key): raise RuntimeError
class Engines( object ): def __init__(self): self._engines = {} def register(self, engine): self._engines[engine.__name__] = engine self._engines[engine.name] = engine def __getitem__(self, key): return self._engines[key] + def __contains__(self, key): + return self._engines.__contains__(key) Engines = Engines() class CacheEngineType( type ): """ Cache Engine Metaclass that registers new engines against the cache for named selection and use. """ def __init__(mcs, name, bases, attrs): super(CacheEngineType, mcs).__init__(name, bases, attrs) if name != 'CacheEngine': # skip base class Engines.register(mcs) class CacheEngine( object ): __metaclass__ = CacheEngineType name = 'unspecified' def __init__(self, parent): self.parent = parent def configure(self): raise RuntimeError def get(self, key): raise RuntimeError def put(self, key, value, lifetime): raise RuntimeError def expire(self, key): raise RuntimeError
88773c6757540c9f1d4dfca2a287512e74bdbc24
python_scripts/mc_config.py
python_scripts/mc_config.py
import yaml import os.path _config_file_base_name = 'mediawords.yml' _config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mediawords.yml')) def read_config(): yml_file = open(_config_file_name, 'rb') config_file = yaml.load( yml_file ) return config_file
import yaml import os.path _config_file_base_name = 'mediawords.yml' _config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mediawords.yml')) _defaults_config_file_base_name = 'defaults.yml' _defaults_config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '../config', _defaults_config_file_base_name)) def _load_yml( file_path ): yml_file = open(file_path, 'rb') config_file = yaml.load( yml_file ) return config_file def deep_merge( original, update ): for key, value in update.iteritems(): if not key in original: original[ key ] = value elif isinstance( value, dict) and isinstance( original[key], dict): deep_merge( original[ key ], value ) return original def read_config(): config_file = _load_yml( _config_file_name ) defaults_file = _load_yml( _defaults_config_file_name ) # print "config_file" # print config_file # print "defaults_file" # print defaults_file config_file = deep_merge( config_file, defaults_file ) # print "Merged" # print config_file return config_file
Read the defaults config file and merge it with mediawords.yml
Read the defaults config file and merge it with mediawords.yml
Python
agpl-3.0
berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud
import yaml import os.path _config_file_base_name = 'mediawords.yml' _config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mediawords.yml')) + _defaults_config_file_base_name = 'defaults.yml' + _defaults_config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '../config', _defaults_config_file_base_name)) + + + def _load_yml( file_path ): + yml_file = open(file_path, 'rb') + config_file = yaml.load( yml_file ) + + return config_file + + def deep_merge( original, update ): + for key, value in update.iteritems(): + if not key in original: + original[ key ] = value + elif isinstance( value, dict) and isinstance( original[key], dict): + deep_merge( original[ key ], value ) + + return original + def read_config(): - yml_file = open(_config_file_name, 'rb') - config_file = yaml.load( yml_file ) + + config_file = _load_yml( _config_file_name ) + defaults_file = _load_yml( _defaults_config_file_name ) + + # print "config_file" + # print config_file + # print "defaults_file" + # print defaults_file + + config_file = deep_merge( config_file, defaults_file ) + + # print "Merged" + # print config_file + return config_file
Read the defaults config file and merge it with mediawords.yml
## Code Before: import yaml import os.path _config_file_base_name = 'mediawords.yml' _config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mediawords.yml')) def read_config(): yml_file = open(_config_file_name, 'rb') config_file = yaml.load( yml_file ) return config_file ## Instruction: Read the defaults config file and merge it with mediawords.yml ## Code After: import yaml import os.path _config_file_base_name = 'mediawords.yml' _config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mediawords.yml')) _defaults_config_file_base_name = 'defaults.yml' _defaults_config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '../config', _defaults_config_file_base_name)) def _load_yml( file_path ): yml_file = open(file_path, 'rb') config_file = yaml.load( yml_file ) return config_file def deep_merge( original, update ): for key, value in update.iteritems(): if not key in original: original[ key ] = value elif isinstance( value, dict) and isinstance( original[key], dict): deep_merge( original[ key ], value ) return original def read_config(): config_file = _load_yml( _config_file_name ) defaults_file = _load_yml( _defaults_config_file_name ) # print "config_file" # print config_file # print "defaults_file" # print defaults_file config_file = deep_merge( config_file, defaults_file ) # print "Merged" # print config_file return config_file
import yaml import os.path _config_file_base_name = 'mediawords.yml' _config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mediawords.yml')) - def read_config(): + _defaults_config_file_base_name = 'defaults.yml' + _defaults_config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '../config', _defaults_config_file_base_name)) + + + def _load_yml( file_path ): - yml_file = open(_config_file_name, 'rb') ? -------- ^ ^^ + yml_file = open(file_path, 'rb') ? ^ ^^ config_file = yaml.load( yml_file ) + return config_file + def deep_merge( original, update ): + for key, value in update.iteritems(): + if not key in original: + original[ key ] = value + elif isinstance( value, dict) and isinstance( original[key], dict): + deep_merge( original[ key ], value ) + + return original + + def read_config(): + + config_file = _load_yml( _config_file_name ) + defaults_file = _load_yml( _defaults_config_file_name ) + + # print "config_file" + # print config_file + # print "defaults_file" + # print defaults_file + + config_file = deep_merge( config_file, defaults_file ) + + # print "Merged" + # print config_file + + return config_file +
e80cc896396b217a3e3a4f01294b50061faf68cd
cyder/cydhcp/range/forms.py
cyder/cydhcp/range/forms.py
from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.range.models import Range, RangeAV from cyder.cydns.forms import ViewChoiceForm class RangeForm(ViewChoiceForm, UsabilityFormMixin): class Meta: model = Range exclude = ('start_upper', 'start_lower', 'end_upper', 'end_lower') fields = ('network', 'ip_type', 'range_type', 'start_str', 'end_str', 'domain', 'is_reserved', 'allow', 'views', 'dhcpd_raw_include', 'dhcp_enabled', 'name') widgets = {'views': forms.CheckboxSelectMultiple, 'range_type': forms.RadioSelect, 'ip_type': forms.RadioSelect} exclude = 'range_usage' def __init__(self, *args, **kwargs): super(RangeForm, self).__init__(*args, **kwargs) self.fields['dhcpd_raw_include'].label = "DHCP Config Extras" self.fields['dhcpd_raw_include'].widget.attrs.update( {'cols': '80', 'style': 'display: none;width: 680px'}) RangeAVForm = get_eav_form(RangeAV, Range)
from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.range.models import Range, RangeAV from cyder.cydns.forms import ViewChoiceForm class RangeForm(ViewChoiceForm, UsabilityFormMixin): class Meta: model = Range exclude = ('start_upper', 'start_lower', 'end_upper', 'end_lower') fields = ('name', 'network', 'ip_type', 'range_type', 'start_str', 'end_str', 'domain', 'is_reserved', 'allow', 'views', 'dhcpd_raw_include', 'dhcp_enabled') widgets = {'views': forms.CheckboxSelectMultiple, 'range_type': forms.RadioSelect, 'ip_type': forms.RadioSelect} exclude = 'range_usage' def __init__(self, *args, **kwargs): super(RangeForm, self).__init__(*args, **kwargs) self.fields['dhcpd_raw_include'].label = "DHCP Config Extras" self.fields['dhcpd_raw_include'].widget.attrs.update( {'cols': '80', 'style': 'display: none;width: 680px'}) RangeAVForm = get_eav_form(RangeAV, Range)
Put name first in range form
Put name first in range form
Python
bsd-3-clause
zeeman/cyder,zeeman/cyder,akeym/cyder,akeym/cyder,akeym/cyder,OSU-Net/cyder,OSU-Net/cyder,murrown/cyder,zeeman/cyder,OSU-Net/cyder,OSU-Net/cyder,murrown/cyder,akeym/cyder,zeeman/cyder,drkitty/cyder,murrown/cyder,murrown/cyder,drkitty/cyder,drkitty/cyder,drkitty/cyder
from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.range.models import Range, RangeAV from cyder.cydns.forms import ViewChoiceForm class RangeForm(ViewChoiceForm, UsabilityFormMixin): class Meta: model = Range exclude = ('start_upper', 'start_lower', 'end_upper', 'end_lower') - fields = ('network', 'ip_type', 'range_type', 'start_str', 'end_str', + fields = ('name', 'network', 'ip_type', 'range_type', 'start_str', - 'domain', 'is_reserved', 'allow', 'views', + 'end_str', 'domain', 'is_reserved', 'allow', 'views', - 'dhcpd_raw_include', 'dhcp_enabled', 'name') + 'dhcpd_raw_include', 'dhcp_enabled') widgets = {'views': forms.CheckboxSelectMultiple, 'range_type': forms.RadioSelect, 'ip_type': forms.RadioSelect} exclude = 'range_usage' def __init__(self, *args, **kwargs): super(RangeForm, self).__init__(*args, **kwargs) self.fields['dhcpd_raw_include'].label = "DHCP Config Extras" self.fields['dhcpd_raw_include'].widget.attrs.update( {'cols': '80', 'style': 'display: none;width: 680px'}) RangeAVForm = get_eav_form(RangeAV, Range)
Put name first in range form
## Code Before: from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.range.models import Range, RangeAV from cyder.cydns.forms import ViewChoiceForm class RangeForm(ViewChoiceForm, UsabilityFormMixin): class Meta: model = Range exclude = ('start_upper', 'start_lower', 'end_upper', 'end_lower') fields = ('network', 'ip_type', 'range_type', 'start_str', 'end_str', 'domain', 'is_reserved', 'allow', 'views', 'dhcpd_raw_include', 'dhcp_enabled', 'name') widgets = {'views': forms.CheckboxSelectMultiple, 'range_type': forms.RadioSelect, 'ip_type': forms.RadioSelect} exclude = 'range_usage' def __init__(self, *args, **kwargs): super(RangeForm, self).__init__(*args, **kwargs) self.fields['dhcpd_raw_include'].label = "DHCP Config Extras" self.fields['dhcpd_raw_include'].widget.attrs.update( {'cols': '80', 'style': 'display: none;width: 680px'}) RangeAVForm = get_eav_form(RangeAV, Range) ## Instruction: Put name first in range form ## Code After: from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.range.models import Range, RangeAV from cyder.cydns.forms import ViewChoiceForm class RangeForm(ViewChoiceForm, UsabilityFormMixin): class Meta: model = Range exclude = ('start_upper', 'start_lower', 'end_upper', 'end_lower') fields = ('name', 'network', 'ip_type', 'range_type', 'start_str', 'end_str', 'domain', 'is_reserved', 'allow', 'views', 'dhcpd_raw_include', 'dhcp_enabled') widgets = {'views': forms.CheckboxSelectMultiple, 'range_type': forms.RadioSelect, 'ip_type': forms.RadioSelect} exclude = 'range_usage' def __init__(self, *args, **kwargs): super(RangeForm, self).__init__(*args, **kwargs) self.fields['dhcpd_raw_include'].label = "DHCP Config Extras" self.fields['dhcpd_raw_include'].widget.attrs.update( {'cols': '80', 'style': 'display: none;width: 680px'}) RangeAVForm = get_eav_form(RangeAV, Range)
from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.range.models import Range, RangeAV from cyder.cydns.forms import ViewChoiceForm class RangeForm(ViewChoiceForm, UsabilityFormMixin): class Meta: model = Range exclude = ('start_upper', 'start_lower', 'end_upper', 'end_lower') - fields = ('network', 'ip_type', 'range_type', 'start_str', 'end_str', ? ----------- + fields = ('name', 'network', 'ip_type', 'range_type', 'start_str', ? ++++++++ - 'domain', 'is_reserved', 'allow', 'views', + 'end_str', 'domain', 'is_reserved', 'allow', 'views', ? +++++++++++ - 'dhcpd_raw_include', 'dhcp_enabled', 'name') ? -------- + 'dhcpd_raw_include', 'dhcp_enabled') widgets = {'views': forms.CheckboxSelectMultiple, 'range_type': forms.RadioSelect, 'ip_type': forms.RadioSelect} exclude = 'range_usage' def __init__(self, *args, **kwargs): super(RangeForm, self).__init__(*args, **kwargs) self.fields['dhcpd_raw_include'].label = "DHCP Config Extras" self.fields['dhcpd_raw_include'].widget.attrs.update( {'cols': '80', 'style': 'display: none;width: 680px'}) RangeAVForm = get_eav_form(RangeAV, Range)
d0461fa033bdca4fffeff718219f8b71123449d7
pskb_website/models/__init__.py
pskb_website/models/__init__.py
from .article import search_for_article from .article import get_available_articles from .article import read_article from .article import save_article from .article import delete_article from .article import branch_article from .article import branch_or_save_article from .article import get_articles_for_author from .article import get_public_articles_for_author from .article import save_article_meta_data from .article import find_article_by_title from .article import change_article_stack from .file import read_file from .file import read_redirects from .file import update_article_listing from .file import published_articles from .file import in_review_articles from .file import draft_articles from .user import find_user from .email_list import add_subscriber from .image import save_image from .lib import to_json
from .article import search_for_article from .article import get_available_articles from .article import read_article from .article import save_article from .article import delete_article from .article import branch_article from .article import branch_or_save_article from .article import get_articles_for_author from .article import get_public_articles_for_author from .article import find_article_by_title from .article import change_article_stack from .file import read_file from .file import read_redirects from .file import update_article_listing from .user import find_user from .email_list import add_subscriber from .image import save_image from .lib import to_json
Remove some functions from exported model API that are not used outside model layer
Remove some functions from exported model API that are not used outside model layer - Just some refactoring to trim down the number of things exported that aren't necessary at this time.
Python
agpl-3.0
paulocheque/guides-cms,pluralsight/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms
from .article import search_for_article from .article import get_available_articles from .article import read_article from .article import save_article from .article import delete_article from .article import branch_article from .article import branch_or_save_article from .article import get_articles_for_author from .article import get_public_articles_for_author - from .article import save_article_meta_data from .article import find_article_by_title from .article import change_article_stack from .file import read_file from .file import read_redirects from .file import update_article_listing - from .file import published_articles - from .file import in_review_articles - from .file import draft_articles from .user import find_user from .email_list import add_subscriber from .image import save_image from .lib import to_json
Remove some functions from exported model API that are not used outside model layer
## Code Before: from .article import search_for_article from .article import get_available_articles from .article import read_article from .article import save_article from .article import delete_article from .article import branch_article from .article import branch_or_save_article from .article import get_articles_for_author from .article import get_public_articles_for_author from .article import save_article_meta_data from .article import find_article_by_title from .article import change_article_stack from .file import read_file from .file import read_redirects from .file import update_article_listing from .file import published_articles from .file import in_review_articles from .file import draft_articles from .user import find_user from .email_list import add_subscriber from .image import save_image from .lib import to_json ## Instruction: Remove some functions from exported model API that are not used outside model layer ## Code After: from .article import search_for_article from .article import get_available_articles from .article import read_article from .article import save_article from .article import delete_article from .article import branch_article from .article import branch_or_save_article from .article import get_articles_for_author from .article import get_public_articles_for_author from .article import find_article_by_title from .article import change_article_stack from .file import read_file from .file import read_redirects from .file import update_article_listing from .user import find_user from .email_list import add_subscriber from .image import save_image from .lib import to_json
from .article import search_for_article from .article import get_available_articles from .article import read_article from .article import save_article from .article import delete_article from .article import branch_article from .article import branch_or_save_article from .article import get_articles_for_author from .article import get_public_articles_for_author - from .article import save_article_meta_data from .article import find_article_by_title from .article import change_article_stack from .file import read_file from .file import read_redirects from .file import update_article_listing - from .file import published_articles - from .file import in_review_articles - from .file import draft_articles from .user import find_user from .email_list import add_subscriber from .image import save_image from .lib import to_json
e6c4d40f0eaa6c93cac88582d862aa8393a3cc10
setup.py
setup.py
from distutils.core import setup setup( name='screenplain', version='0.7.0', description='Convert text file to viewable screenplay.', author='Martin Vilcans', author_email='screenplain@librador.com', url='http://www.screenplain.com/', extras_require={ 'PDF': 'reportlab' }, packages=[ 'screenplain', 'screenplain.export', 'screenplain.parsers', ], package_data={ 'screenplain.export': ['default.css'] }, scripts=[ 'bin/screenplain' ] )
from distutils.core import setup setup( name='screenplain', version='0.7.0', description='Convert text file to viewable screenplay.', author='Martin Vilcans', author_email='screenplain@librador.com', url='http://www.screenplain.com/', install_requires=[ 'six', ], extras_require={ 'PDF': 'reportlab' }, packages=[ 'screenplain', 'screenplain.export', 'screenplain.parsers', ], package_data={ 'screenplain.export': ['default.css'] }, scripts=[ 'bin/screenplain' ] )
Add install_requires six for universal Python support
Add install_requires six for universal Python support
Python
mit
vilcans/screenplain,vilcans/screenplain,vilcans/screenplain
from distutils.core import setup setup( name='screenplain', version='0.7.0', description='Convert text file to viewable screenplay.', author='Martin Vilcans', author_email='screenplain@librador.com', url='http://www.screenplain.com/', + install_requires=[ + 'six', + ], extras_require={ 'PDF': 'reportlab' }, packages=[ 'screenplain', 'screenplain.export', 'screenplain.parsers', ], package_data={ 'screenplain.export': ['default.css'] }, scripts=[ 'bin/screenplain' ] )
Add install_requires six for universal Python support
## Code Before: from distutils.core import setup setup( name='screenplain', version='0.7.0', description='Convert text file to viewable screenplay.', author='Martin Vilcans', author_email='screenplain@librador.com', url='http://www.screenplain.com/', extras_require={ 'PDF': 'reportlab' }, packages=[ 'screenplain', 'screenplain.export', 'screenplain.parsers', ], package_data={ 'screenplain.export': ['default.css'] }, scripts=[ 'bin/screenplain' ] ) ## Instruction: Add install_requires six for universal Python support ## Code After: from distutils.core import setup setup( name='screenplain', version='0.7.0', description='Convert text file to viewable screenplay.', author='Martin Vilcans', author_email='screenplain@librador.com', url='http://www.screenplain.com/', install_requires=[ 'six', ], extras_require={ 'PDF': 'reportlab' }, packages=[ 'screenplain', 'screenplain.export', 'screenplain.parsers', ], package_data={ 'screenplain.export': ['default.css'] }, scripts=[ 'bin/screenplain' ] )
from distutils.core import setup setup( name='screenplain', version='0.7.0', description='Convert text file to viewable screenplay.', author='Martin Vilcans', author_email='screenplain@librador.com', url='http://www.screenplain.com/', + install_requires=[ + 'six', + ], extras_require={ 'PDF': 'reportlab' }, packages=[ 'screenplain', 'screenplain.export', 'screenplain.parsers', ], package_data={ 'screenplain.export': ['default.css'] }, scripts=[ 'bin/screenplain' ] )
adfcd15e8c9f3c4b08bdb358d041401bf77d2a25
calicoctl/calico_ctl/__init__.py
calicoctl/calico_ctl/__init__.py
__version__ = "0.13.0-dev" __kubernetes_plugin_version__ = "v0.6.0" __rkt_plugin_version__ = "v0.1.0" __libnetwork_plugin_version__ = "v0.6.0" __libcalico_version__ = "v0.6.0" __felix_version__ = "1.2.1"
__version__ = "0.13.0-dev" __kubernetes_plugin_version__ = "v0.7.0" __rkt_plugin_version__ = "v0.1.0" __libnetwork_plugin_version__ = "v0.7.0" __libcalico_version__ = "v0.7.0" __felix_version__ = "1.3.0-pre5"
Fix release numbers to be latest values
Fix release numbers to be latest values
Python
apache-2.0
caseydavenport/calico-containers,Metaswitch/calico-docker,caseydavenport/calico-containers,projectcalico/calico-containers,quater/calico-containers,Metaswitch/calico-docker,insequent/calico-docker,projectcalico/calico-containers,TrimBiggs/calico-containers,tomdee/calico-docker,TrimBiggs/calico-docker,caseydavenport/calico-docker,caseydavenport/calico-docker,tomdee/calico-containers,TrimBiggs/calico-docker,caseydavenport/calico-containers,tomdee/calico-docker,tomdee/calico-containers,projectcalico/calico-docker,quater/calico-containers,TrimBiggs/calico-containers,projectcalico/calico-docker,projectcalico/calico-containers,insequent/calico-docker
__version__ = "0.13.0-dev" - __kubernetes_plugin_version__ = "v0.6.0" + __kubernetes_plugin_version__ = "v0.7.0" __rkt_plugin_version__ = "v0.1.0" - __libnetwork_plugin_version__ = "v0.6.0" + __libnetwork_plugin_version__ = "v0.7.0" - __libcalico_version__ = "v0.6.0" + __libcalico_version__ = "v0.7.0" - __felix_version__ = "1.2.1" + __felix_version__ = "1.3.0-pre5"
Fix release numbers to be latest values
## Code Before: __version__ = "0.13.0-dev" __kubernetes_plugin_version__ = "v0.6.0" __rkt_plugin_version__ = "v0.1.0" __libnetwork_plugin_version__ = "v0.6.0" __libcalico_version__ = "v0.6.0" __felix_version__ = "1.2.1" ## Instruction: Fix release numbers to be latest values ## Code After: __version__ = "0.13.0-dev" __kubernetes_plugin_version__ = "v0.7.0" __rkt_plugin_version__ = "v0.1.0" __libnetwork_plugin_version__ = "v0.7.0" __libcalico_version__ = "v0.7.0" __felix_version__ = "1.3.0-pre5"
__version__ = "0.13.0-dev" - __kubernetes_plugin_version__ = "v0.6.0" ? ^ + __kubernetes_plugin_version__ = "v0.7.0" ? ^ __rkt_plugin_version__ = "v0.1.0" - __libnetwork_plugin_version__ = "v0.6.0" ? ^ + __libnetwork_plugin_version__ = "v0.7.0" ? ^ - __libcalico_version__ = "v0.6.0" ? ^ + __libcalico_version__ = "v0.7.0" ? ^ - __felix_version__ = "1.2.1" ? ^ ^ + __felix_version__ = "1.3.0-pre5" ? ^ ^^^^^^
30c875e1ba1dec3bcbd22850cd703198bcc5a1fb
peeringdb/migrations/0013_auto_20201207_2233.py
peeringdb/migrations/0013_auto_20201207_2233.py
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("peeringdb", "0012_peerrecord_visible"), ] def flush_peeringdb_tables(apps, schema_editor): apps.get_model("peeringdb", "Contact").objects.all().delete() apps.get_model("peeringdb", "Network").objects.all().delete() apps.get_model("peeringdb", "NetworkIXLAN").objects.all().delete() apps.get_model("peeringdb", "PeerRecord").objects.all().delete() operations = [migrations.RunPython(flush_peeringdb_tables)]
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("peeringdb", "0012_peerrecord_visible"), ] def flush_peeringdb_tables(apps, schema_editor): apps.get_model("peeringdb", "Contact").objects.all().delete() apps.get_model("peeringdb", "Network").objects.all().delete() apps.get_model("peeringdb", "NetworkIXLAN").objects.all().delete() apps.get_model("peeringdb", "PeerRecord").objects.all().delete() apps.get_model("peeringdb", "Synchronization").objects.all().delete() operations = [migrations.RunPython(flush_peeringdb_tables)]
Remove PeeringDB sync records on migrate
Remove PeeringDB sync records on migrate
Python
apache-2.0
respawner/peering-manager,respawner/peering-manager,respawner/peering-manager,respawner/peering-manager
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("peeringdb", "0012_peerrecord_visible"), ] def flush_peeringdb_tables(apps, schema_editor): apps.get_model("peeringdb", "Contact").objects.all().delete() apps.get_model("peeringdb", "Network").objects.all().delete() apps.get_model("peeringdb", "NetworkIXLAN").objects.all().delete() apps.get_model("peeringdb", "PeerRecord").objects.all().delete() + apps.get_model("peeringdb", "Synchronization").objects.all().delete() operations = [migrations.RunPython(flush_peeringdb_tables)]
Remove PeeringDB sync records on migrate
## Code Before: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("peeringdb", "0012_peerrecord_visible"), ] def flush_peeringdb_tables(apps, schema_editor): apps.get_model("peeringdb", "Contact").objects.all().delete() apps.get_model("peeringdb", "Network").objects.all().delete() apps.get_model("peeringdb", "NetworkIXLAN").objects.all().delete() apps.get_model("peeringdb", "PeerRecord").objects.all().delete() operations = [migrations.RunPython(flush_peeringdb_tables)] ## Instruction: Remove PeeringDB sync records on migrate ## Code After: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("peeringdb", "0012_peerrecord_visible"), ] def flush_peeringdb_tables(apps, schema_editor): apps.get_model("peeringdb", "Contact").objects.all().delete() apps.get_model("peeringdb", "Network").objects.all().delete() apps.get_model("peeringdb", "NetworkIXLAN").objects.all().delete() apps.get_model("peeringdb", "PeerRecord").objects.all().delete() apps.get_model("peeringdb", "Synchronization").objects.all().delete() operations = [migrations.RunPython(flush_peeringdb_tables)]
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("peeringdb", "0012_peerrecord_visible"), ] def flush_peeringdb_tables(apps, schema_editor): apps.get_model("peeringdb", "Contact").objects.all().delete() apps.get_model("peeringdb", "Network").objects.all().delete() apps.get_model("peeringdb", "NetworkIXLAN").objects.all().delete() apps.get_model("peeringdb", "PeerRecord").objects.all().delete() + apps.get_model("peeringdb", "Synchronization").objects.all().delete() operations = [migrations.RunPython(flush_peeringdb_tables)]
7a281be50ba1fc59281a76470776fa9c8efdfd54
pijobs/scrolljob.py
pijobs/scrolljob.py
import scrollphat from pijobs.scrollphatjob import ScrollphatJob class ScrollJob(ScrollphatJob): def default_options(self): opts = { 'brightness': 2, 'interval': 0.1, 'sleep': 1.0, } return opts def init(self): self.set_brightness() self.write_message() def write_message(self): message = self.parse_message() scrollphat.write_string(message, 11) def message(self): return self.options['message'] def parse_message(self): message = self.message() + ' ' if self.options['upper'] == True: message = message.upper() return message def run(self): length = scrollphat.buffer_len() if self.options['loop'] == True: counter = 0 while True: self.scroll() counter += 1 if counter % length == 0: time.sleep(self.options['sleep']) else: for i in range(length): self.scroll() self.sleep() def scroll(self): scrollphat.scroll() self.sleep_interval()
import scrollphat from pijobs.scrollphatjob import ScrollphatJob class ScrollJob(ScrollphatJob): def default_options(self): opts = { 'brightness': 2, 'interval': 0.1, 'sleep': 1.0, } return opts def init(self): self.set_brightness() self.set_rotate() self.write_message() def write_message(self): message = self.parse_message() scrollphat.write_string(message, 11) def message(self): return self.options['message'] def parse_message(self): message = self.message() + ' ' if self.options['upper'] == True: message = message.upper() return message def run(self): length = scrollphat.buffer_len() if self.options['loop'] == True: counter = 0 while True: self.scroll() counter += 1 if counter % length == 0: time.sleep(self.options['sleep']) else: for i in range(length): self.scroll() self.sleep() def scroll(self): scrollphat.scroll() self.sleep_interval()
Add back rotatation for scroll job.
Add back rotatation for scroll job.
Python
mit
ollej/piapi,ollej/piapi
import scrollphat from pijobs.scrollphatjob import ScrollphatJob class ScrollJob(ScrollphatJob): def default_options(self): opts = { 'brightness': 2, 'interval': 0.1, 'sleep': 1.0, } return opts def init(self): self.set_brightness() + self.set_rotate() self.write_message() def write_message(self): message = self.parse_message() scrollphat.write_string(message, 11) def message(self): return self.options['message'] def parse_message(self): message = self.message() + ' ' if self.options['upper'] == True: message = message.upper() return message def run(self): length = scrollphat.buffer_len() if self.options['loop'] == True: counter = 0 while True: self.scroll() counter += 1 if counter % length == 0: time.sleep(self.options['sleep']) else: for i in range(length): self.scroll() self.sleep() def scroll(self): scrollphat.scroll() self.sleep_interval()
Add back rotatation for scroll job.
## Code Before: import scrollphat from pijobs.scrollphatjob import ScrollphatJob class ScrollJob(ScrollphatJob): def default_options(self): opts = { 'brightness': 2, 'interval': 0.1, 'sleep': 1.0, } return opts def init(self): self.set_brightness() self.write_message() def write_message(self): message = self.parse_message() scrollphat.write_string(message, 11) def message(self): return self.options['message'] def parse_message(self): message = self.message() + ' ' if self.options['upper'] == True: message = message.upper() return message def run(self): length = scrollphat.buffer_len() if self.options['loop'] == True: counter = 0 while True: self.scroll() counter += 1 if counter % length == 0: time.sleep(self.options['sleep']) else: for i in range(length): self.scroll() self.sleep() def scroll(self): scrollphat.scroll() self.sleep_interval() ## Instruction: Add back rotatation for scroll job. ## Code After: import scrollphat from pijobs.scrollphatjob import ScrollphatJob class ScrollJob(ScrollphatJob): def default_options(self): opts = { 'brightness': 2, 'interval': 0.1, 'sleep': 1.0, } return opts def init(self): self.set_brightness() self.set_rotate() self.write_message() def write_message(self): message = self.parse_message() scrollphat.write_string(message, 11) def message(self): return self.options['message'] def parse_message(self): message = self.message() + ' ' if self.options['upper'] == True: message = message.upper() return message def run(self): length = scrollphat.buffer_len() if self.options['loop'] == True: counter = 0 while True: self.scroll() counter += 1 if counter % length == 0: time.sleep(self.options['sleep']) else: for i in range(length): self.scroll() self.sleep() def scroll(self): scrollphat.scroll() self.sleep_interval()
import scrollphat from pijobs.scrollphatjob import ScrollphatJob class ScrollJob(ScrollphatJob): def default_options(self): opts = { 'brightness': 2, 'interval': 0.1, 'sleep': 1.0, } return opts def init(self): self.set_brightness() + self.set_rotate() self.write_message() def write_message(self): message = self.parse_message() scrollphat.write_string(message, 11) def message(self): return self.options['message'] def parse_message(self): message = self.message() + ' ' if self.options['upper'] == True: message = message.upper() return message def run(self): length = scrollphat.buffer_len() if self.options['loop'] == True: counter = 0 while True: self.scroll() counter += 1 if counter % length == 0: time.sleep(self.options['sleep']) else: for i in range(length): self.scroll() self.sleep() def scroll(self): scrollphat.scroll() self.sleep_interval()
53b22654b015d1450fe124bc01a2f1bffba816a2
test_hpack_integration.py
test_hpack_integration.py
from hyper.http20.hpack import Decoder from binascii import unhexlify class TestHPACKDecoderIntegration(object): def test_can_decode_a_story(self, story): d = Decoder() for case in story['cases']: d.header_table_size = case['header_table_size'] decoded_headers = d.decode(unhexlify(case['wire'])) # The correct headers are a list of dicts, which is annoying. correct_headers = {(item[0], item[1]) for header in case['headers'] for item in header.items()} assert correct_headers == decoded_headers
from hyper.http20.hpack import Decoder from hyper.http20.huffman import HuffmanDecoder from hyper.http20.huffman_constants import REQUEST_CODES, REQUEST_CODES_LENGTH from binascii import unhexlify class TestHPACKDecoderIntegration(object): def test_can_decode_a_story(self, story): d = Decoder() if story['context'] == 'request': d.huffman_coder = HuffmanDecoder(REQUEST_CODES, REQUEST_CODES_LENGTH) for case in story['cases']: d.header_table_size = case['header_table_size'] decoded_headers = d.decode(unhexlify(case['wire'])) # The correct headers are a list of dicts, which is annoying. correct_headers = {(item[0], item[1]) for header in case['headers'] for item in header.items()} assert correct_headers == decoded_headers
Use the correct decoder for the test.
Use the correct decoder for the test.
Python
mit
Lukasa/hyper,masaori335/hyper,lawnmowerlatte/hyper,fredthomsen/hyper,irvind/hyper,lawnmowerlatte/hyper,masaori335/hyper,jdecuyper/hyper,irvind/hyper,fredthomsen/hyper,plucury/hyper,plucury/hyper,Lukasa/hyper,jdecuyper/hyper
from hyper.http20.hpack import Decoder + from hyper.http20.huffman import HuffmanDecoder + from hyper.http20.huffman_constants import REQUEST_CODES, REQUEST_CODES_LENGTH from binascii import unhexlify class TestHPACKDecoderIntegration(object): def test_can_decode_a_story(self, story): d = Decoder() + + if story['context'] == 'request': + d.huffman_coder = HuffmanDecoder(REQUEST_CODES, REQUEST_CODES_LENGTH) + for case in story['cases']: d.header_table_size = case['header_table_size'] decoded_headers = d.decode(unhexlify(case['wire'])) # The correct headers are a list of dicts, which is annoying. correct_headers = {(item[0], item[1]) for header in case['headers'] for item in header.items()} assert correct_headers == decoded_headers
Use the correct decoder for the test.
## Code Before: from hyper.http20.hpack import Decoder from binascii import unhexlify class TestHPACKDecoderIntegration(object): def test_can_decode_a_story(self, story): d = Decoder() for case in story['cases']: d.header_table_size = case['header_table_size'] decoded_headers = d.decode(unhexlify(case['wire'])) # The correct headers are a list of dicts, which is annoying. correct_headers = {(item[0], item[1]) for header in case['headers'] for item in header.items()} assert correct_headers == decoded_headers ## Instruction: Use the correct decoder for the test. ## Code After: from hyper.http20.hpack import Decoder from hyper.http20.huffman import HuffmanDecoder from hyper.http20.huffman_constants import REQUEST_CODES, REQUEST_CODES_LENGTH from binascii import unhexlify class TestHPACKDecoderIntegration(object): def test_can_decode_a_story(self, story): d = Decoder() if story['context'] == 'request': d.huffman_coder = HuffmanDecoder(REQUEST_CODES, REQUEST_CODES_LENGTH) for case in story['cases']: d.header_table_size = case['header_table_size'] decoded_headers = d.decode(unhexlify(case['wire'])) # The correct headers are a list of dicts, which is annoying. correct_headers = {(item[0], item[1]) for header in case['headers'] for item in header.items()} assert correct_headers == decoded_headers
from hyper.http20.hpack import Decoder + from hyper.http20.huffman import HuffmanDecoder + from hyper.http20.huffman_constants import REQUEST_CODES, REQUEST_CODES_LENGTH from binascii import unhexlify class TestHPACKDecoderIntegration(object): def test_can_decode_a_story(self, story): d = Decoder() + + if story['context'] == 'request': + d.huffman_coder = HuffmanDecoder(REQUEST_CODES, REQUEST_CODES_LENGTH) + for case in story['cases']: d.header_table_size = case['header_table_size'] decoded_headers = d.decode(unhexlify(case['wire'])) # The correct headers are a list of dicts, which is annoying. correct_headers = {(item[0], item[1]) for header in case['headers'] for item in header.items()} assert correct_headers == decoded_headers
a65d6ae9a6be0988bb74ecff7982c91be5273c58
meinberlin/apps/bplan/management/commands/bplan_auto_archive.py
meinberlin/apps/bplan/management/commands/bplan_auto_archive.py
from django.core.management.base import BaseCommand from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): help = 'Archive finished bplan projects.' def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: if bplan.has_finished: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name))
from datetime import timedelta from django.core.management.base import BaseCommand from django.utils import timezone from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): help = 'Archive finished bplan projects and delete old statements.' def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: if bplan.has_finished and not bplan.is_archived: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name)) # Delete statements of archived projects # To prevent deleting statements that have not been sent by mail yet # only statements older then 48h are deleted. num_deleted, _ = bplan_models.Statement.objects\ .filter(module__project__is_archived=True)\ .filter(created__lt=timezone.now() - timedelta(hours=48))\ .delete() if num_deleted: self.stdout.write('Deleted {} statements from archived bplans.' .format(num_deleted))
Delete statements from archived bplans
Delete statements from archived bplans After a bplan is archived it's related statements may be deleted. For simpler development/deployment the auto_archive script is extended to delete the statements, altough it may have been possible to add another command. To prevent from loosing statements that are created just before the participation ends, the deletion is delayed for 48 hours. (In rare cases a statement may not have been sent due to the async nature of our email interface, when the project is already archived)
Python
agpl-3.0
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
+ from datetime import timedelta + from django.core.management.base import BaseCommand + from django.utils import timezone from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): - help = 'Archive finished bplan projects.' + help = 'Archive finished bplan projects and delete old statements.' def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: - if bplan.has_finished: + if bplan.has_finished and not bplan.is_archived: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name)) + # Delete statements of archived projects + # To prevent deleting statements that have not been sent by mail yet + # only statements older then 48h are deleted. + num_deleted, _ = bplan_models.Statement.objects\ + .filter(module__project__is_archived=True)\ + .filter(created__lt=timezone.now() - timedelta(hours=48))\ + .delete() + if num_deleted: + self.stdout.write('Deleted {} statements from archived bplans.' + .format(num_deleted)) +
Delete statements from archived bplans
## Code Before: from django.core.management.base import BaseCommand from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): help = 'Archive finished bplan projects.' def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: if bplan.has_finished: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name)) ## Instruction: Delete statements from archived bplans ## Code After: from datetime import timedelta from django.core.management.base import BaseCommand from django.utils import timezone from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): help = 'Archive finished bplan projects and delete old statements.' def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: if bplan.has_finished and not bplan.is_archived: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name)) # Delete statements of archived projects # To prevent deleting statements that have not been sent by mail yet # only statements older then 48h are deleted. num_deleted, _ = bplan_models.Statement.objects\ .filter(module__project__is_archived=True)\ .filter(created__lt=timezone.now() - timedelta(hours=48))\ .delete() if num_deleted: self.stdout.write('Deleted {} statements from archived bplans.' .format(num_deleted))
+ from datetime import timedelta + from django.core.management.base import BaseCommand + from django.utils import timezone from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): - help = 'Archive finished bplan projects.' + help = 'Archive finished bplan projects and delete old statements.' ? ++++++++++++++++++++++++++ def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: - if bplan.has_finished: + if bplan.has_finished and not bplan.is_archived: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name)) + + # Delete statements of archived projects + # To prevent deleting statements that have not been sent by mail yet + # only statements older then 48h are deleted. + num_deleted, _ = bplan_models.Statement.objects\ + .filter(module__project__is_archived=True)\ + .filter(created__lt=timezone.now() - timedelta(hours=48))\ + .delete() + if num_deleted: + self.stdout.write('Deleted {} statements from archived bplans.' + .format(num_deleted))
cdaffa187b41f3a84cb5a6b44f2e781a9b249f2b
tests/test_users.py
tests/test_users.py
from context import slot_users_controller as uc class TestUsers: def test_validate_credentials_returns_true_for_valid_credentials(self): result = uc.return_user_if_valid_credentials('slot', 'test') assert result is True def test_validate_credentials_returns_false_for_invalid_credentials(self): result = uc.return_user_if_valid_credentials('bad_username', 'bad_password') assert result is False def test_convert_dict_to_user_instance_returns_valid_user_instance(self): result = uc.convert_dict_to_user_instance({}) assert result
from context import slot_users_controller as uc class TestUsers: def test_validate_credentials_returns_true_for_valid_credentials(self): result = uc.return_user_if_valid_credentials('slot', 'test') assert result is True def test_validate_credentials_returns_false_for_invalid_credentials(self): result = uc.return_user_if_valid_credentials('bad_username', 'bad_password') assert result is False def test_convert_dict_to_user_instance_returns_valid_user_instance(self): result = uc.return_user_instance_or_anonymous({}) assert result
Update test to reflect new method name.
Update test to reflect new method name.
Python
mit
nhshd-slot/SLOT,nhshd-slot/SLOT,nhshd-slot/SLOT
from context import slot_users_controller as uc class TestUsers: def test_validate_credentials_returns_true_for_valid_credentials(self): result = uc.return_user_if_valid_credentials('slot', 'test') assert result is True def test_validate_credentials_returns_false_for_invalid_credentials(self): result = uc.return_user_if_valid_credentials('bad_username', 'bad_password') assert result is False def test_convert_dict_to_user_instance_returns_valid_user_instance(self): - result = uc.convert_dict_to_user_instance({}) + result = uc.return_user_instance_or_anonymous({}) assert result
Update test to reflect new method name.
## Code Before: from context import slot_users_controller as uc class TestUsers: def test_validate_credentials_returns_true_for_valid_credentials(self): result = uc.return_user_if_valid_credentials('slot', 'test') assert result is True def test_validate_credentials_returns_false_for_invalid_credentials(self): result = uc.return_user_if_valid_credentials('bad_username', 'bad_password') assert result is False def test_convert_dict_to_user_instance_returns_valid_user_instance(self): result = uc.convert_dict_to_user_instance({}) assert result ## Instruction: Update test to reflect new method name. ## Code After: from context import slot_users_controller as uc class TestUsers: def test_validate_credentials_returns_true_for_valid_credentials(self): result = uc.return_user_if_valid_credentials('slot', 'test') assert result is True def test_validate_credentials_returns_false_for_invalid_credentials(self): result = uc.return_user_if_valid_credentials('bad_username', 'bad_password') assert result is False def test_convert_dict_to_user_instance_returns_valid_user_instance(self): result = uc.return_user_instance_or_anonymous({}) assert result
from context import slot_users_controller as uc class TestUsers: def test_validate_credentials_returns_true_for_valid_credentials(self): result = uc.return_user_if_valid_credentials('slot', 'test') assert result is True def test_validate_credentials_returns_false_for_invalid_credentials(self): result = uc.return_user_if_valid_credentials('bad_username', 'bad_password') assert result is False def test_convert_dict_to_user_instance_returns_valid_user_instance(self): - result = uc.convert_dict_to_user_instance({}) + result = uc.return_user_instance_or_anonymous({}) assert result
2bebbbfc12e1013e3c5c0a42329bac520c574b9b
tests/test_settings.py
tests/test_settings.py
import pytest import npc import os from tests.util import fixture_dir @pytest.fixture def settings(): return npc.settings.Settings() def test_creation(settings): assert settings is not None def test_override(settings): override_path = fixture_dir(['settings/settings-vim.json']) old_editor = settings.get('editor') settings.load_more(override_path) assert settings.get('editor') != old_editor def test_nested_get(settings): assert settings.get('paths.characters') == 'Characters' def test_get_settings_path(settings): assert settings.get_settings_path('default') == os.path.join(settings.default_settings_path, 'settings-default.json') assert settings.get_settings_path('campaign') == os.path.join(settings.campaign_settings_path, 'settings.json') def test_support_paths(settings): """Paths loaded from additional files should be expanded relative to that file""" override_path = fixture_dir(['settings/settings-paths.json']) settings.load_more(override_path) assert settings.get('support.testpath') == fixture_dir(['settings/nothing.json'])
import pytest import npc import os from tests.util import fixture_dir def test_creation(prefs): assert prefs is not None def test_override(prefs): override_path = fixture_dir(['settings/settings-vim.json']) old_editor = prefs.get('editor') prefs.load_more(override_path) assert prefs.get('editor') != old_editor def test_nested_get(prefs): assert prefs.get('paths.characters') == 'Characters' def test_get_settings_path(prefs): assert prefs.get_settings_path('default') == os.path.join(prefs.default_settings_path, 'settings-default.json') assert prefs.get_settings_path('campaign') == os.path.join(prefs.campaign_settings_path, 'settings.json') def test_support_paths(prefs): """Paths loaded from additional files should be expanded relative to that file""" override_path = fixture_dir(['settings/settings-paths.json']) prefs.load_more(override_path) assert prefs.get('support.testpath') == fixture_dir(['settings/nothing.json'])
Refactor settings tests to use global fixture
Refactor settings tests to use global fixture
Python
mit
aurule/npc,aurule/npc
import pytest import npc import os from tests.util import fixture_dir + def test_creation(prefs): + assert prefs is not None - @pytest.fixture - def settings(): - return npc.settings.Settings() - def test_creation(settings): - assert settings is not None + def test_override(prefs): + override_path = fixture_dir(['settings/settings-vim.json']) + old_editor = prefs.get('editor') + prefs.load_more(override_path) + assert prefs.get('editor') != old_editor + def test_nested_get(prefs): + assert prefs.get('paths.characters') == 'Characters' - def test_override(settings): - override_path = fixture_dir(['settings/settings-vim.json']) - old_editor = settings.get('editor') - settings.load_more(override_path) - assert settings.get('editor') != old_editor - def test_nested_get(settings): - assert settings.get('paths.characters') == 'Characters' + def test_get_settings_path(prefs): + assert prefs.get_settings_path('default') == os.path.join(prefs.default_settings_path, 'settings-default.json') + assert prefs.get_settings_path('campaign') == os.path.join(prefs.campaign_settings_path, 'settings.json') - def test_get_settings_path(settings): - assert settings.get_settings_path('default') == os.path.join(settings.default_settings_path, 'settings-default.json') - assert settings.get_settings_path('campaign') == os.path.join(settings.campaign_settings_path, 'settings.json') - - def test_support_paths(settings): + def test_support_paths(prefs): """Paths loaded from additional files should be expanded relative to that file""" override_path = fixture_dir(['settings/settings-paths.json']) - settings.load_more(override_path) + prefs.load_more(override_path) - assert settings.get('support.testpath') == fixture_dir(['settings/nothing.json']) + assert prefs.get('support.testpath') == fixture_dir(['settings/nothing.json'])
Refactor settings tests to use global fixture
## Code Before: import pytest import npc import os from tests.util import fixture_dir @pytest.fixture def settings(): return npc.settings.Settings() def test_creation(settings): assert settings is not None def test_override(settings): override_path = fixture_dir(['settings/settings-vim.json']) old_editor = settings.get('editor') settings.load_more(override_path) assert settings.get('editor') != old_editor def test_nested_get(settings): assert settings.get('paths.characters') == 'Characters' def test_get_settings_path(settings): assert settings.get_settings_path('default') == os.path.join(settings.default_settings_path, 'settings-default.json') assert settings.get_settings_path('campaign') == os.path.join(settings.campaign_settings_path, 'settings.json') def test_support_paths(settings): """Paths loaded from additional files should be expanded relative to that file""" override_path = fixture_dir(['settings/settings-paths.json']) settings.load_more(override_path) assert settings.get('support.testpath') == fixture_dir(['settings/nothing.json']) ## Instruction: Refactor settings tests to use global fixture ## Code After: import pytest import npc import os from tests.util import fixture_dir def test_creation(prefs): assert prefs is not None def test_override(prefs): override_path = fixture_dir(['settings/settings-vim.json']) old_editor = prefs.get('editor') prefs.load_more(override_path) assert prefs.get('editor') != old_editor def test_nested_get(prefs): assert prefs.get('paths.characters') == 'Characters' def test_get_settings_path(prefs): assert prefs.get_settings_path('default') == os.path.join(prefs.default_settings_path, 'settings-default.json') assert prefs.get_settings_path('campaign') == os.path.join(prefs.campaign_settings_path, 'settings.json') def test_support_paths(prefs): """Paths loaded from additional files should be expanded relative to that file""" override_path = fixture_dir(['settings/settings-paths.json']) prefs.load_more(override_path) assert prefs.get('support.testpath') == fixture_dir(['settings/nothing.json'])
import pytest import npc import os from tests.util import fixture_dir + def test_creation(prefs): + assert prefs is not None - @pytest.fixture - def settings(): - return npc.settings.Settings() - def test_creation(settings): - assert settings is not None + def test_override(prefs): + override_path = fixture_dir(['settings/settings-vim.json']) + old_editor = prefs.get('editor') + prefs.load_more(override_path) + assert prefs.get('editor') != old_editor + def test_nested_get(prefs): + assert prefs.get('paths.characters') == 'Characters' - def test_override(settings): - override_path = fixture_dir(['settings/settings-vim.json']) - old_editor = settings.get('editor') - settings.load_more(override_path) - assert settings.get('editor') != old_editor - def test_nested_get(settings): - assert settings.get('paths.characters') == 'Characters' + def test_get_settings_path(prefs): + assert prefs.get_settings_path('default') == os.path.join(prefs.default_settings_path, 'settings-default.json') + assert prefs.get_settings_path('campaign') == os.path.join(prefs.campaign_settings_path, 'settings.json') - def test_get_settings_path(settings): - assert settings.get_settings_path('default') == os.path.join(settings.default_settings_path, 'settings-default.json') - assert settings.get_settings_path('campaign') == os.path.join(settings.campaign_settings_path, 'settings.json') - - def test_support_paths(settings): ? ^ ^^^^^ + def test_support_paths(prefs): ? ^^ ^ """Paths loaded from additional files should be expanded relative to that file""" override_path = fixture_dir(['settings/settings-paths.json']) - settings.load_more(override_path) ? ^ ^^^^^ + prefs.load_more(override_path) ? ^^ ^ - assert settings.get('support.testpath') == fixture_dir(['settings/nothing.json']) ? ^ ^^^^^ + assert prefs.get('support.testpath') == fixture_dir(['settings/nothing.json']) ? ^^ ^
2c54a9eb78a1cb88ef03db97e21e376ae764a33e
errata/admin_actions.py
errata/admin_actions.py
import unicodecsv from django.http import HttpResponse from django.utils.encoding import smart_str def export_as_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True): """ This function returns an export csv action 'fields' and 'exclude' work like in django ModelForm 'header' is whether or not to output the column names as the first row """ def export_as_csv(modeladmin, request, queryset): opts = modeladmin.model._meta if not fields: field_names = [field.name for field in opts.fields] else: field_names = fields response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_') writer = unicodecsv.writer(response, encoding='utf-8') if header: writer.writerow(field_names) for obj in queryset: row = [getattr(obj, field)() if callable(getattr(obj, field)) else getattr(obj, field) for field in field_names] writer.writerow(row) return response export_as_csv.short_description = description return export_as_csv
import unicodecsv from django.http import StreamingHttpResponse class Echo: """An object that implements just the write method of the file-like interface. """ def write(self, value): """Write the value by returning it, instead of storing in a buffer.""" return value def export_as_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True): """ This function returns an export csv action 'fields' and 'exclude' work like in django ModelForm 'header' is whether or not to output the column names as the first row """ def export_as_csv(modeladmin, request, queryset): opts = modeladmin.model._meta if not fields: field_names = [field.name for field in opts.fields] else: field_names = fields response = StreamingHttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_') pseudo_buffer = Echo() writer = unicodecsv.writer(pseudo_buffer) if header: writer.writerow(field_names) for obj in queryset: row = [getattr(obj, field)() if callable(getattr(obj, field)) else getattr(obj, field) for field in field_names] writer.writerow(row) return response export_as_csv.short_description = description return export_as_csv
Make use of Django's StreamingHttpResponse for large CSV exports
Make use of Django's StreamingHttpResponse for large CSV exports
Python
agpl-3.0
Connexions/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms
import unicodecsv - from django.http import HttpResponse + from django.http import StreamingHttpResponse - from django.utils.encoding import smart_str + + class Echo: + """An object that implements just the write method of the file-like + interface. + """ + def write(self, value): + """Write the value by returning it, instead of storing in a buffer.""" + return value def export_as_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True): """ This function returns an export csv action 'fields' and 'exclude' work like in django ModelForm 'header' is whether or not to output the column names as the first row """ def export_as_csv(modeladmin, request, queryset): opts = modeladmin.model._meta if not fields: field_names = [field.name for field in opts.fields] else: field_names = fields - response = HttpResponse(content_type='text/csv') + response = StreamingHttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_') - writer = unicodecsv.writer(response, encoding='utf-8') + pseudo_buffer = Echo() + writer = unicodecsv.writer(pseudo_buffer) if header: writer.writerow(field_names) for obj in queryset: row = [getattr(obj, field)() if callable(getattr(obj, field)) else getattr(obj, field) for field in field_names] writer.writerow(row) return response export_as_csv.short_description = description return export_as_csv +
Make use of Django's StreamingHttpResponse for large CSV exports
## Code Before: import unicodecsv from django.http import HttpResponse from django.utils.encoding import smart_str def export_as_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True): """ This function returns an export csv action 'fields' and 'exclude' work like in django ModelForm 'header' is whether or not to output the column names as the first row """ def export_as_csv(modeladmin, request, queryset): opts = modeladmin.model._meta if not fields: field_names = [field.name for field in opts.fields] else: field_names = fields response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_') writer = unicodecsv.writer(response, encoding='utf-8') if header: writer.writerow(field_names) for obj in queryset: row = [getattr(obj, field)() if callable(getattr(obj, field)) else getattr(obj, field) for field in field_names] writer.writerow(row) return response export_as_csv.short_description = description return export_as_csv ## Instruction: Make use of Django's StreamingHttpResponse for large CSV exports ## Code After: import unicodecsv from django.http import StreamingHttpResponse class Echo: """An object that implements just the write method of the file-like interface. """ def write(self, value): """Write the value by returning it, instead of storing in a buffer.""" return value def export_as_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True): """ This function returns an export csv action 'fields' and 'exclude' work like in django ModelForm 'header' is whether or not to output the column names as the first row """ def export_as_csv(modeladmin, request, queryset): opts = modeladmin.model._meta if not fields: field_names = [field.name for field in opts.fields] else: field_names = fields response = StreamingHttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_') pseudo_buffer = Echo() writer = unicodecsv.writer(pseudo_buffer) if header: writer.writerow(field_names) for obj in queryset: row = [getattr(obj, field)() if callable(getattr(obj, field)) else getattr(obj, field) for field in field_names] writer.writerow(row) return response export_as_csv.short_description = description return export_as_csv
import unicodecsv - from django.http import HttpResponse + from django.http import StreamingHttpResponse ? +++++++++ - from django.utils.encoding import smart_str + + class Echo: + """An object that implements just the write method of the file-like + interface. + """ + def write(self, value): + """Write the value by returning it, instead of storing in a buffer.""" + return value def export_as_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True): """ This function returns an export csv action 'fields' and 'exclude' work like in django ModelForm 'header' is whether or not to output the column names as the first row """ def export_as_csv(modeladmin, request, queryset): opts = modeladmin.model._meta if not fields: field_names = [field.name for field in opts.fields] else: field_names = fields - response = HttpResponse(content_type='text/csv') + response = StreamingHttpResponse(content_type='text/csv') ? +++++++++ response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_') - writer = unicodecsv.writer(response, encoding='utf-8') + pseudo_buffer = Echo() + writer = unicodecsv.writer(pseudo_buffer) if header: writer.writerow(field_names) for obj in queryset: row = [getattr(obj, field)() if callable(getattr(obj, field)) else getattr(obj, field) for field in field_names] writer.writerow(row) return response export_as_csv.short_description = description return export_as_csv
33facaa6e656ecc30233d831ca8c8d1f2abc6d03
src/tmserver/extensions/__init__.py
src/tmserver/extensions/__init__.py
from auth import jwt from spark import Spark spark = Spark() from gc3pie import GC3Pie gc3pie = GC3Pie() from flask.ext.uwsgi_websocket import GeventWebSocket websocket = GeventWebSocket() from flask.ext.redis import FlaskRedis redis_store = FlaskRedis()
from auth import jwt from spark import Spark spark = Spark() from gc3pie import GC3Pie gc3pie = GC3Pie() from flask_uwsgi_websocket import GeventWebSocket websocket = GeventWebSocket() from flask_redis import FlaskRedis redis_store = FlaskRedis()
Update depracted flask extension code
Update depracted flask extension code
Python
agpl-3.0
TissueMAPS/TmServer
from auth import jwt from spark import Spark spark = Spark() from gc3pie import GC3Pie gc3pie = GC3Pie() - from flask.ext.uwsgi_websocket import GeventWebSocket + from flask_uwsgi_websocket import GeventWebSocket websocket = GeventWebSocket() - from flask.ext.redis import FlaskRedis + from flask_redis import FlaskRedis redis_store = FlaskRedis()
Update depracted flask extension code
## Code Before: from auth import jwt from spark import Spark spark = Spark() from gc3pie import GC3Pie gc3pie = GC3Pie() from flask.ext.uwsgi_websocket import GeventWebSocket websocket = GeventWebSocket() from flask.ext.redis import FlaskRedis redis_store = FlaskRedis() ## Instruction: Update depracted flask extension code ## Code After: from auth import jwt from spark import Spark spark = Spark() from gc3pie import GC3Pie gc3pie = GC3Pie() from flask_uwsgi_websocket import GeventWebSocket websocket = GeventWebSocket() from flask_redis import FlaskRedis redis_store = FlaskRedis()
from auth import jwt from spark import Spark spark = Spark() from gc3pie import GC3Pie gc3pie = GC3Pie() - from flask.ext.uwsgi_websocket import GeventWebSocket ? ^^^^^ + from flask_uwsgi_websocket import GeventWebSocket ? ^ websocket = GeventWebSocket() - from flask.ext.redis import FlaskRedis ? ^^^^^ + from flask_redis import FlaskRedis ? ^ redis_store = FlaskRedis()
ff65a3e1b0f061100a20462dea4f654b02707a6f
fig/cli/command.py
fig/cli/command.py
from docker import Client import logging import os import re import yaml from ..project import Project from .docopt_command import DocoptCommand from .formatter import Formatter from .utils import cached_property log = logging.getLogger(__name__) class Command(DocoptCommand): @cached_property def client(self): if os.environ.get('DOCKER_URL'): return Client(os.environ['DOCKER_URL']) else: return Client() @cached_property def project(self): config = yaml.load(open('fig.yml')) return Project.from_config(self.project_name, config, self.client) @cached_property def project_name(self): project = os.path.basename(os.getcwd()) project = re.sub(r'[^a-zA-Z0-9]', '', project) if not project: project = 'default' return project @cached_property def formatter(self): return Formatter()
from docker import Client import logging import os import re import yaml import socket from ..project import Project from .docopt_command import DocoptCommand from .formatter import Formatter from .utils import cached_property from .errors import UserError log = logging.getLogger(__name__) class Command(DocoptCommand): @cached_property def client(self): if os.environ.get('DOCKER_URL'): return Client(os.environ['DOCKER_URL']) socket_path = '/var/run/docker.sock' tcp_host = '127.0.0.1' tcp_port = 4243 if os.path.exists(socket_path): return Client('unix://%s' % socket_path) try: s = socket.socket() s.connect((tcp_host, tcp_port)) s.close() return Client('http://%s:%s' % (tcp_host, tcp_port)) except: pass raise UserError(""" Couldn't find Docker daemon - tried %s and %s:%s. If it's running elsewhere, specify a url with DOCKER_URL. """ % (socket_path, tcp_host, tcp_port)) @cached_property def project(self): config = yaml.load(open('fig.yml')) return Project.from_config(self.project_name, config, self.client) @cached_property def project_name(self): project = os.path.basename(os.getcwd()) project = re.sub(r'[^a-zA-Z0-9]', '', project) if not project: project = 'default' return project @cached_property def formatter(self): return Formatter()
Check default socket and localhost:4243 for Docker daemon
Check default socket and localhost:4243 for Docker daemon
Python
apache-2.0
MSakamaki/compose,alexisbellido/docker.github.io,prologic/compose,KevinGreene/compose,phiroict/docker,calou/compose,rillig/docker.github.io,docker/docker.github.io,phiroict/docker,vlajos/compose,ekristen/compose,JimGalasyn/docker.github.io,albers/compose,zhangspook/compose,charleswhchan/compose,talolard/compose,nhumrich/compose,mrfuxi/compose,rillig/docker.github.io,saada/compose,rgbkrk/compose,ggtools/compose,michael-k/docker-compose,anweiss/docker.github.io,joaofnfernandes/docker.github.io,kikkomep/compose,joaofnfernandes/docker.github.io,funkyfuture/docker-compose,Katlean/fig,menglingwei/denverdino.github.io,abesto/fig,heroku/fig,josephpage/compose,menglingwei/denverdino.github.io,browning/compose,ralphtheninja/compose,bsmr-docker/compose,tangkun75/compose,cclauss/compose,sanscontext/docker.github.io,thaJeztah/compose,ouziel-slama/compose,gtrdotmcs/compose,BSWANG/denverdino.github.io,docker-zh/docker.github.io,bdwill/docker.github.io,thaJeztah/docker.github.io,sanscontext/docker.github.io,vdemeester/compose,bfirsh/fig,gdevillele/docker.github.io,zhangspook/compose,menglingwei/denverdino.github.io,Yelp/docker-compose,jonaseck2/compose,sanscontext/docker.github.io,tiry/compose,menglingwei/denverdino.github.io,bcicen/fig,ChrisChinchilla/compose,thieman/compose,ouziel-slama/compose,ekristen/compose,danix800/docker.github.io,sdurrheimer/compose,goloveychuk/compose,aduermael/docker.github.io,denverdino/docker.github.io,Dakno/compose,sebglazebrook/compose,troy0820/docker.github.io,ZJaffee/compose,dilgerma/compose,shin-/compose,lukemarsden/compose,dockerhn/compose,ain/compose,dnephin/compose,docker/docker.github.io,aanand/fig,simonista/compose,vlajos/compose,docker-zh/docker.github.io,noironetworks/compose,genki/compose,xydinesh/compose,aduermael/docker.github.io,brunocascio/compose,viranch/compose,funkyfuture/docker-compose,bobphill/compose,mohitsoni/compose,benhamill/compose,denverdino/denverdino.github.io,sdurrheimer/compose,anweiss/docker.github.io,alexisbellido/docker.github.io,mbailey/compose,jrabbit/compose,shubheksha/docker.github.io,shakamunyi/fig,denverdino/docker.github.io,phiroict/docker,bdwill/docker.github.io,jiekechoo/compose,danix800/docker.github.io,docker-zh/docker.github.io,xydinesh/compose,mbailey/compose,phiroict/docker,talolard/compose,jeanpralo/compose,bsmr-docker/compose,thaJeztah/docker.github.io,DoubleMalt/compose,LuisBosquez/docker.github.io,BSWANG/denverdino.github.io,JimGalasyn/docker.github.io,hypriot/compose,dopry/compose,jzwlqx/denverdino.github.io,KalleDK/compose,schmunk42/compose,kojiromike/compose,joeuo/docker.github.io,thaJeztah/docker.github.io,viranch/compose,gdevillele/docker.github.io,kojiromike/compose,ain/compose,sebglazebrook/compose,tiry/compose,dopry/compose,au-phiware/compose,BSWANG/denverdino.github.io,phiroict/docker,bdwill/docker.github.io,JimGalasyn/docker.github.io,mark-adams/compose,qzio/compose,mdaue/compose,alexisbellido/docker.github.io,dnephin/compose,marcusmartins/compose,jorgeLuizChaves/compose,troy0820/docker.github.io,shubheksha/docker.github.io,jessekl/compose,pspierce/compose,alunduil/fig,twitherspoon/compose,andrewgee/compose,aanand/fig,screwgoth/compose,jzwlqx/denverdino.github.io,londoncalling/docker.github.io,j-fuentes/compose,joaofnfernandes/docker.github.io,danix800/docker.github.io,mdaue/compose,troy0820/docker.github.io,Chouser/compose,amitsaha/compose,tpounds/compose,thaJeztah/docker.github.io,mosquito/docker-compose,cgvarela/compose,lmesz/compose,ggtools/compose,KevinGreene/compose,LuisBosquez/docker.github.io,JimGalasyn/docker.github.io,pspierce/compose,shubheksha/docker.github.io,screwgoth/compose,runcom/compose,philwrenn/compose,TheDataShed/compose,gtrdotmcs/compose,kikkomep/compose,mnuessler/compose,ph-One/compose,jzwlqx/denverdino.github.io,schmunk42/compose,rillig/docker.github.io,mindaugasrukas/compose,Katlean/fig,BSWANG/denverdino.github.io,unodba/compose,glogiotatidis/compose,shubheksha/docker.github.io,d2bit/compose,nerro/compose,moxiegirl/compose,jiekechoo/compose,alexisbellido/docker.github.io,troy0820/docker.github.io,mrfuxi/compose,alexandrev/compose,denverdino/docker.github.io,uvgroovy/compose,heroku/fig,jzwlqx/denverdino.github.io,RobertNorthard/compose,jgrowl/compose,shin-/docker.github.io,swoopla/compose,prologic/compose,shin-/docker.github.io,unodba/compose,Dakno/compose,JimGalasyn/docker.github.io,LuisBosquez/docker.github.io,denverdino/denverdino.github.io,LuisBosquez/docker.github.io,docker-zh/docker.github.io,thaJeztah/compose,tpounds/compose,iamluc/compose,ionrock/compose,shakamunyi/fig,nerro/compose,uvgroovy/compose,brunocascio/compose,thieman/compose,ph-One/compose,lmesz/compose,gdevillele/docker.github.io,docker/docker.github.io,anweiss/docker.github.io,benhamill/compose,anweiss/docker.github.io,ionrock/compose,joeuo/docker.github.io,BSWANG/denverdino.github.io,londoncalling/docker.github.io,mchasal/compose,denverdino/denverdino.github.io,joeuo/docker.github.io,mark-adams/compose,browning/compose,noironetworks/compose,bdwill/docker.github.io,runcom/compose,charleswhchan/compose,shin-/docker.github.io,ralphtheninja/compose,menglingwei/denverdino.github.io,aduermael/docker.github.io,alexisbellido/docker.github.io,genki/compose,alexandrev/compose,londoncalling/docker.github.io,amitsaha/compose,hypriot/compose,iamluc/compose,rillig/docker.github.io,denverdino/docker.github.io,jeanpralo/compose,j-fuentes/compose,alunduil/fig,feelobot/compose,joeuo/docker.github.io,Yelp/docker-compose,denverdino/denverdino.github.io,mindaugasrukas/compose,swoopla/compose,marcusmartins/compose,shin-/docker.github.io,dilgerma/compose,GM-Alex/compose,londoncalling/docker.github.io,mnuessler/compose,bbirand/compose,rgbkrk/compose,bcicen/fig,TomasTomecek/compose,qzio/compose,denverdino/denverdino.github.io,johnstep/docker.github.io,denverdino/docker.github.io,DoubleMalt/compose,denverdino/compose,KalleDK/compose,michael-k/docker-compose,calou/compose,simonista/compose,bdwill/docker.github.io,aduermael/docker.github.io,GM-Alex/compose,LuisBosquez/docker.github.io,d2bit/compose,dbdd4us/compose,VinceBarresi/compose,TheDataShed/compose,jorgeLuizChaves/compose,andrewgee/compose,mosquito/docker-compose,goloveychuk/compose,mohitsoni/compose,Chouser/compose,docker-zh/docker.github.io,mnowster/compose,johnstep/docker.github.io,albers/compose,hoogenm/compose,lukemarsden/compose,cclauss/compose,anweiss/docker.github.io,artemkaint/compose,bbirand/compose,saada/compose,twitherspoon/compose,shin-/docker.github.io,rstacruz/compose,nhumrich/compose,hoogenm/compose,philwrenn/compose,ChrisChinchilla/compose,danix800/docker.github.io,rstacruz/compose,mchasal/compose,ZJaffee/compose,dbdd4us/compose,shubheksha/docker.github.io,joaofnfernandes/docker.github.io,joeuo/docker.github.io,jrabbit/compose,moxiegirl/compose,heroku/fig,docker/docker.github.io,tangkun75/compose,glogiotatidis/compose,josephpage/compose,jessekl/compose,gdevillele/docker.github.io,johnstep/docker.github.io,joaofnfernandes/docker.github.io,bcicen/fig,feelobot/compose,docker/docker.github.io,artemkaint/compose,johnstep/docker.github.io,au-phiware/compose,jonaseck2/compose,jzwlqx/denverdino.github.io,MSakamaki/compose,bobphill/compose,vdemeester/compose,bfirsh/fig,TomasTomecek/compose,sanscontext/docker.github.io,jgrowl/compose,sanscontext/docker.github.io,cgvarela/compose,thaJeztah/docker.github.io,dockerhn/compose,londoncalling/docker.github.io,johnstep/docker.github.io,shin-/compose,VinceBarresi/compose,abesto/fig,RobertNorthard/compose,gdevillele/docker.github.io,denverdino/compose,mnowster/compose
from docker import Client import logging import os import re import yaml + import socket from ..project import Project from .docopt_command import DocoptCommand from .formatter import Formatter from .utils import cached_property + from .errors import UserError log = logging.getLogger(__name__) class Command(DocoptCommand): @cached_property def client(self): if os.environ.get('DOCKER_URL'): return Client(os.environ['DOCKER_URL']) + + socket_path = '/var/run/docker.sock' + tcp_host = '127.0.0.1' + tcp_port = 4243 + + if os.path.exists(socket_path): + return Client('unix://%s' % socket_path) + + try: + s = socket.socket() + s.connect((tcp_host, tcp_port)) + s.close() + return Client('http://%s:%s' % (tcp_host, tcp_port)) - else: + except: - return Client() + pass + + raise UserError(""" + Couldn't find Docker daemon - tried %s and %s:%s. + If it's running elsewhere, specify a url with DOCKER_URL. + """ % (socket_path, tcp_host, tcp_port)) @cached_property def project(self): config = yaml.load(open('fig.yml')) return Project.from_config(self.project_name, config, self.client) @cached_property def project_name(self): project = os.path.basename(os.getcwd()) project = re.sub(r'[^a-zA-Z0-9]', '', project) if not project: project = 'default' return project @cached_property def formatter(self): return Formatter()
Check default socket and localhost:4243 for Docker daemon
## Code Before: from docker import Client import logging import os import re import yaml from ..project import Project from .docopt_command import DocoptCommand from .formatter import Formatter from .utils import cached_property log = logging.getLogger(__name__) class Command(DocoptCommand): @cached_property def client(self): if os.environ.get('DOCKER_URL'): return Client(os.environ['DOCKER_URL']) else: return Client() @cached_property def project(self): config = yaml.load(open('fig.yml')) return Project.from_config(self.project_name, config, self.client) @cached_property def project_name(self): project = os.path.basename(os.getcwd()) project = re.sub(r'[^a-zA-Z0-9]', '', project) if not project: project = 'default' return project @cached_property def formatter(self): return Formatter() ## Instruction: Check default socket and localhost:4243 for Docker daemon ## Code After: from docker import Client import logging import os import re import yaml import socket from ..project import Project from .docopt_command import DocoptCommand from .formatter import Formatter from .utils import cached_property from .errors import UserError log = logging.getLogger(__name__) class Command(DocoptCommand): @cached_property def client(self): if os.environ.get('DOCKER_URL'): return Client(os.environ['DOCKER_URL']) socket_path = '/var/run/docker.sock' tcp_host = '127.0.0.1' tcp_port = 4243 if os.path.exists(socket_path): return Client('unix://%s' % socket_path) try: s = socket.socket() s.connect((tcp_host, tcp_port)) s.close() return Client('http://%s:%s' % (tcp_host, tcp_port)) except: pass raise UserError(""" Couldn't find Docker daemon - tried %s and %s:%s. If it's running elsewhere, specify a url with DOCKER_URL. """ % (socket_path, tcp_host, tcp_port)) @cached_property def project(self): config = yaml.load(open('fig.yml')) return Project.from_config(self.project_name, config, self.client) @cached_property def project_name(self): project = os.path.basename(os.getcwd()) project = re.sub(r'[^a-zA-Z0-9]', '', project) if not project: project = 'default' return project @cached_property def formatter(self): return Formatter()
from docker import Client import logging import os import re import yaml + import socket from ..project import Project from .docopt_command import DocoptCommand from .formatter import Formatter from .utils import cached_property + from .errors import UserError log = logging.getLogger(__name__) class Command(DocoptCommand): @cached_property def client(self): if os.environ.get('DOCKER_URL'): return Client(os.environ['DOCKER_URL']) + + socket_path = '/var/run/docker.sock' + tcp_host = '127.0.0.1' + tcp_port = 4243 + + if os.path.exists(socket_path): + return Client('unix://%s' % socket_path) + + try: + s = socket.socket() + s.connect((tcp_host, tcp_port)) + s.close() + return Client('http://%s:%s' % (tcp_host, tcp_port)) - else: ? ^^ + except: ? ^^ ++ - return Client() + pass + + raise UserError(""" + Couldn't find Docker daemon - tried %s and %s:%s. + If it's running elsewhere, specify a url with DOCKER_URL. + """ % (socket_path, tcp_host, tcp_port)) @cached_property def project(self): config = yaml.load(open('fig.yml')) return Project.from_config(self.project_name, config, self.client) @cached_property def project_name(self): project = os.path.basename(os.getcwd()) project = re.sub(r'[^a-zA-Z0-9]', '', project) if not project: project = 'default' return project @cached_property def formatter(self): return Formatter()
a95b1b2b5331e4248fe1d80244c763df4d3aca41
taiga/urls.py
taiga/urls.py
from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from .routers import router admin.autodiscover() urlpatterns = patterns('', url(r'^api/v1/', include(router.urls)), url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^admin/', include(admin.site.urls)), ) def mediafiles_urlpatterns(): """ Method for serve media files with runserver. """ _media_url = settings.MEDIA_URL if _media_url.startswith('/'): _media_url = _media_url[1:] from django.views.static import serve return patterns('', (r'^%s(?P<path>.*)$' % 'media', serve, {'document_root': settings.MEDIA_ROOT}) ) urlpatterns += staticfiles_urlpatterns() urlpatterns += mediafiles_urlpatterns()
from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from .routers import router admin.autodiscover() urlpatterns = patterns('', url(r'^api/v1/', include(router.urls)), url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^admin/', include(admin.site.urls)), ) def mediafiles_urlpatterns(): """ Method for serve media files with runserver. """ _media_url = settings.MEDIA_URL if _media_url.startswith('/'): _media_url = _media_url[1:] from django.views.static import serve return patterns('', (r'^%s(?P<path>.*)$' % 'media', serve, {'document_root': settings.MEDIA_ROOT}) ) urlpatterns += staticfiles_urlpatterns(prefix="/static/") urlpatterns += mediafiles_urlpatterns()
Set prefix to static url patterm call
Set prefix to static url patterm call
Python
agpl-3.0
jeffdwyatt/taiga-back,bdang2012/taiga-back-casting,WALR/taiga-back,seanchen/taiga-back,gam-phon/taiga-back,EvgeneOskin/taiga-back,CoolCloud/taiga-back,WALR/taiga-back,Rademade/taiga-back,seanchen/taiga-back,taigaio/taiga-back,astronaut1712/taiga-back,astronaut1712/taiga-back,taigaio/taiga-back,xdevelsistemas/taiga-back-community,coopsource/taiga-back,astagi/taiga-back,coopsource/taiga-back,CMLL/taiga-back,gauravjns/taiga-back,Rademade/taiga-back,EvgeneOskin/taiga-back,dycodedev/taiga-back,CMLL/taiga-back,astagi/taiga-back,dayatz/taiga-back,19kestier/taiga-back,19kestier/taiga-back,coopsource/taiga-back,obimod/taiga-back,rajiteh/taiga-back,crr0004/taiga-back,bdang2012/taiga-back-casting,gauravjns/taiga-back,gam-phon/taiga-back,forging2012/taiga-back,CoolCloud/taiga-back,astagi/taiga-back,19kestier/taiga-back,CoolCloud/taiga-back,bdang2012/taiga-back-casting,dayatz/taiga-back,Rademade/taiga-back,forging2012/taiga-back,dycodedev/taiga-back,jeffdwyatt/taiga-back,taigaio/taiga-back,dayatz/taiga-back,crr0004/taiga-back,xdevelsistemas/taiga-back-community,Tigerwhit4/taiga-back,Tigerwhit4/taiga-back,obimod/taiga-back,Zaneh-/bearded-tribble-back,jeffdwyatt/taiga-back,crr0004/taiga-back,rajiteh/taiga-back,Zaneh-/bearded-tribble-back,obimod/taiga-back,rajiteh/taiga-back,dycodedev/taiga-back,bdang2012/taiga-back-casting,frt-arch/taiga-back,dycodedev/taiga-back,joshisa/taiga-back,Zaneh-/bearded-tribble-back,astronaut1712/taiga-back,forging2012/taiga-back,CoolCloud/taiga-back,Rademade/taiga-back,Tigerwhit4/taiga-back,gauravjns/taiga-back,CMLL/taiga-back,WALR/taiga-back,joshisa/taiga-back,obimod/taiga-back,jeffdwyatt/taiga-back,forging2012/taiga-back,astagi/taiga-back,xdevelsistemas/taiga-back-community,gauravjns/taiga-back,coopsource/taiga-back,joshisa/taiga-back,crr0004/taiga-back,EvgeneOskin/taiga-back,EvgeneOskin/taiga-back,frt-arch/taiga-back,CMLL/taiga-back,seanchen/taiga-back,gam-phon/taiga-back,gam-phon/taiga-back,Tigerwhit4/taiga-back,Rademade/taiga-back,frt-arch/taiga-back,seanchen/taiga-back,WALR/taiga-back,astronaut1712/taiga-back,joshisa/taiga-back,rajiteh/taiga-back
from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from .routers import router admin.autodiscover() urlpatterns = patterns('', url(r'^api/v1/', include(router.urls)), url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^admin/', include(admin.site.urls)), ) def mediafiles_urlpatterns(): """ Method for serve media files with runserver. """ _media_url = settings.MEDIA_URL if _media_url.startswith('/'): _media_url = _media_url[1:] from django.views.static import serve return patterns('', (r'^%s(?P<path>.*)$' % 'media', serve, {'document_root': settings.MEDIA_ROOT}) ) - urlpatterns += staticfiles_urlpatterns() + urlpatterns += staticfiles_urlpatterns(prefix="/static/") urlpatterns += mediafiles_urlpatterns()
Set prefix to static url patterm call
## Code Before: from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from .routers import router admin.autodiscover() urlpatterns = patterns('', url(r'^api/v1/', include(router.urls)), url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^admin/', include(admin.site.urls)), ) def mediafiles_urlpatterns(): """ Method for serve media files with runserver. """ _media_url = settings.MEDIA_URL if _media_url.startswith('/'): _media_url = _media_url[1:] from django.views.static import serve return patterns('', (r'^%s(?P<path>.*)$' % 'media', serve, {'document_root': settings.MEDIA_ROOT}) ) urlpatterns += staticfiles_urlpatterns() urlpatterns += mediafiles_urlpatterns() ## Instruction: Set prefix to static url patterm call ## Code After: from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from .routers import router admin.autodiscover() urlpatterns = patterns('', url(r'^api/v1/', include(router.urls)), url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^admin/', include(admin.site.urls)), ) def mediafiles_urlpatterns(): """ Method for serve media files with runserver. """ _media_url = settings.MEDIA_URL if _media_url.startswith('/'): _media_url = _media_url[1:] from django.views.static import serve return patterns('', (r'^%s(?P<path>.*)$' % 'media', serve, {'document_root': settings.MEDIA_ROOT}) ) urlpatterns += staticfiles_urlpatterns(prefix="/static/") urlpatterns += mediafiles_urlpatterns()
from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from .routers import router admin.autodiscover() urlpatterns = patterns('', url(r'^api/v1/', include(router.urls)), url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^admin/', include(admin.site.urls)), ) def mediafiles_urlpatterns(): """ Method for serve media files with runserver. """ _media_url = settings.MEDIA_URL if _media_url.startswith('/'): _media_url = _media_url[1:] from django.views.static import serve return patterns('', (r'^%s(?P<path>.*)$' % 'media', serve, {'document_root': settings.MEDIA_ROOT}) ) - urlpatterns += staticfiles_urlpatterns() + urlpatterns += staticfiles_urlpatterns(prefix="/static/") ? +++++++++++++++++ urlpatterns += mediafiles_urlpatterns()
68b2536c53426d9b624527f7ef0eb5b22c68986e
helusers/models.py
helusers/models.py
import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField(primary_key=True) department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True
import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField() department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True
Make UUID a non-pk to work around problems in 3rd party apps
Make UUID a non-pk to work around problems in 3rd party apps
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): - uuid = models.UUIDField(primary_key=True) + uuid = models.UUIDField() department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True
Make UUID a non-pk to work around problems in 3rd party apps
## Code Before: import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField(primary_key=True) department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True ## Instruction: Make UUID a non-pk to work around problems in 3rd party apps ## Code After: import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField() department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True
import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): - uuid = models.UUIDField(primary_key=True) ? ---------------- + uuid = models.UUIDField() department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True
525a9fcb14a1f91aa94508ca6dcc362d430d2969
__openerp__.py
__openerp__.py
{ 'name': "Project Logical Framework", 'category': 'Project', 'sequence': 1, 'description': """ Project Logical Framework ========================= """, 'version': '0.3', 'depends': ['project'], 'data': [ 'static/src/xml/create_project.xml', ], }
{ 'name': "Project Logical Framework", 'author' : 'Stéphane Codazzi @ TeMPO-consulting', 'category': 'Project', 'sequence': 1, 'description': """ Project Logical Framework ========================= """, 'version': '0.3', 'depends': ['project'], 'data': [ 'static/src/xml/create_project.xml', ], }
Add o2m between project and logical frameworks lines
Add o2m between project and logical frameworks lines
Python
mit
stephane-/project_logical_framework
{ 'name': "Project Logical Framework", + 'author' : 'Stéphane Codazzi @ TeMPO-consulting', 'category': 'Project', 'sequence': 1, 'description': """ Project Logical Framework ========================= """, 'version': '0.3', 'depends': ['project'], 'data': [ 'static/src/xml/create_project.xml', ], }
Add o2m between project and logical frameworks lines
## Code Before: { 'name': "Project Logical Framework", 'category': 'Project', 'sequence': 1, 'description': """ Project Logical Framework ========================= """, 'version': '0.3', 'depends': ['project'], 'data': [ 'static/src/xml/create_project.xml', ], } ## Instruction: Add o2m between project and logical frameworks lines ## Code After: { 'name': "Project Logical Framework", 'author' : 'Stéphane Codazzi @ TeMPO-consulting', 'category': 'Project', 'sequence': 1, 'description': """ Project Logical Framework ========================= """, 'version': '0.3', 'depends': ['project'], 'data': [ 'static/src/xml/create_project.xml', ], }
{ 'name': "Project Logical Framework", + 'author' : 'Stéphane Codazzi @ TeMPO-consulting', 'category': 'Project', 'sequence': 1, 'description': """ Project Logical Framework ========================= """, 'version': '0.3', 'depends': ['project'], 'data': [ 'static/src/xml/create_project.xml', ], }
023568228dc2ffcf772edb4d5335c0c755a7e37c
revel/setup.py
revel/setup.py
import subprocess import sys import os import setup_util import time def start(args): setup_util.replace_text("revel/src/benchmark/conf/app.conf", "tcp\(.*:3306\)", "tcp(" + args.database_host + ":3306)") subprocess.call("go get github.com/robfig/revel/cmd", shell=True, cwd="revel") subprocess.call("go build -o bin/revel github.com/robfig/revel/cmd", shell=True, cwd="revel") subprocess.Popen("bin/revel run benchmark prod".rsplit(" "), cwd="revel") return 0 def stop(): p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'revel' in line and 'run-tests' not in line: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) return 0
import subprocess import sys import os import setup_util import time def start(args): setup_util.replace_text("revel/src/benchmark/conf/app.conf", "tcp\(.*:3306\)", "tcp(" + args.database_host + ":3306)") subprocess.call("go get -u github.com/robfig/revel/revel", shell=True, cwd="revel") subprocess.call("go build -o bin/revel github.com/robfig/revel/revel", shell=True, cwd="revel") subprocess.Popen("bin/revel run benchmark prod".rsplit(" "), cwd="revel") return 0 def stop(): p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'revel' in line and 'run-tests' not in line: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) return 0
Update start process to reflect new path for /cmd
Update start process to reflect new path for /cmd
Python
bsd-3-clause
raziel057/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,grob/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,khellang/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,methane/FrameworkBenchmarks,Verber/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,Verber/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,zapov/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sxend/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,sgml/FrameworkBenchmarks,khellang/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,grob/FrameworkBenchmarks,zapov/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,valyala/FrameworkBenchmarks,jamming/FrameworkBenchmarks,zloster/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,leafo/FrameworkBenchmarks,joshk/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,actframework/FrameworkBenchmarks,testn/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,denkab/FrameworkBenchmarks,Verber/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,torhve/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zapov/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,actframework/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,methane/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,denkab/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,grob/FrameworkBenchmarks,Verber/FrameworkBenchmarks,denkab/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,valyala/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,jamming/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,herloct/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,leafo/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Verber/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,sxend/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,khellang/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,khellang/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,doom369/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,actframework/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,zloster/FrameworkBenchmarks,valyala/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,jamming/FrameworkBenchmarks,herloct/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,leafo/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,actframework/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,herloct/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,dmacd/FB-try1,diablonhn/FrameworkBenchmarks,khellang/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,zloster/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,grob/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,actframework/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,Verber/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,grob/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,grob/FrameworkBenchmarks,torhve/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,zloster/FrameworkBenchmarks,sgml/FrameworkBenchmarks,testn/FrameworkBenchmarks,valyala/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,dmacd/FB-try1,victorbriz/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,jamming/FrameworkBenchmarks,doom369/FrameworkBenchmarks,herloct/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,joshk/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,jamming/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jamming/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,valyala/FrameworkBenchmarks,doom369/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,khellang/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,zloster/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,jamming/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,sxend/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,Verber/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,joshk/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,grob/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,zloster/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,doom369/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,valyala/FrameworkBenchmarks,valyala/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,zapov/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,methane/FrameworkBenchmarks,dmacd/FB-try1,jeevatkm/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,khellang/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,methane/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,dmacd/FB-try1,dmacd/FB-try1,jebbstewart/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,denkab/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,zapov/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,herloct/FrameworkBenchmarks,sxend/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,testn/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,actframework/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,zloster/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,grob/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,denkab/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,testn/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,zapov/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,leafo/FrameworkBenchmarks,khellang/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,sxend/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,sxend/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Verber/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,testn/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,valyala/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,herloct/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,sgml/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,sgml/FrameworkBenchmarks,sgml/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,denkab/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,torhve/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,herloct/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,sxend/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,leafo/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,actframework/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,testn/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,joshk/FrameworkBenchmarks,herloct/FrameworkBenchmarks,sgml/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,joshk/FrameworkBenchmarks,sgml/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,zloster/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,dmacd/FB-try1,joshk/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,Verber/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,zloster/FrameworkBenchmarks,testn/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,testn/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,sgml/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,dmacd/FB-try1,kbrock/FrameworkBenchmarks,khellang/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,zloster/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,sgml/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,testn/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,torhve/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,actframework/FrameworkBenchmarks,herloct/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,methane/FrameworkBenchmarks,grob/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,denkab/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,doom369/FrameworkBenchmarks,khellang/FrameworkBenchmarks,jamming/FrameworkBenchmarks,joshk/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,actframework/FrameworkBenchmarks,methane/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,dmacd/FB-try1,seem-sky/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,denkab/FrameworkBenchmarks,grob/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,zloster/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,herloct/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,methane/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,khellang/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,torhve/FrameworkBenchmarks,sgml/FrameworkBenchmarks,zloster/FrameworkBenchmarks,doom369/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,sxend/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,zapov/FrameworkBenchmarks,zloster/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,zloster/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,testn/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,sxend/FrameworkBenchmarks,joshk/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,zloster/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,Verber/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,leafo/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,khellang/FrameworkBenchmarks,denkab/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,leafo/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,actframework/FrameworkBenchmarks,khellang/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,doom369/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,denkab/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,denkab/FrameworkBenchmarks,jamming/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,torhve/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,sgml/FrameworkBenchmarks,doom369/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,joshk/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,grob/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,herloct/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,leafo/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,torhve/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,methane/FrameworkBenchmarks,jamming/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,jamming/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,torhve/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,valyala/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,methane/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,denkab/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,methane/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,actframework/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,valyala/FrameworkBenchmarks,testn/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,actframework/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,doom369/FrameworkBenchmarks,methane/FrameworkBenchmarks,grob/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,grob/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,zapov/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,actframework/FrameworkBenchmarks,doom369/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,zapov/FrameworkBenchmarks,zloster/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,testn/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,zapov/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,Verber/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,dmacd/FB-try1,Rydgel/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,doom369/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,testn/FrameworkBenchmarks,methane/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,doom369/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,denkab/FrameworkBenchmarks,leafo/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,zloster/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Verber/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,methane/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,jamming/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,sxend/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,herloct/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,doom369/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,doom369/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,sgml/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sgml/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,joshk/FrameworkBenchmarks,doom369/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,leafo/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,valyala/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,methane/FrameworkBenchmarks,zapov/FrameworkBenchmarks,torhve/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,joshk/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,zloster/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,dmacd/FB-try1,zane-techempower/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,torhve/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,dmacd/FB-try1,ashawnbandy-te-tfb/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,torhve/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Verber/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,valyala/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,zapov/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,actframework/FrameworkBenchmarks,herloct/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,herloct/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,zapov/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,grob/FrameworkBenchmarks,doom369/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,torhve/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,herloct/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,leafo/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,leafo/FrameworkBenchmarks,dmacd/FB-try1,Rayne/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,khellang/FrameworkBenchmarks,valyala/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,denkab/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,testn/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,joshk/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,joshk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,Verber/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,valyala/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,sgml/FrameworkBenchmarks,sxend/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,jamming/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,jamming/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks
import subprocess import sys import os import setup_util import time def start(args): setup_util.replace_text("revel/src/benchmark/conf/app.conf", "tcp\(.*:3306\)", "tcp(" + args.database_host + ":3306)") - subprocess.call("go get github.com/robfig/revel/cmd", shell=True, cwd="revel") + subprocess.call("go get -u github.com/robfig/revel/revel", shell=True, cwd="revel") - subprocess.call("go build -o bin/revel github.com/robfig/revel/cmd", shell=True, cwd="revel") + subprocess.call("go build -o bin/revel github.com/robfig/revel/revel", shell=True, cwd="revel") subprocess.Popen("bin/revel run benchmark prod".rsplit(" "), cwd="revel") return 0 def stop(): p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'revel' in line and 'run-tests' not in line: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) return 0
Update start process to reflect new path for /cmd
## Code Before: import subprocess import sys import os import setup_util import time def start(args): setup_util.replace_text("revel/src/benchmark/conf/app.conf", "tcp\(.*:3306\)", "tcp(" + args.database_host + ":3306)") subprocess.call("go get github.com/robfig/revel/cmd", shell=True, cwd="revel") subprocess.call("go build -o bin/revel github.com/robfig/revel/cmd", shell=True, cwd="revel") subprocess.Popen("bin/revel run benchmark prod".rsplit(" "), cwd="revel") return 0 def stop(): p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'revel' in line and 'run-tests' not in line: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) return 0 ## Instruction: Update start process to reflect new path for /cmd ## Code After: import subprocess import sys import os import setup_util import time def start(args): setup_util.replace_text("revel/src/benchmark/conf/app.conf", "tcp\(.*:3306\)", "tcp(" + args.database_host + ":3306)") subprocess.call("go get -u github.com/robfig/revel/revel", shell=True, cwd="revel") subprocess.call("go build -o bin/revel github.com/robfig/revel/revel", shell=True, cwd="revel") subprocess.Popen("bin/revel run benchmark prod".rsplit(" "), cwd="revel") return 0 def stop(): p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'revel' in line and 'run-tests' not in line: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) return 0
import subprocess import sys import os import setup_util import time def start(args): setup_util.replace_text("revel/src/benchmark/conf/app.conf", "tcp\(.*:3306\)", "tcp(" + args.database_host + ":3306)") - subprocess.call("go get github.com/robfig/revel/cmd", shell=True, cwd="revel") ? ^^^ + subprocess.call("go get -u github.com/robfig/revel/revel", shell=True, cwd="revel") ? +++ ^^^^^ - subprocess.call("go build -o bin/revel github.com/robfig/revel/cmd", shell=True, cwd="revel") ? ^^^ + subprocess.call("go build -o bin/revel github.com/robfig/revel/revel", shell=True, cwd="revel") ? ^^^^^ subprocess.Popen("bin/revel run benchmark prod".rsplit(" "), cwd="revel") return 0 def stop(): p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'revel' in line and 'run-tests' not in line: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) return 0
520487df7b9612e18dc06764ba8632b0ef28aad2
solvent/bring.py
solvent/bring.py
from solvent import config from solvent import run from solvent import requirementlabel import logging import os class Bring: def __init__(self, repositoryBasename, product, hash, destination): self._repositoryBasename = repositoryBasename self._product = product self._hash = hash self._destination = destination def go(self): requirementLabel = requirementlabel.RequirementLabel( basename=self._repositoryBasename, product=self._product, hash=self._hash) label = requirementLabel.matching() self.label(label=label, destination=self._destination) @classmethod def label(cls, label, destination): logging.info("Checking out '%(label)s'", dict(label=label)) if not os.path.isdir(destination): os.makedirs(destination) run.run([ "osmosis", "checkout", destination, label, "--MD5", "--removeUnknownFiles", "--putIfMissing", "--objectStores=" + config.objectStoresOsmosisParameter()])
from solvent import config from solvent import run from solvent import requirementlabel import logging import os class Bring: def __init__(self, repositoryBasename, product, hash, destination): self._repositoryBasename = repositoryBasename self._product = product self._hash = hash self._destination = destination def go(self): requirementLabel = requirementlabel.RequirementLabel( basename=self._repositoryBasename, product=self._product, hash=self._hash) label = requirementLabel.matching() self.label(label=label, destination=self._destination) @classmethod def label(cls, label, destination): logging.info("Checking out '%(label)s'", dict(label=label)) if not os.path.isdir(destination): os.makedirs(destination) myUIDandGID = ["--myUIDandGIDcheckout"] if os.getuid() != 0 else [] run.run([ "osmosis", "checkout", destination, label, "--MD5", "--removeUnknownFiles", "--putIfMissing", "--objectStores=" + config.objectStoresOsmosisParameter()] + myUIDandGID)
Bring now uses --myUIDandGIDCheckout if root is not the invoker
Bring now uses --myUIDandGIDCheckout if root is not the invoker
Python
apache-2.0
Stratoscale/solvent,Stratoscale/solvent
from solvent import config from solvent import run from solvent import requirementlabel import logging import os class Bring: def __init__(self, repositoryBasename, product, hash, destination): self._repositoryBasename = repositoryBasename self._product = product self._hash = hash self._destination = destination def go(self): requirementLabel = requirementlabel.RequirementLabel( basename=self._repositoryBasename, product=self._product, hash=self._hash) label = requirementLabel.matching() self.label(label=label, destination=self._destination) @classmethod def label(cls, label, destination): logging.info("Checking out '%(label)s'", dict(label=label)) if not os.path.isdir(destination): os.makedirs(destination) + myUIDandGID = ["--myUIDandGIDcheckout"] if os.getuid() != 0 else [] run.run([ "osmosis", "checkout", destination, label, "--MD5", "--removeUnknownFiles", "--putIfMissing", - "--objectStores=" + config.objectStoresOsmosisParameter()]) + "--objectStores=" + config.objectStoresOsmosisParameter()] + myUIDandGID)
Bring now uses --myUIDandGIDCheckout if root is not the invoker
## Code Before: from solvent import config from solvent import run from solvent import requirementlabel import logging import os class Bring: def __init__(self, repositoryBasename, product, hash, destination): self._repositoryBasename = repositoryBasename self._product = product self._hash = hash self._destination = destination def go(self): requirementLabel = requirementlabel.RequirementLabel( basename=self._repositoryBasename, product=self._product, hash=self._hash) label = requirementLabel.matching() self.label(label=label, destination=self._destination) @classmethod def label(cls, label, destination): logging.info("Checking out '%(label)s'", dict(label=label)) if not os.path.isdir(destination): os.makedirs(destination) run.run([ "osmosis", "checkout", destination, label, "--MD5", "--removeUnknownFiles", "--putIfMissing", "--objectStores=" + config.objectStoresOsmosisParameter()]) ## Instruction: Bring now uses --myUIDandGIDCheckout if root is not the invoker ## Code After: from solvent import config from solvent import run from solvent import requirementlabel import logging import os class Bring: def __init__(self, repositoryBasename, product, hash, destination): self._repositoryBasename = repositoryBasename self._product = product self._hash = hash self._destination = destination def go(self): requirementLabel = requirementlabel.RequirementLabel( basename=self._repositoryBasename, product=self._product, hash=self._hash) label = requirementLabel.matching() self.label(label=label, destination=self._destination) @classmethod def label(cls, label, destination): logging.info("Checking out '%(label)s'", dict(label=label)) if not os.path.isdir(destination): os.makedirs(destination) myUIDandGID = ["--myUIDandGIDcheckout"] if os.getuid() != 0 else [] run.run([ "osmosis", "checkout", destination, label, "--MD5", "--removeUnknownFiles", "--putIfMissing", "--objectStores=" + config.objectStoresOsmosisParameter()] + myUIDandGID)
from solvent import config from solvent import run from solvent import requirementlabel import logging import os class Bring: def __init__(self, repositoryBasename, product, hash, destination): self._repositoryBasename = repositoryBasename self._product = product self._hash = hash self._destination = destination def go(self): requirementLabel = requirementlabel.RequirementLabel( basename=self._repositoryBasename, product=self._product, hash=self._hash) label = requirementLabel.matching() self.label(label=label, destination=self._destination) @classmethod def label(cls, label, destination): logging.info("Checking out '%(label)s'", dict(label=label)) if not os.path.isdir(destination): os.makedirs(destination) + myUIDandGID = ["--myUIDandGIDcheckout"] if os.getuid() != 0 else [] run.run([ "osmosis", "checkout", destination, label, "--MD5", "--removeUnknownFiles", "--putIfMissing", - "--objectStores=" + config.objectStoresOsmosisParameter()]) + "--objectStores=" + config.objectStoresOsmosisParameter()] + myUIDandGID) ? ++++++++++++++
0d89712bda6e85901e839dec3e639c16aea42d48
tests/test_proxy_pagination.py
tests/test_proxy_pagination.py
import json from django.test import TestCase from rest_framework import status from tests.models import TestModel class ProxyPaginationTests(TestCase): """ Tests for drf-proxy-pagination """ def setUp(self): for n in range(200): TestModel.objects.create(n=n) def test_without_pager_param(self): resp = self.client.get('/data/', HTTP_ACCEPT='application/json') self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertEqual(resp['Content-Type'], 'application/json') content = json.loads(resp.content) self.assertIn('next', content) self.assertIn('count', content) self.assertIn('page=', content['next']) self.assertNotIn('cursor=', content['next']) def test_with_pager_param(self): resp = self.client.get('/data/?pager=cursor', HTTP_ACCEPT='application/json') self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertEqual(resp['Content-Type'], 'application/json') self.assertNotIn('count', resp.content) content = json.loads(resp.content) self.assertIn('next', content) self.assertNotIn('page=', content['next']) self.assertIn('cursor=', content['next'])
import json from django.test import TestCase from django.utils import six from rest_framework import status from tests.models import TestModel class ProxyPaginationTests(TestCase): """ Tests for drf-proxy-pagination """ def setUp(self): for n in range(200): TestModel.objects.create(n=n) def test_without_pager_param(self): resp = self.client.get('/data/', HTTP_ACCEPT='application/json') self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertEqual(resp['Content-Type'], 'application/json') content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content) self.assertIn('next', content) self.assertIn('count', content) self.assertIn('page=', content['next']) self.assertNotIn('cursor=', content['next']) def test_with_pager_param(self): resp = self.client.get('/data/?pager=cursor', HTTP_ACCEPT='application/json') self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertEqual(resp['Content-Type'], 'application/json') content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content) self.assertIn('next', content) self.assertNotIn('count', content) self.assertNotIn('page=', content['next']) self.assertIn('cursor=', content['next'])
Fix tests failing with Python 3
Fix tests failing with Python 3
Python
mit
tuffnatty/drf-proxy-pagination
import json from django.test import TestCase + from django.utils import six from rest_framework import status from tests.models import TestModel class ProxyPaginationTests(TestCase): """ Tests for drf-proxy-pagination """ def setUp(self): for n in range(200): TestModel.objects.create(n=n) def test_without_pager_param(self): resp = self.client.get('/data/', HTTP_ACCEPT='application/json') self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertEqual(resp['Content-Type'], 'application/json') - content = json.loads(resp.content) + content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content) self.assertIn('next', content) self.assertIn('count', content) self.assertIn('page=', content['next']) self.assertNotIn('cursor=', content['next']) def test_with_pager_param(self): resp = self.client.get('/data/?pager=cursor', HTTP_ACCEPT='application/json') self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertEqual(resp['Content-Type'], 'application/json') + content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content) - self.assertNotIn('count', resp.content) - content = json.loads(resp.content) self.assertIn('next', content) + self.assertNotIn('count', content) self.assertNotIn('page=', content['next']) self.assertIn('cursor=', content['next'])
Fix tests failing with Python 3
## Code Before: import json from django.test import TestCase from rest_framework import status from tests.models import TestModel class ProxyPaginationTests(TestCase): """ Tests for drf-proxy-pagination """ def setUp(self): for n in range(200): TestModel.objects.create(n=n) def test_without_pager_param(self): resp = self.client.get('/data/', HTTP_ACCEPT='application/json') self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertEqual(resp['Content-Type'], 'application/json') content = json.loads(resp.content) self.assertIn('next', content) self.assertIn('count', content) self.assertIn('page=', content['next']) self.assertNotIn('cursor=', content['next']) def test_with_pager_param(self): resp = self.client.get('/data/?pager=cursor', HTTP_ACCEPT='application/json') self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertEqual(resp['Content-Type'], 'application/json') self.assertNotIn('count', resp.content) content = json.loads(resp.content) self.assertIn('next', content) self.assertNotIn('page=', content['next']) self.assertIn('cursor=', content['next']) ## Instruction: Fix tests failing with Python 3 ## Code After: import json from django.test import TestCase from django.utils import six from rest_framework import status from tests.models import TestModel class ProxyPaginationTests(TestCase): """ Tests for drf-proxy-pagination """ def setUp(self): for n in range(200): TestModel.objects.create(n=n) def test_without_pager_param(self): resp = self.client.get('/data/', HTTP_ACCEPT='application/json') self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertEqual(resp['Content-Type'], 'application/json') content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content) self.assertIn('next', content) self.assertIn('count', content) self.assertIn('page=', content['next']) self.assertNotIn('cursor=', content['next']) def test_with_pager_param(self): resp = self.client.get('/data/?pager=cursor', HTTP_ACCEPT='application/json') self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertEqual(resp['Content-Type'], 'application/json') content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content) self.assertIn('next', content) self.assertNotIn('count', content) self.assertNotIn('page=', content['next']) self.assertIn('cursor=', content['next'])
import json from django.test import TestCase + from django.utils import six from rest_framework import status from tests.models import TestModel class ProxyPaginationTests(TestCase): """ Tests for drf-proxy-pagination """ def setUp(self): for n in range(200): TestModel.objects.create(n=n) def test_without_pager_param(self): resp = self.client.get('/data/', HTTP_ACCEPT='application/json') self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertEqual(resp['Content-Type'], 'application/json') - content = json.loads(resp.content) + content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content) self.assertIn('next', content) self.assertIn('count', content) self.assertIn('page=', content['next']) self.assertNotIn('cursor=', content['next']) def test_with_pager_param(self): resp = self.client.get('/data/?pager=cursor', HTTP_ACCEPT='application/json') self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertEqual(resp['Content-Type'], 'application/json') + content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content) - self.assertNotIn('count', resp.content) - content = json.loads(resp.content) self.assertIn('next', content) + self.assertNotIn('count', content) self.assertNotIn('page=', content['next']) self.assertIn('cursor=', content['next'])
09268200fcc1ae21206659ae261c488eb1567071
app/__init__.py
app/__init__.py
from flask import Flask from flask.ext.bootstrap import Bootstrap from config import config from datetime import timedelta from .main import main as main_blueprint from .main.helpers.auth import requires_auth bootstrap = Bootstrap() def create_app(config_name): application = Flask(__name__, static_folder='static/', static_url_path=config[config_name].STATIC_URL_PATH) application.config.from_object(config[config_name]) config[config_name].init_app(application) bootstrap.init_app(application) application.register_blueprint(main_blueprint) main_blueprint.config = application.config.copy() if application.config['AUTHENTICATION']: application.permanent_session_lifetime = timedelta(minutes=60) application.before_request(requires_auth) return application
from flask import Flask from flask.ext.bootstrap import Bootstrap from config import config from datetime import timedelta from .main import main as main_blueprint from .main.helpers.auth import requires_auth bootstrap = Bootstrap() def create_app(config_name): application = Flask(__name__, static_folder='static/', static_url_path=config[config_name].STATIC_URL_PATH) application.config.from_object(config[config_name]) config[config_name].init_app(application) bootstrap.init_app(application) if application.config['AUTHENTICATION']: application.permanent_session_lifetime = timedelta(minutes=60) main_blueprint.before_request(requires_auth) application.register_blueprint(main_blueprint, url_prefix='/admin') main_blueprint.config = application.config.copy() return application
Add '/admin' url_prefix to main blueprint
Add '/admin' url_prefix to main blueprint Also attaches the authentication check to main blueprint instead of the app itself. This means we can use other blueprints for status and internal use that don't require authentication. One important note: before_request must be added before registering the blueprint, otherwise it won't be activated.
Python
mit
alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend
from flask import Flask from flask.ext.bootstrap import Bootstrap from config import config from datetime import timedelta from .main import main as main_blueprint from .main.helpers.auth import requires_auth bootstrap = Bootstrap() def create_app(config_name): application = Flask(__name__, static_folder='static/', static_url_path=config[config_name].STATIC_URL_PATH) application.config.from_object(config[config_name]) config[config_name].init_app(application) bootstrap.init_app(application) - application.register_blueprint(main_blueprint) - main_blueprint.config = application.config.copy() - if application.config['AUTHENTICATION']: application.permanent_session_lifetime = timedelta(minutes=60) - application.before_request(requires_auth) + main_blueprint.before_request(requires_auth) + + application.register_blueprint(main_blueprint, url_prefix='/admin') + main_blueprint.config = application.config.copy() return application
Add '/admin' url_prefix to main blueprint
## Code Before: from flask import Flask from flask.ext.bootstrap import Bootstrap from config import config from datetime import timedelta from .main import main as main_blueprint from .main.helpers.auth import requires_auth bootstrap = Bootstrap() def create_app(config_name): application = Flask(__name__, static_folder='static/', static_url_path=config[config_name].STATIC_URL_PATH) application.config.from_object(config[config_name]) config[config_name].init_app(application) bootstrap.init_app(application) application.register_blueprint(main_blueprint) main_blueprint.config = application.config.copy() if application.config['AUTHENTICATION']: application.permanent_session_lifetime = timedelta(minutes=60) application.before_request(requires_auth) return application ## Instruction: Add '/admin' url_prefix to main blueprint ## Code After: from flask import Flask from flask.ext.bootstrap import Bootstrap from config import config from datetime import timedelta from .main import main as main_blueprint from .main.helpers.auth import requires_auth bootstrap = Bootstrap() def create_app(config_name): application = Flask(__name__, static_folder='static/', static_url_path=config[config_name].STATIC_URL_PATH) application.config.from_object(config[config_name]) config[config_name].init_app(application) bootstrap.init_app(application) if application.config['AUTHENTICATION']: application.permanent_session_lifetime = timedelta(minutes=60) main_blueprint.before_request(requires_auth) application.register_blueprint(main_blueprint, url_prefix='/admin') main_blueprint.config = application.config.copy() return application
from flask import Flask from flask.ext.bootstrap import Bootstrap from config import config from datetime import timedelta from .main import main as main_blueprint from .main.helpers.auth import requires_auth bootstrap = Bootstrap() def create_app(config_name): application = Flask(__name__, static_folder='static/', static_url_path=config[config_name].STATIC_URL_PATH) application.config.from_object(config[config_name]) config[config_name].init_app(application) bootstrap.init_app(application) + if application.config['AUTHENTICATION']: + application.permanent_session_lifetime = timedelta(minutes=60) + main_blueprint.before_request(requires_auth) + - application.register_blueprint(main_blueprint) + application.register_blueprint(main_blueprint, url_prefix='/admin') ? +++++++++++++++++++++ main_blueprint.config = application.config.copy() - if application.config['AUTHENTICATION']: - application.permanent_session_lifetime = timedelta(minutes=60) - application.before_request(requires_auth) - return application
0141340d2abddc954ea4388fe31629d98189632c
tests/test_exceptions.py
tests/test_exceptions.py
from marshmallow.exceptions import ValidationError class TestValidationError: def test_stores_message_in_list(self): err = ValidationError('foo') assert err.messages == ['foo'] def test_can_pass_list_of_messages(self): err = ValidationError(['foo', 'bar']) assert err.messages == ['foo', 'bar']
from marshmallow.exceptions import ValidationError class TestValidationError: def test_stores_message_in_list(self): err = ValidationError('foo') assert err.messages == ['foo'] def test_can_pass_list_of_messages(self): err = ValidationError(['foo', 'bar']) assert err.messages == ['foo', 'bar'] def test_stores_dictionaries(self): messages = {'user': {'email': ['email is invalid']}} err = ValidationError(messages) assert err.messages == messages
Add test for storing dictionaries on ValidationError
Add test for storing dictionaries on ValidationError
Python
mit
0xDCA/marshmallow,Bachmann1234/marshmallow,xLegoz/marshmallow,bartaelterman/marshmallow,VladimirPal/marshmallow,daniloakamine/marshmallow,mwstobo/marshmallow,dwieeb/marshmallow,etataurov/marshmallow,maximkulkin/marshmallow,marshmallow-code/marshmallow,0xDCA/marshmallow,quxiaolong1504/marshmallow,Tim-Erwin/marshmallow
from marshmallow.exceptions import ValidationError class TestValidationError: def test_stores_message_in_list(self): err = ValidationError('foo') assert err.messages == ['foo'] def test_can_pass_list_of_messages(self): err = ValidationError(['foo', 'bar']) assert err.messages == ['foo', 'bar'] + def test_stores_dictionaries(self): + messages = {'user': {'email': ['email is invalid']}} + err = ValidationError(messages) + assert err.messages == messages +
Add test for storing dictionaries on ValidationError
## Code Before: from marshmallow.exceptions import ValidationError class TestValidationError: def test_stores_message_in_list(self): err = ValidationError('foo') assert err.messages == ['foo'] def test_can_pass_list_of_messages(self): err = ValidationError(['foo', 'bar']) assert err.messages == ['foo', 'bar'] ## Instruction: Add test for storing dictionaries on ValidationError ## Code After: from marshmallow.exceptions import ValidationError class TestValidationError: def test_stores_message_in_list(self): err = ValidationError('foo') assert err.messages == ['foo'] def test_can_pass_list_of_messages(self): err = ValidationError(['foo', 'bar']) assert err.messages == ['foo', 'bar'] def test_stores_dictionaries(self): messages = {'user': {'email': ['email is invalid']}} err = ValidationError(messages) assert err.messages == messages
from marshmallow.exceptions import ValidationError class TestValidationError: def test_stores_message_in_list(self): err = ValidationError('foo') assert err.messages == ['foo'] def test_can_pass_list_of_messages(self): err = ValidationError(['foo', 'bar']) assert err.messages == ['foo', 'bar'] + + def test_stores_dictionaries(self): + messages = {'user': {'email': ['email is invalid']}} + err = ValidationError(messages) + assert err.messages == messages
c8cc1f8e0e9b6d7dfb29ff9aef04bf2b5867cceb
genomediff/records.py
genomediff/records.py
class Metadata(object): def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "Metadata({}, {})".format(repr(self.name), repr(self.value)) def __eq__(self, other): return self.__dict__ == other.__dict__ class Record(object): def __init__(self, type, id, document=None, parent_ids=None, **extra): self.document = document self.type = type self.id = id self.parent_ids = parent_ids self._extra = extra @property def parents(self): if not self.parent_ids is None: return [self.document[pid] for pid in self.parent_ids] else: return [] def __getattr__(self, item): return self._extra[item] def __repr__(self): return "Record('{}', {}, {}, {})".format(self.type, self.id, self.parent_ids, ', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items())) def __eq__(self, other): return self.__dict__ == other.__dict__
class Metadata(object): def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "Metadata({}, {})".format(repr(self.name), repr(self.value)) def __eq__(self, other): return self.__dict__ == other.__dict__ class Record(object): def __init__(self, type, id, document=None, parent_ids=None, **attributes): self.document = document self.type = type self.id = id self.parent_ids = parent_ids self.attributes = attributes @property def parents(self): if not self.parent_ids is None: return [self.document[pid] for pid in self.parent_ids] else: return [] def __getattr__(self, item): try: return self.attributes[item] except KeyError: raise AttributeError def __repr__(self): return "Record('{}', {}, {}, {})".format(self.type, self.id, self.parent_ids, ', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items())) def __eq__(self, other): return self.__dict__ == other.__dict__
Raise AttributeError if key does not exist when trying to get it from a Record
Raise AttributeError if key does not exist when trying to get it from a Record
Python
mit
biosustain/genomediff-python
class Metadata(object): def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "Metadata({}, {})".format(repr(self.name), repr(self.value)) def __eq__(self, other): return self.__dict__ == other.__dict__ class Record(object): - def __init__(self, type, id, document=None, parent_ids=None, **extra): + def __init__(self, type, id, document=None, parent_ids=None, **attributes): self.document = document self.type = type self.id = id self.parent_ids = parent_ids - self._extra = extra + self.attributes = attributes @property def parents(self): if not self.parent_ids is None: return [self.document[pid] for pid in self.parent_ids] else: return [] def __getattr__(self, item): + try: - return self._extra[item] + return self.attributes[item] + except KeyError: + raise AttributeError - def __repr__(self): - return "Record('{}', {}, {}, {})".format(self.type, - self.id, - self.parent_ids, - ', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items())) - def __eq__(self, other): - return self.__dict__ == other.__dict__ + def __repr__(self): + return "Record('{}', {}, {}, {})".format(self.type, + self.id, + self.parent_ids, + ', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items())) + + def __eq__(self, other): + return self.__dict__ == other.__dict__ +
Raise AttributeError if key does not exist when trying to get it from a Record
## Code Before: class Metadata(object): def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "Metadata({}, {})".format(repr(self.name), repr(self.value)) def __eq__(self, other): return self.__dict__ == other.__dict__ class Record(object): def __init__(self, type, id, document=None, parent_ids=None, **extra): self.document = document self.type = type self.id = id self.parent_ids = parent_ids self._extra = extra @property def parents(self): if not self.parent_ids is None: return [self.document[pid] for pid in self.parent_ids] else: return [] def __getattr__(self, item): return self._extra[item] def __repr__(self): return "Record('{}', {}, {}, {})".format(self.type, self.id, self.parent_ids, ', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items())) def __eq__(self, other): return self.__dict__ == other.__dict__ ## Instruction: Raise AttributeError if key does not exist when trying to get it from a Record ## Code After: class Metadata(object): def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "Metadata({}, {})".format(repr(self.name), repr(self.value)) def __eq__(self, other): return self.__dict__ == other.__dict__ class Record(object): def __init__(self, type, id, document=None, parent_ids=None, **attributes): self.document = document self.type = type self.id = id self.parent_ids = parent_ids self.attributes = attributes @property def parents(self): if not self.parent_ids is None: return [self.document[pid] for pid in self.parent_ids] else: return [] def __getattr__(self, item): try: return self.attributes[item] except KeyError: raise AttributeError def __repr__(self): return "Record('{}', {}, {}, {})".format(self.type, self.id, self.parent_ids, ', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items())) def __eq__(self, other): return self.__dict__ == other.__dict__
class Metadata(object): def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "Metadata({}, {})".format(repr(self.name), repr(self.value)) def __eq__(self, other): return self.__dict__ == other.__dict__ class Record(object): - def __init__(self, type, id, document=None, parent_ids=None, **extra): ? ^^ ^ + def __init__(self, type, id, document=None, parent_ids=None, **attributes): ? ^^ ^^^^^^ self.document = document self.type = type self.id = id self.parent_ids = parent_ids - self._extra = extra + self.attributes = attributes @property def parents(self): if not self.parent_ids is None: return [self.document[pid] for pid in self.parent_ids] else: return [] def __getattr__(self, item): + try: - return self._extra[item] ? ^^^ ^ + return self.attributes[item] ? +++++ ^^ ^^^^^^ + except KeyError: + raise AttributeError - def __repr__(self): - return "Record('{}', {}, {}, {})".format(self.type, - self.id, - self.parent_ids, - ', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items())) + def __repr__(self): + return "Record('{}', {}, {}, {})".format(self.type, + self.id, + self.parent_ids, + ', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items())) + + - def __eq__(self, other): ? ---- + def __eq__(self, other): - return self.__dict__ == other.__dict__ ? ---- + return self.__dict__ == other.__dict__
53a442ac37bf58bca16dee2ad0787bdf2df98555
nltk/test/gluesemantics_malt_fixt.py
nltk/test/gluesemantics_malt_fixt.py
from __future__ import absolute_import def setup_module(module): from nose import SkipTest from nltk.parse.malt import MaltParser try: depparser = MaltParser() except LookupError: raise SkipTest("MaltParser is not available")
from __future__ import absolute_import def setup_module(module): from nose import SkipTest from nltk.parse.malt import MaltParser try: depparser = MaltParser('maltparser-1.7.2') except LookupError: raise SkipTest("MaltParser is not available")
Add the malt parser directory name in the unittest
Add the malt parser directory name in the unittest Fixes https://nltk.ci.cloudbees.com/job/nltk/TOXENV=py34-jenkins,jdk=jdk8latestOnlineInstall/lastCompletedBuild/testReport/%3Cnose/suite/ContextSuite_context_gluesemantics_malt_fixt__setup/
Python
apache-2.0
nltk/nltk,nltk/nltk,nltk/nltk
from __future__ import absolute_import def setup_module(module): from nose import SkipTest from nltk.parse.malt import MaltParser try: - depparser = MaltParser() + depparser = MaltParser('maltparser-1.7.2') except LookupError: raise SkipTest("MaltParser is not available")
Add the malt parser directory name in the unittest
## Code Before: from __future__ import absolute_import def setup_module(module): from nose import SkipTest from nltk.parse.malt import MaltParser try: depparser = MaltParser() except LookupError: raise SkipTest("MaltParser is not available") ## Instruction: Add the malt parser directory name in the unittest ## Code After: from __future__ import absolute_import def setup_module(module): from nose import SkipTest from nltk.parse.malt import MaltParser try: depparser = MaltParser('maltparser-1.7.2') except LookupError: raise SkipTest("MaltParser is not available")
from __future__ import absolute_import def setup_module(module): from nose import SkipTest from nltk.parse.malt import MaltParser try: - depparser = MaltParser() + depparser = MaltParser('maltparser-1.7.2') ? ++++++++++++++++++ except LookupError: raise SkipTest("MaltParser is not available")
fa0d478aeb167422a56d6e9e8c3e0a35947765e9
pipeline_notifier_test/routes_test.py
pipeline_notifier_test/routes_test.py
import unittest from unittest.mock import Mock from pipeline_notifier.routes import setup_routes class RoutesTests(unittest.TestCase): def test_route_setup_works(self): setup_routes(Mock(), [])
import unittest from unittest.mock import Mock from pipeline_notifier.routes import setup_routes class RoutesTests(unittest.TestCase): def setUp(self): self.pipeline = Mock() self.app = AppMock() setup_routes(self.app, [self.pipeline]) def test_root_route_returns_something(self): result = self.app['/']() self.assertNotEqual(result, None) class AppMock: """ Acts as a mock flask app, but only recording the routes, so they can be then easily accessed for testing later. """ def __init__(self): self.routes = {} def route(self, route): return self.decoratorFor(route) def decoratorFor(self, route): def decorator(routeTarget): self.routes[route] = routeTarget return routeTarget return decorator def __getitem__(self, item): return self.routes[item]
Add framework for unit testing flask routes
Add framework for unit testing flask routes
Python
mit
pimterry/pipeline-notifier
import unittest from unittest.mock import Mock from pipeline_notifier.routes import setup_routes class RoutesTests(unittest.TestCase): - def test_route_setup_works(self): - setup_routes(Mock(), []) + def setUp(self): + self.pipeline = Mock() + self.app = AppMock() + setup_routes(self.app, [self.pipeline]) + + def test_root_route_returns_something(self): + result = self.app['/']() + self.assertNotEqual(result, None) + + class AppMock: + """ + Acts as a mock flask app, but only recording the routes, + so they can be then easily accessed for testing later. + """ + + def __init__(self): + self.routes = {} + + def route(self, route): + return self.decoratorFor(route) + + def decoratorFor(self, route): + def decorator(routeTarget): + self.routes[route] = routeTarget + return routeTarget + return decorator + + def __getitem__(self, item): + return self.routes[item]
Add framework for unit testing flask routes
## Code Before: import unittest from unittest.mock import Mock from pipeline_notifier.routes import setup_routes class RoutesTests(unittest.TestCase): def test_route_setup_works(self): setup_routes(Mock(), []) ## Instruction: Add framework for unit testing flask routes ## Code After: import unittest from unittest.mock import Mock from pipeline_notifier.routes import setup_routes class RoutesTests(unittest.TestCase): def setUp(self): self.pipeline = Mock() self.app = AppMock() setup_routes(self.app, [self.pipeline]) def test_root_route_returns_something(self): result = self.app['/']() self.assertNotEqual(result, None) class AppMock: """ Acts as a mock flask app, but only recording the routes, so they can be then easily accessed for testing later. """ def __init__(self): self.routes = {} def route(self, route): return self.decoratorFor(route) def decoratorFor(self, route): def decorator(routeTarget): self.routes[route] = routeTarget return routeTarget return decorator def __getitem__(self, item): return self.routes[item]
import unittest from unittest.mock import Mock from pipeline_notifier.routes import setup_routes class RoutesTests(unittest.TestCase): - def test_route_setup_works(self): - setup_routes(Mock(), []) + def setUp(self): + self.pipeline = Mock() + self.app = AppMock() + setup_routes(self.app, [self.pipeline]) + + def test_root_route_returns_something(self): + result = self.app['/']() + self.assertNotEqual(result, None) + + class AppMock: + """ + Acts as a mock flask app, but only recording the routes, + so they can be then easily accessed for testing later. + """ + + def __init__(self): + self.routes = {} + + def route(self, route): + return self.decoratorFor(route) + + def decoratorFor(self, route): + def decorator(routeTarget): + self.routes[route] = routeTarget + return routeTarget + return decorator + + def __getitem__(self, item): + return self.routes[item]
709017ea46cd3784983ef0ee64cfe608aa44cf0c
tests/integration/aiohttp_utils.py
tests/integration/aiohttp_utils.py
import asyncio import aiohttp @asyncio.coroutine def aiohttp_request(loop, method, url, output='text', **kwargs): session = aiohttp.ClientSession(loop=loop) response_ctx = session.request(method, url, **kwargs) # NOQA: E999 response = yield from response_ctx.__aenter__() # NOQA: E999 if output == 'text': content = yield from response.text() # NOQA: E999 elif output == 'json': content = yield from response.json() # NOQA: E999 elif output == 'raw': content = yield from response.read() # NOQA: E999 response_ctx._resp.close() yield from session.close() return response, content
import asyncio import aiohttp @asyncio.coroutine def aiohttp_request(loop, method, url, output='text', encoding='utf-8', **kwargs): session = aiohttp.ClientSession(loop=loop) response_ctx = session.request(method, url, **kwargs) # NOQA: E999 response = yield from response_ctx.__aenter__() # NOQA: E999 if output == 'text': content = yield from response.text() # NOQA: E999 elif output == 'json': content = yield from response.json(encoding=encoding) # NOQA: E999 elif output == 'raw': content = yield from response.read() # NOQA: E999 response_ctx._resp.close() yield from session.close() return response, content
Fix aiohttp utils to pass encondig to response.json
Fix aiohttp utils to pass encondig to response.json
Python
mit
graingert/vcrpy,graingert/vcrpy,kevin1024/vcrpy,kevin1024/vcrpy
import asyncio import aiohttp @asyncio.coroutine - def aiohttp_request(loop, method, url, output='text', **kwargs): + def aiohttp_request(loop, method, url, output='text', encoding='utf-8', **kwargs): session = aiohttp.ClientSession(loop=loop) response_ctx = session.request(method, url, **kwargs) # NOQA: E999 response = yield from response_ctx.__aenter__() # NOQA: E999 if output == 'text': content = yield from response.text() # NOQA: E999 elif output == 'json': - content = yield from response.json() # NOQA: E999 + content = yield from response.json(encoding=encoding) # NOQA: E999 elif output == 'raw': content = yield from response.read() # NOQA: E999 response_ctx._resp.close() yield from session.close() return response, content
Fix aiohttp utils to pass encondig to response.json
## Code Before: import asyncio import aiohttp @asyncio.coroutine def aiohttp_request(loop, method, url, output='text', **kwargs): session = aiohttp.ClientSession(loop=loop) response_ctx = session.request(method, url, **kwargs) # NOQA: E999 response = yield from response_ctx.__aenter__() # NOQA: E999 if output == 'text': content = yield from response.text() # NOQA: E999 elif output == 'json': content = yield from response.json() # NOQA: E999 elif output == 'raw': content = yield from response.read() # NOQA: E999 response_ctx._resp.close() yield from session.close() return response, content ## Instruction: Fix aiohttp utils to pass encondig to response.json ## Code After: import asyncio import aiohttp @asyncio.coroutine def aiohttp_request(loop, method, url, output='text', encoding='utf-8', **kwargs): session = aiohttp.ClientSession(loop=loop) response_ctx = session.request(method, url, **kwargs) # NOQA: E999 response = yield from response_ctx.__aenter__() # NOQA: E999 if output == 'text': content = yield from response.text() # NOQA: E999 elif output == 'json': content = yield from response.json(encoding=encoding) # NOQA: E999 elif output == 'raw': content = yield from response.read() # NOQA: E999 response_ctx._resp.close() yield from session.close() return response, content
import asyncio import aiohttp @asyncio.coroutine - def aiohttp_request(loop, method, url, output='text', **kwargs): + def aiohttp_request(loop, method, url, output='text', encoding='utf-8', **kwargs): ? ++++++++++++++++++ session = aiohttp.ClientSession(loop=loop) response_ctx = session.request(method, url, **kwargs) # NOQA: E999 response = yield from response_ctx.__aenter__() # NOQA: E999 if output == 'text': content = yield from response.text() # NOQA: E999 elif output == 'json': - content = yield from response.json() # NOQA: E999 + content = yield from response.json(encoding=encoding) # NOQA: E999 ? +++++++++++++++++ elif output == 'raw': content = yield from response.read() # NOQA: E999 response_ctx._resp.close() yield from session.close() return response, content
9858c56188f4d6c81daf6535e7cd58ff23e20712
application/senic/nuimo_hub/tests/test_setup_wifi.py
application/senic/nuimo_hub/tests/test_setup_wifi.py
import pytest from mock import patch @pytest.fixture def url(route_url): return route_url('wifi_setup') def test_get_scanned_wifi(browser, url): assert browser.get_json(url).json == ['grandpausethisnetwork'] @pytest.fixture def no_such_wifi(settings): settings['wifi_networks_path'] = '/no/such/file' return settings def test_get_scanned_wifi_empty(no_such_wifi, browser, url): assert browser.get_json(url).json == [] @pytest.yield_fixture(autouse=True) def mocked_run(request): """don't run actual external commands during these tests """ with patch('senic.nuimo_hub.views.setup_wifi.run')\ as mocked_run: yield mocked_run def test_join_wifi(browser, url, mocked_run, settings): browser.post_json(url, dict( ssid='grandpausethisnetwork', password='foobar', device='wlan0')).json mocked_run.assert_called_once_with( [ 'sudo', '%s/join_wifi' % settings['bin_path'], '-c {fs_config_ini}'.format(**settings), 'grandpausethisnetwork', 'foobar', ] )
import pytest from mock import patch @pytest.fixture def setup_url(route_url): return route_url('wifi_setup') def test_get_scanned_wifi(browser, setup_url): assert browser.get_json(setup_url).json == ['grandpausethisnetwork'] @pytest.fixture def no_such_wifi(settings): settings['wifi_networks_path'] = '/no/such/file' return settings def test_get_scanned_wifi_empty(no_such_wifi, browser, setup_url): assert browser.get_json(setup_url).json == [] @pytest.yield_fixture(autouse=True) def mocked_run(request): """don't run actual external commands during these tests """ with patch('senic.nuimo_hub.views.setup_wifi.run')\ as mocked_run: yield mocked_run def test_join_wifi(browser, setup_url, mocked_run, settings): browser.post_json(setup_url, dict( ssid='grandpausethisnetwork', password='foobar', device='wlan0')).json mocked_run.assert_called_once_with( [ 'sudo', '%s/join_wifi' % settings['bin_path'], '-c {fs_config_ini}'.format(**settings), 'grandpausethisnetwork', 'foobar', ] )
Make `url` fixture less generic
Make `url` fixture less generic in preparation for additional endpoints
Python
mit
grunskis/nuimo-hub-backend,grunskis/nuimo-hub-backend,getsenic/senic-hub,grunskis/senic-hub,grunskis/senic-hub,grunskis/nuimo-hub-backend,grunskis/senic-hub,grunskis/senic-hub,getsenic/senic-hub,grunskis/senic-hub,grunskis/nuimo-hub-backend,grunskis/senic-hub,grunskis/nuimo-hub-backend
import pytest from mock import patch @pytest.fixture - def url(route_url): + def setup_url(route_url): return route_url('wifi_setup') - def test_get_scanned_wifi(browser, url): + def test_get_scanned_wifi(browser, setup_url): - assert browser.get_json(url).json == ['grandpausethisnetwork'] + assert browser.get_json(setup_url).json == ['grandpausethisnetwork'] @pytest.fixture def no_such_wifi(settings): settings['wifi_networks_path'] = '/no/such/file' return settings - def test_get_scanned_wifi_empty(no_such_wifi, browser, url): + def test_get_scanned_wifi_empty(no_such_wifi, browser, setup_url): - assert browser.get_json(url).json == [] + assert browser.get_json(setup_url).json == [] @pytest.yield_fixture(autouse=True) def mocked_run(request): """don't run actual external commands during these tests """ with patch('senic.nuimo_hub.views.setup_wifi.run')\ as mocked_run: yield mocked_run - def test_join_wifi(browser, url, mocked_run, settings): + def test_join_wifi(browser, setup_url, mocked_run, settings): - browser.post_json(url, dict( + browser.post_json(setup_url, dict( ssid='grandpausethisnetwork', password='foobar', device='wlan0')).json mocked_run.assert_called_once_with( [ 'sudo', '%s/join_wifi' % settings['bin_path'], '-c {fs_config_ini}'.format(**settings), 'grandpausethisnetwork', 'foobar', ] )
Make `url` fixture less generic
## Code Before: import pytest from mock import patch @pytest.fixture def url(route_url): return route_url('wifi_setup') def test_get_scanned_wifi(browser, url): assert browser.get_json(url).json == ['grandpausethisnetwork'] @pytest.fixture def no_such_wifi(settings): settings['wifi_networks_path'] = '/no/such/file' return settings def test_get_scanned_wifi_empty(no_such_wifi, browser, url): assert browser.get_json(url).json == [] @pytest.yield_fixture(autouse=True) def mocked_run(request): """don't run actual external commands during these tests """ with patch('senic.nuimo_hub.views.setup_wifi.run')\ as mocked_run: yield mocked_run def test_join_wifi(browser, url, mocked_run, settings): browser.post_json(url, dict( ssid='grandpausethisnetwork', password='foobar', device='wlan0')).json mocked_run.assert_called_once_with( [ 'sudo', '%s/join_wifi' % settings['bin_path'], '-c {fs_config_ini}'.format(**settings), 'grandpausethisnetwork', 'foobar', ] ) ## Instruction: Make `url` fixture less generic ## Code After: import pytest from mock import patch @pytest.fixture def setup_url(route_url): return route_url('wifi_setup') def test_get_scanned_wifi(browser, setup_url): assert browser.get_json(setup_url).json == ['grandpausethisnetwork'] @pytest.fixture def no_such_wifi(settings): settings['wifi_networks_path'] = '/no/such/file' return settings def test_get_scanned_wifi_empty(no_such_wifi, browser, setup_url): assert browser.get_json(setup_url).json == [] @pytest.yield_fixture(autouse=True) def mocked_run(request): """don't run actual external commands during these tests """ with patch('senic.nuimo_hub.views.setup_wifi.run')\ as mocked_run: yield mocked_run def test_join_wifi(browser, setup_url, mocked_run, settings): browser.post_json(setup_url, dict( ssid='grandpausethisnetwork', password='foobar', device='wlan0')).json mocked_run.assert_called_once_with( [ 'sudo', '%s/join_wifi' % settings['bin_path'], '-c {fs_config_ini}'.format(**settings), 'grandpausethisnetwork', 'foobar', ] )
import pytest from mock import patch @pytest.fixture - def url(route_url): + def setup_url(route_url): ? ++++++ return route_url('wifi_setup') - def test_get_scanned_wifi(browser, url): + def test_get_scanned_wifi(browser, setup_url): ? ++++++ - assert browser.get_json(url).json == ['grandpausethisnetwork'] + assert browser.get_json(setup_url).json == ['grandpausethisnetwork'] ? ++++++ @pytest.fixture def no_such_wifi(settings): settings['wifi_networks_path'] = '/no/such/file' return settings - def test_get_scanned_wifi_empty(no_such_wifi, browser, url): + def test_get_scanned_wifi_empty(no_such_wifi, browser, setup_url): ? ++++++ - assert browser.get_json(url).json == [] + assert browser.get_json(setup_url).json == [] ? ++++++ @pytest.yield_fixture(autouse=True) def mocked_run(request): """don't run actual external commands during these tests """ with patch('senic.nuimo_hub.views.setup_wifi.run')\ as mocked_run: yield mocked_run - def test_join_wifi(browser, url, mocked_run, settings): + def test_join_wifi(browser, setup_url, mocked_run, settings): ? ++++++ - browser.post_json(url, dict( + browser.post_json(setup_url, dict( ? ++++++ ssid='grandpausethisnetwork', password='foobar', device='wlan0')).json mocked_run.assert_called_once_with( [ 'sudo', '%s/join_wifi' % settings['bin_path'], '-c {fs_config_ini}'.format(**settings), 'grandpausethisnetwork', 'foobar', ] )
606cb3475e2e4220822f924d13881dfaefb51aa4
teryt_tree/rest_framework_ext/viewsets.py
teryt_tree/rest_framework_ext/viewsets.py
import django_filters from django.shortcuts import get_object_or_404 try: from django_filters import rest_framework as filters except ImportError: # Back-ward compatible for django-rest-framework<3.7 from rest_framework import filters from rest_framework import viewsets from teryt_tree.models import JednostkaAdministracyjna from teryt_tree.rest_framework_ext.serializers import JednostkaAdministracyjnaSerializer def custom_area_filter(queryset, _, value): if not value: return queryset return queryset.area(get_object_or_404(JednostkaAdministracyjna, pk=value)) class JednostkaAdministracyjnaFilter(filters.FilterSet): area = django_filters.CharFilter(action=custom_area_filter) class Meta: model = JednostkaAdministracyjna fields = ['name', 'category', 'category__level', 'area'] class JednostkaAdministracyjnaViewSet(viewsets.ModelViewSet): queryset = (JednostkaAdministracyjna.objects. select_related('category'). prefetch_related('children'). all()) serializer_class = JednostkaAdministracyjnaSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = JednostkaAdministracyjnaFilter
import django_filters from django.shortcuts import get_object_or_404 from django.utils.translation import ugettext_lazy as _ try: from django_filters import rest_framework as filters except ImportError: # Back-ward compatible for django-rest-framework<3.7 from rest_framework import filters from rest_framework import viewsets from teryt_tree.models import JednostkaAdministracyjna from teryt_tree.rest_framework_ext.serializers import \ JednostkaAdministracyjnaSerializer def custom_area_filter(queryset, _, value): if not value: return queryset return queryset.area(get_object_or_404(JednostkaAdministracyjna, pk=value)) class JednostkaAdministracyjnaFilter(filters.FilterSet): area = django_filters.CharFilter( method=custom_area_filter, label=_("Area") ) class Meta: model = JednostkaAdministracyjna fields = ['name', 'category', 'category__level', 'area'] class JednostkaAdministracyjnaViewSet(viewsets.ModelViewSet): queryset = (JednostkaAdministracyjna.objects. select_related('category'). prefetch_related('children'). all()) serializer_class = JednostkaAdministracyjnaSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = JednostkaAdministracyjnaFilter
Update JednostkaAdministracyjnaFilter for new django-filters
Update JednostkaAdministracyjnaFilter for new django-filters
Python
bsd-3-clause
ad-m/django-teryt-tree
import django_filters from django.shortcuts import get_object_or_404 + from django.utils.translation import ugettext_lazy as _ + try: from django_filters import rest_framework as filters except ImportError: # Back-ward compatible for django-rest-framework<3.7 from rest_framework import filters from rest_framework import viewsets from teryt_tree.models import JednostkaAdministracyjna - from teryt_tree.rest_framework_ext.serializers import JednostkaAdministracyjnaSerializer + from teryt_tree.rest_framework_ext.serializers import \ + JednostkaAdministracyjnaSerializer def custom_area_filter(queryset, _, value): if not value: return queryset return queryset.area(get_object_or_404(JednostkaAdministracyjna, pk=value)) class JednostkaAdministracyjnaFilter(filters.FilterSet): - area = django_filters.CharFilter(action=custom_area_filter) + area = django_filters.CharFilter( + method=custom_area_filter, + label=_("Area") + ) class Meta: model = JednostkaAdministracyjna fields = ['name', 'category', 'category__level', 'area'] class JednostkaAdministracyjnaViewSet(viewsets.ModelViewSet): queryset = (JednostkaAdministracyjna.objects. select_related('category'). prefetch_related('children'). all()) serializer_class = JednostkaAdministracyjnaSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = JednostkaAdministracyjnaFilter
Update JednostkaAdministracyjnaFilter for new django-filters
## Code Before: import django_filters from django.shortcuts import get_object_or_404 try: from django_filters import rest_framework as filters except ImportError: # Back-ward compatible for django-rest-framework<3.7 from rest_framework import filters from rest_framework import viewsets from teryt_tree.models import JednostkaAdministracyjna from teryt_tree.rest_framework_ext.serializers import JednostkaAdministracyjnaSerializer def custom_area_filter(queryset, _, value): if not value: return queryset return queryset.area(get_object_or_404(JednostkaAdministracyjna, pk=value)) class JednostkaAdministracyjnaFilter(filters.FilterSet): area = django_filters.CharFilter(action=custom_area_filter) class Meta: model = JednostkaAdministracyjna fields = ['name', 'category', 'category__level', 'area'] class JednostkaAdministracyjnaViewSet(viewsets.ModelViewSet): queryset = (JednostkaAdministracyjna.objects. select_related('category'). prefetch_related('children'). all()) serializer_class = JednostkaAdministracyjnaSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = JednostkaAdministracyjnaFilter ## Instruction: Update JednostkaAdministracyjnaFilter for new django-filters ## Code After: import django_filters from django.shortcuts import get_object_or_404 from django.utils.translation import ugettext_lazy as _ try: from django_filters import rest_framework as filters except ImportError: # Back-ward compatible for django-rest-framework<3.7 from rest_framework import filters from rest_framework import viewsets from teryt_tree.models import JednostkaAdministracyjna from teryt_tree.rest_framework_ext.serializers import \ JednostkaAdministracyjnaSerializer def custom_area_filter(queryset, _, value): if not value: return queryset return queryset.area(get_object_or_404(JednostkaAdministracyjna, pk=value)) class JednostkaAdministracyjnaFilter(filters.FilterSet): area = django_filters.CharFilter( method=custom_area_filter, label=_("Area") ) class Meta: model = JednostkaAdministracyjna fields = ['name', 'category', 'category__level', 'area'] class JednostkaAdministracyjnaViewSet(viewsets.ModelViewSet): queryset = (JednostkaAdministracyjna.objects. select_related('category'). prefetch_related('children'). all()) serializer_class = JednostkaAdministracyjnaSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = JednostkaAdministracyjnaFilter
import django_filters from django.shortcuts import get_object_or_404 + from django.utils.translation import ugettext_lazy as _ + try: from django_filters import rest_framework as filters except ImportError: # Back-ward compatible for django-rest-framework<3.7 from rest_framework import filters from rest_framework import viewsets from teryt_tree.models import JednostkaAdministracyjna - from teryt_tree.rest_framework_ext.serializers import JednostkaAdministracyjnaSerializer ? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + from teryt_tree.rest_framework_ext.serializers import \ ? ^ + JednostkaAdministracyjnaSerializer def custom_area_filter(queryset, _, value): if not value: return queryset return queryset.area(get_object_or_404(JednostkaAdministracyjna, pk=value)) class JednostkaAdministracyjnaFilter(filters.FilterSet): - area = django_filters.CharFilter(action=custom_area_filter) + area = django_filters.CharFilter( + method=custom_area_filter, + label=_("Area") + ) class Meta: model = JednostkaAdministracyjna fields = ['name', 'category', 'category__level', 'area'] class JednostkaAdministracyjnaViewSet(viewsets.ModelViewSet): queryset = (JednostkaAdministracyjna.objects. select_related('category'). prefetch_related('children'). all()) serializer_class = JednostkaAdministracyjnaSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = JednostkaAdministracyjnaFilter
61d71b27111f255c3dad3f974e6c7e0ace0c2ce9
karld/iter_utils.py
karld/iter_utils.py
from functools import partial from itertools import imap from itertools import islice from itertools import izip_longest from itertools import ifilter from operator import itemgetter from operator import is_not def yield_getter_of(getter_maker, iterator): """ Iteratively map iterator over the result of getter_maker. :param getter_maker: function that returns a getter function. :param iterator: An iterator. """ return imap(getter_maker(), iterator) def yield_nth_of(nth, iterator): """ For an iterator that returns sequences, yield the nth value of each. :param nth: Index desired column of each sequence. :type nth: int :param iterator: iterator of sequences. """ return yield_getter_of(partial(itemgetter, nth), iterator) def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) fo = object() is_not_fo = partial(is_not, fo) def batcher(n, iterable): for batch in grouper(iterable, n, fillvalue=fo): yield filter(is_not_fo, batch) def i_batcher(n, iterable): for batch in grouper(iterable, n, fillvalue=fo): yield ifilter(is_not_fo, batch) def i_batch(max_size, iterable): """ Generator that iteratively batches items to a max size and consumes the items iterable as each batch is yielded. :param max_size: Max size of each batch. :type max_size: int :param iterable: An iterable :type iterable: iter """ iterable_items = iter(iterable) while True: items_batch = tuple(islice(iterable_items, max_size)) if not items_batch: break yield items_batch
from functools import partial from itertools import imap from itertools import islice from operator import itemgetter def yield_getter_of(getter_maker, iterator): """ Iteratively map iterator over the result of getter_maker. :param getter_maker: function that returns a getter function. :param iterator: An iterator. """ return imap(getter_maker(), iterator) def yield_nth_of(nth, iterator): """ For an iterator that returns sequences, yield the nth value of each. :param nth: Index desired column of each sequence. :type nth: int :param iterator: iterator of sequences. """ return yield_getter_of(partial(itemgetter, nth), iterator) def i_batch(max_size, iterable): """ Generator that iteratively batches items to a max size and consumes the items iterable as each batch is yielded. :param max_size: Max size of each batch. :type max_size: int :param iterable: An iterable :type iterable: iter """ iterable_items = iter(iterable) while True: items_batch = tuple(islice(iterable_items, max_size)) if not items_batch: break yield items_batch
Remove grouper and grouper based batchers
Remove grouper and grouper based batchers I prefer to not use the filter fill value method to batch. I don't like the need to allocate room for the fill value object.
Python
apache-2.0
johnwlockwood/stream_tap,johnwlockwood/karl_data,johnwlockwood/iter_karld_tools,johnwlockwood/stream_tap
from functools import partial from itertools import imap from itertools import islice - from itertools import izip_longest - from itertools import ifilter from operator import itemgetter - from operator import is_not def yield_getter_of(getter_maker, iterator): """ Iteratively map iterator over the result of getter_maker. :param getter_maker: function that returns a getter function. :param iterator: An iterator. """ return imap(getter_maker(), iterator) def yield_nth_of(nth, iterator): """ For an iterator that returns sequences, yield the nth value of each. :param nth: Index desired column of each sequence. :type nth: int :param iterator: iterator of sequences. """ return yield_getter_of(partial(itemgetter, nth), iterator) - def grouper(iterable, n, fillvalue=None): - "Collect data into fixed-length chunks or blocks" - # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx - args = [iter(iterable)] * n - return izip_longest(fillvalue=fillvalue, *args) - - - fo = object() - is_not_fo = partial(is_not, fo) - - - def batcher(n, iterable): - for batch in grouper(iterable, n, fillvalue=fo): - yield filter(is_not_fo, batch) - - - def i_batcher(n, iterable): - for batch in grouper(iterable, n, fillvalue=fo): - yield ifilter(is_not_fo, batch) - - def i_batch(max_size, iterable): """ Generator that iteratively batches items to a max size and consumes the items iterable as each batch is yielded. :param max_size: Max size of each batch. :type max_size: int :param iterable: An iterable :type iterable: iter """ iterable_items = iter(iterable) while True: items_batch = tuple(islice(iterable_items, max_size)) if not items_batch: break yield items_batch
Remove grouper and grouper based batchers
## Code Before: from functools import partial from itertools import imap from itertools import islice from itertools import izip_longest from itertools import ifilter from operator import itemgetter from operator import is_not def yield_getter_of(getter_maker, iterator): """ Iteratively map iterator over the result of getter_maker. :param getter_maker: function that returns a getter function. :param iterator: An iterator. """ return imap(getter_maker(), iterator) def yield_nth_of(nth, iterator): """ For an iterator that returns sequences, yield the nth value of each. :param nth: Index desired column of each sequence. :type nth: int :param iterator: iterator of sequences. """ return yield_getter_of(partial(itemgetter, nth), iterator) def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) fo = object() is_not_fo = partial(is_not, fo) def batcher(n, iterable): for batch in grouper(iterable, n, fillvalue=fo): yield filter(is_not_fo, batch) def i_batcher(n, iterable): for batch in grouper(iterable, n, fillvalue=fo): yield ifilter(is_not_fo, batch) def i_batch(max_size, iterable): """ Generator that iteratively batches items to a max size and consumes the items iterable as each batch is yielded. :param max_size: Max size of each batch. :type max_size: int :param iterable: An iterable :type iterable: iter """ iterable_items = iter(iterable) while True: items_batch = tuple(islice(iterable_items, max_size)) if not items_batch: break yield items_batch ## Instruction: Remove grouper and grouper based batchers ## Code After: from functools import partial from itertools import imap from itertools import islice from operator import itemgetter def yield_getter_of(getter_maker, iterator): """ Iteratively map iterator over the result of getter_maker. :param getter_maker: function that returns a getter function. :param iterator: An iterator. """ return imap(getter_maker(), iterator) def yield_nth_of(nth, iterator): """ For an iterator that returns sequences, yield the nth value of each. :param nth: Index desired column of each sequence. :type nth: int :param iterator: iterator of sequences. """ return yield_getter_of(partial(itemgetter, nth), iterator) def i_batch(max_size, iterable): """ Generator that iteratively batches items to a max size and consumes the items iterable as each batch is yielded. :param max_size: Max size of each batch. :type max_size: int :param iterable: An iterable :type iterable: iter """ iterable_items = iter(iterable) while True: items_batch = tuple(islice(iterable_items, max_size)) if not items_batch: break yield items_batch
from functools import partial from itertools import imap from itertools import islice - from itertools import izip_longest - from itertools import ifilter from operator import itemgetter - from operator import is_not def yield_getter_of(getter_maker, iterator): """ Iteratively map iterator over the result of getter_maker. :param getter_maker: function that returns a getter function. :param iterator: An iterator. """ return imap(getter_maker(), iterator) def yield_nth_of(nth, iterator): """ For an iterator that returns sequences, yield the nth value of each. :param nth: Index desired column of each sequence. :type nth: int :param iterator: iterator of sequences. """ return yield_getter_of(partial(itemgetter, nth), iterator) - def grouper(iterable, n, fillvalue=None): - "Collect data into fixed-length chunks or blocks" - # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx - args = [iter(iterable)] * n - return izip_longest(fillvalue=fillvalue, *args) - - - fo = object() - is_not_fo = partial(is_not, fo) - - - def batcher(n, iterable): - for batch in grouper(iterable, n, fillvalue=fo): - yield filter(is_not_fo, batch) - - - def i_batcher(n, iterable): - for batch in grouper(iterable, n, fillvalue=fo): - yield ifilter(is_not_fo, batch) - - def i_batch(max_size, iterable): """ Generator that iteratively batches items to a max size and consumes the items iterable as each batch is yielded. :param max_size: Max size of each batch. :type max_size: int :param iterable: An iterable :type iterable: iter """ iterable_items = iter(iterable) while True: items_batch = tuple(islice(iterable_items, max_size)) if not items_batch: break yield items_batch
abf48b4c3ab7c78e44bc2d28ef6f3271c00abc42
ylio/__init__.py
ylio/__init__.py
from flask import Flask from flask.ext.assets import Environment, Bundle app = Flask(__name__, static_folder=None) app.config.from_pyfile('config.py') # Route static folder to /static in dev # and a subdomain in production app.static_folder = 'static' static_path = '/<path:filename>' static_subdomain = 'static' if app.config.get('DEBUG', False): static_path = '/static/<path:filename>' static_subdomain = None app.add_url_rule( static_path, endpoint='static', subdomain=static_subdomain, view_func=app.send_static_file ) assets = Environment(app) js = Bundle( 'js/colorpicker.js', 'js/modernizr.js', 'js/lightordark.js', 'js/ylio.js', filters='jsmin', output='scripts.js' ) css = Bundle( 'css/colorpicker.css', 'css/ylio.css', filters='cssmin', output='styles.css' ) assets.register('js', js) assets.register('css', css) import ylio.views
from flask import Flask from flask.ext.assets import Environment, Bundle app = Flask(__name__, static_folder=None) app.config.from_pyfile('config.py') # Route static folder to /static in dev # and a subdomain in production app.static_folder = 'static' static_path = '/<path:filename>' static_subdomain = 'static' if app.config.get('SERVER_NAME') is None: static_path = '/static/<path:filename>' static_subdomain = None app.add_url_rule( static_path, endpoint='static', subdomain=static_subdomain, view_func=app.send_static_file ) assets = Environment(app) js = Bundle( 'js/colorpicker.js', 'js/modernizr.js', 'js/lightordark.js', 'js/ylio.js', filters='jsmin', output='scripts.js' ) css = Bundle( 'css/colorpicker.css', 'css/ylio.css', filters='cssmin', output='styles.css' ) assets.register('js', js) assets.register('css', css) import ylio.views
Put static folder on a subdomain if SERVER_NAME isn't None, not if debug is False
Put static folder on a subdomain if SERVER_NAME isn't None, not if debug is False
Python
mit
joealcorn/yl.io,joealcorn/yl.io
from flask import Flask from flask.ext.assets import Environment, Bundle app = Flask(__name__, static_folder=None) app.config.from_pyfile('config.py') # Route static folder to /static in dev # and a subdomain in production app.static_folder = 'static' static_path = '/<path:filename>' static_subdomain = 'static' - if app.config.get('DEBUG', False): + if app.config.get('SERVER_NAME') is None: static_path = '/static/<path:filename>' static_subdomain = None app.add_url_rule( static_path, endpoint='static', subdomain=static_subdomain, view_func=app.send_static_file ) assets = Environment(app) js = Bundle( 'js/colorpicker.js', 'js/modernizr.js', 'js/lightordark.js', 'js/ylio.js', filters='jsmin', output='scripts.js' ) css = Bundle( 'css/colorpicker.css', 'css/ylio.css', filters='cssmin', output='styles.css' ) assets.register('js', js) assets.register('css', css) import ylio.views
Put static folder on a subdomain if SERVER_NAME isn't None, not if debug is False
## Code Before: from flask import Flask from flask.ext.assets import Environment, Bundle app = Flask(__name__, static_folder=None) app.config.from_pyfile('config.py') # Route static folder to /static in dev # and a subdomain in production app.static_folder = 'static' static_path = '/<path:filename>' static_subdomain = 'static' if app.config.get('DEBUG', False): static_path = '/static/<path:filename>' static_subdomain = None app.add_url_rule( static_path, endpoint='static', subdomain=static_subdomain, view_func=app.send_static_file ) assets = Environment(app) js = Bundle( 'js/colorpicker.js', 'js/modernizr.js', 'js/lightordark.js', 'js/ylio.js', filters='jsmin', output='scripts.js' ) css = Bundle( 'css/colorpicker.css', 'css/ylio.css', filters='cssmin', output='styles.css' ) assets.register('js', js) assets.register('css', css) import ylio.views ## Instruction: Put static folder on a subdomain if SERVER_NAME isn't None, not if debug is False ## Code After: from flask import Flask from flask.ext.assets import Environment, Bundle app = Flask(__name__, static_folder=None) app.config.from_pyfile('config.py') # Route static folder to /static in dev # and a subdomain in production app.static_folder = 'static' static_path = '/<path:filename>' static_subdomain = 'static' if app.config.get('SERVER_NAME') is None: static_path = '/static/<path:filename>' static_subdomain = None app.add_url_rule( static_path, endpoint='static', subdomain=static_subdomain, view_func=app.send_static_file ) assets = Environment(app) js = Bundle( 'js/colorpicker.js', 'js/modernizr.js', 'js/lightordark.js', 'js/ylio.js', filters='jsmin', output='scripts.js' ) css = Bundle( 'css/colorpicker.css', 'css/ylio.css', filters='cssmin', output='styles.css' ) assets.register('js', js) assets.register('css', css) import ylio.views
from flask import Flask from flask.ext.assets import Environment, Bundle app = Flask(__name__, static_folder=None) app.config.from_pyfile('config.py') # Route static folder to /static in dev # and a subdomain in production app.static_folder = 'static' static_path = '/<path:filename>' static_subdomain = 'static' - if app.config.get('DEBUG', False): + if app.config.get('SERVER_NAME') is None: static_path = '/static/<path:filename>' static_subdomain = None app.add_url_rule( static_path, endpoint='static', subdomain=static_subdomain, view_func=app.send_static_file ) assets = Environment(app) js = Bundle( 'js/colorpicker.js', 'js/modernizr.js', 'js/lightordark.js', 'js/ylio.js', filters='jsmin', output='scripts.js' ) css = Bundle( 'css/colorpicker.css', 'css/ylio.css', filters='cssmin', output='styles.css' ) assets.register('js', js) assets.register('css', css) import ylio.views
f2a46687e24d82060b687922de3495111f82e558
geist/backends/fake.py
geist/backends/fake.py
import numpy as np from ..core import Location class GeistFakeBackend(object): def __init__(self, w=800, h=600): self.image = np.zeros((h, w, 3)) self.locations = [Location(0, 0, w=w, h=h, image=self.image)] def create_process(self, command): pass def actions_transaction(self): pass def capture_locations(self): for loc in self.locations: yield loc def key_down(self, name): pass def key_up(self, name): pass def button_down(self, button_num): pass def button_up(self, button_num): pass def move(self, point): pass def close(self): pass
import numpy as np from ..core import Location class GeistFakeBackend(object): def __init__(self, image=None, w=800, h=600): if image is None: self.image = np.zeros((h, w, 3)) self.locations = [Location(0, 0, w=w, h=h, image=self.image)] else: if isinstance(image, basestring): image = np.load(image) self.image = image h, w, _ = image.shape self.locations = [Location(0, 0, w=w, h=h, image=self.image)] def create_process(self, command): pass def actions_transaction(self): pass def capture_locations(self): for loc in self.locations: yield loc def key_down(self, name): pass def key_up(self, name): pass def button_down(self, button_num): pass def button_up(self, button_num): pass def move(self, point): pass def close(self): pass
Allow Fake Backend to take an image as the screen
Allow Fake Backend to take an image as the screen
Python
mit
kebarr/Geist,thetestpeople/Geist
import numpy as np from ..core import Location class GeistFakeBackend(object): - def __init__(self, w=800, h=600): + def __init__(self, image=None, w=800, h=600): + if image is None: - self.image = np.zeros((h, w, 3)) + self.image = np.zeros((h, w, 3)) - self.locations = [Location(0, 0, w=w, h=h, image=self.image)] + self.locations = [Location(0, 0, w=w, h=h, image=self.image)] + else: + if isinstance(image, basestring): + image = np.load(image) + self.image = image + h, w, _ = image.shape + self.locations = [Location(0, 0, w=w, h=h, image=self.image)] def create_process(self, command): pass def actions_transaction(self): pass def capture_locations(self): for loc in self.locations: yield loc def key_down(self, name): pass def key_up(self, name): pass def button_down(self, button_num): pass def button_up(self, button_num): pass def move(self, point): pass def close(self): pass
Allow Fake Backend to take an image as the screen
## Code Before: import numpy as np from ..core import Location class GeistFakeBackend(object): def __init__(self, w=800, h=600): self.image = np.zeros((h, w, 3)) self.locations = [Location(0, 0, w=w, h=h, image=self.image)] def create_process(self, command): pass def actions_transaction(self): pass def capture_locations(self): for loc in self.locations: yield loc def key_down(self, name): pass def key_up(self, name): pass def button_down(self, button_num): pass def button_up(self, button_num): pass def move(self, point): pass def close(self): pass ## Instruction: Allow Fake Backend to take an image as the screen ## Code After: import numpy as np from ..core import Location class GeistFakeBackend(object): def __init__(self, image=None, w=800, h=600): if image is None: self.image = np.zeros((h, w, 3)) self.locations = [Location(0, 0, w=w, h=h, image=self.image)] else: if isinstance(image, basestring): image = np.load(image) self.image = image h, w, _ = image.shape self.locations = [Location(0, 0, w=w, h=h, image=self.image)] def create_process(self, command): pass def actions_transaction(self): pass def capture_locations(self): for loc in self.locations: yield loc def key_down(self, name): pass def key_up(self, name): pass def button_down(self, button_num): pass def button_up(self, button_num): pass def move(self, point): pass def close(self): pass
import numpy as np from ..core import Location class GeistFakeBackend(object): - def __init__(self, w=800, h=600): + def __init__(self, image=None, w=800, h=600): ? ++++++++++++ + if image is None: - self.image = np.zeros((h, w, 3)) + self.image = np.zeros((h, w, 3)) ? ++++ - self.locations = [Location(0, 0, w=w, h=h, image=self.image)] + self.locations = [Location(0, 0, w=w, h=h, image=self.image)] ? ++++ + else: + if isinstance(image, basestring): + image = np.load(image) + self.image = image + h, w, _ = image.shape + self.locations = [Location(0, 0, w=w, h=h, image=self.image)] def create_process(self, command): pass def actions_transaction(self): pass def capture_locations(self): for loc in self.locations: yield loc def key_down(self, name): pass def key_up(self, name): pass def button_down(self, button_num): pass def button_up(self, button_num): pass def move(self, point): pass def close(self): pass
e9df15b0f084ed9e026a5de129b109a3c546f99c
src/libeeyore/parse_tree_to_cpp.py
src/libeeyore/parse_tree_to_cpp.py
import builtins from cpp.cpprenderer import EeyCppRenderer from environment import EeyEnvironment from values import * def parse_tree_string_to_values( string ): return eval( string ) def non_empty_line( ln ): return ( ln.strip() != "" ) def parse_tree_to_cpp( parse_tree_in_fl, cpp_out_fl ): env = EeyEnvironment( EeyCppRenderer() ) builtins.add_builtins( self ) values = ( parse_tree_string_to_values( ln ) for ln in filter( non_empty_line, parse_tree_in_fl ) ) cpp_out_fl.write( env.render_exe( values ) )
from itertools import imap import builtins from cpp.cpprenderer import EeyCppRenderer from environment import EeyEnvironment from functionvalues import * from languagevalues import * from values import * def parse_tree_string_to_values( string ): return eval( string ) def remove_comments( ln ): i = ln.find( "#" ) if i != -1: return ln[:i] else: return ln def non_empty_line( ln ): return ( ln.strip() != "" ) def parse_tree_to_cpp( parse_tree_in_fl, cpp_out_fl ): env = EeyEnvironment( EeyCppRenderer() ) builtins.add_builtins( env ) values = ( parse_tree_string_to_values( ln ) for ln in filter( non_empty_line, imap( remove_comments, parse_tree_in_fl ) ) ) cpp_out_fl.write( env.render_exe( values ) )
Handle comments in parse tree.
Handle comments in parse tree.
Python
mit
andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper
+ from itertools import imap import builtins from cpp.cpprenderer import EeyCppRenderer from environment import EeyEnvironment + from functionvalues import * + from languagevalues import * from values import * def parse_tree_string_to_values( string ): return eval( string ) + + def remove_comments( ln ): + i = ln.find( "#" ) + if i != -1: + return ln[:i] + else: + return ln def non_empty_line( ln ): return ( ln.strip() != "" ) def parse_tree_to_cpp( parse_tree_in_fl, cpp_out_fl ): env = EeyEnvironment( EeyCppRenderer() ) - builtins.add_builtins( self ) + builtins.add_builtins( env ) values = ( parse_tree_string_to_values( ln ) for ln in - filter( non_empty_line, parse_tree_in_fl ) ) + filter( non_empty_line, imap( remove_comments, parse_tree_in_fl ) ) ) cpp_out_fl.write( env.render_exe( values ) )
Handle comments in parse tree.
## Code Before: import builtins from cpp.cpprenderer import EeyCppRenderer from environment import EeyEnvironment from values import * def parse_tree_string_to_values( string ): return eval( string ) def non_empty_line( ln ): return ( ln.strip() != "" ) def parse_tree_to_cpp( parse_tree_in_fl, cpp_out_fl ): env = EeyEnvironment( EeyCppRenderer() ) builtins.add_builtins( self ) values = ( parse_tree_string_to_values( ln ) for ln in filter( non_empty_line, parse_tree_in_fl ) ) cpp_out_fl.write( env.render_exe( values ) ) ## Instruction: Handle comments in parse tree. ## Code After: from itertools import imap import builtins from cpp.cpprenderer import EeyCppRenderer from environment import EeyEnvironment from functionvalues import * from languagevalues import * from values import * def parse_tree_string_to_values( string ): return eval( string ) def remove_comments( ln ): i = ln.find( "#" ) if i != -1: return ln[:i] else: return ln def non_empty_line( ln ): return ( ln.strip() != "" ) def parse_tree_to_cpp( parse_tree_in_fl, cpp_out_fl ): env = EeyEnvironment( EeyCppRenderer() ) builtins.add_builtins( env ) values = ( parse_tree_string_to_values( ln ) for ln in filter( non_empty_line, imap( remove_comments, parse_tree_in_fl ) ) ) cpp_out_fl.write( env.render_exe( values ) )
+ from itertools import imap import builtins from cpp.cpprenderer import EeyCppRenderer from environment import EeyEnvironment + from functionvalues import * + from languagevalues import * from values import * def parse_tree_string_to_values( string ): return eval( string ) + + def remove_comments( ln ): + i = ln.find( "#" ) + if i != -1: + return ln[:i] + else: + return ln def non_empty_line( ln ): return ( ln.strip() != "" ) def parse_tree_to_cpp( parse_tree_in_fl, cpp_out_fl ): env = EeyEnvironment( EeyCppRenderer() ) - builtins.add_builtins( self ) ? - ^^ + builtins.add_builtins( env ) ? ^^ values = ( parse_tree_string_to_values( ln ) for ln in - filter( non_empty_line, parse_tree_in_fl ) ) + filter( non_empty_line, imap( remove_comments, parse_tree_in_fl ) ) ) ? +++++++++++++++++++++++ ++ cpp_out_fl.write( env.render_exe( values ) )
22888f6731cf7e6ab0a6cb14088075cf7061d310
sympy/interactive/ipythonprinting.py
sympy/interactive/ipythonprinting.py
#----------------------------------------------------------------------------- # Copyright (C) 2008 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from sympy.interactive.printing import init_printing #----------------------------------------------------------------------------- # Definitions of special display functions for use with IPython #----------------------------------------------------------------------------- _loaded = False def load_ipython_extension(ip): """Load the extension in IPython.""" import IPython global _loaded # Use extension manager to track loaded status if available # This is currently in IPython 0.14.dev if hasattr(ip.extension_manager, 'loaded'): loaded = 'sympy.interactive.ipythonprinting' in ip.extension_manager.loaded else: loaded = _loaded if not loaded: init_printing(ip=ip) _loaded = True
#----------------------------------------------------------------------------- # Copyright (C) 2008 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from sympy.interactive.printing import init_printing #----------------------------------------------------------------------------- # Definitions of special display functions for use with IPython #----------------------------------------------------------------------------- def load_ipython_extension(ip): """Load the extension in IPython.""" init_printing(ip=ip)
Remove checks that module is loaded
Remove checks that module is loaded
Python
bsd-3-clause
wanglongqi/sympy,meghana1995/sympy,skirpichev/omg,ga7g08/sympy,jamesblunt/sympy,Shaswat27/sympy,amitjamadagni/sympy,saurabhjn76/sympy,shikil/sympy,ga7g08/sympy,kevalds51/sympy,maniteja123/sympy,sampadsaha5/sympy,postvakje/sympy,debugger22/sympy,emon10005/sympy,farhaanbukhsh/sympy,diofant/diofant,sunny94/temp,souravsingh/sympy,Designist/sympy,liangjiaxing/sympy,dqnykamp/sympy,Vishluck/sympy,yashsharan/sympy,vipulroxx/sympy,skidzo/sympy,jbbskinny/sympy,farhaanbukhsh/sympy,souravsingh/sympy,AunShiLord/sympy,Titan-C/sympy,Curious72/sympy,garvitr/sympy,chaffra/sympy,shipci/sympy,ChristinaZografou/sympy,mcdaniel67/sympy,pandeyadarsh/sympy,sahilshekhawat/sympy,Sumith1896/sympy,aktech/sympy,liangjiaxing/sympy,kumarkrishna/sympy,Davidjohnwilson/sympy,meghana1995/sympy,mcdaniel67/sympy,toolforger/sympy,farhaanbukhsh/sympy,yashsharan/sympy,dqnykamp/sympy,toolforger/sympy,Mitchkoens/sympy,ChristinaZografou/sympy,Curious72/sympy,madan96/sympy,beni55/sympy,aktech/sympy,jamesblunt/sympy,sahmed95/sympy,ahhda/sympy,oliverlee/sympy,rahuldan/sympy,atsao72/sympy,kaushik94/sympy,Vishluck/sympy,Vishluck/sympy,atreyv/sympy,kaushik94/sympy,Shaswat27/sympy,abloomston/sympy,postvakje/sympy,shipci/sympy,dqnykamp/sympy,madan96/sympy,iamutkarshtiwari/sympy,wanglongqi/sympy,drufat/sympy,asm666/sympy,jamesblunt/sympy,Sumith1896/sympy,pandeyadarsh/sympy,mafiya69/sympy,Davidjohnwilson/sympy,Davidjohnwilson/sympy,skidzo/sympy,VaibhavAgarwalVA/sympy,Arafatk/sympy,grevutiu-gabriel/sympy,pbrady/sympy,MridulS/sympy,ahhda/sympy,jbbskinny/sympy,yukoba/sympy,aktech/sympy,Designist/sympy,kmacinnis/sympy,abhiii5459/sympy,cccfran/sympy,mafiya69/sympy,kmacinnis/sympy,AunShiLord/sympy,sahilshekhawat/sympy,pbrady/sympy,MridulS/sympy,vipulroxx/sympy,abhiii5459/sympy,Arafatk/sympy,abloomston/sympy,lindsayad/sympy,saurabhjn76/sympy,MridulS/sympy,liangjiaxing/sympy,pbrady/sympy,Curious72/sympy,mcdaniel67/sympy,lidavidm/sympy,hrashk/sympy,atreyv/sympy,VaibhavAgarwalVA/sympy,kumarkrishna/sympy,hrashk/sympy,jaimahajan1997/sympy,abloomston/sympy,hargup/sympy,beni55/sympy,bukzor/sympy,iamutkarshtiwari/sympy,Titan-C/sympy,MechCoder/sympy,cswiercz/sympy,mafiya69/sympy,Sumith1896/sympy,MechCoder/sympy,toolforger/sympy,Shaswat27/sympy,kaushik94/sympy,jbbskinny/sympy,Titan-C/sympy,jaimahajan1997/sympy,atsao72/sympy,lidavidm/sympy,postvakje/sympy,lidavidm/sympy,Mitchkoens/sympy,hargup/sympy,grevutiu-gabriel/sympy,MechCoder/sympy,abhiii5459/sympy,shikil/sympy,AunShiLord/sympy,kevalds51/sympy,meghana1995/sympy,sahmed95/sympy,sahilshekhawat/sympy,Designist/sympy,atsao72/sympy,asm666/sympy,sampadsaha5/sympy,garvitr/sympy,sampadsaha5/sympy,bukzor/sympy,oliverlee/sympy,AkademieOlympia/sympy,ahhda/sympy,jerli/sympy,sunny94/temp,grevutiu-gabriel/sympy,sahmed95/sympy,Gadal/sympy,yukoba/sympy,chaffra/sympy,wyom/sympy,drufat/sympy,oliverlee/sympy,iamutkarshtiwari/sympy,kaichogami/sympy,cswiercz/sympy,asm666/sympy,cccfran/sympy,kevalds51/sympy,hargup/sympy,kumarkrishna/sympy,amitjamadagni/sympy,lindsayad/sympy,debugger22/sympy,chaffra/sympy,cccfran/sympy,wyom/sympy,AkademieOlympia/sympy,Gadal/sympy,AkademieOlympia/sympy,ga7g08/sympy,yashsharan/sympy,kaichogami/sympy,atreyv/sympy,jerli/sympy,kaichogami/sympy,moble/sympy,skidzo/sympy,souravsingh/sympy,Arafatk/sympy,emon10005/sympy,lindsayad/sympy,yukoba/sympy,sunny94/temp,Gadal/sympy,moble/sympy,maniteja123/sympy,jerli/sympy,debugger22/sympy,maniteja123/sympy,wyom/sympy,kmacinnis/sympy,emon10005/sympy,jaimahajan1997/sympy,madan96/sympy,vipulroxx/sympy,saurabhjn76/sympy,ChristinaZografou/sympy,wanglongqi/sympy,shikil/sympy,beni55/sympy,rahuldan/sympy,bukzor/sympy,Mitchkoens/sympy,VaibhavAgarwalVA/sympy,garvitr/sympy,moble/sympy,hrashk/sympy,drufat/sympy,cswiercz/sympy,rahuldan/sympy,pandeyadarsh/sympy,shipci/sympy
#----------------------------------------------------------------------------- # Copyright (C) 2008 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from sympy.interactive.printing import init_printing #----------------------------------------------------------------------------- # Definitions of special display functions for use with IPython #----------------------------------------------------------------------------- - _loaded = False - - def load_ipython_extension(ip): """Load the extension in IPython.""" - import IPython + init_printing(ip=ip) - global _loaded - # Use extension manager to track loaded status if available - # This is currently in IPython 0.14.dev - if hasattr(ip.extension_manager, 'loaded'): - loaded = 'sympy.interactive.ipythonprinting' in ip.extension_manager.loaded - else: - loaded = _loaded - - if not loaded: - init_printing(ip=ip) - _loaded = True -
Remove checks that module is loaded
## Code Before: #----------------------------------------------------------------------------- # Copyright (C) 2008 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from sympy.interactive.printing import init_printing #----------------------------------------------------------------------------- # Definitions of special display functions for use with IPython #----------------------------------------------------------------------------- _loaded = False def load_ipython_extension(ip): """Load the extension in IPython.""" import IPython global _loaded # Use extension manager to track loaded status if available # This is currently in IPython 0.14.dev if hasattr(ip.extension_manager, 'loaded'): loaded = 'sympy.interactive.ipythonprinting' in ip.extension_manager.loaded else: loaded = _loaded if not loaded: init_printing(ip=ip) _loaded = True ## Instruction: Remove checks that module is loaded ## Code After: #----------------------------------------------------------------------------- # Copyright (C) 2008 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from sympy.interactive.printing import init_printing #----------------------------------------------------------------------------- # Definitions of special display functions for use with IPython #----------------------------------------------------------------------------- def load_ipython_extension(ip): """Load the extension in IPython.""" init_printing(ip=ip)
#----------------------------------------------------------------------------- # Copyright (C) 2008 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from sympy.interactive.printing import init_printing #----------------------------------------------------------------------------- # Definitions of special display functions for use with IPython #----------------------------------------------------------------------------- - _loaded = False - - def load_ipython_extension(ip): """Load the extension in IPython.""" - import IPython - - global _loaded - # Use extension manager to track loaded status if available - # This is currently in IPython 0.14.dev - if hasattr(ip.extension_manager, 'loaded'): - loaded = 'sympy.interactive.ipythonprinting' in ip.extension_manager.loaded - else: - loaded = _loaded - - if not loaded: - init_printing(ip=ip) ? ---- + init_printing(ip=ip) - _loaded = True
0eca195f9c29824f354cae53a4005f04c67eb86f
nodeconductor/cloud/views.py
nodeconductor/cloud/views.py
from rest_framework import permissions as rf_permissions from rest_framework import exceptions from nodeconductor.core import viewsets from nodeconductor.cloud import models from nodeconductor.cloud import serializers from nodeconductor.structure import filters as structure_filters from nodeconductor.structure import models as structure_models class FlavorViewSet(viewsets.ReadOnlyModelViewSet): model = models.Flavor serializer_class = serializers.FlavorSerializer lookup_field = 'uuid' filter_backends = (structure_filters.GenericRoleFilter,) class CloudViewSet(viewsets.ModelViewSet): model = models.Cloud serializer_class = serializers.CloudSerializer lookup_field = 'uuid' filter_backends = (structure_filters.GenericRoleFilter,) permission_classes = (rf_permissions.IsAuthenticated, rf_permissions.DjangoObjectPermissions) def pre_save(self, cloud): super(CloudViewSet, self).pre_save(cloud) if not cloud.customer.roles.filter( permission_group__user=self.request.user, role_type=structure_models.CustomerRole.OWNER, ).exists(): raise exceptions.PermissionDenied()
from rest_framework import permissions as rf_permissions from rest_framework import exceptions from nodeconductor.core import viewsets from nodeconductor.cloud import models from nodeconductor.cloud import serializers from nodeconductor.structure import filters as structure_filters from nodeconductor.structure import models as structure_models class FlavorViewSet(viewsets.ReadOnlyModelViewSet): model = models.Flavor serializer_class = serializers.FlavorSerializer lookup_field = 'uuid' filter_backends = (structure_filters.GenericRoleFilter,) class CloudViewSet(viewsets.ModelViewSet): queryset = models.Cloud.objects.all().prefetch_related('flavors') serializer_class = serializers.CloudSerializer lookup_field = 'uuid' filter_backends = (structure_filters.GenericRoleFilter,) permission_classes = (rf_permissions.IsAuthenticated, rf_permissions.DjangoObjectPermissions) def pre_save(self, cloud): super(CloudViewSet, self).pre_save(cloud) if not cloud.customer.roles.filter( permission_group__user=self.request.user, role_type=structure_models.CustomerRole.OWNER, ).exists(): raise exceptions.PermissionDenied()
Optimize SQL queries used for fetching clouds
Optimize SQL queries used for fetching clouds
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
from rest_framework import permissions as rf_permissions from rest_framework import exceptions from nodeconductor.core import viewsets from nodeconductor.cloud import models from nodeconductor.cloud import serializers from nodeconductor.structure import filters as structure_filters from nodeconductor.structure import models as structure_models class FlavorViewSet(viewsets.ReadOnlyModelViewSet): model = models.Flavor serializer_class = serializers.FlavorSerializer lookup_field = 'uuid' filter_backends = (structure_filters.GenericRoleFilter,) class CloudViewSet(viewsets.ModelViewSet): - model = models.Cloud + queryset = models.Cloud.objects.all().prefetch_related('flavors') serializer_class = serializers.CloudSerializer lookup_field = 'uuid' filter_backends = (structure_filters.GenericRoleFilter,) permission_classes = (rf_permissions.IsAuthenticated, rf_permissions.DjangoObjectPermissions) def pre_save(self, cloud): super(CloudViewSet, self).pre_save(cloud) if not cloud.customer.roles.filter( permission_group__user=self.request.user, role_type=structure_models.CustomerRole.OWNER, ).exists(): raise exceptions.PermissionDenied()
Optimize SQL queries used for fetching clouds
## Code Before: from rest_framework import permissions as rf_permissions from rest_framework import exceptions from nodeconductor.core import viewsets from nodeconductor.cloud import models from nodeconductor.cloud import serializers from nodeconductor.structure import filters as structure_filters from nodeconductor.structure import models as structure_models class FlavorViewSet(viewsets.ReadOnlyModelViewSet): model = models.Flavor serializer_class = serializers.FlavorSerializer lookup_field = 'uuid' filter_backends = (structure_filters.GenericRoleFilter,) class CloudViewSet(viewsets.ModelViewSet): model = models.Cloud serializer_class = serializers.CloudSerializer lookup_field = 'uuid' filter_backends = (structure_filters.GenericRoleFilter,) permission_classes = (rf_permissions.IsAuthenticated, rf_permissions.DjangoObjectPermissions) def pre_save(self, cloud): super(CloudViewSet, self).pre_save(cloud) if not cloud.customer.roles.filter( permission_group__user=self.request.user, role_type=structure_models.CustomerRole.OWNER, ).exists(): raise exceptions.PermissionDenied() ## Instruction: Optimize SQL queries used for fetching clouds ## Code After: from rest_framework import permissions as rf_permissions from rest_framework import exceptions from nodeconductor.core import viewsets from nodeconductor.cloud import models from nodeconductor.cloud import serializers from nodeconductor.structure import filters as structure_filters from nodeconductor.structure import models as structure_models class FlavorViewSet(viewsets.ReadOnlyModelViewSet): model = models.Flavor serializer_class = serializers.FlavorSerializer lookup_field = 'uuid' filter_backends = (structure_filters.GenericRoleFilter,) class CloudViewSet(viewsets.ModelViewSet): queryset = models.Cloud.objects.all().prefetch_related('flavors') serializer_class = serializers.CloudSerializer lookup_field = 'uuid' filter_backends = (structure_filters.GenericRoleFilter,) permission_classes = (rf_permissions.IsAuthenticated, rf_permissions.DjangoObjectPermissions) def pre_save(self, cloud): super(CloudViewSet, self).pre_save(cloud) if not cloud.customer.roles.filter( permission_group__user=self.request.user, role_type=structure_models.CustomerRole.OWNER, ).exists(): raise exceptions.PermissionDenied()
from rest_framework import permissions as rf_permissions from rest_framework import exceptions from nodeconductor.core import viewsets from nodeconductor.cloud import models from nodeconductor.cloud import serializers from nodeconductor.structure import filters as structure_filters from nodeconductor.structure import models as structure_models class FlavorViewSet(viewsets.ReadOnlyModelViewSet): model = models.Flavor serializer_class = serializers.FlavorSerializer lookup_field = 'uuid' filter_backends = (structure_filters.GenericRoleFilter,) class CloudViewSet(viewsets.ModelViewSet): - model = models.Cloud + queryset = models.Cloud.objects.all().prefetch_related('flavors') serializer_class = serializers.CloudSerializer lookup_field = 'uuid' filter_backends = (structure_filters.GenericRoleFilter,) permission_classes = (rf_permissions.IsAuthenticated, rf_permissions.DjangoObjectPermissions) def pre_save(self, cloud): super(CloudViewSet, self).pre_save(cloud) if not cloud.customer.roles.filter( permission_group__user=self.request.user, role_type=structure_models.CustomerRole.OWNER, ).exists(): raise exceptions.PermissionDenied()
d2991a6385be74debf71eb8404e362c6027e6d50
molecule/default/tests/test_default.py
molecule/default/tests/test_default.py
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_command(host): assert host.command('i3 --version').rc == 0 assert host.command('pactl --version').rc == 0 assert host.command('Xorg -version').rc == 0
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_command(host): assert host.command('i3 --version').rc == 0 assert host.command('pactl --version').rc == 0
Remove redundant xorg command test
Remove redundant xorg command test
Python
mit
nephelaiio/ansible-role-i3,nephelaiio/ansible-role-i3
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_command(host): assert host.command('i3 --version').rc == 0 assert host.command('pactl --version').rc == 0 - assert host.command('Xorg -version').rc == 0
Remove redundant xorg command test
## Code Before: import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_command(host): assert host.command('i3 --version').rc == 0 assert host.command('pactl --version').rc == 0 assert host.command('Xorg -version').rc == 0 ## Instruction: Remove redundant xorg command test ## Code After: import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_command(host): assert host.command('i3 --version').rc == 0 assert host.command('pactl --version').rc == 0
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_command(host): assert host.command('i3 --version').rc == 0 assert host.command('pactl --version').rc == 0 - assert host.command('Xorg -version').rc == 0
2d3b899011c79324195a36aaf3bd53dae6abe961
seleniumrequests/__init__.py
seleniumrequests/__init__.py
from selenium.webdriver import Firefox, Chrome, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote from seleniumrequests.request import RequestsSessionMixin class Firefox(RequestsSessionMixin, Firefox): pass class Chrome(RequestsSessionMixin, Chrome): pass class Ie(RequestsSessionMixin, Ie): pass class Edge(RequestsSessionMixin, Edge): pass class Opera(RequestsSessionMixin, Opera): pass class Safari(RequestsSessionMixin, Safari): pass class BlackBerry(RequestsSessionMixin, BlackBerry): pass class PhantomJS(RequestsSessionMixin, PhantomJS): pass class Android(RequestsSessionMixin, Android): pass class Remote(RequestsSessionMixin, Remote): pass
from selenium.webdriver import _Firefox, _Chrome, _Ie, _Edge, _Opera, _Safari, _BlackBerry, _PhantomJS, _Android, \ _Remote from seleniumrequests.request import RequestsSessionMixin class Firefox(RequestsSessionMixin, _Firefox): pass class Chrome(RequestsSessionMixin, _Chrome): pass class Ie(RequestsSessionMixin, _Ie): pass class Edge(RequestsSessionMixin, _Edge): pass class Opera(RequestsSessionMixin, _Opera): pass class Safari(RequestsSessionMixin, _Safari): pass class BlackBerry(RequestsSessionMixin, _BlackBerry): pass class PhantomJS(RequestsSessionMixin, _PhantomJS): pass class Android(RequestsSessionMixin, _Android): pass class Remote(RequestsSessionMixin, _Remote): pass
Fix PyCharm warnings like this: "Cannot find reference `request` in `PhantomJS | WebDriver`"
Fix PyCharm warnings like this: "Cannot find reference `request` in `PhantomJS | WebDriver`"
Python
mit
cryzed/Selenium-Requests
- from selenium.webdriver import Firefox, Chrome, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote + from selenium.webdriver import _Firefox, _Chrome, _Ie, _Edge, _Opera, _Safari, _BlackBerry, _PhantomJS, _Android, \ + _Remote from seleniumrequests.request import RequestsSessionMixin - class Firefox(RequestsSessionMixin, Firefox): + class Firefox(RequestsSessionMixin, _Firefox): pass - class Chrome(RequestsSessionMixin, Chrome): + class Chrome(RequestsSessionMixin, _Chrome): pass - class Ie(RequestsSessionMixin, Ie): + class Ie(RequestsSessionMixin, _Ie): pass - class Edge(RequestsSessionMixin, Edge): + class Edge(RequestsSessionMixin, _Edge): pass - class Opera(RequestsSessionMixin, Opera): + class Opera(RequestsSessionMixin, _Opera): pass - class Safari(RequestsSessionMixin, Safari): + class Safari(RequestsSessionMixin, _Safari): pass - class BlackBerry(RequestsSessionMixin, BlackBerry): + class BlackBerry(RequestsSessionMixin, _BlackBerry): pass - class PhantomJS(RequestsSessionMixin, PhantomJS): + class PhantomJS(RequestsSessionMixin, _PhantomJS): pass - class Android(RequestsSessionMixin, Android): + class Android(RequestsSessionMixin, _Android): pass - class Remote(RequestsSessionMixin, Remote): + class Remote(RequestsSessionMixin, _Remote): pass
Fix PyCharm warnings like this: "Cannot find reference `request` in `PhantomJS | WebDriver`"
## Code Before: from selenium.webdriver import Firefox, Chrome, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote from seleniumrequests.request import RequestsSessionMixin class Firefox(RequestsSessionMixin, Firefox): pass class Chrome(RequestsSessionMixin, Chrome): pass class Ie(RequestsSessionMixin, Ie): pass class Edge(RequestsSessionMixin, Edge): pass class Opera(RequestsSessionMixin, Opera): pass class Safari(RequestsSessionMixin, Safari): pass class BlackBerry(RequestsSessionMixin, BlackBerry): pass class PhantomJS(RequestsSessionMixin, PhantomJS): pass class Android(RequestsSessionMixin, Android): pass class Remote(RequestsSessionMixin, Remote): pass ## Instruction: Fix PyCharm warnings like this: "Cannot find reference `request` in `PhantomJS | WebDriver`" ## Code After: from selenium.webdriver import _Firefox, _Chrome, _Ie, _Edge, _Opera, _Safari, _BlackBerry, _PhantomJS, _Android, \ _Remote from seleniumrequests.request import RequestsSessionMixin class Firefox(RequestsSessionMixin, _Firefox): pass class Chrome(RequestsSessionMixin, _Chrome): pass class Ie(RequestsSessionMixin, _Ie): pass class Edge(RequestsSessionMixin, _Edge): pass class Opera(RequestsSessionMixin, _Opera): pass class Safari(RequestsSessionMixin, _Safari): pass class BlackBerry(RequestsSessionMixin, _BlackBerry): pass class PhantomJS(RequestsSessionMixin, _PhantomJS): pass class Android(RequestsSessionMixin, _Android): pass class Remote(RequestsSessionMixin, _Remote): pass
- from selenium.webdriver import Firefox, Chrome, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote ? ^^^^^^ + from selenium.webdriver import _Firefox, _Chrome, _Ie, _Edge, _Opera, _Safari, _BlackBerry, _PhantomJS, _Android, \ ? + + + + + + + + + ^ + _Remote from seleniumrequests.request import RequestsSessionMixin - class Firefox(RequestsSessionMixin, Firefox): + class Firefox(RequestsSessionMixin, _Firefox): ? + pass - class Chrome(RequestsSessionMixin, Chrome): + class Chrome(RequestsSessionMixin, _Chrome): ? + pass - class Ie(RequestsSessionMixin, Ie): + class Ie(RequestsSessionMixin, _Ie): ? + pass - class Edge(RequestsSessionMixin, Edge): + class Edge(RequestsSessionMixin, _Edge): ? + pass - class Opera(RequestsSessionMixin, Opera): + class Opera(RequestsSessionMixin, _Opera): ? + pass - class Safari(RequestsSessionMixin, Safari): + class Safari(RequestsSessionMixin, _Safari): ? + pass - class BlackBerry(RequestsSessionMixin, BlackBerry): + class BlackBerry(RequestsSessionMixin, _BlackBerry): ? + pass - class PhantomJS(RequestsSessionMixin, PhantomJS): + class PhantomJS(RequestsSessionMixin, _PhantomJS): ? + pass - class Android(RequestsSessionMixin, Android): + class Android(RequestsSessionMixin, _Android): ? + pass - class Remote(RequestsSessionMixin, Remote): + class Remote(RequestsSessionMixin, _Remote): ? + pass
2263d180184c908b0e96d53f43f6c81aa23a3c92
push/urls.py
push/urls.py
from django.conf.urls import url from push import views urlpatterns = [ url(r'^$', views.index, name = 'index'), url(r'^sender', views.sender, name = 'sender'), url(r'^notification_list', views.notification_list, name = 'notification_list'), url(r'^settings', views.settings, name = 'settings'), url(r'^notification', views.notification, name = 'notification'), url(r'^register', views.device_token_register, name = 'device_token_register'), url(r'^delete/device_token/(?P<device_token_id>\d+)/$', views.delete_device_token, name = 'delete_device_token'), ]
from django.conf.urls import url from push import views urlpatterns = [ url(r'^$', views.index, name = 'index'), url(r'^sender', views.sender, name = 'sender'), url(r'^notification_list', views.notification_list, name = 'notification_list'), url(r'^settings', views.settings, name = 'settings'), url(r'^notification', views.notification, name = 'notification'), url(r'^(?P<username>\w+)/register', views.device_token_register, name = 'device_token_register'), url(r'^delete/device_token/(?P<device_token_id>\d+)/$', views.delete_device_token, name = 'delete_device_token'), ]
Modify device_token register URL dispatcher
Modify device_token register URL dispatcher
Python
apache-2.0
nnsnodnb/django-mbaas,nnsnodnb/django-mbaas,nnsnodnb/django-mbaas
from django.conf.urls import url from push import views urlpatterns = [ url(r'^$', views.index, name = 'index'), url(r'^sender', views.sender, name = 'sender'), url(r'^notification_list', views.notification_list, name = 'notification_list'), url(r'^settings', views.settings, name = 'settings'), url(r'^notification', views.notification, name = 'notification'), - url(r'^register', views.device_token_register, name = 'device_token_register'), + url(r'^(?P<username>\w+)/register', views.device_token_register, name = 'device_token_register'), url(r'^delete/device_token/(?P<device_token_id>\d+)/$', views.delete_device_token, name = 'delete_device_token'), ]
Modify device_token register URL dispatcher
## Code Before: from django.conf.urls import url from push import views urlpatterns = [ url(r'^$', views.index, name = 'index'), url(r'^sender', views.sender, name = 'sender'), url(r'^notification_list', views.notification_list, name = 'notification_list'), url(r'^settings', views.settings, name = 'settings'), url(r'^notification', views.notification, name = 'notification'), url(r'^register', views.device_token_register, name = 'device_token_register'), url(r'^delete/device_token/(?P<device_token_id>\d+)/$', views.delete_device_token, name = 'delete_device_token'), ] ## Instruction: Modify device_token register URL dispatcher ## Code After: from django.conf.urls import url from push import views urlpatterns = [ url(r'^$', views.index, name = 'index'), url(r'^sender', views.sender, name = 'sender'), url(r'^notification_list', views.notification_list, name = 'notification_list'), url(r'^settings', views.settings, name = 'settings'), url(r'^notification', views.notification, name = 'notification'), url(r'^(?P<username>\w+)/register', views.device_token_register, name = 'device_token_register'), url(r'^delete/device_token/(?P<device_token_id>\d+)/$', views.delete_device_token, name = 'delete_device_token'), ]
from django.conf.urls import url from push import views urlpatterns = [ url(r'^$', views.index, name = 'index'), url(r'^sender', views.sender, name = 'sender'), url(r'^notification_list', views.notification_list, name = 'notification_list'), url(r'^settings', views.settings, name = 'settings'), url(r'^notification', views.notification, name = 'notification'), - url(r'^register', views.device_token_register, name = 'device_token_register'), + url(r'^(?P<username>\w+)/register', views.device_token_register, name = 'device_token_register'), ? ++++++++++++++++++ url(r'^delete/device_token/(?P<device_token_id>\d+)/$', views.delete_device_token, name = 'delete_device_token'), ]
f54fd0bf65d731b4f25cfc2ddffb8d6f472e0d7c
examples/eiger_use_case.py
examples/eiger_use_case.py
'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files),) + sh, dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0)
'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0)
Fix layout for Eiger example
Fix layout for Eiger example
Python
bsd-3-clause
h5py/h5py,h5py/h5py,h5py/h5py
'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. - layout = h5py.VirtualLayout(shape=(len(files),) + sh, dtype=np.float) + layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0)
Fix layout for Eiger example
## Code Before: '''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files),) + sh, dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0) ## Instruction: Fix layout for Eiger example ## Code After: '''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0)
'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. - layout = h5py.VirtualLayout(shape=(len(files),) + sh, dtype=np.float) + layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float) ? ++++++++ + ++++ M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0)
6881d127cf55dc96c44467ea807a9288a5108dff
scripts/lib/check_for_course_revisions.py
scripts/lib/check_for_course_revisions.py
from collections import OrderedDict import json from .load_data_from_file import load_data_from_file from .get_old_dict_values import get_old_dict_values from .log import log from .paths import make_course_path def load_previous(course_path): try: prior_data = load_data_from_file(course_path) prior = json.loads(prior_data) except FileNotFoundError: prior = None revisions = [] # print(course_path, revisions) if prior and ('revisions' in prior): revisions = prior['revisions'] del prior['revisions'] return (prior, revisions or []) def check_for_revisions(course): prior, revisions = load_previous(make_course_path(course['clbid'])) if not prior: return None diff = get_old_dict_values(prior, course) ordered_diff = OrderedDict() for key in sorted(diff.keys()): ordered_diff[key] = diff[key] if ordered_diff: revisions.append(ordered_diff) log('revision in %d:' % (course['clbid']), ordered_diff) if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))): return revisions return None
from collections import OrderedDict from tzlocal import get_localzone import json from .load_data_from_file import load_data_from_file from .get_old_dict_values import get_old_dict_values from .log import log from .paths import make_course_path def load_previous(course_path): try: prior_data = load_data_from_file(course_path) prior = json.loads(prior_data) except FileNotFoundError: prior = None revisions = [] # print(course_path, revisions) if prior and ('revisions' in prior): revisions = prior['revisions'] del prior['revisions'] return (prior, revisions or []) def check_for_revisions(course): prior, revisions = load_previous(make_course_path(course['clbid'])) if not prior: return None diff = get_old_dict_values(prior, course) ordered_diff = OrderedDict() for key in sorted(diff.keys()): ordered_diff[key] = diff[key] if ordered_diff: ordered_diff['_updated'] = get_localzone().localize(datetime.now()).isoformat() revisions.append(ordered_diff) log('revision in %d:' % (course['clbid']), ordered_diff) if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))): return revisions return None
Add '_updated' property to revisions
Add '_updated' property to revisions
Python
mit
StoDevX/course-data-tools,StoDevX/course-data-tools
from collections import OrderedDict + from tzlocal import get_localzone import json from .load_data_from_file import load_data_from_file from .get_old_dict_values import get_old_dict_values from .log import log from .paths import make_course_path def load_previous(course_path): try: prior_data = load_data_from_file(course_path) prior = json.loads(prior_data) except FileNotFoundError: prior = None revisions = [] # print(course_path, revisions) if prior and ('revisions' in prior): revisions = prior['revisions'] del prior['revisions'] return (prior, revisions or []) def check_for_revisions(course): prior, revisions = load_previous(make_course_path(course['clbid'])) if not prior: return None diff = get_old_dict_values(prior, course) ordered_diff = OrderedDict() for key in sorted(diff.keys()): ordered_diff[key] = diff[key] if ordered_diff: + ordered_diff['_updated'] = get_localzone().localize(datetime.now()).isoformat() revisions.append(ordered_diff) log('revision in %d:' % (course['clbid']), ordered_diff) if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))): return revisions return None
Add '_updated' property to revisions
## Code Before: from collections import OrderedDict import json from .load_data_from_file import load_data_from_file from .get_old_dict_values import get_old_dict_values from .log import log from .paths import make_course_path def load_previous(course_path): try: prior_data = load_data_from_file(course_path) prior = json.loads(prior_data) except FileNotFoundError: prior = None revisions = [] # print(course_path, revisions) if prior and ('revisions' in prior): revisions = prior['revisions'] del prior['revisions'] return (prior, revisions or []) def check_for_revisions(course): prior, revisions = load_previous(make_course_path(course['clbid'])) if not prior: return None diff = get_old_dict_values(prior, course) ordered_diff = OrderedDict() for key in sorted(diff.keys()): ordered_diff[key] = diff[key] if ordered_diff: revisions.append(ordered_diff) log('revision in %d:' % (course['clbid']), ordered_diff) if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))): return revisions return None ## Instruction: Add '_updated' property to revisions ## Code After: from collections import OrderedDict from tzlocal import get_localzone import json from .load_data_from_file import load_data_from_file from .get_old_dict_values import get_old_dict_values from .log import log from .paths import make_course_path def load_previous(course_path): try: prior_data = load_data_from_file(course_path) prior = json.loads(prior_data) except FileNotFoundError: prior = None revisions = [] # print(course_path, revisions) if prior and ('revisions' in prior): revisions = prior['revisions'] del prior['revisions'] return (prior, revisions or []) def check_for_revisions(course): prior, revisions = load_previous(make_course_path(course['clbid'])) if not prior: return None diff = get_old_dict_values(prior, course) ordered_diff = OrderedDict() for key in sorted(diff.keys()): ordered_diff[key] = diff[key] if ordered_diff: ordered_diff['_updated'] = get_localzone().localize(datetime.now()).isoformat() revisions.append(ordered_diff) log('revision in %d:' % (course['clbid']), ordered_diff) if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))): return revisions return None
from collections import OrderedDict + from tzlocal import get_localzone import json from .load_data_from_file import load_data_from_file from .get_old_dict_values import get_old_dict_values from .log import log from .paths import make_course_path def load_previous(course_path): try: prior_data = load_data_from_file(course_path) prior = json.loads(prior_data) except FileNotFoundError: prior = None revisions = [] # print(course_path, revisions) if prior and ('revisions' in prior): revisions = prior['revisions'] del prior['revisions'] return (prior, revisions or []) def check_for_revisions(course): prior, revisions = load_previous(make_course_path(course['clbid'])) if not prior: return None diff = get_old_dict_values(prior, course) ordered_diff = OrderedDict() for key in sorted(diff.keys()): ordered_diff[key] = diff[key] if ordered_diff: + ordered_diff['_updated'] = get_localzone().localize(datetime.now()).isoformat() revisions.append(ordered_diff) log('revision in %d:' % (course['clbid']), ordered_diff) if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))): return revisions return None
a68f7ea6a9335a54762bfecf7b8f0a186bab8ed8
detectron2/projects/__init__.py
detectron2/projects/__init__.py
import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder())
import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder())
Resolve path in case it involves a symlink
Resolve path in case it involves a symlink Reviewed By: ppwwyyxx Differential Revision: D27823003 fbshipit-source-id: 67e6905f3c5c7bb1f593ee004160b195925f6d39
Python
apache-2.0
facebookresearch/detectron2,facebookresearch/detectron2,facebookresearch/detectron2
import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } - _PROJECT_ROOT = Path(__file__).parent.parent.parent / "projects" + _PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder())
Resolve path in case it involves a symlink
## Code Before: import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder()) ## Instruction: Resolve path in case it involves a symlink ## Code After: import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder())
import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } - _PROJECT_ROOT = Path(__file__).parent.parent.parent / "projects" + _PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "projects" ? ++++++++++ if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder())
a4efdb71c2c067af52d871711632eba0c06dc811
django_extensions/jobs/daily/daily_cleanup.py
django_extensions/jobs/daily/daily_cleanup.py
from django_extensions.management.jobs import DailyJob class Job(DailyJob): help = "Django Daily Cleanup Job" def execute(self): from django.core import management try: management.call_command('clearsessions') except management.CommandError: management.call_command("cleanup") # Django <1.5
from django_extensions.management.jobs import DailyJob class Job(DailyJob): help = "Django Daily Cleanup Job" def execute(self): from django.core import management from django import VERSION if VERSION[:2] < (1, 5): management.call_command("cleanup") else: management.call_command("clearsessions")
Use Django's VERSION to determine which cleanup command to call
Use Django's VERSION to determine which cleanup command to call
Python
mit
marctc/django-extensions,jpadilla/django-extensions,frewsxcv/django-extensions,gvangool/django-extensions,nikolas/django-extensions,haakenlid/django-extensions,ctrl-alt-d/django-extensions,django-extensions/django-extensions,helenst/django-extensions,helenst/django-extensions,github-account-because-they-want-it/django-extensions,levic/django-extensions,atchariya/django-extensions,artscoop/django-extensions,haakenlid/django-extensions,joeyespo/django-extensions,lamby/django-extensions,django-extensions/django-extensions,maroux/django-extensions,JoseTomasTocino/django-extensions,mandx/django-extensions,bionikspoon/django-extensions,bionikspoon/django-extensions,ewjoachim/django-extensions,nikolas/django-extensions,mandx/django-extensions,helenst/django-extensions,levic/django-extensions,barseghyanartur/django-extensions,barseghyanartur/django-extensions,barseghyanartur/django-extensions,rodo/django-extensions,dpetzold/django-extensions,maroux/django-extensions,joeyespo/django-extensions,gvangool/django-extensions,frewsxcv/django-extensions,github-account-because-they-want-it/django-extensions,marctc/django-extensions,marctc/django-extensions,jpadilla/django-extensions,linuxmaniac/django-extensions,ctrl-alt-d/django-extensions,t1m0thy/django-extensions,bionikspoon/django-extensions,zefciu/django-extensions,VishvajitP/django-extensions,t1m0thy/django-extensions,nikolas/django-extensions,haakenlid/django-extensions,VishvajitP/django-extensions,django-extensions/django-extensions,ewjoachim/django-extensions,jpadilla/django-extensions,ctrl-alt-d/django-extensions,lamby/django-extensions,kevgathuku/django-extensions,atchariya/django-extensions,JoseTomasTocino/django-extensions,linuxmaniac/django-extensions,dpetzold/django-extensions,dpetzold/django-extensions,VishvajitP/django-extensions,Moulde/django-extensions,artscoop/django-extensions,zefciu/django-extensions,kevgathuku/django-extensions,joeyespo/django-extensions,zefciu/django-extensions,mandx/django-extensions,lamby/django-extensions,ewjoachim/django-extensions,levic/django-extensions,t1m0thy/django-extensions,frewsxcv/django-extensions,Moulde/django-extensions,Moulde/django-extensions,kevgathuku/django-extensions,github-account-because-they-want-it/django-extensions,linuxmaniac/django-extensions,rodo/django-extensions,artscoop/django-extensions,JoseTomasTocino/django-extensions,atchariya/django-extensions,rodo/django-extensions,gvangool/django-extensions,maroux/django-extensions
from django_extensions.management.jobs import DailyJob class Job(DailyJob): help = "Django Daily Cleanup Job" def execute(self): from django.core import management + from django import VERSION - try: - management.call_command('clearsessions') - except management.CommandError: - management.call_command("cleanup") # Django <1.5 + if VERSION[:2] < (1, 5): + management.call_command("cleanup") + else: + management.call_command("clearsessions") +
Use Django's VERSION to determine which cleanup command to call
## Code Before: from django_extensions.management.jobs import DailyJob class Job(DailyJob): help = "Django Daily Cleanup Job" def execute(self): from django.core import management try: management.call_command('clearsessions') except management.CommandError: management.call_command("cleanup") # Django <1.5 ## Instruction: Use Django's VERSION to determine which cleanup command to call ## Code After: from django_extensions.management.jobs import DailyJob class Job(DailyJob): help = "Django Daily Cleanup Job" def execute(self): from django.core import management from django import VERSION if VERSION[:2] < (1, 5): management.call_command("cleanup") else: management.call_command("clearsessions")
from django_extensions.management.jobs import DailyJob class Job(DailyJob): help = "Django Daily Cleanup Job" def execute(self): from django.core import management - try: + from django import VERSION + + if VERSION[:2] < (1, 5): + management.call_command("cleanup") + else: - management.call_command('clearsessions') ? ^ ^ + management.call_command("clearsessions") ? ^ ^ - except management.CommandError: - management.call_command("cleanup") # Django <1.5
157c08a6ccd738d5bccfe8145c2a1f1e9d21ba82
madlib_web_client.py
madlib_web_client.py
import os from flask import Flask import psycopg2 from urllib.parse import urlparse url = urlparse(os.environ["DATABASE_URL"]) # Connect to a database conn = psycopg2.connect( database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port ) # Open a cursor to perform database operations cur = conn.cursor() # Create a table cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);") # Insert test data cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",(100, "abc'def")) # Query the database and obtain data as Python objects cur.execute("SELECT * FROM test;") print(cur.fetchone()) # Make the changes to the database persistent conn.commit() # Close the cursor and the connection to the database cur.close() conn.close() app = Flask(__name__) @app.route("/") def hello(): return "Hello world!" if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
import os from flask import Flask import psycopg2 from urllib.parse import urlparse url = urlparse(os.environ["DATABASE_URL"]) # Connect to a database conn = psycopg2.connect( database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port ) # Open a cursor to perform database operations cur = conn.cursor() # Drop table if it already exists cur.execute("DROP TABLE test;") # Create a table cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);") # Insert test data cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (100, "abc'def")) # Query the database and obtain data as Python objects cur.execute("SELECT * FROM test;") print(cur.fetchone()) # Make the changes to the database persistent conn.commit() # Close the cursor and the connection to the database cur.close() conn.close() app = Flask(__name__) @app.route("/") def hello(): return "Hello world!" if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
Add a drop table for testing.
Add a drop table for testing.
Python
isc
appletonmakerspace/madlib,mikeputnam/madlib
import os from flask import Flask import psycopg2 from urllib.parse import urlparse url = urlparse(os.environ["DATABASE_URL"]) # Connect to a database conn = psycopg2.connect( database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port ) # Open a cursor to perform database operations cur = conn.cursor() + # Drop table if it already exists + cur.execute("DROP TABLE test;") + # Create a table cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);") # Insert test data - cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",(100, "abc'def")) + cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (100, "abc'def")) # Query the database and obtain data as Python objects cur.execute("SELECT * FROM test;") print(cur.fetchone()) # Make the changes to the database persistent conn.commit() # Close the cursor and the connection to the database cur.close() conn.close() app = Flask(__name__) + @app.route("/") def hello(): return "Hello world!" if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
Add a drop table for testing.
## Code Before: import os from flask import Flask import psycopg2 from urllib.parse import urlparse url = urlparse(os.environ["DATABASE_URL"]) # Connect to a database conn = psycopg2.connect( database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port ) # Open a cursor to perform database operations cur = conn.cursor() # Create a table cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);") # Insert test data cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",(100, "abc'def")) # Query the database and obtain data as Python objects cur.execute("SELECT * FROM test;") print(cur.fetchone()) # Make the changes to the database persistent conn.commit() # Close the cursor and the connection to the database cur.close() conn.close() app = Flask(__name__) @app.route("/") def hello(): return "Hello world!" if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port) ## Instruction: Add a drop table for testing. ## Code After: import os from flask import Flask import psycopg2 from urllib.parse import urlparse url = urlparse(os.environ["DATABASE_URL"]) # Connect to a database conn = psycopg2.connect( database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port ) # Open a cursor to perform database operations cur = conn.cursor() # Drop table if it already exists cur.execute("DROP TABLE test;") # Create a table cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);") # Insert test data cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (100, "abc'def")) # Query the database and obtain data as Python objects cur.execute("SELECT * FROM test;") print(cur.fetchone()) # Make the changes to the database persistent conn.commit() # Close the cursor and the connection to the database cur.close() conn.close() app = Flask(__name__) @app.route("/") def hello(): return "Hello world!" if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
import os from flask import Flask import psycopg2 from urllib.parse import urlparse url = urlparse(os.environ["DATABASE_URL"]) # Connect to a database conn = psycopg2.connect( database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port ) # Open a cursor to perform database operations cur = conn.cursor() + # Drop table if it already exists + cur.execute("DROP TABLE test;") + # Create a table cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);") # Insert test data - cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",(100, "abc'def")) + cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (100, "abc'def")) ? + # Query the database and obtain data as Python objects cur.execute("SELECT * FROM test;") print(cur.fetchone()) # Make the changes to the database persistent conn.commit() # Close the cursor and the connection to the database cur.close() conn.close() app = Flask(__name__) + @app.route("/") def hello(): return "Hello world!" if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
46245254cdf9c3f2f6a9c27fe7e089867b4f394f
cloudbio/custom/versioncheck.py
cloudbio/custom/versioncheck.py
from distutils.version import LooseVersion from fabric.api import quiet from cloudbio.custom import shared def _parse_from_stdoutflag(out, flag): """Extract version information from a flag in verbose stdout. """ for line in out.split("\n") + out.stderr.split("\n"): if line.find(flag) >= 0: parts = [x for x in line.split() if not x.startswith(flag)] return parts[0] return "" def up_to_date(env, cmd, version, args=None, stdout_flag=None): """Check if the given command is up to date with the provided version. """ if shared._executable_not_on_path(cmd): return False if args: cmd = cmd + " " + " ".join(args) with quiet(): out = env.safe_run_output(cmd) if stdout_flag: iversion = _parse_from_stdoutflag(out, stdout_flag) else: iversion = out.strip() return LooseVersion(iversion) >= LooseVersion(version)
from distutils.version import LooseVersion from fabric.api import quiet from cloudbio.custom import shared def _parse_from_stdoutflag(out, flag): """Extract version information from a flag in verbose stdout. """ for line in out.split("\n") + out.stderr.split("\n"): if line.find(flag) >= 0: parts = [x for x in line.split() if not x.startswith(flag)] return parts[0] return "" def up_to_date(env, cmd, version, args=None, stdout_flag=None): """Check if the given command is up to date with the provided version. """ if shared._executable_not_on_path(cmd): return False if args: cmd = cmd + " " + " ".join(args) with quiet(): path_safe = "export PATH=$PATH:%s/bin && " out = env.safe_run_output(path_safe + cmd) if stdout_flag: iversion = _parse_from_stdoutflag(out, stdout_flag) else: iversion = out.strip() return LooseVersion(iversion) >= LooseVersion(version)
Include env.system_install PATH as part of version checking to work with installed software not on the global PATH. Thanks to James Cuff
Include env.system_install PATH as part of version checking to work with installed software not on the global PATH. Thanks to James Cuff
Python
mit
chapmanb/cloudbiolinux,elkingtonmcb/cloudbiolinux,kdaily/cloudbiolinux,elkingtonmcb/cloudbiolinux,kdaily/cloudbiolinux,averagehat/cloudbiolinux,kdaily/cloudbiolinux,chapmanb/cloudbiolinux,joemphilips/cloudbiolinux,AICIDNN/cloudbiolinux,joemphilips/cloudbiolinux,pjotrp/cloudbiolinux,pjotrp/cloudbiolinux,elkingtonmcb/cloudbiolinux,lpantano/cloudbiolinux,joemphilips/cloudbiolinux,kdaily/cloudbiolinux,heuermh/cloudbiolinux,rchekaluk/cloudbiolinux,heuermh/cloudbiolinux,averagehat/cloudbiolinux,AICIDNN/cloudbiolinux,pjotrp/cloudbiolinux,heuermh/cloudbiolinux,rchekaluk/cloudbiolinux,AICIDNN/cloudbiolinux,rchekaluk/cloudbiolinux,rchekaluk/cloudbiolinux,chapmanb/cloudbiolinux,averagehat/cloudbiolinux,chapmanb/cloudbiolinux,joemphilips/cloudbiolinux,pjotrp/cloudbiolinux,elkingtonmcb/cloudbiolinux,averagehat/cloudbiolinux,AICIDNN/cloudbiolinux,lpantano/cloudbiolinux,heuermh/cloudbiolinux,lpantano/cloudbiolinux
from distutils.version import LooseVersion from fabric.api import quiet from cloudbio.custom import shared def _parse_from_stdoutflag(out, flag): """Extract version information from a flag in verbose stdout. """ for line in out.split("\n") + out.stderr.split("\n"): if line.find(flag) >= 0: parts = [x for x in line.split() if not x.startswith(flag)] return parts[0] return "" def up_to_date(env, cmd, version, args=None, stdout_flag=None): """Check if the given command is up to date with the provided version. """ if shared._executable_not_on_path(cmd): return False if args: cmd = cmd + " " + " ".join(args) with quiet(): + path_safe = "export PATH=$PATH:%s/bin && " - out = env.safe_run_output(cmd) + out = env.safe_run_output(path_safe + cmd) if stdout_flag: iversion = _parse_from_stdoutflag(out, stdout_flag) else: iversion = out.strip() return LooseVersion(iversion) >= LooseVersion(version)
Include env.system_install PATH as part of version checking to work with installed software not on the global PATH. Thanks to James Cuff
## Code Before: from distutils.version import LooseVersion from fabric.api import quiet from cloudbio.custom import shared def _parse_from_stdoutflag(out, flag): """Extract version information from a flag in verbose stdout. """ for line in out.split("\n") + out.stderr.split("\n"): if line.find(flag) >= 0: parts = [x for x in line.split() if not x.startswith(flag)] return parts[0] return "" def up_to_date(env, cmd, version, args=None, stdout_flag=None): """Check if the given command is up to date with the provided version. """ if shared._executable_not_on_path(cmd): return False if args: cmd = cmd + " " + " ".join(args) with quiet(): out = env.safe_run_output(cmd) if stdout_flag: iversion = _parse_from_stdoutflag(out, stdout_flag) else: iversion = out.strip() return LooseVersion(iversion) >= LooseVersion(version) ## Instruction: Include env.system_install PATH as part of version checking to work with installed software not on the global PATH. Thanks to James Cuff ## Code After: from distutils.version import LooseVersion from fabric.api import quiet from cloudbio.custom import shared def _parse_from_stdoutflag(out, flag): """Extract version information from a flag in verbose stdout. """ for line in out.split("\n") + out.stderr.split("\n"): if line.find(flag) >= 0: parts = [x for x in line.split() if not x.startswith(flag)] return parts[0] return "" def up_to_date(env, cmd, version, args=None, stdout_flag=None): """Check if the given command is up to date with the provided version. """ if shared._executable_not_on_path(cmd): return False if args: cmd = cmd + " " + " ".join(args) with quiet(): path_safe = "export PATH=$PATH:%s/bin && " out = env.safe_run_output(path_safe + cmd) if stdout_flag: iversion = _parse_from_stdoutflag(out, stdout_flag) else: iversion = out.strip() return LooseVersion(iversion) >= LooseVersion(version)
from distutils.version import LooseVersion from fabric.api import quiet from cloudbio.custom import shared def _parse_from_stdoutflag(out, flag): """Extract version information from a flag in verbose stdout. """ for line in out.split("\n") + out.stderr.split("\n"): if line.find(flag) >= 0: parts = [x for x in line.split() if not x.startswith(flag)] return parts[0] return "" def up_to_date(env, cmd, version, args=None, stdout_flag=None): """Check if the given command is up to date with the provided version. """ if shared._executable_not_on_path(cmd): return False if args: cmd = cmd + " " + " ".join(args) with quiet(): + path_safe = "export PATH=$PATH:%s/bin && " - out = env.safe_run_output(cmd) + out = env.safe_run_output(path_safe + cmd) ? ++++++++++++ if stdout_flag: iversion = _parse_from_stdoutflag(out, stdout_flag) else: iversion = out.strip() return LooseVersion(iversion) >= LooseVersion(version)
4ab14b3de299b58aee94511910d199cd1d1737a5
zou/app/utils/emails.py
zou/app/utils/emails.py
from flask_mail import Message from zou.app import mail def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body message = Message( body=body, html=html, subject=subject, recipients=[recipient_email] ) mail.send(message)
from flask_mail import Message from zou.app import mail, app def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body with app.app_context(): message = Message( body=body, html=html, subject=subject, recipients=[recipient_email] ) mail.send(message)
Fix email sending in production environment
Fix email sending in production environment
Python
agpl-3.0
cgwire/zou
from flask_mail import Message - from zou.app import mail + from zou.app import mail, app def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body + with app.app_context(): - message = Message( + message = Message( - body=body, + body=body, - html=html, + html=html, - subject=subject, + subject=subject, - recipients=[recipient_email] + recipients=[recipient_email] - ) + ) - mail.send(message) + mail.send(message)
Fix email sending in production environment
## Code Before: from flask_mail import Message from zou.app import mail def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body message = Message( body=body, html=html, subject=subject, recipients=[recipient_email] ) mail.send(message) ## Instruction: Fix email sending in production environment ## Code After: from flask_mail import Message from zou.app import mail, app def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body with app.app_context(): message = Message( body=body, html=html, subject=subject, recipients=[recipient_email] ) mail.send(message)
from flask_mail import Message - from zou.app import mail + from zou.app import mail, app ? +++++ def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body + with app.app_context(): - message = Message( + message = Message( ? ++++ - body=body, + body=body, ? ++++ - html=html, + html=html, ? ++++ - subject=subject, + subject=subject, ? ++++ - recipients=[recipient_email] + recipients=[recipient_email] ? ++++ - ) + ) - mail.send(message) + mail.send(message) ? ++++
9a81d58bfb1088c8c6286c65150cd13c54c0b4c5
wagtail/wagtailredirects/middleware.py
wagtail/wagtailredirects/middleware.py
from django import http from wagtail.wagtailredirects import models # Originally pinched from: https://github.com/django/django/blob/master/django/contrib/redirects/middleware.py class RedirectMiddleware(object): def process_response(self, request, response): # No need to check for a redirect for non-404 responses. if response.status_code != 404: return response # Get the path path = models.Redirect.normalise_path(request.get_full_path()) # Find redirect try: redirect = models.Redirect.get_for_site(request.site).get(old_path=path) if redirect.is_permanent: return http.HttpResponsePermanentRedirect(redirect.link) else: return http.HttpResponseRedirect(redirect.link) except: pass return response
from django import http from wagtail.wagtailredirects import models # Originally pinched from: https://github.com/django/django/blob/master/django/contrib/redirects/middleware.py class RedirectMiddleware(object): def process_response(self, request, response): # No need to check for a redirect for non-404 responses. if response.status_code != 404: return response # Get the path path = models.Redirect.normalise_path(request.get_full_path()) # Find redirect try: redirect = models.Redirect.get_for_site(request.site).get(old_path=path) except models.Redirect.DoesNotExist: # No redirect found, return the 400 page return response if redirect.is_permanent: return http.HttpResponsePermanentRedirect(redirect.link) else: return http.HttpResponseRedirect(redirect.link)
Refactor out a bare except: statement
Refactor out a bare except: statement It now catches `Redirect.DoesNotExist`, returning the normal 404 page if no redirect is found. Any other exception should not be caught here.
Python
bsd-3-clause
rjsproxy/wagtail,jnns/wagtail,chrxr/wagtail,Klaudit/wagtail,iansprice/wagtail,kaedroho/wagtail,wagtail/wagtail,mixxorz/wagtail,kurtrwall/wagtail,kurtrwall/wagtail,FlipperPA/wagtail,chrxr/wagtail,mayapurmedia/wagtail,JoshBarr/wagtail,Klaudit/wagtail,torchbox/wagtail,nrsimha/wagtail,nimasmi/wagtail,iansprice/wagtail,hamsterbacke23/wagtail,FlipperPA/wagtail,Toshakins/wagtail,hanpama/wagtail,Toshakins/wagtail,takeflight/wagtail,takeshineshiro/wagtail,kurtrwall/wagtail,mikedingjan/wagtail,nutztherookie/wagtail,hamsterbacke23/wagtail,gogobook/wagtail,rjsproxy/wagtail,jnns/wagtail,kurtw/wagtail,gasman/wagtail,hanpama/wagtail,nealtodd/wagtail,torchbox/wagtail,Pennebaker/wagtail,hanpama/wagtail,kurtw/wagtail,Pennebaker/wagtail,inonit/wagtail,takeshineshiro/wagtail,takeflight/wagtail,kaedroho/wagtail,rjsproxy/wagtail,nilnvoid/wagtail,timorieber/wagtail,JoshBarr/wagtail,quru/wagtail,Pennebaker/wagtail,serzans/wagtail,nealtodd/wagtail,hamsterbacke23/wagtail,thenewguy/wagtail,gasman/wagtail,davecranwell/wagtail,thenewguy/wagtail,davecranwell/wagtail,tangentlabs/wagtail,nutztherookie/wagtail,mikedingjan/wagtail,Tivix/wagtail,tangentlabs/wagtail,nrsimha/wagtail,rsalmaso/wagtail,takeflight/wagtail,takeflight/wagtail,nealtodd/wagtail,timorieber/wagtail,kurtw/wagtail,zerolab/wagtail,JoshBarr/wagtail,FlipperPA/wagtail,nrsimha/wagtail,nilnvoid/wagtail,nutztherookie/wagtail,gogobook/wagtail,mayapurmedia/wagtail,Klaudit/wagtail,thenewguy/wagtail,wagtail/wagtail,nimasmi/wagtail,chrxr/wagtail,rsalmaso/wagtail,rjsproxy/wagtail,davecranwell/wagtail,Toshakins/wagtail,takeshineshiro/wagtail,quru/wagtail,kurtrwall/wagtail,nimasmi/wagtail,JoshBarr/wagtail,serzans/wagtail,thenewguy/wagtail,iansprice/wagtail,nutztherookie/wagtail,hanpama/wagtail,gogobook/wagtail,tangentlabs/wagtail,kaedroho/wagtail,Pennebaker/wagtail,jnns/wagtail,mikedingjan/wagtail,Klaudit/wagtail,iansprice/wagtail,kurtw/wagtail,timorieber/wagtail,nealtodd/wagtail,inonit/wagtail,Tivix/wagtail,nilnvoid/wagtail,Tivix/wagtail,quru/wagtail,rsalmaso/wagtail,wagtail/wagtail,gasman/wagtail,jnns/wagtail,FlipperPA/wagtail,davecranwell/wagtail,takeshineshiro/wagtail,zerolab/wagtail,quru/wagtail,inonit/wagtail,wagtail/wagtail,hamsterbacke23/wagtail,mikedingjan/wagtail,gasman/wagtail,kaedroho/wagtail,rsalmaso/wagtail,gasman/wagtail,nrsimha/wagtail,serzans/wagtail,nimasmi/wagtail,inonit/wagtail,rsalmaso/wagtail,wagtail/wagtail,mixxorz/wagtail,timorieber/wagtail,Tivix/wagtail,serzans/wagtail,mayapurmedia/wagtail,kaedroho/wagtail,tangentlabs/wagtail,torchbox/wagtail,zerolab/wagtail,mixxorz/wagtail,thenewguy/wagtail,zerolab/wagtail,Toshakins/wagtail,chrxr/wagtail,torchbox/wagtail,mixxorz/wagtail,gogobook/wagtail,zerolab/wagtail,mixxorz/wagtail,mayapurmedia/wagtail,nilnvoid/wagtail
from django import http from wagtail.wagtailredirects import models # Originally pinched from: https://github.com/django/django/blob/master/django/contrib/redirects/middleware.py class RedirectMiddleware(object): def process_response(self, request, response): # No need to check for a redirect for non-404 responses. if response.status_code != 404: return response # Get the path path = models.Redirect.normalise_path(request.get_full_path()) # Find redirect try: redirect = models.Redirect.get_for_site(request.site).get(old_path=path) + except models.Redirect.DoesNotExist: + # No redirect found, return the 400 page + return response - if redirect.is_permanent: + if redirect.is_permanent: - return http.HttpResponsePermanentRedirect(redirect.link) + return http.HttpResponsePermanentRedirect(redirect.link) - else: + else: - return http.HttpResponseRedirect(redirect.link) + return http.HttpResponseRedirect(redirect.link) - except: - pass - return response -
Refactor out a bare except: statement
## Code Before: from django import http from wagtail.wagtailredirects import models # Originally pinched from: https://github.com/django/django/blob/master/django/contrib/redirects/middleware.py class RedirectMiddleware(object): def process_response(self, request, response): # No need to check for a redirect for non-404 responses. if response.status_code != 404: return response # Get the path path = models.Redirect.normalise_path(request.get_full_path()) # Find redirect try: redirect = models.Redirect.get_for_site(request.site).get(old_path=path) if redirect.is_permanent: return http.HttpResponsePermanentRedirect(redirect.link) else: return http.HttpResponseRedirect(redirect.link) except: pass return response ## Instruction: Refactor out a bare except: statement ## Code After: from django import http from wagtail.wagtailredirects import models # Originally pinched from: https://github.com/django/django/blob/master/django/contrib/redirects/middleware.py class RedirectMiddleware(object): def process_response(self, request, response): # No need to check for a redirect for non-404 responses. if response.status_code != 404: return response # Get the path path = models.Redirect.normalise_path(request.get_full_path()) # Find redirect try: redirect = models.Redirect.get_for_site(request.site).get(old_path=path) except models.Redirect.DoesNotExist: # No redirect found, return the 400 page return response if redirect.is_permanent: return http.HttpResponsePermanentRedirect(redirect.link) else: return http.HttpResponseRedirect(redirect.link)
from django import http from wagtail.wagtailredirects import models # Originally pinched from: https://github.com/django/django/blob/master/django/contrib/redirects/middleware.py class RedirectMiddleware(object): def process_response(self, request, response): # No need to check for a redirect for non-404 responses. if response.status_code != 404: return response # Get the path path = models.Redirect.normalise_path(request.get_full_path()) # Find redirect try: redirect = models.Redirect.get_for_site(request.site).get(old_path=path) + except models.Redirect.DoesNotExist: + # No redirect found, return the 400 page + return response - if redirect.is_permanent: ? ---- + if redirect.is_permanent: - return http.HttpResponsePermanentRedirect(redirect.link) ? ---- + return http.HttpResponsePermanentRedirect(redirect.link) - else: ? ---- + else: - return http.HttpResponseRedirect(redirect.link) ? ---- + return http.HttpResponseRedirect(redirect.link) - except: - pass - - return response
4291d80377e970e02fb95afa6f9f85246cb9c498
DjangoLibrary/tests/factories.py
DjangoLibrary/tests/factories.py
import datetime from django.template.defaultfilters import slugify from factory import DjangoModelFactory, lazy_attribute from random import randint from .models import Author from .models import Book class UserFactory(DjangoModelFactory): class Meta: model = 'auth.User' django_get_or_create = ('username',) first_name = 'John' last_name = 'Doe' username = lazy_attribute( lambda o: slugify(o.first_name + '.' + o.last_name) ) email = lazy_attribute(lambda o: o.username + "@example.com") @lazy_attribute def date_joined(self): return datetime.datetime.now() - datetime.timedelta( days=randint(5, 50) ) last_login = lazy_attribute( lambda o: o.date_joined + datetime.timedelta(days=4) ) class AuthorFactory(DjangoModelFactory): class Meta: model = Author django_get_or_create = ('name',) name = 'Noam Chomsky' class BookFactory(DjangoModelFactory): class Meta: model = Book django_get_or_create = ('title',) title = 'Colorless Green Ideas Sleep Furiously'
import datetime from django.template.defaultfilters import slugify from factory import DjangoModelFactory, lazy_attribute from random import randint class UserFactory(DjangoModelFactory): class Meta: model = 'auth.User' django_get_or_create = ('username',) first_name = 'John' last_name = 'Doe' username = lazy_attribute( lambda o: slugify(o.first_name + '.' + o.last_name) ) email = lazy_attribute(lambda o: o.username + "@example.com") @lazy_attribute def date_joined(self): return datetime.datetime.now() - datetime.timedelta( days=randint(5, 50) ) last_login = lazy_attribute( lambda o: o.date_joined + datetime.timedelta(days=4) )
Revert "Add AuthorFactory and BookFactory."
Revert "Add AuthorFactory and BookFactory." This reverts commit 8cde42f87a82206cf63b3a5e4b0ec6c38d66d3a7.
Python
apache-2.0
kitconcept/robotframework-djangolibrary
import datetime from django.template.defaultfilters import slugify from factory import DjangoModelFactory, lazy_attribute from random import randint - from .models import Author - from .models import Book class UserFactory(DjangoModelFactory): class Meta: model = 'auth.User' django_get_or_create = ('username',) first_name = 'John' last_name = 'Doe' username = lazy_attribute( lambda o: slugify(o.first_name + '.' + o.last_name) ) email = lazy_attribute(lambda o: o.username + "@example.com") @lazy_attribute def date_joined(self): return datetime.datetime.now() - datetime.timedelta( days=randint(5, 50) ) last_login = lazy_attribute( lambda o: o.date_joined + datetime.timedelta(days=4) ) - - class AuthorFactory(DjangoModelFactory): - class Meta: - model = Author - django_get_or_create = ('name',) - - name = 'Noam Chomsky' - - - class BookFactory(DjangoModelFactory): - class Meta: - model = Book - django_get_or_create = ('title',) - - title = 'Colorless Green Ideas Sleep Furiously' -
Revert "Add AuthorFactory and BookFactory."
## Code Before: import datetime from django.template.defaultfilters import slugify from factory import DjangoModelFactory, lazy_attribute from random import randint from .models import Author from .models import Book class UserFactory(DjangoModelFactory): class Meta: model = 'auth.User' django_get_or_create = ('username',) first_name = 'John' last_name = 'Doe' username = lazy_attribute( lambda o: slugify(o.first_name + '.' + o.last_name) ) email = lazy_attribute(lambda o: o.username + "@example.com") @lazy_attribute def date_joined(self): return datetime.datetime.now() - datetime.timedelta( days=randint(5, 50) ) last_login = lazy_attribute( lambda o: o.date_joined + datetime.timedelta(days=4) ) class AuthorFactory(DjangoModelFactory): class Meta: model = Author django_get_or_create = ('name',) name = 'Noam Chomsky' class BookFactory(DjangoModelFactory): class Meta: model = Book django_get_or_create = ('title',) title = 'Colorless Green Ideas Sleep Furiously' ## Instruction: Revert "Add AuthorFactory and BookFactory." ## Code After: import datetime from django.template.defaultfilters import slugify from factory import DjangoModelFactory, lazy_attribute from random import randint class UserFactory(DjangoModelFactory): class Meta: model = 'auth.User' django_get_or_create = ('username',) first_name = 'John' last_name = 'Doe' username = lazy_attribute( lambda o: slugify(o.first_name + '.' + o.last_name) ) email = lazy_attribute(lambda o: o.username + "@example.com") @lazy_attribute def date_joined(self): return datetime.datetime.now() - datetime.timedelta( days=randint(5, 50) ) last_login = lazy_attribute( lambda o: o.date_joined + datetime.timedelta(days=4) )
import datetime from django.template.defaultfilters import slugify from factory import DjangoModelFactory, lazy_attribute from random import randint - from .models import Author - from .models import Book class UserFactory(DjangoModelFactory): class Meta: model = 'auth.User' django_get_or_create = ('username',) first_name = 'John' last_name = 'Doe' username = lazy_attribute( lambda o: slugify(o.first_name + '.' + o.last_name) ) email = lazy_attribute(lambda o: o.username + "@example.com") @lazy_attribute def date_joined(self): return datetime.datetime.now() - datetime.timedelta( days=randint(5, 50) ) last_login = lazy_attribute( lambda o: o.date_joined + datetime.timedelta(days=4) ) - - - class AuthorFactory(DjangoModelFactory): - class Meta: - model = Author - django_get_or_create = ('name',) - - name = 'Noam Chomsky' - - - class BookFactory(DjangoModelFactory): - class Meta: - model = Book - django_get_or_create = ('title',) - - title = 'Colorless Green Ideas Sleep Furiously'
018d062f2ed9ca9acd3d555d439dd81b89c88a6f
parse_push/managers.py
parse_push/managers.py
from django.db import models class DeviceManager(models.Manager): def latest(self): """ Returns latest Device instance """ return self.latest('created_at')
from django.db import models class DeviceManager(models.Manager): def get_latest(self): """ Returns latest Device instance """ return self.get_queryset().latest('created_at')
Use .get_latest() instead so that we do not override built-in .latest()
Use .get_latest() instead so that we do not override built-in .latest()
Python
bsd-3-clause
willandskill/django-parse-push
from django.db import models class DeviceManager(models.Manager): - def latest(self): + def get_latest(self): """ Returns latest Device instance """ - return self.latest('created_at') + return self.get_queryset().latest('created_at')
Use .get_latest() instead so that we do not override built-in .latest()
## Code Before: from django.db import models class DeviceManager(models.Manager): def latest(self): """ Returns latest Device instance """ return self.latest('created_at') ## Instruction: Use .get_latest() instead so that we do not override built-in .latest() ## Code After: from django.db import models class DeviceManager(models.Manager): def get_latest(self): """ Returns latest Device instance """ return self.get_queryset().latest('created_at')
from django.db import models class DeviceManager(models.Manager): - def latest(self): + def get_latest(self): ? ++++ """ Returns latest Device instance """ - return self.latest('created_at') + return self.get_queryset().latest('created_at') ? +++++++++++++++
d14c0aeba5304ba66649c9d6a0a9d144a9ef1e43
api/teams/admin.py
api/teams/admin.py
from django.contrib import admin from .models import Team from nucleus.admin import TeamMemberInline class TeamAdmin(admin.ModelAdmin): inlines = (TeamMemberInline, ) raw_id_fields = ('captain', 'creator', ) list_display = ( 'name', 'get_player_count', 'get_player_list', 'created', 'updated', ) search_fields = ('name', ) def get_queryset(self, request): queryset = super().get_queryset(request) return queryset.prefetch_related('players') def get_player_count(self, obj): return obj.players.count() get_player_count.short_description = 'Num Players' def get_player_list(self, obj): return ', '.join([p.username for p in obj.players.all()]) get_player_list.short_description = 'Players' admin.site.register(Team, TeamAdmin)
from django.contrib import admin from django.db.models import Count from .models import Team from nucleus.admin import TeamMemberInline class TeamAdmin(admin.ModelAdmin): inlines = (TeamMemberInline, ) raw_id_fields = ('captain', 'creator', ) list_display = ( 'name', 'get_player_count', 'get_player_list', 'created', 'updated', ) search_fields = ('name', ) def get_queryset(self, request): queryset = super().get_queryset(request) return queryset.prefetch_related('players').annotate( player_count=Count('players') ) def get_player_count(self, obj): return obj.player_count get_player_count.short_description = 'Num Players' get_player_count.admin_order_field = 'player_count' def get_player_list(self, obj): return ', '.join([p.username for p in obj.players.all()]) get_player_list.short_description = 'Players' admin.site.register(Team, TeamAdmin)
Allow team num players column to be ordered
Allow team num players column to be ordered
Python
mit
prattl/wepickheroes,prattl/wepickheroes,prattl/wepickheroes,prattl/wepickheroes
from django.contrib import admin + from django.db.models import Count from .models import Team from nucleus.admin import TeamMemberInline class TeamAdmin(admin.ModelAdmin): inlines = (TeamMemberInline, ) raw_id_fields = ('captain', 'creator', ) list_display = ( 'name', 'get_player_count', 'get_player_list', 'created', 'updated', ) search_fields = ('name', ) def get_queryset(self, request): queryset = super().get_queryset(request) - return queryset.prefetch_related('players') + return queryset.prefetch_related('players').annotate( + player_count=Count('players') + ) def get_player_count(self, obj): - return obj.players.count() + return obj.player_count get_player_count.short_description = 'Num Players' + get_player_count.admin_order_field = 'player_count' def get_player_list(self, obj): return ', '.join([p.username for p in obj.players.all()]) get_player_list.short_description = 'Players' admin.site.register(Team, TeamAdmin)
Allow team num players column to be ordered
## Code Before: from django.contrib import admin from .models import Team from nucleus.admin import TeamMemberInline class TeamAdmin(admin.ModelAdmin): inlines = (TeamMemberInline, ) raw_id_fields = ('captain', 'creator', ) list_display = ( 'name', 'get_player_count', 'get_player_list', 'created', 'updated', ) search_fields = ('name', ) def get_queryset(self, request): queryset = super().get_queryset(request) return queryset.prefetch_related('players') def get_player_count(self, obj): return obj.players.count() get_player_count.short_description = 'Num Players' def get_player_list(self, obj): return ', '.join([p.username for p in obj.players.all()]) get_player_list.short_description = 'Players' admin.site.register(Team, TeamAdmin) ## Instruction: Allow team num players column to be ordered ## Code After: from django.contrib import admin from django.db.models import Count from .models import Team from nucleus.admin import TeamMemberInline class TeamAdmin(admin.ModelAdmin): inlines = (TeamMemberInline, ) raw_id_fields = ('captain', 'creator', ) list_display = ( 'name', 'get_player_count', 'get_player_list', 'created', 'updated', ) search_fields = ('name', ) def get_queryset(self, request): queryset = super().get_queryset(request) return queryset.prefetch_related('players').annotate( player_count=Count('players') ) def get_player_count(self, obj): return obj.player_count get_player_count.short_description = 'Num Players' get_player_count.admin_order_field = 'player_count' def get_player_list(self, obj): return ', '.join([p.username for p in obj.players.all()]) get_player_list.short_description = 'Players' admin.site.register(Team, TeamAdmin)
from django.contrib import admin + from django.db.models import Count from .models import Team from nucleus.admin import TeamMemberInline class TeamAdmin(admin.ModelAdmin): inlines = (TeamMemberInline, ) raw_id_fields = ('captain', 'creator', ) list_display = ( 'name', 'get_player_count', 'get_player_list', 'created', 'updated', ) search_fields = ('name', ) def get_queryset(self, request): queryset = super().get_queryset(request) - return queryset.prefetch_related('players') + return queryset.prefetch_related('players').annotate( ? ++++++++++ + player_count=Count('players') + ) def get_player_count(self, obj): - return obj.players.count() ? ^^ -- + return obj.player_count ? ^ get_player_count.short_description = 'Num Players' + get_player_count.admin_order_field = 'player_count' def get_player_list(self, obj): return ', '.join([p.username for p in obj.players.all()]) get_player_list.short_description = 'Players' admin.site.register(Team, TeamAdmin)
8e3abcd310b7e932d769f05fa0a7135cc1a53b76
setup.py
setup.py
from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { "excludes": [ "numpy" ], "bin_includes": [ "libcrypto.so.1.0.0", "libssl.so.1.0.0" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "encodings", "idna", "motor", "packaging", "raven", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] setup(name='virtool', executables=executables, options=options)
from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { "bin_includes": [ "libcrypto.so.1.0.0", "libssl.so.1.0.0" ], "includes": [ "numpy", "numpy.core._methods", "numpy.lib", "numpy.lib.format" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "encodings", "idna", "motor", "packaging", "raven", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] setup(name='virtool', executables=executables, options=options)
Include missing numpy modules in build
Include missing numpy modules in build
Python
mit
igboyes/virtool,virtool/virtool,igboyes/virtool,virtool/virtool
from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { - "excludes": [ - "numpy" - ], "bin_includes": [ "libcrypto.so.1.0.0", "libssl.so.1.0.0" + ], + "includes": [ + "numpy", + "numpy.core._methods", + "numpy.lib", + "numpy.lib.format" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "encodings", "idna", "motor", "packaging", "raven", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] setup(name='virtool', executables=executables, options=options)
Include missing numpy modules in build
## Code Before: from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { "excludes": [ "numpy" ], "bin_includes": [ "libcrypto.so.1.0.0", "libssl.so.1.0.0" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "encodings", "idna", "motor", "packaging", "raven", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] setup(name='virtool', executables=executables, options=options) ## Instruction: Include missing numpy modules in build ## Code After: from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { "bin_includes": [ "libcrypto.so.1.0.0", "libssl.so.1.0.0" ], "includes": [ "numpy", "numpy.core._methods", "numpy.lib", "numpy.lib.format" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "encodings", "idna", "motor", "packaging", "raven", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] setup(name='virtool', executables=executables, options=options)
from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { - "excludes": [ - "numpy" - ], "bin_includes": [ "libcrypto.so.1.0.0", "libssl.so.1.0.0" + ], + "includes": [ + "numpy", + "numpy.core._methods", + "numpy.lib", + "numpy.lib.format" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "encodings", "idna", "motor", "packaging", "raven", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] setup(name='virtool', executables=executables, options=options)
0611f0ca617c3463a69e5bd627e821ae55c822ec
logintokens/tests/util.py
logintokens/tests/util.py
from time import time class MockTime: time_passed = 0.0 def time(self): return time() + self.time_passed def sleep(self, seconds): self.time_passed += seconds mock_time = MockTime()
from time import time class MockTime: """Provide mocked time and sleep methods to simulate the passage of time. """ time_passed = 0.0 def time(self): """Return current time with a consistent offset. """ return time() + self.time_passed def sleep(self, seconds): """Increase the offset to make it seem as though time has passed. """ self.time_passed += seconds mock_time = MockTime()
Add docstrings to mocked time methods
Add docstrings to mocked time methods
Python
mit
randomic/aniauth-tdd,randomic/aniauth-tdd
from time import time class MockTime: + """Provide mocked time and sleep methods to simulate the passage of time. + + """ time_passed = 0.0 def time(self): + """Return current time with a consistent offset. + + """ return time() + self.time_passed def sleep(self, seconds): + """Increase the offset to make it seem as though time has passed. + + """ self.time_passed += seconds mock_time = MockTime()
Add docstrings to mocked time methods
## Code Before: from time import time class MockTime: time_passed = 0.0 def time(self): return time() + self.time_passed def sleep(self, seconds): self.time_passed += seconds mock_time = MockTime() ## Instruction: Add docstrings to mocked time methods ## Code After: from time import time class MockTime: """Provide mocked time and sleep methods to simulate the passage of time. """ time_passed = 0.0 def time(self): """Return current time with a consistent offset. """ return time() + self.time_passed def sleep(self, seconds): """Increase the offset to make it seem as though time has passed. """ self.time_passed += seconds mock_time = MockTime()
from time import time class MockTime: + """Provide mocked time and sleep methods to simulate the passage of time. + + """ time_passed = 0.0 def time(self): + """Return current time with a consistent offset. + + """ return time() + self.time_passed def sleep(self, seconds): + """Increase the offset to make it seem as though time has passed. + + """ self.time_passed += seconds mock_time = MockTime()
222a87ef324f66baf8113020b41d336c459ab847
stdnum/fi/__init__.py
stdnum/fi/__init__.py
"""Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid
"""Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid from stdnum.fi import hetu as personalid
Add alias to hetu in for finnish personal id code
Add alias to hetu in for finnish personal id code
Python
lgpl-2.1
holvi/python-stdnum,holvi/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum,holvi/python-stdnum,arthurdejong/python-stdnum
"""Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid + from stdnum.fi import hetu as personalid
Add alias to hetu in for finnish personal id code
## Code Before: """Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid ## Instruction: Add alias to hetu in for finnish personal id code ## Code After: """Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid from stdnum.fi import hetu as personalid
"""Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid + from stdnum.fi import hetu as personalid
0470d1243ad2d7e7fd086c2b2f695dc431eaf2ea
pycroscopy/io/translators/df_utils/beps_gen_utils.py
pycroscopy/io/translators/df_utils/beps_gen_utils.py
import numpy as np def combine_in_out_field_loops(in_vec, out_vec): """ Parameters ---------- in_vec out_vec Returns ------- """ return np.vstack((in_vec, out_vec)) def build_loop_from_mat(loop_mat, num_steps): """ Parameters ---------- loop_mat num_steps Returns ------- """ return np.vstack((loop_mat[0, :int(num_steps / 4) + 1], loop_mat[1], loop_mat[0, int(num_steps / 4) + 1: int(num_steps / 2)])) def get_noise_vec(num_pts, noise_coeff): """ Parameters ---------- num_pts noise_coeff Returns ------- """ return np.ones(num_pts) * (1 + 0.5 * noise_coeff) - np.random.random(num_pts) * noise_coeff
import numpy as np import os beps_image_folder = os.path.abspath(os.path.join(os.path.realpath(__file__), '../beps_data_gen_images')) def combine_in_out_field_loops(in_vec, out_vec): """ Parameters ---------- in_vec out_vec Returns ------- """ return np.vstack((in_vec, out_vec)) def build_loop_from_mat(loop_mat, num_steps): """ Parameters ---------- loop_mat num_steps Returns ------- """ return np.vstack((loop_mat[0, :int(num_steps / 4) + 1], loop_mat[1], loop_mat[0, int(num_steps / 4) + 1: int(num_steps / 2)])) def get_noise_vec(num_pts, noise_coeff): """ Parameters ---------- num_pts noise_coeff Returns ------- """ return np.ones(num_pts) * (1 + 0.5 * noise_coeff) - np.random.random(num_pts) * noise_coeff
Define a path to the image folder for fake beps generator
Define a path to the image folder for fake beps generator Path is defined in beps_gen_utils Users can still provide their own images if they want.
Python
mit
anugrah-saxena/pycroscopy,pycroscopy/pycroscopy
import numpy as np + import os + + beps_image_folder = os.path.abspath(os.path.join(os.path.realpath(__file__), '../beps_data_gen_images')) def combine_in_out_field_loops(in_vec, out_vec): """ Parameters ---------- in_vec out_vec Returns ------- """ return np.vstack((in_vec, out_vec)) def build_loop_from_mat(loop_mat, num_steps): """ Parameters ---------- loop_mat num_steps Returns ------- """ return np.vstack((loop_mat[0, :int(num_steps / 4) + 1], loop_mat[1], loop_mat[0, int(num_steps / 4) + 1: int(num_steps / 2)])) def get_noise_vec(num_pts, noise_coeff): """ Parameters ---------- num_pts noise_coeff Returns ------- """ return np.ones(num_pts) * (1 + 0.5 * noise_coeff) - np.random.random(num_pts) * noise_coeff
Define a path to the image folder for fake beps generator
## Code Before: import numpy as np def combine_in_out_field_loops(in_vec, out_vec): """ Parameters ---------- in_vec out_vec Returns ------- """ return np.vstack((in_vec, out_vec)) def build_loop_from_mat(loop_mat, num_steps): """ Parameters ---------- loop_mat num_steps Returns ------- """ return np.vstack((loop_mat[0, :int(num_steps / 4) + 1], loop_mat[1], loop_mat[0, int(num_steps / 4) + 1: int(num_steps / 2)])) def get_noise_vec(num_pts, noise_coeff): """ Parameters ---------- num_pts noise_coeff Returns ------- """ return np.ones(num_pts) * (1 + 0.5 * noise_coeff) - np.random.random(num_pts) * noise_coeff ## Instruction: Define a path to the image folder for fake beps generator ## Code After: import numpy as np import os beps_image_folder = os.path.abspath(os.path.join(os.path.realpath(__file__), '../beps_data_gen_images')) def combine_in_out_field_loops(in_vec, out_vec): """ Parameters ---------- in_vec out_vec Returns ------- """ return np.vstack((in_vec, out_vec)) def build_loop_from_mat(loop_mat, num_steps): """ Parameters ---------- loop_mat num_steps Returns ------- """ return np.vstack((loop_mat[0, :int(num_steps / 4) + 1], loop_mat[1], loop_mat[0, int(num_steps / 4) + 1: int(num_steps / 2)])) def get_noise_vec(num_pts, noise_coeff): """ Parameters ---------- num_pts noise_coeff Returns ------- """ return np.ones(num_pts) * (1 + 0.5 * noise_coeff) - np.random.random(num_pts) * noise_coeff
import numpy as np + import os + + beps_image_folder = os.path.abspath(os.path.join(os.path.realpath(__file__), '../beps_data_gen_images')) def combine_in_out_field_loops(in_vec, out_vec): """ Parameters ---------- in_vec out_vec Returns ------- """ return np.vstack((in_vec, out_vec)) def build_loop_from_mat(loop_mat, num_steps): """ Parameters ---------- loop_mat num_steps Returns ------- """ return np.vstack((loop_mat[0, :int(num_steps / 4) + 1], loop_mat[1], loop_mat[0, int(num_steps / 4) + 1: int(num_steps / 2)])) def get_noise_vec(num_pts, noise_coeff): """ Parameters ---------- num_pts noise_coeff Returns ------- """ return np.ones(num_pts) * (1 + 0.5 * noise_coeff) - np.random.random(num_pts) * noise_coeff
f1e516e8002425f5f4f9904096848798b2bc97fa
jesusmtnez/python/kata/game.py
jesusmtnez/python/kata/game.py
class Game(): def __init__(self): self._rolls = [0] * 21 self._current_roll = 0 def roll(self, pins): self._rolls[self._current_roll] += pins self._current_roll += 1 def score(self): score = 0 for frame in range(0, 20, 2): if self._is_spare(frame): score += 10 + self._rolls[frame + 2] else: score += self._frame_score(frame) return score def _is_spare(self, frame): return self._rolls[frame] + self._rolls[frame + 1] == 10 def _frame_score(self, frame): return self._rolls[frame] + self._rolls[frame + 1]
class Game(): def __init__(self): self._rolls = [0] * 21 self._current_roll = 0 def roll(self, pins): self._rolls[self._current_roll] += pins self._current_roll += 1 if pins < 10 else 2 def score(self): score = 0 for frame in range(0, 20, 2): if self._is_strike(frame): score += 10 + self._rolls[frame + 2] + self._rolls[frame + 3] elif self._is_spare(frame): score += 10 + self._rolls[frame + 2] else: score += self._frame_score(frame) return score def _is_spare(self, frame): return self._rolls[frame] + self._rolls[frame + 1] == 10 def _is_strike(self, frame): print(frame) return self._rolls[frame] == 10 def _frame_score(self, frame): return self._rolls[frame] + self._rolls[frame + 1]
Add strikes support when rolling
[Python] Add strikes support when rolling
Python
mit
JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge
class Game(): def __init__(self): self._rolls = [0] * 21 self._current_roll = 0 def roll(self, pins): self._rolls[self._current_roll] += pins - self._current_roll += 1 + self._current_roll += 1 if pins < 10 else 2 def score(self): score = 0 for frame in range(0, 20, 2): + if self._is_strike(frame): + score += 10 + self._rolls[frame + 2] + self._rolls[frame + 3] - if self._is_spare(frame): + elif self._is_spare(frame): score += 10 + self._rolls[frame + 2] else: score += self._frame_score(frame) return score def _is_spare(self, frame): return self._rolls[frame] + self._rolls[frame + 1] == 10 + def _is_strike(self, frame): + print(frame) + return self._rolls[frame] == 10 + def _frame_score(self, frame): return self._rolls[frame] + self._rolls[frame + 1]
Add strikes support when rolling
## Code Before: class Game(): def __init__(self): self._rolls = [0] * 21 self._current_roll = 0 def roll(self, pins): self._rolls[self._current_roll] += pins self._current_roll += 1 def score(self): score = 0 for frame in range(0, 20, 2): if self._is_spare(frame): score += 10 + self._rolls[frame + 2] else: score += self._frame_score(frame) return score def _is_spare(self, frame): return self._rolls[frame] + self._rolls[frame + 1] == 10 def _frame_score(self, frame): return self._rolls[frame] + self._rolls[frame + 1] ## Instruction: Add strikes support when rolling ## Code After: class Game(): def __init__(self): self._rolls = [0] * 21 self._current_roll = 0 def roll(self, pins): self._rolls[self._current_roll] += pins self._current_roll += 1 if pins < 10 else 2 def score(self): score = 0 for frame in range(0, 20, 2): if self._is_strike(frame): score += 10 + self._rolls[frame + 2] + self._rolls[frame + 3] elif self._is_spare(frame): score += 10 + self._rolls[frame + 2] else: score += self._frame_score(frame) return score def _is_spare(self, frame): return self._rolls[frame] + self._rolls[frame + 1] == 10 def _is_strike(self, frame): print(frame) return self._rolls[frame] == 10 def _frame_score(self, frame): return self._rolls[frame] + self._rolls[frame + 1]
class Game(): def __init__(self): self._rolls = [0] * 21 self._current_roll = 0 def roll(self, pins): self._rolls[self._current_roll] += pins - self._current_roll += 1 + self._current_roll += 1 if pins < 10 else 2 ? ++++++++++++++++++++ def score(self): score = 0 for frame in range(0, 20, 2): + if self._is_strike(frame): + score += 10 + self._rolls[frame + 2] + self._rolls[frame + 3] - if self._is_spare(frame): + elif self._is_spare(frame): ? ++ score += 10 + self._rolls[frame + 2] else: score += self._frame_score(frame) return score def _is_spare(self, frame): return self._rolls[frame] + self._rolls[frame + 1] == 10 + def _is_strike(self, frame): + print(frame) + return self._rolls[frame] == 10 + def _frame_score(self, frame): return self._rolls[frame] + self._rolls[frame + 1]