commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
0
2.94k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
444
message
stringlengths
16
3.45k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43.2k
prompt
stringlengths
17
4.58k
response
stringlengths
1
4.43k
prompt_tagged
stringlengths
58
4.62k
response_tagged
stringlengths
1
4.43k
text
stringlengths
132
7.29k
text_tagged
stringlengths
173
7.33k
79770a0e0f31f1292f8b5ab103509e7835570f20
src/collectors/SmartCollector/SmartCollector.py
src/collectors/SmartCollector/SmartCollector.py
import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { 'path': 'smart', 'devices': '^disk[0-9]$|^sd[a-z]$|^hd[a-z]$' } def collect(self): """ Collect and publish S.M.A.R.T. attributes """ devices = re.compile(self.config['devices']) for device in os.listdir('/dev'): if devices.match(device): attributes = subprocess.Popen(["smartctl", "-A", os.path.join('/dev',device)], stdout=subprocess.PIPE).communicate()[0].strip().splitlines() for attr in attributes[7:]: self.publish("%s.%s" % (device, attr.split()[1]), attr.split()[9])
import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { 'path': 'smart', 'devices': '^disk[0-9]$|^sd[a-z]$|^hd[a-z]$' } def collect(self): """ Collect and publish S.M.A.R.T. attributes """ devices = re.compile(self.config['devices']) for device in os.listdir('/dev'): if devices.match(device): attributes = subprocess.Popen(["smartctl", "-A", os.path.join('/dev',device)], stdout=subprocess.PIPE).communicate()[0].strip().splitlines() for attr in attributes[7:]: attribute = attr.split() if attribute[1] != "Unknown_Attribute": self.publish("%s.%s" % (device, attribute[1]), attribute[9]) else: self.publish("%s.%s" % (device, attribute[0]), attribute[9])
Use ID instead of attribute if attribute name is 'Unknown_Attribute'.
Use ID instead of attribute if attribute name is 'Unknown_Attribute'.
Python
mit
zoidbergwill/Diamond,CYBERBUGJR/Diamond,TinLe/Diamond,tellapart/Diamond,Netuitive/Diamond,socialwareinc/Diamond,hvnsweeting/Diamond,joel-airspring/Diamond,joel-airspring/Diamond,hamelg/Diamond,signalfx/Diamond,stuartbfox/Diamond,disqus/Diamond,python-diamond/Diamond,rtoma/Diamond,mfriedenhagen/Diamond,socialwareinc/Diamond,EzyInsights/Diamond,gg7/diamond,CYBERBUGJR/Diamond,jriguera/Diamond,timchenxiaoyu/Diamond,jumping/Diamond,ramjothikumar/Diamond,anandbhoraskar/Diamond,sebbrandt87/Diamond,thardie/Diamond,eMerzh/Diamond-1,metamx/Diamond,eMerzh/Diamond-1,hamelg/Diamond,tuenti/Diamond,datafiniti/Diamond,janisz/Diamond-1,jumping/Diamond,janisz/Diamond-1,TinLe/Diamond,works-mobile/Diamond,skbkontur/Diamond,h00dy/Diamond,disqus/Diamond,timchenxiaoyu/Diamond,actmd/Diamond,mzupan/Diamond,Nihn/Diamond-1,signalfx/Diamond,eMerzh/Diamond-1,hvnsweeting/Diamond,russss/Diamond,Slach/Diamond,h00dy/Diamond,MediaMath/Diamond,szibis/Diamond,EzyInsights/Diamond,MediaMath/Diamond,mzupan/Diamond,krbaker/Diamond,eMerzh/Diamond-1,jriguera/Diamond,codepython/Diamond,sebbrandt87/Diamond,janisz/Diamond-1,h00dy/Diamond,anandbhoraskar/Diamond,dcsquared13/Diamond,zoidbergwill/Diamond,acquia/Diamond,codepython/Diamond,Basis/Diamond,mfriedenhagen/Diamond,signalfx/Diamond,saucelabs/Diamond,joel-airspring/Diamond,saucelabs/Diamond,TinLe/Diamond,stuartbfox/Diamond,works-mobile/Diamond,Clever/Diamond,MediaMath/Diamond,szibis/Diamond,Precis/Diamond,sebbrandt87/Diamond,cannium/Diamond,Netuitive/Diamond,timchenxiaoyu/Diamond,jriguera/Diamond,Ssawa/Diamond,h00dy/Diamond,szibis/Diamond,russss/Diamond,mfriedenhagen/Diamond,Netuitive/netuitive-diamond,jaingaurav/Diamond,janisz/Diamond-1,anandbhoraskar/Diamond,Netuitive/Diamond,thardie/Diamond,acquia/Diamond,bmhatfield/Diamond,datafiniti/Diamond,disqus/Diamond,signalfx/Diamond,stuartbfox/Diamond,hamelg/Diamond,tuenti/Diamond,python-diamond/Diamond,Basis/Diamond,cannium/Diamond,codepython/Diamond,TinLe/Diamond,jaingaurav/Diamond,bmhatfield/Diamond,tellapart/Diamond,Nihn/Diamond-1,works-mobile/Diamond,codepython/Diamond,skbkontur/Diamond,ramjothikumar/Diamond,Ssawa/Diamond,mzupan/Diamond,MediaMath/Diamond,bmhatfield/Diamond,Precis/Diamond,Ensighten/Diamond,TAKEALOT/Diamond,ramjothikumar/Diamond,ramjothikumar/Diamond,acquia/Diamond,dcsquared13/Diamond,krbaker/Diamond,Ormod/Diamond,Ensighten/Diamond,metamx/Diamond,Clever/Diamond,jriguera/Diamond,Ssawa/Diamond,Basis/Diamond,datafiniti/Diamond,Ensighten/Diamond,python-diamond/Diamond,cannium/Diamond,dcsquared13/Diamond,ceph/Diamond,jaingaurav/Diamond,socialwareinc/Diamond,Nihn/Diamond-1,Ormod/Diamond,tuenti/Diamond,anandbhoraskar/Diamond,Basis/Diamond,skbkontur/Diamond,socialwareinc/Diamond,acquia/Diamond,thardie/Diamond,Precis/Diamond,Clever/Diamond,rtoma/Diamond,ceph/Diamond,rtoma/Diamond,rtoma/Diamond,actmd/Diamond,russss/Diamond,tusharmakkar08/Diamond,actmd/Diamond,zoidbergwill/Diamond,hamelg/Diamond,Ssawa/Diamond,timchenxiaoyu/Diamond,ceph/Diamond,Precis/Diamond,tusharmakkar08/Diamond,Slach/Diamond,krbaker/Diamond,Slach/Diamond,Slach/Diamond,skbkontur/Diamond,datafiniti/Diamond,jaingaurav/Diamond,Clever/Diamond,gg7/diamond,sebbrandt87/Diamond,szibis/Diamond,Ormod/Diamond,tusharmakkar08/Diamond,zoidbergwill/Diamond,bmhatfield/Diamond,TAKEALOT/Diamond,hvnsweeting/Diamond,saucelabs/Diamond,gg7/diamond,Netuitive/Diamond,tuenti/Diamond,Netuitive/netuitive-diamond,tellapart/Diamond,dcsquared13/Diamond,krbaker/Diamond,mzupan/Diamond,MichaelDoyle/Diamond,Ormod/Diamond,joel-airspring/Diamond,tusharmakkar08/Diamond,russss/Diamond,TAKEALOT/Diamond,TAKEALOT/Diamond,CYBERBUGJR/Diamond,thardie/Diamond,MichaelDoyle/Diamond,works-mobile/Diamond,EzyInsights/Diamond,cannium/Diamond,Nihn/Diamond-1,tellapart/Diamond,Ensighten/Diamond,EzyInsights/Diamond,jumping/Diamond,stuartbfox/Diamond,Netuitive/netuitive-diamond,jumping/Diamond,hvnsweeting/Diamond,saucelabs/Diamond,mfriedenhagen/Diamond,MichaelDoyle/Diamond,MichaelDoyle/Diamond,CYBERBUGJR/Diamond,ceph/Diamond,Netuitive/netuitive-diamond,metamx/Diamond,actmd/Diamond,gg7/diamond
import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { 'path': 'smart', 'devices': '^disk[0-9]$|^sd[a-z]$|^hd[a-z]$' } def collect(self): """ Collect and publish S.M.A.R.T. attributes """ devices = re.compile(self.config['devices']) for device in os.listdir('/dev'): if devices.match(device): attributes = subprocess.Popen(["smartctl", "-A", os.path.join('/dev',device)], stdout=subprocess.PIPE).communicate()[0].strip().splitlines() for attr in attributes[7:]: self.publish("%s.%s" % (device, attr.split()[1]), attr.split()[9]) Use ID instead of attribute if attribute name is 'Unknown_Attribute'.
import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { 'path': 'smart', 'devices': '^disk[0-9]$|^sd[a-z]$|^hd[a-z]$' } def collect(self): """ Collect and publish S.M.A.R.T. attributes """ devices = re.compile(self.config['devices']) for device in os.listdir('/dev'): if devices.match(device): attributes = subprocess.Popen(["smartctl", "-A", os.path.join('/dev',device)], stdout=subprocess.PIPE).communicate()[0].strip().splitlines() for attr in attributes[7:]: attribute = attr.split() if attribute[1] != "Unknown_Attribute": self.publish("%s.%s" % (device, attribute[1]), attribute[9]) else: self.publish("%s.%s" % (device, attribute[0]), attribute[9])
<commit_before>import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { 'path': 'smart', 'devices': '^disk[0-9]$|^sd[a-z]$|^hd[a-z]$' } def collect(self): """ Collect and publish S.M.A.R.T. attributes """ devices = re.compile(self.config['devices']) for device in os.listdir('/dev'): if devices.match(device): attributes = subprocess.Popen(["smartctl", "-A", os.path.join('/dev',device)], stdout=subprocess.PIPE).communicate()[0].strip().splitlines() for attr in attributes[7:]: self.publish("%s.%s" % (device, attr.split()[1]), attr.split()[9]) <commit_msg>Use ID instead of attribute if attribute name is 'Unknown_Attribute'.<commit_after>
import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { 'path': 'smart', 'devices': '^disk[0-9]$|^sd[a-z]$|^hd[a-z]$' } def collect(self): """ Collect and publish S.M.A.R.T. attributes """ devices = re.compile(self.config['devices']) for device in os.listdir('/dev'): if devices.match(device): attributes = subprocess.Popen(["smartctl", "-A", os.path.join('/dev',device)], stdout=subprocess.PIPE).communicate()[0].strip().splitlines() for attr in attributes[7:]: attribute = attr.split() if attribute[1] != "Unknown_Attribute": self.publish("%s.%s" % (device, attribute[1]), attribute[9]) else: self.publish("%s.%s" % (device, attribute[0]), attribute[9])
import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { 'path': 'smart', 'devices': '^disk[0-9]$|^sd[a-z]$|^hd[a-z]$' } def collect(self): """ Collect and publish S.M.A.R.T. attributes """ devices = re.compile(self.config['devices']) for device in os.listdir('/dev'): if devices.match(device): attributes = subprocess.Popen(["smartctl", "-A", os.path.join('/dev',device)], stdout=subprocess.PIPE).communicate()[0].strip().splitlines() for attr in attributes[7:]: self.publish("%s.%s" % (device, attr.split()[1]), attr.split()[9]) Use ID instead of attribute if attribute name is 'Unknown_Attribute'.import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { 'path': 'smart', 'devices': '^disk[0-9]$|^sd[a-z]$|^hd[a-z]$' } def collect(self): """ Collect and publish S.M.A.R.T. attributes """ devices = re.compile(self.config['devices']) for device in os.listdir('/dev'): if devices.match(device): attributes = subprocess.Popen(["smartctl", "-A", os.path.join('/dev',device)], stdout=subprocess.PIPE).communicate()[0].strip().splitlines() for attr in attributes[7:]: attribute = attr.split() if attribute[1] != "Unknown_Attribute": self.publish("%s.%s" % (device, attribute[1]), attribute[9]) else: self.publish("%s.%s" % (device, attribute[0]), attribute[9])
<commit_before>import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { 'path': 'smart', 'devices': '^disk[0-9]$|^sd[a-z]$|^hd[a-z]$' } def collect(self): """ Collect and publish S.M.A.R.T. attributes """ devices = re.compile(self.config['devices']) for device in os.listdir('/dev'): if devices.match(device): attributes = subprocess.Popen(["smartctl", "-A", os.path.join('/dev',device)], stdout=subprocess.PIPE).communicate()[0].strip().splitlines() for attr in attributes[7:]: self.publish("%s.%s" % (device, attr.split()[1]), attr.split()[9]) <commit_msg>Use ID instead of attribute if attribute name is 'Unknown_Attribute'.<commit_after>import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { 'path': 'smart', 'devices': '^disk[0-9]$|^sd[a-z]$|^hd[a-z]$' } def collect(self): """ Collect and publish S.M.A.R.T. attributes """ devices = re.compile(self.config['devices']) for device in os.listdir('/dev'): if devices.match(device): attributes = subprocess.Popen(["smartctl", "-A", os.path.join('/dev',device)], stdout=subprocess.PIPE).communicate()[0].strip().splitlines() for attr in attributes[7:]: attribute = attr.split() if attribute[1] != "Unknown_Attribute": self.publish("%s.%s" % (device, attribute[1]), attribute[9]) else: self.publish("%s.%s" % (device, attribute[0]), attribute[9])
c642acd29a013c25fab420961109a0a1ebe3c195
open511/views.py
open511/views.py
from open511.models import RoadEvent from open511.utils.views import JSONView class RoadEventListView(JSONView): def get(self, request): return [ rdev.to_json_structure() for rdev in RoadEvent.objects.all() ] list_roadevents = RoadEventListView.as_view()
from open511.models import RoadEvent from open511.utils.views import JSONView class RoadEventListView(JSONView): allow_jsonp = True def get(self, request): return [ rdev.to_json_structure() for rdev in RoadEvent.objects.all() ] list_roadevents = RoadEventListView.as_view()
Allow JSONP requests to the roadevents API
Allow JSONP requests to the roadevents API
Python
mit
Open511/open511-server,Open511/open511-server,Open511/open511-server
from open511.models import RoadEvent from open511.utils.views import JSONView class RoadEventListView(JSONView): def get(self, request): return [ rdev.to_json_structure() for rdev in RoadEvent.objects.all() ] list_roadevents = RoadEventListView.as_view() Allow JSONP requests to the roadevents API
from open511.models import RoadEvent from open511.utils.views import JSONView class RoadEventListView(JSONView): allow_jsonp = True def get(self, request): return [ rdev.to_json_structure() for rdev in RoadEvent.objects.all() ] list_roadevents = RoadEventListView.as_view()
<commit_before>from open511.models import RoadEvent from open511.utils.views import JSONView class RoadEventListView(JSONView): def get(self, request): return [ rdev.to_json_structure() for rdev in RoadEvent.objects.all() ] list_roadevents = RoadEventListView.as_view() <commit_msg>Allow JSONP requests to the roadevents API<commit_after>
from open511.models import RoadEvent from open511.utils.views import JSONView class RoadEventListView(JSONView): allow_jsonp = True def get(self, request): return [ rdev.to_json_structure() for rdev in RoadEvent.objects.all() ] list_roadevents = RoadEventListView.as_view()
from open511.models import RoadEvent from open511.utils.views import JSONView class RoadEventListView(JSONView): def get(self, request): return [ rdev.to_json_structure() for rdev in RoadEvent.objects.all() ] list_roadevents = RoadEventListView.as_view() Allow JSONP requests to the roadevents APIfrom open511.models import RoadEvent from open511.utils.views import JSONView class RoadEventListView(JSONView): allow_jsonp = True def get(self, request): return [ rdev.to_json_structure() for rdev in RoadEvent.objects.all() ] list_roadevents = RoadEventListView.as_view()
<commit_before>from open511.models import RoadEvent from open511.utils.views import JSONView class RoadEventListView(JSONView): def get(self, request): return [ rdev.to_json_structure() for rdev in RoadEvent.objects.all() ] list_roadevents = RoadEventListView.as_view() <commit_msg>Allow JSONP requests to the roadevents API<commit_after>from open511.models import RoadEvent from open511.utils.views import JSONView class RoadEventListView(JSONView): allow_jsonp = True def get(self, request): return [ rdev.to_json_structure() for rdev in RoadEvent.objects.all() ] list_roadevents = RoadEventListView.as_view()
09c1941ecf6ab6bc61dff67ed0e33badee5048d4
ipy_user_conf.py
ipy_user_conf.py
# Case Conductor is a Test Case Management system. # Copyright (C) 2011 uTest Inc. # # This file is part of Case Conductor. # # Case Conductor is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Case Conductor is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Case Conductor. If not, see <http://www.gnu.org/licenses/>. """ Makes IPython import all of your projects models when shell is started. 1. Save as ipy_user_conf.py in project root 2. ./manage.py shell 3. profit """ import IPython.ipapi ip = IPython.ipapi.get() def main(): print "\nImported:\n\n" imports = [ "import datetime", "from cc.core.models import Product", "from cc.library.models import Suite, Case, CaseVersion, CaseStep", ] for imp in imports: ip.ex(imp) print imp print "\n" main()
# Case Conductor is a Test Case Management system. # Copyright (C) 2011 uTest Inc. # # This file is part of Case Conductor. # # Case Conductor is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Case Conductor is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Case Conductor. If not, see <http://www.gnu.org/licenses/>. """ Makes IPython import all of your projects models when shell is started. 1. Save as ipy_user_conf.py in project root 2. ./manage.py shell 3. profit """ import IPython.ipapi ip = IPython.ipapi.get() def main(): print "\nImported:\n\n" imports = [ "import datetime", "from django.contrib.auth.models import User", "from cc.core.models import Product", "from cc.library.models import Suite, Case, CaseVersion, CaseStep, CaseAttachment, SuiteCase", "from cc.execution.models import Cycle, Run, RunCaseVersion, RunSuite, Result, StepResult", "from cc.environments.models import Profile, Category, Element, Environment", "from cc.tags.models import Tag", ] for imp in imports: ip.ex(imp) print imp print "\n" main()
Add model auto-imports to IPython profile.
Add model auto-imports to IPython profile.
Python
bsd-2-clause
shinglyu/moztrap,mccarrmb/moztrap,mccarrmb/moztrap,bobsilverberg/moztrap,shinglyu/moztrap,mozilla/moztrap,mozilla/moztrap,bobsilverberg/moztrap,mccarrmb/moztrap,mozilla/moztrap,shinglyu/moztrap,mozilla/moztrap,shinglyu/moztrap,mccarrmb/moztrap,mozilla/moztrap,bobsilverberg/moztrap,mccarrmb/moztrap,shinglyu/moztrap,bobsilverberg/moztrap
# Case Conductor is a Test Case Management system. # Copyright (C) 2011 uTest Inc. # # This file is part of Case Conductor. # # Case Conductor is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Case Conductor is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Case Conductor. If not, see <http://www.gnu.org/licenses/>. """ Makes IPython import all of your projects models when shell is started. 1. Save as ipy_user_conf.py in project root 2. ./manage.py shell 3. profit """ import IPython.ipapi ip = IPython.ipapi.get() def main(): print "\nImported:\n\n" imports = [ "import datetime", "from cc.core.models import Product", "from cc.library.models import Suite, Case, CaseVersion, CaseStep", ] for imp in imports: ip.ex(imp) print imp print "\n" main() Add model auto-imports to IPython profile.
# Case Conductor is a Test Case Management system. # Copyright (C) 2011 uTest Inc. # # This file is part of Case Conductor. # # Case Conductor is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Case Conductor is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Case Conductor. If not, see <http://www.gnu.org/licenses/>. """ Makes IPython import all of your projects models when shell is started. 1. Save as ipy_user_conf.py in project root 2. ./manage.py shell 3. profit """ import IPython.ipapi ip = IPython.ipapi.get() def main(): print "\nImported:\n\n" imports = [ "import datetime", "from django.contrib.auth.models import User", "from cc.core.models import Product", "from cc.library.models import Suite, Case, CaseVersion, CaseStep, CaseAttachment, SuiteCase", "from cc.execution.models import Cycle, Run, RunCaseVersion, RunSuite, Result, StepResult", "from cc.environments.models import Profile, Category, Element, Environment", "from cc.tags.models import Tag", ] for imp in imports: ip.ex(imp) print imp print "\n" main()
<commit_before># Case Conductor is a Test Case Management system. # Copyright (C) 2011 uTest Inc. # # This file is part of Case Conductor. # # Case Conductor is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Case Conductor is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Case Conductor. If not, see <http://www.gnu.org/licenses/>. """ Makes IPython import all of your projects models when shell is started. 1. Save as ipy_user_conf.py in project root 2. ./manage.py shell 3. profit """ import IPython.ipapi ip = IPython.ipapi.get() def main(): print "\nImported:\n\n" imports = [ "import datetime", "from cc.core.models import Product", "from cc.library.models import Suite, Case, CaseVersion, CaseStep", ] for imp in imports: ip.ex(imp) print imp print "\n" main() <commit_msg>Add model auto-imports to IPython profile.<commit_after>
# Case Conductor is a Test Case Management system. # Copyright (C) 2011 uTest Inc. # # This file is part of Case Conductor. # # Case Conductor is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Case Conductor is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Case Conductor. If not, see <http://www.gnu.org/licenses/>. """ Makes IPython import all of your projects models when shell is started. 1. Save as ipy_user_conf.py in project root 2. ./manage.py shell 3. profit """ import IPython.ipapi ip = IPython.ipapi.get() def main(): print "\nImported:\n\n" imports = [ "import datetime", "from django.contrib.auth.models import User", "from cc.core.models import Product", "from cc.library.models import Suite, Case, CaseVersion, CaseStep, CaseAttachment, SuiteCase", "from cc.execution.models import Cycle, Run, RunCaseVersion, RunSuite, Result, StepResult", "from cc.environments.models import Profile, Category, Element, Environment", "from cc.tags.models import Tag", ] for imp in imports: ip.ex(imp) print imp print "\n" main()
# Case Conductor is a Test Case Management system. # Copyright (C) 2011 uTest Inc. # # This file is part of Case Conductor. # # Case Conductor is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Case Conductor is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Case Conductor. If not, see <http://www.gnu.org/licenses/>. """ Makes IPython import all of your projects models when shell is started. 1. Save as ipy_user_conf.py in project root 2. ./manage.py shell 3. profit """ import IPython.ipapi ip = IPython.ipapi.get() def main(): print "\nImported:\n\n" imports = [ "import datetime", "from cc.core.models import Product", "from cc.library.models import Suite, Case, CaseVersion, CaseStep", ] for imp in imports: ip.ex(imp) print imp print "\n" main() Add model auto-imports to IPython profile.# Case Conductor is a Test Case Management system. # Copyright (C) 2011 uTest Inc. # # This file is part of Case Conductor. # # Case Conductor is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Case Conductor is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Case Conductor. If not, see <http://www.gnu.org/licenses/>. """ Makes IPython import all of your projects models when shell is started. 1. Save as ipy_user_conf.py in project root 2. ./manage.py shell 3. profit """ import IPython.ipapi ip = IPython.ipapi.get() def main(): print "\nImported:\n\n" imports = [ "import datetime", "from django.contrib.auth.models import User", "from cc.core.models import Product", "from cc.library.models import Suite, Case, CaseVersion, CaseStep, CaseAttachment, SuiteCase", "from cc.execution.models import Cycle, Run, RunCaseVersion, RunSuite, Result, StepResult", "from cc.environments.models import Profile, Category, Element, Environment", "from cc.tags.models import Tag", ] for imp in imports: ip.ex(imp) print imp print "\n" main()
<commit_before># Case Conductor is a Test Case Management system. # Copyright (C) 2011 uTest Inc. # # This file is part of Case Conductor. # # Case Conductor is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Case Conductor is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Case Conductor. If not, see <http://www.gnu.org/licenses/>. """ Makes IPython import all of your projects models when shell is started. 1. Save as ipy_user_conf.py in project root 2. ./manage.py shell 3. profit """ import IPython.ipapi ip = IPython.ipapi.get() def main(): print "\nImported:\n\n" imports = [ "import datetime", "from cc.core.models import Product", "from cc.library.models import Suite, Case, CaseVersion, CaseStep", ] for imp in imports: ip.ex(imp) print imp print "\n" main() <commit_msg>Add model auto-imports to IPython profile.<commit_after># Case Conductor is a Test Case Management system. # Copyright (C) 2011 uTest Inc. # # This file is part of Case Conductor. # # Case Conductor is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Case Conductor is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Case Conductor. If not, see <http://www.gnu.org/licenses/>. """ Makes IPython import all of your projects models when shell is started. 1. Save as ipy_user_conf.py in project root 2. ./manage.py shell 3. profit """ import IPython.ipapi ip = IPython.ipapi.get() def main(): print "\nImported:\n\n" imports = [ "import datetime", "from django.contrib.auth.models import User", "from cc.core.models import Product", "from cc.library.models import Suite, Case, CaseVersion, CaseStep, CaseAttachment, SuiteCase", "from cc.execution.models import Cycle, Run, RunCaseVersion, RunSuite, Result, StepResult", "from cc.environments.models import Profile, Category, Element, Environment", "from cc.tags.models import Tag", ] for imp in imports: ip.ex(imp) print imp print "\n" main()
c6a62a538411ef571ccec364b0ee0fe07379836f
unsquasher.py
unsquasher.py
#!/usr/bin/env python import zlib import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test/out") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print("Received compressed on: " + msg.topic) print(zlib.decompress(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()
#!/usr/bin/env python # Very very very quick demo of how to recover the compressed payloads again. # TODO - at least take the same command line arguments as mosq-squasher # See LICENSE.txt import zlib import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test/out") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print("Received compressed on: " + msg.topic) print(zlib.decompress(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()
Update docs and license for python
Update docs and license for python
Python
mit
remakeelectric/mosq-squasher,remakeelectric/mosq-squasher
#!/usr/bin/env python import zlib import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test/out") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print("Received compressed on: " + msg.topic) print(zlib.decompress(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever() Update docs and license for python
#!/usr/bin/env python # Very very very quick demo of how to recover the compressed payloads again. # TODO - at least take the same command line arguments as mosq-squasher # See LICENSE.txt import zlib import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test/out") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print("Received compressed on: " + msg.topic) print(zlib.decompress(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()
<commit_before>#!/usr/bin/env python import zlib import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test/out") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print("Received compressed on: " + msg.topic) print(zlib.decompress(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever() <commit_msg>Update docs and license for python<commit_after>
#!/usr/bin/env python # Very very very quick demo of how to recover the compressed payloads again. # TODO - at least take the same command line arguments as mosq-squasher # See LICENSE.txt import zlib import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test/out") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print("Received compressed on: " + msg.topic) print(zlib.decompress(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()
#!/usr/bin/env python import zlib import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test/out") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print("Received compressed on: " + msg.topic) print(zlib.decompress(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever() Update docs and license for python#!/usr/bin/env python # Very very very quick demo of how to recover the compressed payloads again. # TODO - at least take the same command line arguments as mosq-squasher # See LICENSE.txt import zlib import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test/out") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print("Received compressed on: " + msg.topic) print(zlib.decompress(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()
<commit_before>#!/usr/bin/env python import zlib import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test/out") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print("Received compressed on: " + msg.topic) print(zlib.decompress(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever() <commit_msg>Update docs and license for python<commit_after>#!/usr/bin/env python # Very very very quick demo of how to recover the compressed payloads again. # TODO - at least take the same command line arguments as mosq-squasher # See LICENSE.txt import zlib import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test/out") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print("Received compressed on: " + msg.topic) print(zlib.decompress(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()
a15e3b80383ba6ca79a19a566beeb9290d1ad017
conference_scheduler/tests/test_scheduler.py
conference_scheduler/tests/test_scheduler.py
from collections import Counter from conference_scheduler import scheduler def test_is_valid_schedule(people): # Test empty schedule schedule = tuple() assert not scheduler.is_valid_schedule(schedule) def test_schedule(events, rooms, slots): schedule = scheduler.schedule(events, rooms, slots) # A room may only have a maximum of one event scheduled in any time slot # A room may only be scheduled to host an event for which it is deemed # suitable for item in schedule: assert item.event.event_type in item.room.suitability # An event may only be scheduled in one combination of room and time slot assert len(schedule) == len(events) scheduled_events = set([item.event.name for item in schedule]) assert scheduled_events == set([event.name for event in events])
from collections import Counter from conference_scheduler import scheduler def test_is_valid_schedule(people): # Test empty schedule schedule = tuple() assert not scheduler.is_valid_schedule(schedule) def test_schedule(events, rooms, slots): schedule = scheduler.schedule(events, rooms, slots) # A room may only have a maximum of one event scheduled in any time slot scheduled = Counter([(item.room.name, item.slot) for item in schedule]) for item, count in scheduled.items(): assert count <= 1 # A room may only be scheduled to host an event for which it is deemed # suitable for item in schedule: assert item.event.event_type in item.room.suitability # An event may only be scheduled in one combination of room and time slot assert len(schedule) == len(events) scheduled_events = set([item.event.name for item in schedule]) assert scheduled_events == set([event.name for event in events])
Add working test for only one event per room per slot
Add working test for only one event per room per slot
Python
mit
PyconUK/ConferenceScheduler
from collections import Counter from conference_scheduler import scheduler def test_is_valid_schedule(people): # Test empty schedule schedule = tuple() assert not scheduler.is_valid_schedule(schedule) def test_schedule(events, rooms, slots): schedule = scheduler.schedule(events, rooms, slots) # A room may only have a maximum of one event scheduled in any time slot # A room may only be scheduled to host an event for which it is deemed # suitable for item in schedule: assert item.event.event_type in item.room.suitability # An event may only be scheduled in one combination of room and time slot assert len(schedule) == len(events) scheduled_events = set([item.event.name for item in schedule]) assert scheduled_events == set([event.name for event in events]) Add working test for only one event per room per slot
from collections import Counter from conference_scheduler import scheduler def test_is_valid_schedule(people): # Test empty schedule schedule = tuple() assert not scheduler.is_valid_schedule(schedule) def test_schedule(events, rooms, slots): schedule = scheduler.schedule(events, rooms, slots) # A room may only have a maximum of one event scheduled in any time slot scheduled = Counter([(item.room.name, item.slot) for item in schedule]) for item, count in scheduled.items(): assert count <= 1 # A room may only be scheduled to host an event for which it is deemed # suitable for item in schedule: assert item.event.event_type in item.room.suitability # An event may only be scheduled in one combination of room and time slot assert len(schedule) == len(events) scheduled_events = set([item.event.name for item in schedule]) assert scheduled_events == set([event.name for event in events])
<commit_before>from collections import Counter from conference_scheduler import scheduler def test_is_valid_schedule(people): # Test empty schedule schedule = tuple() assert not scheduler.is_valid_schedule(schedule) def test_schedule(events, rooms, slots): schedule = scheduler.schedule(events, rooms, slots) # A room may only have a maximum of one event scheduled in any time slot # A room may only be scheduled to host an event for which it is deemed # suitable for item in schedule: assert item.event.event_type in item.room.suitability # An event may only be scheduled in one combination of room and time slot assert len(schedule) == len(events) scheduled_events = set([item.event.name for item in schedule]) assert scheduled_events == set([event.name for event in events]) <commit_msg>Add working test for only one event per room per slot<commit_after>
from collections import Counter from conference_scheduler import scheduler def test_is_valid_schedule(people): # Test empty schedule schedule = tuple() assert not scheduler.is_valid_schedule(schedule) def test_schedule(events, rooms, slots): schedule = scheduler.schedule(events, rooms, slots) # A room may only have a maximum of one event scheduled in any time slot scheduled = Counter([(item.room.name, item.slot) for item in schedule]) for item, count in scheduled.items(): assert count <= 1 # A room may only be scheduled to host an event for which it is deemed # suitable for item in schedule: assert item.event.event_type in item.room.suitability # An event may only be scheduled in one combination of room and time slot assert len(schedule) == len(events) scheduled_events = set([item.event.name for item in schedule]) assert scheduled_events == set([event.name for event in events])
from collections import Counter from conference_scheduler import scheduler def test_is_valid_schedule(people): # Test empty schedule schedule = tuple() assert not scheduler.is_valid_schedule(schedule) def test_schedule(events, rooms, slots): schedule = scheduler.schedule(events, rooms, slots) # A room may only have a maximum of one event scheduled in any time slot # A room may only be scheduled to host an event for which it is deemed # suitable for item in schedule: assert item.event.event_type in item.room.suitability # An event may only be scheduled in one combination of room and time slot assert len(schedule) == len(events) scheduled_events = set([item.event.name for item in schedule]) assert scheduled_events == set([event.name for event in events]) Add working test for only one event per room per slotfrom collections import Counter from conference_scheduler import scheduler def test_is_valid_schedule(people): # Test empty schedule schedule = tuple() assert not scheduler.is_valid_schedule(schedule) def test_schedule(events, rooms, slots): schedule = scheduler.schedule(events, rooms, slots) # A room may only have a maximum of one event scheduled in any time slot scheduled = Counter([(item.room.name, item.slot) for item in schedule]) for item, count in scheduled.items(): assert count <= 1 # A room may only be scheduled to host an event for which it is deemed # suitable for item in schedule: assert item.event.event_type in item.room.suitability # An event may only be scheduled in one combination of room and time slot assert len(schedule) == len(events) scheduled_events = set([item.event.name for item in schedule]) assert scheduled_events == set([event.name for event in events])
<commit_before>from collections import Counter from conference_scheduler import scheduler def test_is_valid_schedule(people): # Test empty schedule schedule = tuple() assert not scheduler.is_valid_schedule(schedule) def test_schedule(events, rooms, slots): schedule = scheduler.schedule(events, rooms, slots) # A room may only have a maximum of one event scheduled in any time slot # A room may only be scheduled to host an event for which it is deemed # suitable for item in schedule: assert item.event.event_type in item.room.suitability # An event may only be scheduled in one combination of room and time slot assert len(schedule) == len(events) scheduled_events = set([item.event.name for item in schedule]) assert scheduled_events == set([event.name for event in events]) <commit_msg>Add working test for only one event per room per slot<commit_after>from collections import Counter from conference_scheduler import scheduler def test_is_valid_schedule(people): # Test empty schedule schedule = tuple() assert not scheduler.is_valid_schedule(schedule) def test_schedule(events, rooms, slots): schedule = scheduler.schedule(events, rooms, slots) # A room may only have a maximum of one event scheduled in any time slot scheduled = Counter([(item.room.name, item.slot) for item in schedule]) for item, count in scheduled.items(): assert count <= 1 # A room may only be scheduled to host an event for which it is deemed # suitable for item in schedule: assert item.event.event_type in item.room.suitability # An event may only be scheduled in one combination of room and time slot assert len(schedule) == len(events) scheduled_events = set([item.event.name for item in schedule]) assert scheduled_events == set([event.name for event in events])
9b80275d589aef1cca81f29de0eff6eca18e8565
pywt/setup.py
pywt/setup.py
#!/usr/bin/env python from __future__ import division, print_function, absolute_import def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration import numpy as np config = Configuration('pywt', parent_package, top_path) config.add_data_dir('tests') sources = ["_pywt", "common", "convolution", "wavelets", "wt"] source_templates = ["convolution", "wt"] headers = ["templating", "wavelets_coeffs"] header_templates = ["convolution", "wt", "wavelets_coeffs"] # add main PyWavelets module config.add_extension( '_pywt', sources=["src/{}.c".format(s) for s in sources], depends=(["src/{}.template.c".format(s) for s in source_templates] + ["src/{}.template.h".format(s) for s in header_templates] + ["src/{}.h".format(s) for s in headers]), include_dirs=["src", np.get_include()], define_macros=[("PY_EXTENSION", None)], ) config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
#!/usr/bin/env python from __future__ import division, print_function, absolute_import def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration import numpy as np config = Configuration('pywt', parent_package, top_path) config.add_data_dir('tests') sources = ["_pywt", "common", "convolution", "wavelets", "wt"] source_templates = ["convolution", "wt"] headers = ["templating", "wavelets_coeffs"] header_templates = ["convolution", "wt", "wavelets_coeffs"] # add main PyWavelets module config.add_extension( '_pywt', sources=["src/{0}.c".format(s) for s in sources], depends=(["src/{0}.template.c".format(s) for s in source_templates] + ["src/{0}.template.h".format(s) for s in header_templates] + ["src/{0}.h".format(s) for s in headers]), include_dirs=["src", np.get_include()], define_macros=[("PY_EXTENSION", None)], ) config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
Fix format string for Python-2.6
BLD: Fix format string for Python-2.6
Python
mit
aaren/pywt,ThomasA/pywt,rgommers/pywt,ThomasA/pywt,michelp/pywt,grlee77/pywt,rgommers/pywt,kwohlfahrt/pywt,rgommers/pywt,aaren/pywt,michelp/pywt,rgommers/pywt,kwohlfahrt/pywt,ThomasA/pywt,kwohlfahrt/pywt,michelp/pywt,eriol/pywt,PyWavelets/pywt,aaren/pywt,grlee77/pywt,PyWavelets/pywt,eriol/pywt,eriol/pywt
#!/usr/bin/env python from __future__ import division, print_function, absolute_import def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration import numpy as np config = Configuration('pywt', parent_package, top_path) config.add_data_dir('tests') sources = ["_pywt", "common", "convolution", "wavelets", "wt"] source_templates = ["convolution", "wt"] headers = ["templating", "wavelets_coeffs"] header_templates = ["convolution", "wt", "wavelets_coeffs"] # add main PyWavelets module config.add_extension( '_pywt', sources=["src/{}.c".format(s) for s in sources], depends=(["src/{}.template.c".format(s) for s in source_templates] + ["src/{}.template.h".format(s) for s in header_templates] + ["src/{}.h".format(s) for s in headers]), include_dirs=["src", np.get_include()], define_macros=[("PY_EXTENSION", None)], ) config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) BLD: Fix format string for Python-2.6
#!/usr/bin/env python from __future__ import division, print_function, absolute_import def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration import numpy as np config = Configuration('pywt', parent_package, top_path) config.add_data_dir('tests') sources = ["_pywt", "common", "convolution", "wavelets", "wt"] source_templates = ["convolution", "wt"] headers = ["templating", "wavelets_coeffs"] header_templates = ["convolution", "wt", "wavelets_coeffs"] # add main PyWavelets module config.add_extension( '_pywt', sources=["src/{0}.c".format(s) for s in sources], depends=(["src/{0}.template.c".format(s) for s in source_templates] + ["src/{0}.template.h".format(s) for s in header_templates] + ["src/{0}.h".format(s) for s in headers]), include_dirs=["src", np.get_include()], define_macros=[("PY_EXTENSION", None)], ) config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
<commit_before>#!/usr/bin/env python from __future__ import division, print_function, absolute_import def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration import numpy as np config = Configuration('pywt', parent_package, top_path) config.add_data_dir('tests') sources = ["_pywt", "common", "convolution", "wavelets", "wt"] source_templates = ["convolution", "wt"] headers = ["templating", "wavelets_coeffs"] header_templates = ["convolution", "wt", "wavelets_coeffs"] # add main PyWavelets module config.add_extension( '_pywt', sources=["src/{}.c".format(s) for s in sources], depends=(["src/{}.template.c".format(s) for s in source_templates] + ["src/{}.template.h".format(s) for s in header_templates] + ["src/{}.h".format(s) for s in headers]), include_dirs=["src", np.get_include()], define_macros=[("PY_EXTENSION", None)], ) config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) <commit_msg>BLD: Fix format string for Python-2.6<commit_after>
#!/usr/bin/env python from __future__ import division, print_function, absolute_import def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration import numpy as np config = Configuration('pywt', parent_package, top_path) config.add_data_dir('tests') sources = ["_pywt", "common", "convolution", "wavelets", "wt"] source_templates = ["convolution", "wt"] headers = ["templating", "wavelets_coeffs"] header_templates = ["convolution", "wt", "wavelets_coeffs"] # add main PyWavelets module config.add_extension( '_pywt', sources=["src/{0}.c".format(s) for s in sources], depends=(["src/{0}.template.c".format(s) for s in source_templates] + ["src/{0}.template.h".format(s) for s in header_templates] + ["src/{0}.h".format(s) for s in headers]), include_dirs=["src", np.get_include()], define_macros=[("PY_EXTENSION", None)], ) config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
#!/usr/bin/env python from __future__ import division, print_function, absolute_import def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration import numpy as np config = Configuration('pywt', parent_package, top_path) config.add_data_dir('tests') sources = ["_pywt", "common", "convolution", "wavelets", "wt"] source_templates = ["convolution", "wt"] headers = ["templating", "wavelets_coeffs"] header_templates = ["convolution", "wt", "wavelets_coeffs"] # add main PyWavelets module config.add_extension( '_pywt', sources=["src/{}.c".format(s) for s in sources], depends=(["src/{}.template.c".format(s) for s in source_templates] + ["src/{}.template.h".format(s) for s in header_templates] + ["src/{}.h".format(s) for s in headers]), include_dirs=["src", np.get_include()], define_macros=[("PY_EXTENSION", None)], ) config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) BLD: Fix format string for Python-2.6#!/usr/bin/env python from __future__ import division, print_function, absolute_import def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration import numpy as np config = Configuration('pywt', parent_package, top_path) config.add_data_dir('tests') sources = ["_pywt", "common", "convolution", "wavelets", "wt"] source_templates = ["convolution", "wt"] headers = ["templating", "wavelets_coeffs"] header_templates = ["convolution", "wt", "wavelets_coeffs"] # add main PyWavelets module config.add_extension( '_pywt', sources=["src/{0}.c".format(s) for s in sources], depends=(["src/{0}.template.c".format(s) for s in source_templates] + ["src/{0}.template.h".format(s) for s in header_templates] + ["src/{0}.h".format(s) for s in headers]), include_dirs=["src", np.get_include()], define_macros=[("PY_EXTENSION", None)], ) config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
<commit_before>#!/usr/bin/env python from __future__ import division, print_function, absolute_import def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration import numpy as np config = Configuration('pywt', parent_package, top_path) config.add_data_dir('tests') sources = ["_pywt", "common", "convolution", "wavelets", "wt"] source_templates = ["convolution", "wt"] headers = ["templating", "wavelets_coeffs"] header_templates = ["convolution", "wt", "wavelets_coeffs"] # add main PyWavelets module config.add_extension( '_pywt', sources=["src/{}.c".format(s) for s in sources], depends=(["src/{}.template.c".format(s) for s in source_templates] + ["src/{}.template.h".format(s) for s in header_templates] + ["src/{}.h".format(s) for s in headers]), include_dirs=["src", np.get_include()], define_macros=[("PY_EXTENSION", None)], ) config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) <commit_msg>BLD: Fix format string for Python-2.6<commit_after>#!/usr/bin/env python from __future__ import division, print_function, absolute_import def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration import numpy as np config = Configuration('pywt', parent_package, top_path) config.add_data_dir('tests') sources = ["_pywt", "common", "convolution", "wavelets", "wt"] source_templates = ["convolution", "wt"] headers = ["templating", "wavelets_coeffs"] header_templates = ["convolution", "wt", "wavelets_coeffs"] # add main PyWavelets module config.add_extension( '_pywt', sources=["src/{0}.c".format(s) for s in sources], depends=(["src/{0}.template.c".format(s) for s in source_templates] + ["src/{0}.template.h".format(s) for s in header_templates] + ["src/{0}.h".format(s) for s in headers]), include_dirs=["src", np.get_include()], define_macros=[("PY_EXTENSION", None)], ) config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
6b2a287ccd6c0c399488d8c3e3f487b0a4ca6c04
yarn_api_client/__init__.py
yarn_api_client/__init__.py
# -*- coding: utf-8 -*- __version__ = '0.3.5' __all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager'] from .application_master import ApplicationMaster from .history_server import HistoryServer from .node_manager import NodeManager from .resource_manager import ResourceManager
# -*- coding: utf-8 -*- __version__ = '0.3.6.dev' __all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager'] from .application_master import ApplicationMaster from .history_server import HistoryServer from .node_manager import NodeManager from .resource_manager import ResourceManager
Prepare for next development iteration
Prepare for next development iteration
Python
bsd-3-clause
toidi/hadoop-yarn-api-python-client
# -*- coding: utf-8 -*- __version__ = '0.3.5' __all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager'] from .application_master import ApplicationMaster from .history_server import HistoryServer from .node_manager import NodeManager from .resource_manager import ResourceManager Prepare for next development iteration
# -*- coding: utf-8 -*- __version__ = '0.3.6.dev' __all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager'] from .application_master import ApplicationMaster from .history_server import HistoryServer from .node_manager import NodeManager from .resource_manager import ResourceManager
<commit_before># -*- coding: utf-8 -*- __version__ = '0.3.5' __all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager'] from .application_master import ApplicationMaster from .history_server import HistoryServer from .node_manager import NodeManager from .resource_manager import ResourceManager <commit_msg>Prepare for next development iteration<commit_after>
# -*- coding: utf-8 -*- __version__ = '0.3.6.dev' __all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager'] from .application_master import ApplicationMaster from .history_server import HistoryServer from .node_manager import NodeManager from .resource_manager import ResourceManager
# -*- coding: utf-8 -*- __version__ = '0.3.5' __all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager'] from .application_master import ApplicationMaster from .history_server import HistoryServer from .node_manager import NodeManager from .resource_manager import ResourceManager Prepare for next development iteration# -*- coding: utf-8 -*- __version__ = '0.3.6.dev' __all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager'] from .application_master import ApplicationMaster from .history_server import HistoryServer from .node_manager import NodeManager from .resource_manager import ResourceManager
<commit_before># -*- coding: utf-8 -*- __version__ = '0.3.5' __all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager'] from .application_master import ApplicationMaster from .history_server import HistoryServer from .node_manager import NodeManager from .resource_manager import ResourceManager <commit_msg>Prepare for next development iteration<commit_after># -*- coding: utf-8 -*- __version__ = '0.3.6.dev' __all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager'] from .application_master import ApplicationMaster from .history_server import HistoryServer from .node_manager import NodeManager from .resource_manager import ResourceManager
ebe7b76a441311afb2369b1e24640a790a5b4c77
setuptools_extversion/__init__.py
setuptools_extversion/__init__.py
""" setuptools_extversion Allows getting distribution version from external sources (e.g.: shell command, Python function) """ import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PROVIDER_KEY: if callable(value): extversion = value elif hasattr(value, 'get'): if value.get('command'): extversion = command(value.get('command'), shell=True) else: raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs)
""" setuptools_extversion Allows getting distribution version from external sources (e.g.: shell command, Python function) """ import pkg_resources import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PROVIDER_KEY: if callable(value): extversion = value elif hasattr(value, 'get'): if value.get('command'): extversion = command(value.get('command'), shell=True) if value.get('function'): extversion = function(value.get('function')) else: raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs)
Add support for using a function
Add support for using a function `extversion` can be a a dict with a `function` key -- e.g.: setup( ... setup_requires='setuptools_extversion', extversion={'function': 'my_package.version:get_package_version'}, )
Python
mit
msabramo/python_setuptools_extversion
""" setuptools_extversion Allows getting distribution version from external sources (e.g.: shell command, Python function) """ import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PROVIDER_KEY: if callable(value): extversion = value elif hasattr(value, 'get'): if value.get('command'): extversion = command(value.get('command'), shell=True) else: raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs) Add support for using a function `extversion` can be a a dict with a `function` key -- e.g.: setup( ... setup_requires='setuptools_extversion', extversion={'function': 'my_package.version:get_package_version'}, )
""" setuptools_extversion Allows getting distribution version from external sources (e.g.: shell command, Python function) """ import pkg_resources import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PROVIDER_KEY: if callable(value): extversion = value elif hasattr(value, 'get'): if value.get('command'): extversion = command(value.get('command'), shell=True) if value.get('function'): extversion = function(value.get('function')) else: raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs)
<commit_before>""" setuptools_extversion Allows getting distribution version from external sources (e.g.: shell command, Python function) """ import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PROVIDER_KEY: if callable(value): extversion = value elif hasattr(value, 'get'): if value.get('command'): extversion = command(value.get('command'), shell=True) else: raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs) <commit_msg>Add support for using a function `extversion` can be a a dict with a `function` key -- e.g.: setup( ... setup_requires='setuptools_extversion', extversion={'function': 'my_package.version:get_package_version'}, )<commit_after>
""" setuptools_extversion Allows getting distribution version from external sources (e.g.: shell command, Python function) """ import pkg_resources import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PROVIDER_KEY: if callable(value): extversion = value elif hasattr(value, 'get'): if value.get('command'): extversion = command(value.get('command'), shell=True) if value.get('function'): extversion = function(value.get('function')) else: raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs)
""" setuptools_extversion Allows getting distribution version from external sources (e.g.: shell command, Python function) """ import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PROVIDER_KEY: if callable(value): extversion = value elif hasattr(value, 'get'): if value.get('command'): extversion = command(value.get('command'), shell=True) else: raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs) Add support for using a function `extversion` can be a a dict with a `function` key -- e.g.: setup( ... setup_requires='setuptools_extversion', extversion={'function': 'my_package.version:get_package_version'}, )""" setuptools_extversion Allows getting distribution version from external sources (e.g.: shell command, Python function) """ import pkg_resources import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PROVIDER_KEY: if callable(value): extversion = value elif hasattr(value, 'get'): if value.get('command'): extversion = command(value.get('command'), shell=True) if value.get('function'): extversion = function(value.get('function')) else: raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs)
<commit_before>""" setuptools_extversion Allows getting distribution version from external sources (e.g.: shell command, Python function) """ import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PROVIDER_KEY: if callable(value): extversion = value elif hasattr(value, 'get'): if value.get('command'): extversion = command(value.get('command'), shell=True) else: raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs) <commit_msg>Add support for using a function `extversion` can be a a dict with a `function` key -- e.g.: setup( ... setup_requires='setuptools_extversion', extversion={'function': 'my_package.version:get_package_version'}, )<commit_after>""" setuptools_extversion Allows getting distribution version from external sources (e.g.: shell command, Python function) """ import pkg_resources import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PROVIDER_KEY: if callable(value): extversion = value elif hasattr(value, 'get'): if value.get('command'): extversion = command(value.get('command'), shell=True) if value.get('function'): extversion = function(value.get('function')) else: raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs)
2f0819fa6bea3e6f034516358563086d5ab9aa67
dasem/app/__init__.py
dasem/app/__init__.py
"""Dasem app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap from ..dannet import Dannet from ..semantic import Semantic app = Flask(__name__) Bootstrap(app) app.dasem_dannet = Dannet() app.dasem_semantic = Semantic() from . import views
"""Dasem app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap from ..dannet import Dannet from ..wikipedia import ExplicitSemanticAnalysis app = Flask(__name__) Bootstrap(app) app.dasem_dannet = Dannet() app.dasem_wikipedia_esa = ExplicitSemanticAnalysis(display=True) from . import views
Change to use ESA class in other module
Change to use ESA class in other module
Python
apache-2.0
fnielsen/dasem,fnielsen/dasem
"""Dasem app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap from ..dannet import Dannet from ..semantic import Semantic app = Flask(__name__) Bootstrap(app) app.dasem_dannet = Dannet() app.dasem_semantic = Semantic() from . import views Change to use ESA class in other module
"""Dasem app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap from ..dannet import Dannet from ..wikipedia import ExplicitSemanticAnalysis app = Flask(__name__) Bootstrap(app) app.dasem_dannet = Dannet() app.dasem_wikipedia_esa = ExplicitSemanticAnalysis(display=True) from . import views
<commit_before>"""Dasem app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap from ..dannet import Dannet from ..semantic import Semantic app = Flask(__name__) Bootstrap(app) app.dasem_dannet = Dannet() app.dasem_semantic = Semantic() from . import views <commit_msg>Change to use ESA class in other module<commit_after>
"""Dasem app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap from ..dannet import Dannet from ..wikipedia import ExplicitSemanticAnalysis app = Flask(__name__) Bootstrap(app) app.dasem_dannet = Dannet() app.dasem_wikipedia_esa = ExplicitSemanticAnalysis(display=True) from . import views
"""Dasem app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap from ..dannet import Dannet from ..semantic import Semantic app = Flask(__name__) Bootstrap(app) app.dasem_dannet = Dannet() app.dasem_semantic = Semantic() from . import views Change to use ESA class in other module"""Dasem app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap from ..dannet import Dannet from ..wikipedia import ExplicitSemanticAnalysis app = Flask(__name__) Bootstrap(app) app.dasem_dannet = Dannet() app.dasem_wikipedia_esa = ExplicitSemanticAnalysis(display=True) from . import views
<commit_before>"""Dasem app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap from ..dannet import Dannet from ..semantic import Semantic app = Flask(__name__) Bootstrap(app) app.dasem_dannet = Dannet() app.dasem_semantic = Semantic() from . import views <commit_msg>Change to use ESA class in other module<commit_after>"""Dasem app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap from ..dannet import Dannet from ..wikipedia import ExplicitSemanticAnalysis app = Flask(__name__) Bootstrap(app) app.dasem_dannet = Dannet() app.dasem_wikipedia_esa = ExplicitSemanticAnalysis(display=True) from . import views
7763133ec4c3d51d37b5205a1740e574f20963ae
numpy/doc/pyrex/setup.py
numpy/doc/pyrex/setup.py
#!/usr/bin/env python """Install file for example on how to use Pyrex with Numpy. For more details, see: http://www.scipy.org/Cookbook/Pyrex_and_NumPy http://www.scipy.org/Cookbook/ArrayStruct_and_Pyrex """ from distutils.core import setup from distutils.extension import Extension # Make this usable by people who don't have pyrex installed (I've committed # the generated C sources to SVN). try: from Pyrex.Distutils import build_ext has_pyrex = True except ImportError: has_pyrex = False import numpy # Define a pyrex-based extension module, using the generated sources if pyrex # is not available. if has_pyrex: pyx_sources = ['numpyx.pyx'] cmdclass = {'build_ext': build_ext} else: pyx_sources = ['numpyx.c'] cmdclass = {} pyx_ext = Extension('numpyx', pyx_sources, include_dirs = [numpy.get_numpy_include()]) # Call the routine which does the real work setup(name = 'numpyx', description = 'Small example on using Pyrex to write a Numpy extension', url = 'http://www.scipy.org/Cookbook/Pyrex_and_NumPy', ext_modules = [pyx_ext], cmdclass = cmdclass, )
#!/usr/bin/env python """Install file for example on how to use Pyrex with Numpy. For more details, see: http://www.scipy.org/Cookbook/Pyrex_and_NumPy http://www.scipy.org/Cookbook/ArrayStruct_and_Pyrex """ from distutils.core import setup from distutils.extension import Extension # Make this usable by people who don't have pyrex installed (I've committed # the generated C sources to SVN). try: from Pyrex.Distutils import build_ext has_pyrex = True except ImportError: has_pyrex = False import numpy # Define a pyrex-based extension module, using the generated sources if pyrex # is not available. if has_pyrex: pyx_sources = ['numpyx.pyx'] cmdclass = {'build_ext': build_ext} else: pyx_sources = ['numpyx.c'] cmdclass = {} pyx_ext = Extension('numpyx', pyx_sources, include_dirs = [numpy.get_include()]) # Call the routine which does the real work setup(name = 'numpyx', description = 'Small example on using Pyrex to write a Numpy extension', url = 'http://www.scipy.org/Cookbook/Pyrex_and_NumPy', ext_modules = [pyx_ext], cmdclass = cmdclass, )
Use get_include instead of get_numpy_include.
Use get_include instead of get_numpy_include.
Python
bsd-3-clause
brandon-rhodes/numpy,skwbc/numpy,kiwifb/numpy,astrofrog/numpy,Eric89GXL/numpy,stuarteberg/numpy,dwillmer/numpy,mortada/numpy,rherault-insa/numpy,Srisai85/numpy,astrofrog/numpy,matthew-brett/numpy,rmcgibbo/numpy,numpy/numpy-refactor,SiccarPoint/numpy,pelson/numpy,b-carter/numpy,grlee77/numpy,jankoslavic/numpy,gfyoung/numpy,kiwifb/numpy,nbeaver/numpy,WarrenWeckesser/numpy,MSeifert04/numpy,Srisai85/numpy,mortada/numpy,ssanderson/numpy,madphysicist/numpy,chiffa/numpy,utke1/numpy,jakirkham/numpy,maniteja123/numpy,seberg/numpy,Yusa95/numpy,tdsmith/numpy,matthew-brett/numpy,has2k1/numpy,skwbc/numpy,ogrisel/numpy,jankoslavic/numpy,Yusa95/numpy,groutr/numpy,andsor/numpy,dwillmer/numpy,tdsmith/numpy,yiakwy/numpy,CMartelLML/numpy,rajathkumarmp/numpy,dwf/numpy,mwiebe/numpy,bringingheavendown/numpy,mindw/numpy,pdebuyl/numpy,immerrr/numpy,trankmichael/numpy,tynn/numpy,Yusa95/numpy,joferkington/numpy,anntzer/numpy,grlee77/numpy,felipebetancur/numpy,hainm/numpy,naritta/numpy,larsmans/numpy,ewmoore/numpy,has2k1/numpy,rudimeier/numpy,BabeNovelty/numpy,jorisvandenbossche/numpy,ajdawson/numpy,jorisvandenbossche/numpy,MichaelAquilina/numpy,embray/numpy,BMJHayward/numpy,chatcannon/numpy,ssanderson/numpy,ekalosak/numpy,matthew-brett/numpy,andsor/numpy,mingwpy/numpy,stefanv/numpy,joferkington/numpy,cjermain/numpy,MaPePeR/numpy,madphysicist/numpy,simongibbons/numpy,Eric89GXL/numpy,charris/numpy,mathdd/numpy,numpy/numpy,SunghanKim/numpy,pdebuyl/numpy,jonathanunderwood/numpy,ajdawson/numpy,pdebuyl/numpy,MichaelAquilina/numpy,yiakwy/numpy,Dapid/numpy,gfyoung/numpy,tacaswell/numpy,githubmlai/numpy,AustereCuriosity/numpy,dato-code/numpy,madphysicist/numpy,brandon-rhodes/numpy,pelson/numpy,dwf/numpy,numpy/numpy-refactor,drasmuss/numpy,sigma-random/numpy,WarrenWeckesser/numpy,BabeNovelty/numpy,ESSS/numpy,musically-ut/numpy,abalkin/numpy,sinhrks/numpy,ChristopherHogan/numpy,dwf/numpy,ddasilva/numpy,pbrod/numpy,sonnyhu/numpy,ahaldane/numpy,GrimDerp/numpy,stuarteberg/numpy,larsmans/numpy,pyparallel/numpy,solarjoe/numpy,mhvk/numpy,rmcgibbo/numpy,sigma-random/numpy,jschueller/numpy,bringingheavendown/numpy,musically-ut/numpy,GaZ3ll3/numpy,njase/numpy,jakirkham/numpy,mattip/numpy,rhythmsosad/numpy,hainm/numpy,nguyentu1602/numpy,gfyoung/numpy,ewmoore/numpy,jankoslavic/numpy,ahaldane/numpy,b-carter/numpy,ESSS/numpy,mingwpy/numpy,MichaelAquilina/numpy,dch312/numpy,b-carter/numpy,WillieMaddox/numpy,pizzathief/numpy,shoyer/numpy,GaZ3ll3/numpy,jorisvandenbossche/numpy,yiakwy/numpy,ajdawson/numpy,ChristopherHogan/numpy,pdebuyl/numpy,Srisai85/numpy,rgommers/numpy,GrimDerp/numpy,MaPePeR/numpy,ekalosak/numpy,kirillzhuravlev/numpy,skymanaditya1/numpy,ogrisel/numpy,jakirkham/numpy,gmcastil/numpy,Eric89GXL/numpy,githubmlai/numpy,madphysicist/numpy,jschueller/numpy,MichaelAquilina/numpy,kirillzhuravlev/numpy,mhvk/numpy,SiccarPoint/numpy,mindw/numpy,ESSS/numpy,MaPePeR/numpy,nguyentu1602/numpy,charris/numpy,has2k1/numpy,CMartelLML/numpy,NextThought/pypy-numpy,numpy/numpy,ewmoore/numpy,shoyer/numpy,immerrr/numpy,astrofrog/numpy,dimasad/numpy,Yusa95/numpy,BMJHayward/numpy,maniteja123/numpy,ViralLeadership/numpy,endolith/numpy,sinhrks/numpy,felipebetancur/numpy,BMJHayward/numpy,grlee77/numpy,tdsmith/numpy,rhythmsosad/numpy,ddasilva/numpy,skwbc/numpy,utke1/numpy,Linkid/numpy,joferkington/numpy,sinhrks/numpy,rudimeier/numpy,rudimeier/numpy,MSeifert04/numpy,dch312/numpy,bmorris3/numpy,rhythmsosad/numpy,ewmoore/numpy,anntzer/numpy,mattip/numpy,sonnyhu/numpy,andsor/numpy,ChanderG/numpy,endolith/numpy,ContinuumIO/numpy,hainm/numpy,MSeifert04/numpy,gmcastil/numpy,pyparallel/numpy,cjermain/numpy,utke1/numpy,githubmlai/numpy,shoyer/numpy,mattip/numpy,astrofrog/numpy,embray/numpy,hainm/numpy,matthew-brett/numpy,bmorris3/numpy,sigma-random/numpy,ChanderG/numpy,tacaswell/numpy,jschueller/numpy,felipebetancur/numpy,pelson/numpy,chiffa/numpy,dwillmer/numpy,numpy/numpy-refactor,argriffing/numpy,bertrand-l/numpy,skymanaditya1/numpy,SiccarPoint/numpy,WarrenWeckesser/numpy,naritta/numpy,mwiebe/numpy,brandon-rhodes/numpy,maniteja123/numpy,ogrisel/numpy,rajathkumarmp/numpy,musically-ut/numpy,Linkid/numpy,andsor/numpy,rajathkumarmp/numpy,ssanderson/numpy,jorisvandenbossche/numpy,jonathanunderwood/numpy,dato-code/numpy,shoyer/numpy,stefanv/numpy,GaZ3ll3/numpy,NextThought/pypy-numpy,empeeu/numpy,mindw/numpy,grlee77/numpy,jschueller/numpy,ChristopherHogan/numpy,sigma-random/numpy,moreati/numpy,BabeNovelty/numpy,trankmichael/numpy,ViralLeadership/numpy,behzadnouri/numpy,ewmoore/numpy,GrimDerp/numpy,chiffa/numpy,nguyentu1602/numpy,ContinuumIO/numpy,drasmuss/numpy,dwf/numpy,pizzathief/numpy,pbrod/numpy,bringingheavendown/numpy,naritta/numpy,SiccarPoint/numpy,mathdd/numpy,trankmichael/numpy,jorisvandenbossche/numpy,moreati/numpy,mingwpy/numpy,nbeaver/numpy,ahaldane/numpy,brandon-rhodes/numpy,argriffing/numpy,ddasilva/numpy,rgommers/numpy,rherault-insa/numpy,MaPePeR/numpy,stefanv/numpy,MSeifert04/numpy,felipebetancur/numpy,GaZ3ll3/numpy,Anwesh43/numpy,ajdawson/numpy,WillieMaddox/numpy,MSeifert04/numpy,rajathkumarmp/numpy,kirillzhuravlev/numpy,mortada/numpy,bmorris3/numpy,Eric89GXL/numpy,has2k1/numpy,moreati/numpy,empeeu/numpy,chatcannon/numpy,WillieMaddox/numpy,mortada/numpy,behzadnouri/numpy,pelson/numpy,endolith/numpy,grlee77/numpy,KaelChen/numpy,CMartelLML/numpy,CMartelLML/numpy,mathdd/numpy,dimasad/numpy,pizzathief/numpy,rudimeier/numpy,rmcgibbo/numpy,seberg/numpy,jakirkham/numpy,embray/numpy,skymanaditya1/numpy,joferkington/numpy,pbrod/numpy,kiwifb/numpy,musically-ut/numpy,bertrand-l/numpy,ahaldane/numpy,ogrisel/numpy,stefanv/numpy,immerrr/numpy,NextThought/pypy-numpy,dimasad/numpy,seberg/numpy,pbrod/numpy,Anwesh43/numpy,empeeu/numpy,dwf/numpy,BabeNovelty/numpy,dimasad/numpy,numpy/numpy,Anwesh43/numpy,KaelChen/numpy,tynn/numpy,Dapid/numpy,abalkin/numpy,mingwpy/numpy,dwillmer/numpy,dato-code/numpy,KaelChen/numpy,SunghanKim/numpy,bertrand-l/numpy,sinhrks/numpy,simongibbons/numpy,endolith/numpy,larsmans/numpy,stefanv/numpy,WarrenWeckesser/numpy,yiakwy/numpy,matthew-brett/numpy,dato-code/numpy,dch312/numpy,gmcastil/numpy,AustereCuriosity/numpy,empeeu/numpy,WarrenWeckesser/numpy,cowlicks/numpy,nguyentu1602/numpy,ogrisel/numpy,jakirkham/numpy,cjermain/numpy,Linkid/numpy,skymanaditya1/numpy,shoyer/numpy,solarjoe/numpy,AustereCuriosity/numpy,tacaswell/numpy,immerrr/numpy,numpy/numpy-refactor,sonnyhu/numpy,mindw/numpy,kirillzhuravlev/numpy,mwiebe/numpy,abalkin/numpy,bmorris3/numpy,jankoslavic/numpy,githubmlai/numpy,mhvk/numpy,ChristopherHogan/numpy,Linkid/numpy,naritta/numpy,cowlicks/numpy,pelson/numpy,anntzer/numpy,chatcannon/numpy,madphysicist/numpy,rherault-insa/numpy,simongibbons/numpy,rhythmsosad/numpy,sonnyhu/numpy,behzadnouri/numpy,ahaldane/numpy,mhvk/numpy,argriffing/numpy,trankmichael/numpy,pyparallel/numpy,drasmuss/numpy,ContinuumIO/numpy,SunghanKim/numpy,leifdenby/numpy,pbrod/numpy,pizzathief/numpy,Anwesh43/numpy,cjermain/numpy,rmcgibbo/numpy,simongibbons/numpy,anntzer/numpy,leifdenby/numpy,larsmans/numpy,numpy/numpy,mhvk/numpy,NextThought/pypy-numpy,cowlicks/numpy,nbeaver/numpy,ekalosak/numpy,embray/numpy,charris/numpy,stuarteberg/numpy,KaelChen/numpy,seberg/numpy,Srisai85/numpy,astrofrog/numpy,pizzathief/numpy,njase/numpy,mathdd/numpy,rgommers/numpy,ViralLeadership/numpy,numpy/numpy-refactor,groutr/numpy,embray/numpy,tdsmith/numpy,mattip/numpy,SunghanKim/numpy,ChanderG/numpy,ChanderG/numpy,ekalosak/numpy,groutr/numpy,tynn/numpy,Dapid/numpy,jonathanunderwood/numpy,njase/numpy,cowlicks/numpy,dch312/numpy,rgommers/numpy,leifdenby/numpy,simongibbons/numpy,BMJHayward/numpy,GrimDerp/numpy,solarjoe/numpy,charris/numpy,stuarteberg/numpy
#!/usr/bin/env python """Install file for example on how to use Pyrex with Numpy. For more details, see: http://www.scipy.org/Cookbook/Pyrex_and_NumPy http://www.scipy.org/Cookbook/ArrayStruct_and_Pyrex """ from distutils.core import setup from distutils.extension import Extension # Make this usable by people who don't have pyrex installed (I've committed # the generated C sources to SVN). try: from Pyrex.Distutils import build_ext has_pyrex = True except ImportError: has_pyrex = False import numpy # Define a pyrex-based extension module, using the generated sources if pyrex # is not available. if has_pyrex: pyx_sources = ['numpyx.pyx'] cmdclass = {'build_ext': build_ext} else: pyx_sources = ['numpyx.c'] cmdclass = {} pyx_ext = Extension('numpyx', pyx_sources, include_dirs = [numpy.get_numpy_include()]) # Call the routine which does the real work setup(name = 'numpyx', description = 'Small example on using Pyrex to write a Numpy extension', url = 'http://www.scipy.org/Cookbook/Pyrex_and_NumPy', ext_modules = [pyx_ext], cmdclass = cmdclass, ) Use get_include instead of get_numpy_include.
#!/usr/bin/env python """Install file for example on how to use Pyrex with Numpy. For more details, see: http://www.scipy.org/Cookbook/Pyrex_and_NumPy http://www.scipy.org/Cookbook/ArrayStruct_and_Pyrex """ from distutils.core import setup from distutils.extension import Extension # Make this usable by people who don't have pyrex installed (I've committed # the generated C sources to SVN). try: from Pyrex.Distutils import build_ext has_pyrex = True except ImportError: has_pyrex = False import numpy # Define a pyrex-based extension module, using the generated sources if pyrex # is not available. if has_pyrex: pyx_sources = ['numpyx.pyx'] cmdclass = {'build_ext': build_ext} else: pyx_sources = ['numpyx.c'] cmdclass = {} pyx_ext = Extension('numpyx', pyx_sources, include_dirs = [numpy.get_include()]) # Call the routine which does the real work setup(name = 'numpyx', description = 'Small example on using Pyrex to write a Numpy extension', url = 'http://www.scipy.org/Cookbook/Pyrex_and_NumPy', ext_modules = [pyx_ext], cmdclass = cmdclass, )
<commit_before>#!/usr/bin/env python """Install file for example on how to use Pyrex with Numpy. For more details, see: http://www.scipy.org/Cookbook/Pyrex_and_NumPy http://www.scipy.org/Cookbook/ArrayStruct_and_Pyrex """ from distutils.core import setup from distutils.extension import Extension # Make this usable by people who don't have pyrex installed (I've committed # the generated C sources to SVN). try: from Pyrex.Distutils import build_ext has_pyrex = True except ImportError: has_pyrex = False import numpy # Define a pyrex-based extension module, using the generated sources if pyrex # is not available. if has_pyrex: pyx_sources = ['numpyx.pyx'] cmdclass = {'build_ext': build_ext} else: pyx_sources = ['numpyx.c'] cmdclass = {} pyx_ext = Extension('numpyx', pyx_sources, include_dirs = [numpy.get_numpy_include()]) # Call the routine which does the real work setup(name = 'numpyx', description = 'Small example on using Pyrex to write a Numpy extension', url = 'http://www.scipy.org/Cookbook/Pyrex_and_NumPy', ext_modules = [pyx_ext], cmdclass = cmdclass, ) <commit_msg>Use get_include instead of get_numpy_include.<commit_after>
#!/usr/bin/env python """Install file for example on how to use Pyrex with Numpy. For more details, see: http://www.scipy.org/Cookbook/Pyrex_and_NumPy http://www.scipy.org/Cookbook/ArrayStruct_and_Pyrex """ from distutils.core import setup from distutils.extension import Extension # Make this usable by people who don't have pyrex installed (I've committed # the generated C sources to SVN). try: from Pyrex.Distutils import build_ext has_pyrex = True except ImportError: has_pyrex = False import numpy # Define a pyrex-based extension module, using the generated sources if pyrex # is not available. if has_pyrex: pyx_sources = ['numpyx.pyx'] cmdclass = {'build_ext': build_ext} else: pyx_sources = ['numpyx.c'] cmdclass = {} pyx_ext = Extension('numpyx', pyx_sources, include_dirs = [numpy.get_include()]) # Call the routine which does the real work setup(name = 'numpyx', description = 'Small example on using Pyrex to write a Numpy extension', url = 'http://www.scipy.org/Cookbook/Pyrex_and_NumPy', ext_modules = [pyx_ext], cmdclass = cmdclass, )
#!/usr/bin/env python """Install file for example on how to use Pyrex with Numpy. For more details, see: http://www.scipy.org/Cookbook/Pyrex_and_NumPy http://www.scipy.org/Cookbook/ArrayStruct_and_Pyrex """ from distutils.core import setup from distutils.extension import Extension # Make this usable by people who don't have pyrex installed (I've committed # the generated C sources to SVN). try: from Pyrex.Distutils import build_ext has_pyrex = True except ImportError: has_pyrex = False import numpy # Define a pyrex-based extension module, using the generated sources if pyrex # is not available. if has_pyrex: pyx_sources = ['numpyx.pyx'] cmdclass = {'build_ext': build_ext} else: pyx_sources = ['numpyx.c'] cmdclass = {} pyx_ext = Extension('numpyx', pyx_sources, include_dirs = [numpy.get_numpy_include()]) # Call the routine which does the real work setup(name = 'numpyx', description = 'Small example on using Pyrex to write a Numpy extension', url = 'http://www.scipy.org/Cookbook/Pyrex_and_NumPy', ext_modules = [pyx_ext], cmdclass = cmdclass, ) Use get_include instead of get_numpy_include.#!/usr/bin/env python """Install file for example on how to use Pyrex with Numpy. For more details, see: http://www.scipy.org/Cookbook/Pyrex_and_NumPy http://www.scipy.org/Cookbook/ArrayStruct_and_Pyrex """ from distutils.core import setup from distutils.extension import Extension # Make this usable by people who don't have pyrex installed (I've committed # the generated C sources to SVN). try: from Pyrex.Distutils import build_ext has_pyrex = True except ImportError: has_pyrex = False import numpy # Define a pyrex-based extension module, using the generated sources if pyrex # is not available. if has_pyrex: pyx_sources = ['numpyx.pyx'] cmdclass = {'build_ext': build_ext} else: pyx_sources = ['numpyx.c'] cmdclass = {} pyx_ext = Extension('numpyx', pyx_sources, include_dirs = [numpy.get_include()]) # Call the routine which does the real work setup(name = 'numpyx', description = 'Small example on using Pyrex to write a Numpy extension', url = 'http://www.scipy.org/Cookbook/Pyrex_and_NumPy', ext_modules = [pyx_ext], cmdclass = cmdclass, )
<commit_before>#!/usr/bin/env python """Install file for example on how to use Pyrex with Numpy. For more details, see: http://www.scipy.org/Cookbook/Pyrex_and_NumPy http://www.scipy.org/Cookbook/ArrayStruct_and_Pyrex """ from distutils.core import setup from distutils.extension import Extension # Make this usable by people who don't have pyrex installed (I've committed # the generated C sources to SVN). try: from Pyrex.Distutils import build_ext has_pyrex = True except ImportError: has_pyrex = False import numpy # Define a pyrex-based extension module, using the generated sources if pyrex # is not available. if has_pyrex: pyx_sources = ['numpyx.pyx'] cmdclass = {'build_ext': build_ext} else: pyx_sources = ['numpyx.c'] cmdclass = {} pyx_ext = Extension('numpyx', pyx_sources, include_dirs = [numpy.get_numpy_include()]) # Call the routine which does the real work setup(name = 'numpyx', description = 'Small example on using Pyrex to write a Numpy extension', url = 'http://www.scipy.org/Cookbook/Pyrex_and_NumPy', ext_modules = [pyx_ext], cmdclass = cmdclass, ) <commit_msg>Use get_include instead of get_numpy_include.<commit_after>#!/usr/bin/env python """Install file for example on how to use Pyrex with Numpy. For more details, see: http://www.scipy.org/Cookbook/Pyrex_and_NumPy http://www.scipy.org/Cookbook/ArrayStruct_and_Pyrex """ from distutils.core import setup from distutils.extension import Extension # Make this usable by people who don't have pyrex installed (I've committed # the generated C sources to SVN). try: from Pyrex.Distutils import build_ext has_pyrex = True except ImportError: has_pyrex = False import numpy # Define a pyrex-based extension module, using the generated sources if pyrex # is not available. if has_pyrex: pyx_sources = ['numpyx.pyx'] cmdclass = {'build_ext': build_ext} else: pyx_sources = ['numpyx.c'] cmdclass = {} pyx_ext = Extension('numpyx', pyx_sources, include_dirs = [numpy.get_include()]) # Call the routine which does the real work setup(name = 'numpyx', description = 'Small example on using Pyrex to write a Numpy extension', url = 'http://www.scipy.org/Cookbook/Pyrex_and_NumPy', ext_modules = [pyx_ext], cmdclass = cmdclass, )
6272798c06da66bb3c9b8d2c9ea45c3bceb9a550
diss/tests/test_fs.py
diss/tests/test_fs.py
import os import pytest from fuse import FUSE, FuseOSError from diss.fs import id_from_path, DissFilesystem from .testdata import ID @pytest.fixture def fs(): return DissFilesystem() def test_id_from_path(): assert id_from_path('/blobs/SOMEID') == 'SOMEID' assert id_from_path('/files/hello.txt') == ID with pytest.raises(FuseOSError): id_from_path('/DOES NOT EXIST') with pytest.raises(FuseOSError): id_from_path('/files/DOES NOT EXIST') def test_readdir(fs): assert fs.readdir('/', None) == ['blobs', 'files'] assert set(fs.readdir('/blobs', None)).issuperset([ID]) assert set(fs.readdir('/files', None)).issuperset(['hello.txt']) def test_read(fs): data = fs.read('/files/hello.txt', 100, 0, None) assert data == b"Hello world !\n\n"
import os import pytest from fuse import FUSE, FuseOSError from diss.fs import id_from_path, DissFilesystem from .testdata import ID @pytest.fixture def fs(): return DissFilesystem() def test_id_from_path(): assert id_from_path('/blobs/SOMEID') == 'SOMEID' assert id_from_path('/files/hello.txt') == ID with pytest.raises(FuseOSError): id_from_path('/DOES NOT EXIST') with pytest.raises(FuseOSError): id_from_path('/files/DOES NOT EXIST') def test_readdir(fs): assert fs.readdir('/', None) == ['blobs', 'files'] assert set(fs.readdir('/blobs', None)).issuperset([ID]) assert set(fs.readdir('/files', None)).issuperset(['hello.txt']) def test_read(fs): data = fs.read('/files/hello.txt', 100, 0, None) assert data == b"Hello world !\n\n" def test_getattr(fs): assert fs.getattr('/').get('st_size') assert fs.getattr('/files/hello.txt').get('st_size')
Add test getattr for FUSE
Add test getattr for FUSE
Python
agpl-3.0
hoh/Billabong,hoh/Billabong
import os import pytest from fuse import FUSE, FuseOSError from diss.fs import id_from_path, DissFilesystem from .testdata import ID @pytest.fixture def fs(): return DissFilesystem() def test_id_from_path(): assert id_from_path('/blobs/SOMEID') == 'SOMEID' assert id_from_path('/files/hello.txt') == ID with pytest.raises(FuseOSError): id_from_path('/DOES NOT EXIST') with pytest.raises(FuseOSError): id_from_path('/files/DOES NOT EXIST') def test_readdir(fs): assert fs.readdir('/', None) == ['blobs', 'files'] assert set(fs.readdir('/blobs', None)).issuperset([ID]) assert set(fs.readdir('/files', None)).issuperset(['hello.txt']) def test_read(fs): data = fs.read('/files/hello.txt', 100, 0, None) assert data == b"Hello world !\n\n" Add test getattr for FUSE
import os import pytest from fuse import FUSE, FuseOSError from diss.fs import id_from_path, DissFilesystem from .testdata import ID @pytest.fixture def fs(): return DissFilesystem() def test_id_from_path(): assert id_from_path('/blobs/SOMEID') == 'SOMEID' assert id_from_path('/files/hello.txt') == ID with pytest.raises(FuseOSError): id_from_path('/DOES NOT EXIST') with pytest.raises(FuseOSError): id_from_path('/files/DOES NOT EXIST') def test_readdir(fs): assert fs.readdir('/', None) == ['blobs', 'files'] assert set(fs.readdir('/blobs', None)).issuperset([ID]) assert set(fs.readdir('/files', None)).issuperset(['hello.txt']) def test_read(fs): data = fs.read('/files/hello.txt', 100, 0, None) assert data == b"Hello world !\n\n" def test_getattr(fs): assert fs.getattr('/').get('st_size') assert fs.getattr('/files/hello.txt').get('st_size')
<commit_before> import os import pytest from fuse import FUSE, FuseOSError from diss.fs import id_from_path, DissFilesystem from .testdata import ID @pytest.fixture def fs(): return DissFilesystem() def test_id_from_path(): assert id_from_path('/blobs/SOMEID') == 'SOMEID' assert id_from_path('/files/hello.txt') == ID with pytest.raises(FuseOSError): id_from_path('/DOES NOT EXIST') with pytest.raises(FuseOSError): id_from_path('/files/DOES NOT EXIST') def test_readdir(fs): assert fs.readdir('/', None) == ['blobs', 'files'] assert set(fs.readdir('/blobs', None)).issuperset([ID]) assert set(fs.readdir('/files', None)).issuperset(['hello.txt']) def test_read(fs): data = fs.read('/files/hello.txt', 100, 0, None) assert data == b"Hello world !\n\n" <commit_msg>Add test getattr for FUSE<commit_after>
import os import pytest from fuse import FUSE, FuseOSError from diss.fs import id_from_path, DissFilesystem from .testdata import ID @pytest.fixture def fs(): return DissFilesystem() def test_id_from_path(): assert id_from_path('/blobs/SOMEID') == 'SOMEID' assert id_from_path('/files/hello.txt') == ID with pytest.raises(FuseOSError): id_from_path('/DOES NOT EXIST') with pytest.raises(FuseOSError): id_from_path('/files/DOES NOT EXIST') def test_readdir(fs): assert fs.readdir('/', None) == ['blobs', 'files'] assert set(fs.readdir('/blobs', None)).issuperset([ID]) assert set(fs.readdir('/files', None)).issuperset(['hello.txt']) def test_read(fs): data = fs.read('/files/hello.txt', 100, 0, None) assert data == b"Hello world !\n\n" def test_getattr(fs): assert fs.getattr('/').get('st_size') assert fs.getattr('/files/hello.txt').get('st_size')
import os import pytest from fuse import FUSE, FuseOSError from diss.fs import id_from_path, DissFilesystem from .testdata import ID @pytest.fixture def fs(): return DissFilesystem() def test_id_from_path(): assert id_from_path('/blobs/SOMEID') == 'SOMEID' assert id_from_path('/files/hello.txt') == ID with pytest.raises(FuseOSError): id_from_path('/DOES NOT EXIST') with pytest.raises(FuseOSError): id_from_path('/files/DOES NOT EXIST') def test_readdir(fs): assert fs.readdir('/', None) == ['blobs', 'files'] assert set(fs.readdir('/blobs', None)).issuperset([ID]) assert set(fs.readdir('/files', None)).issuperset(['hello.txt']) def test_read(fs): data = fs.read('/files/hello.txt', 100, 0, None) assert data == b"Hello world !\n\n" Add test getattr for FUSE import os import pytest from fuse import FUSE, FuseOSError from diss.fs import id_from_path, DissFilesystem from .testdata import ID @pytest.fixture def fs(): return DissFilesystem() def test_id_from_path(): assert id_from_path('/blobs/SOMEID') == 'SOMEID' assert id_from_path('/files/hello.txt') == ID with pytest.raises(FuseOSError): id_from_path('/DOES NOT EXIST') with pytest.raises(FuseOSError): id_from_path('/files/DOES NOT EXIST') def test_readdir(fs): assert fs.readdir('/', None) == ['blobs', 'files'] assert set(fs.readdir('/blobs', None)).issuperset([ID]) assert set(fs.readdir('/files', None)).issuperset(['hello.txt']) def test_read(fs): data = fs.read('/files/hello.txt', 100, 0, None) assert data == b"Hello world !\n\n" def test_getattr(fs): assert fs.getattr('/').get('st_size') assert fs.getattr('/files/hello.txt').get('st_size')
<commit_before> import os import pytest from fuse import FUSE, FuseOSError from diss.fs import id_from_path, DissFilesystem from .testdata import ID @pytest.fixture def fs(): return DissFilesystem() def test_id_from_path(): assert id_from_path('/blobs/SOMEID') == 'SOMEID' assert id_from_path('/files/hello.txt') == ID with pytest.raises(FuseOSError): id_from_path('/DOES NOT EXIST') with pytest.raises(FuseOSError): id_from_path('/files/DOES NOT EXIST') def test_readdir(fs): assert fs.readdir('/', None) == ['blobs', 'files'] assert set(fs.readdir('/blobs', None)).issuperset([ID]) assert set(fs.readdir('/files', None)).issuperset(['hello.txt']) def test_read(fs): data = fs.read('/files/hello.txt', 100, 0, None) assert data == b"Hello world !\n\n" <commit_msg>Add test getattr for FUSE<commit_after> import os import pytest from fuse import FUSE, FuseOSError from diss.fs import id_from_path, DissFilesystem from .testdata import ID @pytest.fixture def fs(): return DissFilesystem() def test_id_from_path(): assert id_from_path('/blobs/SOMEID') == 'SOMEID' assert id_from_path('/files/hello.txt') == ID with pytest.raises(FuseOSError): id_from_path('/DOES NOT EXIST') with pytest.raises(FuseOSError): id_from_path('/files/DOES NOT EXIST') def test_readdir(fs): assert fs.readdir('/', None) == ['blobs', 'files'] assert set(fs.readdir('/blobs', None)).issuperset([ID]) assert set(fs.readdir('/files', None)).issuperset(['hello.txt']) def test_read(fs): data = fs.read('/files/hello.txt', 100, 0, None) assert data == b"Hello world !\n\n" def test_getattr(fs): assert fs.getattr('/').get('st_size') assert fs.getattr('/files/hello.txt').get('st_size')
471fc55cd7dc968a9891b571aad5bf745a52fd01
ckanext/stadtzhtheme/tests/test_validation.py
ckanext/stadtzhtheme/tests/test_validation.py
import nose from ckanapi import TestAppCKAN, ValidationError from ckan.tests import helpers, factories eq_ = nose.tools.eq_ assert_true = nose.tools.assert_true class TestValidation(helpers.FunctionalTestBase): def test_invalid_url(self): factories.Sysadmin(apikey="my-test-key") app = self._get_test_app() demo = TestAppCKAN(app, apikey="my-test-key") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]' ) except ValidationError as e: eq_( e.error_dict['url'], [u'Bitte eine valide URL angeben'] ) else: raise AssertionError('ValidationError not raised')
import nose from ckanapi import TestAppCKAN, ValidationError from ckan.tests import helpers, factories eq_ = nose.tools.eq_ assert_true = nose.tools.assert_true class TestValidation(helpers.FunctionalTestBase): def test_invalid_url(self): """Test that an invalid resource url is caught by our validator. """ factories.Sysadmin(apikey="my-test-key") app = self._get_test_app() demo = TestAppCKAN(app, apikey="my-test-key") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]' ) except ValidationError as e: eq_( e.error_dict['url'], [u'Bitte eine valide URL angeben'] ) else: raise AssertionError('ValidationError not raised') def test_invalid_url_for_upload_resource_type(self): """Test that the resource url is not validated if the url_type is 'upload'. """ factories.Sysadmin(apikey="my-test-key") app = self._get_test_app() demo = TestAppCKAN(app, apikey="my-test-key") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]', url_type='upload' ) except ValidationError as e: raise AssertionError('ValidationError raised erroneously')
Add extra test for resource url validator
Add extra test for resource url validator
Python
agpl-3.0
opendatazurich/ckanext-stadtzh-theme,opendatazurich/ckanext-stadtzh-theme,opendatazurich/ckanext-stadtzh-theme
import nose from ckanapi import TestAppCKAN, ValidationError from ckan.tests import helpers, factories eq_ = nose.tools.eq_ assert_true = nose.tools.assert_true class TestValidation(helpers.FunctionalTestBase): def test_invalid_url(self): factories.Sysadmin(apikey="my-test-key") app = self._get_test_app() demo = TestAppCKAN(app, apikey="my-test-key") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]' ) except ValidationError as e: eq_( e.error_dict['url'], [u'Bitte eine valide URL angeben'] ) else: raise AssertionError('ValidationError not raised') Add extra test for resource url validator
import nose from ckanapi import TestAppCKAN, ValidationError from ckan.tests import helpers, factories eq_ = nose.tools.eq_ assert_true = nose.tools.assert_true class TestValidation(helpers.FunctionalTestBase): def test_invalid_url(self): """Test that an invalid resource url is caught by our validator. """ factories.Sysadmin(apikey="my-test-key") app = self._get_test_app() demo = TestAppCKAN(app, apikey="my-test-key") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]' ) except ValidationError as e: eq_( e.error_dict['url'], [u'Bitte eine valide URL angeben'] ) else: raise AssertionError('ValidationError not raised') def test_invalid_url_for_upload_resource_type(self): """Test that the resource url is not validated if the url_type is 'upload'. """ factories.Sysadmin(apikey="my-test-key") app = self._get_test_app() demo = TestAppCKAN(app, apikey="my-test-key") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]', url_type='upload' ) except ValidationError as e: raise AssertionError('ValidationError raised erroneously')
<commit_before>import nose from ckanapi import TestAppCKAN, ValidationError from ckan.tests import helpers, factories eq_ = nose.tools.eq_ assert_true = nose.tools.assert_true class TestValidation(helpers.FunctionalTestBase): def test_invalid_url(self): factories.Sysadmin(apikey="my-test-key") app = self._get_test_app() demo = TestAppCKAN(app, apikey="my-test-key") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]' ) except ValidationError as e: eq_( e.error_dict['url'], [u'Bitte eine valide URL angeben'] ) else: raise AssertionError('ValidationError not raised') <commit_msg>Add extra test for resource url validator<commit_after>
import nose from ckanapi import TestAppCKAN, ValidationError from ckan.tests import helpers, factories eq_ = nose.tools.eq_ assert_true = nose.tools.assert_true class TestValidation(helpers.FunctionalTestBase): def test_invalid_url(self): """Test that an invalid resource url is caught by our validator. """ factories.Sysadmin(apikey="my-test-key") app = self._get_test_app() demo = TestAppCKAN(app, apikey="my-test-key") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]' ) except ValidationError as e: eq_( e.error_dict['url'], [u'Bitte eine valide URL angeben'] ) else: raise AssertionError('ValidationError not raised') def test_invalid_url_for_upload_resource_type(self): """Test that the resource url is not validated if the url_type is 'upload'. """ factories.Sysadmin(apikey="my-test-key") app = self._get_test_app() demo = TestAppCKAN(app, apikey="my-test-key") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]', url_type='upload' ) except ValidationError as e: raise AssertionError('ValidationError raised erroneously')
import nose from ckanapi import TestAppCKAN, ValidationError from ckan.tests import helpers, factories eq_ = nose.tools.eq_ assert_true = nose.tools.assert_true class TestValidation(helpers.FunctionalTestBase): def test_invalid_url(self): factories.Sysadmin(apikey="my-test-key") app = self._get_test_app() demo = TestAppCKAN(app, apikey="my-test-key") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]' ) except ValidationError as e: eq_( e.error_dict['url'], [u'Bitte eine valide URL angeben'] ) else: raise AssertionError('ValidationError not raised') Add extra test for resource url validatorimport nose from ckanapi import TestAppCKAN, ValidationError from ckan.tests import helpers, factories eq_ = nose.tools.eq_ assert_true = nose.tools.assert_true class TestValidation(helpers.FunctionalTestBase): def test_invalid_url(self): """Test that an invalid resource url is caught by our validator. """ factories.Sysadmin(apikey="my-test-key") app = self._get_test_app() demo = TestAppCKAN(app, apikey="my-test-key") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]' ) except ValidationError as e: eq_( e.error_dict['url'], [u'Bitte eine valide URL angeben'] ) else: raise AssertionError('ValidationError not raised') def test_invalid_url_for_upload_resource_type(self): """Test that the resource url is not validated if the url_type is 'upload'. """ factories.Sysadmin(apikey="my-test-key") app = self._get_test_app() demo = TestAppCKAN(app, apikey="my-test-key") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]', url_type='upload' ) except ValidationError as e: raise AssertionError('ValidationError raised erroneously')
<commit_before>import nose from ckanapi import TestAppCKAN, ValidationError from ckan.tests import helpers, factories eq_ = nose.tools.eq_ assert_true = nose.tools.assert_true class TestValidation(helpers.FunctionalTestBase): def test_invalid_url(self): factories.Sysadmin(apikey="my-test-key") app = self._get_test_app() demo = TestAppCKAN(app, apikey="my-test-key") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]' ) except ValidationError as e: eq_( e.error_dict['url'], [u'Bitte eine valide URL angeben'] ) else: raise AssertionError('ValidationError not raised') <commit_msg>Add extra test for resource url validator<commit_after>import nose from ckanapi import TestAppCKAN, ValidationError from ckan.tests import helpers, factories eq_ = nose.tools.eq_ assert_true = nose.tools.assert_true class TestValidation(helpers.FunctionalTestBase): def test_invalid_url(self): """Test that an invalid resource url is caught by our validator. """ factories.Sysadmin(apikey="my-test-key") app = self._get_test_app() demo = TestAppCKAN(app, apikey="my-test-key") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]' ) except ValidationError as e: eq_( e.error_dict['url'], [u'Bitte eine valide URL angeben'] ) else: raise AssertionError('ValidationError not raised') def test_invalid_url_for_upload_resource_type(self): """Test that the resource url is not validated if the url_type is 'upload'. """ factories.Sysadmin(apikey="my-test-key") app = self._get_test_app() demo = TestAppCKAN(app, apikey="my-test-key") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]', url_type='upload' ) except ValidationError as e: raise AssertionError('ValidationError raised erroneously')
bea8123561c24391a6db368773a56a04a1a98fb2
dataprep/dataframe.py
dataprep/dataframe.py
from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") tokens = lines.map(lambda l: l.split("\t")) data = tokens.map(lambda t: Row(year=int(t[0]), month=int(t[1]), day=int(t[2]), hour=int(t[3]), page=t[4], hits=int(t[5]))) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect()
from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") def parse_line(line): tokens = line.split('\t') return Row(page=tokens[4], hits=int(tokens[5])) data = lines.map(parse_line) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect()
Use parse_line function like in later sections
Use parse_line function like in later sections
Python
apache-2.0
aba1476/ds-for-wall-street,thekovinc/ds-for-wall-street,cdalzell/ds-for-wall-street,nishantyp/ds-for-wall-street
from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") tokens = lines.map(lambda l: l.split("\t")) data = tokens.map(lambda t: Row(year=int(t[0]), month=int(t[1]), day=int(t[2]), hour=int(t[3]), page=t[4], hits=int(t[5]))) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect() Use parse_line function like in later sections
from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") def parse_line(line): tokens = line.split('\t') return Row(page=tokens[4], hits=int(tokens[5])) data = lines.map(parse_line) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect()
<commit_before>from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") tokens = lines.map(lambda l: l.split("\t")) data = tokens.map(lambda t: Row(year=int(t[0]), month=int(t[1]), day=int(t[2]), hour=int(t[3]), page=t[4], hits=int(t[5]))) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect() <commit_msg>Use parse_line function like in later sections<commit_after>
from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") def parse_line(line): tokens = line.split('\t') return Row(page=tokens[4], hits=int(tokens[5])) data = lines.map(parse_line) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect()
from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") tokens = lines.map(lambda l: l.split("\t")) data = tokens.map(lambda t: Row(year=int(t[0]), month=int(t[1]), day=int(t[2]), hour=int(t[3]), page=t[4], hits=int(t[5]))) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect() Use parse_line function like in later sectionsfrom pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") def parse_line(line): tokens = line.split('\t') return Row(page=tokens[4], hits=int(tokens[5])) data = lines.map(parse_line) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect()
<commit_before>from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") tokens = lines.map(lambda l: l.split("\t")) data = tokens.map(lambda t: Row(year=int(t[0]), month=int(t[1]), day=int(t[2]), hour=int(t[3]), page=t[4], hits=int(t[5]))) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect() <commit_msg>Use parse_line function like in later sections<commit_after>from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") def parse_line(line): tokens = line.split('\t') return Row(page=tokens[4], hits=int(tokens[5])) data = lines.map(parse_line) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect()
bb8f1d915785fbcbbd8ccd99436a63a449d26e88
patterns.py
patterns.py
# -*- coding: utf-8 -*- import re pre_patterns = [ ( r'(\d{16}-[-\w]*\b)', r'REQUEST_ID_SUBSTITUTE', ), ( # r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}', r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}', # r'[0-9A-F-]{36}', # r'ACE088EB-ECA6-4348-905A-041EF10DBD53', r'UUID_SUBSTITUTE', ), ]
# -*- coding: utf-8 -*- import re pre_patterns = [ ( r'(\d{16}-[-\w]*\b)', r'REQUEST_ID_SUBSTITUTE', ), ( # r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}', r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}', # r'[0-9A-F-]{36}', # r'ACE088EB-ECA6-4348-905A-041EF10DBD53', r'UUID_SUBSTITUTE', ), ( # r""" # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) # """, # r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', r'\b(\d{1,3}\.){3}\d{1,3}\b', r'IP_ADDRESS_SUBSTITUTE', ), ( r'js:\d+:\d+', r'js:POSITION_SUBSTITUTE', ), ]
Add js error position SUBSTITUTE
Add js error position SUBSTITUTE
Python
mit
abcdw/direlog,abcdw/direlog
# -*- coding: utf-8 -*- import re pre_patterns = [ ( r'(\d{16}-[-\w]*\b)', r'REQUEST_ID_SUBSTITUTE', ), ( # r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}', r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}', # r'[0-9A-F-]{36}', # r'ACE088EB-ECA6-4348-905A-041EF10DBD53', r'UUID_SUBSTITUTE', ), ] Add js error position SUBSTITUTE
# -*- coding: utf-8 -*- import re pre_patterns = [ ( r'(\d{16}-[-\w]*\b)', r'REQUEST_ID_SUBSTITUTE', ), ( # r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}', r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}', # r'[0-9A-F-]{36}', # r'ACE088EB-ECA6-4348-905A-041EF10DBD53', r'UUID_SUBSTITUTE', ), ( # r""" # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) # """, # r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', r'\b(\d{1,3}\.){3}\d{1,3}\b', r'IP_ADDRESS_SUBSTITUTE', ), ( r'js:\d+:\d+', r'js:POSITION_SUBSTITUTE', ), ]
<commit_before># -*- coding: utf-8 -*- import re pre_patterns = [ ( r'(\d{16}-[-\w]*\b)', r'REQUEST_ID_SUBSTITUTE', ), ( # r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}', r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}', # r'[0-9A-F-]{36}', # r'ACE088EB-ECA6-4348-905A-041EF10DBD53', r'UUID_SUBSTITUTE', ), ] <commit_msg>Add js error position SUBSTITUTE<commit_after>
# -*- coding: utf-8 -*- import re pre_patterns = [ ( r'(\d{16}-[-\w]*\b)', r'REQUEST_ID_SUBSTITUTE', ), ( # r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}', r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}', # r'[0-9A-F-]{36}', # r'ACE088EB-ECA6-4348-905A-041EF10DBD53', r'UUID_SUBSTITUTE', ), ( # r""" # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) # """, # r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', r'\b(\d{1,3}\.){3}\d{1,3}\b', r'IP_ADDRESS_SUBSTITUTE', ), ( r'js:\d+:\d+', r'js:POSITION_SUBSTITUTE', ), ]
# -*- coding: utf-8 -*- import re pre_patterns = [ ( r'(\d{16}-[-\w]*\b)', r'REQUEST_ID_SUBSTITUTE', ), ( # r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}', r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}', # r'[0-9A-F-]{36}', # r'ACE088EB-ECA6-4348-905A-041EF10DBD53', r'UUID_SUBSTITUTE', ), ] Add js error position SUBSTITUTE# -*- coding: utf-8 -*- import re pre_patterns = [ ( r'(\d{16}-[-\w]*\b)', r'REQUEST_ID_SUBSTITUTE', ), ( # r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}', r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}', # r'[0-9A-F-]{36}', # r'ACE088EB-ECA6-4348-905A-041EF10DBD53', r'UUID_SUBSTITUTE', ), ( # r""" # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) # """, # r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', r'\b(\d{1,3}\.){3}\d{1,3}\b', r'IP_ADDRESS_SUBSTITUTE', ), ( r'js:\d+:\d+', r'js:POSITION_SUBSTITUTE', ), ]
<commit_before># -*- coding: utf-8 -*- import re pre_patterns = [ ( r'(\d{16}-[-\w]*\b)', r'REQUEST_ID_SUBSTITUTE', ), ( # r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}', r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}', # r'[0-9A-F-]{36}', # r'ACE088EB-ECA6-4348-905A-041EF10DBD53', r'UUID_SUBSTITUTE', ), ] <commit_msg>Add js error position SUBSTITUTE<commit_after># -*- coding: utf-8 -*- import re pre_patterns = [ ( r'(\d{16}-[-\w]*\b)', r'REQUEST_ID_SUBSTITUTE', ), ( # r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}', r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}', # r'[0-9A-F-]{36}', # r'ACE088EB-ECA6-4348-905A-041EF10DBD53', r'UUID_SUBSTITUTE', ), ( # r""" # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) # """, # r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', r'\b(\d{1,3}\.){3}\d{1,3}\b', r'IP_ADDRESS_SUBSTITUTE', ), ( r'js:\d+:\d+', r'js:POSITION_SUBSTITUTE', ), ]
f63c37597a51f738bbd478afaf2d21b10741dc91
kid_readout/utils/easync.py
kid_readout/utils/easync.py
""" easync.py - easier access to netCDF4 files """ import netCDF4 class EasyGroup(object): def __repr__(self): return "EasyNC: %s %s" % (self._filename,self.group.path) def __str__(self): return self.__repr__() def __init__(self,group,filename): self._filename = filename self.group = group self.groups = group.groups self.variables = group.variables self.dimensions = group.dimensions for gname in group.groups.keys(): if hasattr(self,gname): print self,"already has an attribute",gname,"skipping" continue self.__setattr__(gname,EasyGroup(group.groups[gname],self._filename)) for vname in group.variables.keys(): if hasattr(self,vname): print self,"already has an attribute",vname,"skipping" continue self.__setattr__(vname,group.variables[vname]) for dname in group.dimensions.keys(): dimname = "dim_" + dname if hasattr(self,dimname): print self,"already has an attribute",dimname,"skipping" continue self.__setattr__(dimname,group.dimensions[dname]) def EasyNetCDF4(*args,**kwargs): nc = netCDF4.Dataset(*args,**kwargs) if len(args) > 0: fn = args[0] else: fn = kwargs['filename'] return EasyGroup(nc,fn)
""" easync.py - easier access to netCDF4 files """ import netCDF4 class EasyGroup(object): def __repr__(self): return "EasyNC: %s %s" % (self._filename,self.group.path) def __str__(self): return self.__repr__() def __init__(self,group,filename): self._filename = filename self.group = group self.groups = group.groups self.variables = group.variables self.dimensions = group.dimensions for gname in group.groups.keys(): if hasattr(self,gname): print self,"already has an attribute",gname,"skipping" continue self.__setattr__(gname,EasyGroup(group.groups[gname],self._filename)) for vname in group.variables.keys(): if hasattr(self,vname): print self,"already has an attribute",vname,"skipping" continue self.__setattr__(vname,group.variables[vname]) for dname in group.dimensions.keys(): dimname = "dim_" + dname if hasattr(self,dimname): print self,"already has an attribute",dimname,"skipping" continue self.__setattr__(dimname,group.dimensions[dname]) def EasyNetCDF4(*args,**kwargs): nc = netCDF4.Dataset(*args,**kwargs) if len(args) > 0: fn = args[0] else: fn = kwargs['filename'] enc = EasyGroup(nc,fn) enc.close = nc.close enc.sync = nc.sync return enc
Add easy access to close and sync methods of nc files
Add easy access to close and sync methods of nc files
Python
bsd-2-clause
ColumbiaCMB/kid_readout,ColumbiaCMB/kid_readout
""" easync.py - easier access to netCDF4 files """ import netCDF4 class EasyGroup(object): def __repr__(self): return "EasyNC: %s %s" % (self._filename,self.group.path) def __str__(self): return self.__repr__() def __init__(self,group,filename): self._filename = filename self.group = group self.groups = group.groups self.variables = group.variables self.dimensions = group.dimensions for gname in group.groups.keys(): if hasattr(self,gname): print self,"already has an attribute",gname,"skipping" continue self.__setattr__(gname,EasyGroup(group.groups[gname],self._filename)) for vname in group.variables.keys(): if hasattr(self,vname): print self,"already has an attribute",vname,"skipping" continue self.__setattr__(vname,group.variables[vname]) for dname in group.dimensions.keys(): dimname = "dim_" + dname if hasattr(self,dimname): print self,"already has an attribute",dimname,"skipping" continue self.__setattr__(dimname,group.dimensions[dname]) def EasyNetCDF4(*args,**kwargs): nc = netCDF4.Dataset(*args,**kwargs) if len(args) > 0: fn = args[0] else: fn = kwargs['filename'] return EasyGroup(nc,fn)Add easy access to close and sync methods of nc files
""" easync.py - easier access to netCDF4 files """ import netCDF4 class EasyGroup(object): def __repr__(self): return "EasyNC: %s %s" % (self._filename,self.group.path) def __str__(self): return self.__repr__() def __init__(self,group,filename): self._filename = filename self.group = group self.groups = group.groups self.variables = group.variables self.dimensions = group.dimensions for gname in group.groups.keys(): if hasattr(self,gname): print self,"already has an attribute",gname,"skipping" continue self.__setattr__(gname,EasyGroup(group.groups[gname],self._filename)) for vname in group.variables.keys(): if hasattr(self,vname): print self,"already has an attribute",vname,"skipping" continue self.__setattr__(vname,group.variables[vname]) for dname in group.dimensions.keys(): dimname = "dim_" + dname if hasattr(self,dimname): print self,"already has an attribute",dimname,"skipping" continue self.__setattr__(dimname,group.dimensions[dname]) def EasyNetCDF4(*args,**kwargs): nc = netCDF4.Dataset(*args,**kwargs) if len(args) > 0: fn = args[0] else: fn = kwargs['filename'] enc = EasyGroup(nc,fn) enc.close = nc.close enc.sync = nc.sync return enc
<commit_before>""" easync.py - easier access to netCDF4 files """ import netCDF4 class EasyGroup(object): def __repr__(self): return "EasyNC: %s %s" % (self._filename,self.group.path) def __str__(self): return self.__repr__() def __init__(self,group,filename): self._filename = filename self.group = group self.groups = group.groups self.variables = group.variables self.dimensions = group.dimensions for gname in group.groups.keys(): if hasattr(self,gname): print self,"already has an attribute",gname,"skipping" continue self.__setattr__(gname,EasyGroup(group.groups[gname],self._filename)) for vname in group.variables.keys(): if hasattr(self,vname): print self,"already has an attribute",vname,"skipping" continue self.__setattr__(vname,group.variables[vname]) for dname in group.dimensions.keys(): dimname = "dim_" + dname if hasattr(self,dimname): print self,"already has an attribute",dimname,"skipping" continue self.__setattr__(dimname,group.dimensions[dname]) def EasyNetCDF4(*args,**kwargs): nc = netCDF4.Dataset(*args,**kwargs) if len(args) > 0: fn = args[0] else: fn = kwargs['filename'] return EasyGroup(nc,fn)<commit_msg>Add easy access to close and sync methods of nc files<commit_after>
""" easync.py - easier access to netCDF4 files """ import netCDF4 class EasyGroup(object): def __repr__(self): return "EasyNC: %s %s" % (self._filename,self.group.path) def __str__(self): return self.__repr__() def __init__(self,group,filename): self._filename = filename self.group = group self.groups = group.groups self.variables = group.variables self.dimensions = group.dimensions for gname in group.groups.keys(): if hasattr(self,gname): print self,"already has an attribute",gname,"skipping" continue self.__setattr__(gname,EasyGroup(group.groups[gname],self._filename)) for vname in group.variables.keys(): if hasattr(self,vname): print self,"already has an attribute",vname,"skipping" continue self.__setattr__(vname,group.variables[vname]) for dname in group.dimensions.keys(): dimname = "dim_" + dname if hasattr(self,dimname): print self,"already has an attribute",dimname,"skipping" continue self.__setattr__(dimname,group.dimensions[dname]) def EasyNetCDF4(*args,**kwargs): nc = netCDF4.Dataset(*args,**kwargs) if len(args) > 0: fn = args[0] else: fn = kwargs['filename'] enc = EasyGroup(nc,fn) enc.close = nc.close enc.sync = nc.sync return enc
""" easync.py - easier access to netCDF4 files """ import netCDF4 class EasyGroup(object): def __repr__(self): return "EasyNC: %s %s" % (self._filename,self.group.path) def __str__(self): return self.__repr__() def __init__(self,group,filename): self._filename = filename self.group = group self.groups = group.groups self.variables = group.variables self.dimensions = group.dimensions for gname in group.groups.keys(): if hasattr(self,gname): print self,"already has an attribute",gname,"skipping" continue self.__setattr__(gname,EasyGroup(group.groups[gname],self._filename)) for vname in group.variables.keys(): if hasattr(self,vname): print self,"already has an attribute",vname,"skipping" continue self.__setattr__(vname,group.variables[vname]) for dname in group.dimensions.keys(): dimname = "dim_" + dname if hasattr(self,dimname): print self,"already has an attribute",dimname,"skipping" continue self.__setattr__(dimname,group.dimensions[dname]) def EasyNetCDF4(*args,**kwargs): nc = netCDF4.Dataset(*args,**kwargs) if len(args) > 0: fn = args[0] else: fn = kwargs['filename'] return EasyGroup(nc,fn)Add easy access to close and sync methods of nc files""" easync.py - easier access to netCDF4 files """ import netCDF4 class EasyGroup(object): def __repr__(self): return "EasyNC: %s %s" % (self._filename,self.group.path) def __str__(self): return self.__repr__() def __init__(self,group,filename): self._filename = filename self.group = group self.groups = group.groups self.variables = group.variables self.dimensions = group.dimensions for gname in group.groups.keys(): if hasattr(self,gname): print self,"already has an attribute",gname,"skipping" continue self.__setattr__(gname,EasyGroup(group.groups[gname],self._filename)) for vname in group.variables.keys(): if hasattr(self,vname): print self,"already has an attribute",vname,"skipping" continue self.__setattr__(vname,group.variables[vname]) for dname in group.dimensions.keys(): dimname = "dim_" + dname if hasattr(self,dimname): print self,"already has an attribute",dimname,"skipping" continue self.__setattr__(dimname,group.dimensions[dname]) def EasyNetCDF4(*args,**kwargs): nc = netCDF4.Dataset(*args,**kwargs) if len(args) > 0: fn = args[0] else: fn = kwargs['filename'] enc = EasyGroup(nc,fn) enc.close = nc.close enc.sync = nc.sync return enc
<commit_before>""" easync.py - easier access to netCDF4 files """ import netCDF4 class EasyGroup(object): def __repr__(self): return "EasyNC: %s %s" % (self._filename,self.group.path) def __str__(self): return self.__repr__() def __init__(self,group,filename): self._filename = filename self.group = group self.groups = group.groups self.variables = group.variables self.dimensions = group.dimensions for gname in group.groups.keys(): if hasattr(self,gname): print self,"already has an attribute",gname,"skipping" continue self.__setattr__(gname,EasyGroup(group.groups[gname],self._filename)) for vname in group.variables.keys(): if hasattr(self,vname): print self,"already has an attribute",vname,"skipping" continue self.__setattr__(vname,group.variables[vname]) for dname in group.dimensions.keys(): dimname = "dim_" + dname if hasattr(self,dimname): print self,"already has an attribute",dimname,"skipping" continue self.__setattr__(dimname,group.dimensions[dname]) def EasyNetCDF4(*args,**kwargs): nc = netCDF4.Dataset(*args,**kwargs) if len(args) > 0: fn = args[0] else: fn = kwargs['filename'] return EasyGroup(nc,fn)<commit_msg>Add easy access to close and sync methods of nc files<commit_after>""" easync.py - easier access to netCDF4 files """ import netCDF4 class EasyGroup(object): def __repr__(self): return "EasyNC: %s %s" % (self._filename,self.group.path) def __str__(self): return self.__repr__() def __init__(self,group,filename): self._filename = filename self.group = group self.groups = group.groups self.variables = group.variables self.dimensions = group.dimensions for gname in group.groups.keys(): if hasattr(self,gname): print self,"already has an attribute",gname,"skipping" continue self.__setattr__(gname,EasyGroup(group.groups[gname],self._filename)) for vname in group.variables.keys(): if hasattr(self,vname): print self,"already has an attribute",vname,"skipping" continue self.__setattr__(vname,group.variables[vname]) for dname in group.dimensions.keys(): dimname = "dim_" + dname if hasattr(self,dimname): print self,"already has an attribute",dimname,"skipping" continue self.__setattr__(dimname,group.dimensions[dname]) def EasyNetCDF4(*args,**kwargs): nc = netCDF4.Dataset(*args,**kwargs) if len(args) > 0: fn = args[0] else: fn = kwargs['filename'] enc = EasyGroup(nc,fn) enc.close = nc.close enc.sync = nc.sync return enc
5d519c31b17a60441d522ab2a5c17c944c376afd
py/brick-wall.py
py/brick-wall.py
import heapq class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ n_row = len(wall) heap = [(wall[i][0], i, 0) for i in xrange(n_row)] heapq.heapify(heap) max_noncross = 0 while True: l, idx, offset = heapq.heappop(heap) cur_l = l if offset == len(wall[idx]) - 1: break heapq.heappush(heap, (l + wall[idx][offset + 1], idx, offset + 1)) cnt = 1 while True: ol, oidx, ooffset = heapq.heappop(heap) if ol == l: cnt += 1 heapq.heappush(heap, (ol + wall[oidx][ooffset + 1], oidx, ooffset + 1)) elif ol > l: heapq.heappush(heap, (ol, oidx, ooffset)) break max_noncross = max(max_noncross, cnt) return n_row - max_noncross
from collections import Counter class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ c = Counter() wall_width = sum(wall[0]) max_non_cut = 0 for row in wall: subsum = 0 for n in row: subsum += n c[subsum] += 1 if subsum < wall_width: max_non_cut = max(c[subsum], max_non_cut) return len(wall) - max_non_cut
Add py solution for 554. Brick Wall
Add py solution for 554. Brick Wall 554. Brick Wall: https://leetcode.com/problems/brick-wall/ Approach2: O(n_brick): Count # of every length can formed by any row
Python
apache-2.0
ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode
import heapq class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ n_row = len(wall) heap = [(wall[i][0], i, 0) for i in xrange(n_row)] heapq.heapify(heap) max_noncross = 0 while True: l, idx, offset = heapq.heappop(heap) cur_l = l if offset == len(wall[idx]) - 1: break heapq.heappush(heap, (l + wall[idx][offset + 1], idx, offset + 1)) cnt = 1 while True: ol, oidx, ooffset = heapq.heappop(heap) if ol == l: cnt += 1 heapq.heappush(heap, (ol + wall[oidx][ooffset + 1], oidx, ooffset + 1)) elif ol > l: heapq.heappush(heap, (ol, oidx, ooffset)) break max_noncross = max(max_noncross, cnt) return n_row - max_noncross Add py solution for 554. Brick Wall 554. Brick Wall: https://leetcode.com/problems/brick-wall/ Approach2: O(n_brick): Count # of every length can formed by any row
from collections import Counter class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ c = Counter() wall_width = sum(wall[0]) max_non_cut = 0 for row in wall: subsum = 0 for n in row: subsum += n c[subsum] += 1 if subsum < wall_width: max_non_cut = max(c[subsum], max_non_cut) return len(wall) - max_non_cut
<commit_before>import heapq class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ n_row = len(wall) heap = [(wall[i][0], i, 0) for i in xrange(n_row)] heapq.heapify(heap) max_noncross = 0 while True: l, idx, offset = heapq.heappop(heap) cur_l = l if offset == len(wall[idx]) - 1: break heapq.heappush(heap, (l + wall[idx][offset + 1], idx, offset + 1)) cnt = 1 while True: ol, oidx, ooffset = heapq.heappop(heap) if ol == l: cnt += 1 heapq.heappush(heap, (ol + wall[oidx][ooffset + 1], oidx, ooffset + 1)) elif ol > l: heapq.heappush(heap, (ol, oidx, ooffset)) break max_noncross = max(max_noncross, cnt) return n_row - max_noncross <commit_msg>Add py solution for 554. Brick Wall 554. Brick Wall: https://leetcode.com/problems/brick-wall/ Approach2: O(n_brick): Count # of every length can formed by any row<commit_after>
from collections import Counter class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ c = Counter() wall_width = sum(wall[0]) max_non_cut = 0 for row in wall: subsum = 0 for n in row: subsum += n c[subsum] += 1 if subsum < wall_width: max_non_cut = max(c[subsum], max_non_cut) return len(wall) - max_non_cut
import heapq class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ n_row = len(wall) heap = [(wall[i][0], i, 0) for i in xrange(n_row)] heapq.heapify(heap) max_noncross = 0 while True: l, idx, offset = heapq.heappop(heap) cur_l = l if offset == len(wall[idx]) - 1: break heapq.heappush(heap, (l + wall[idx][offset + 1], idx, offset + 1)) cnt = 1 while True: ol, oidx, ooffset = heapq.heappop(heap) if ol == l: cnt += 1 heapq.heappush(heap, (ol + wall[oidx][ooffset + 1], oidx, ooffset + 1)) elif ol > l: heapq.heappush(heap, (ol, oidx, ooffset)) break max_noncross = max(max_noncross, cnt) return n_row - max_noncross Add py solution for 554. Brick Wall 554. Brick Wall: https://leetcode.com/problems/brick-wall/ Approach2: O(n_brick): Count # of every length can formed by any rowfrom collections import Counter class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ c = Counter() wall_width = sum(wall[0]) max_non_cut = 0 for row in wall: subsum = 0 for n in row: subsum += n c[subsum] += 1 if subsum < wall_width: max_non_cut = max(c[subsum], max_non_cut) return len(wall) - max_non_cut
<commit_before>import heapq class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ n_row = len(wall) heap = [(wall[i][0], i, 0) for i in xrange(n_row)] heapq.heapify(heap) max_noncross = 0 while True: l, idx, offset = heapq.heappop(heap) cur_l = l if offset == len(wall[idx]) - 1: break heapq.heappush(heap, (l + wall[idx][offset + 1], idx, offset + 1)) cnt = 1 while True: ol, oidx, ooffset = heapq.heappop(heap) if ol == l: cnt += 1 heapq.heappush(heap, (ol + wall[oidx][ooffset + 1], oidx, ooffset + 1)) elif ol > l: heapq.heappush(heap, (ol, oidx, ooffset)) break max_noncross = max(max_noncross, cnt) return n_row - max_noncross <commit_msg>Add py solution for 554. Brick Wall 554. Brick Wall: https://leetcode.com/problems/brick-wall/ Approach2: O(n_brick): Count # of every length can formed by any row<commit_after>from collections import Counter class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ c = Counter() wall_width = sum(wall[0]) max_non_cut = 0 for row in wall: subsum = 0 for n in row: subsum += n c[subsum] += 1 if subsum < wall_width: max_non_cut = max(c[subsum], max_non_cut) return len(wall) - max_non_cut
e366abe34f3cf2ac98572d8d3a4bab19343610c7
lambda_uploader/__init__.py
lambda_uploader/__init__.py
# Copyright 2015-2016 Rackspace US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __title__ = 'lambda_uploader' __version__ = '1.2.0' __license__ = 'Apache 2.0' __copyright__ = 'Copyright Rackspace US, Inc. 2015-2016' __url__ = 'https://github.com/rackerlabs/lambda-uploader'
# Copyright 2015-2016 Rackspace US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __title__ = 'lambda_uploader' __version__ = '1.2.1' __license__ = 'Apache 2.0' __copyright__ = 'Copyright Rackspace US, Inc. 2015-2016' __url__ = 'https://github.com/rackerlabs/lambda-uploader'
Bump release version in source
Bump release version in source
Python
apache-2.0
rackerlabs/lambda-uploader
# Copyright 2015-2016 Rackspace US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __title__ = 'lambda_uploader' __version__ = '1.2.0' __license__ = 'Apache 2.0' __copyright__ = 'Copyright Rackspace US, Inc. 2015-2016' __url__ = 'https://github.com/rackerlabs/lambda-uploader' Bump release version in source
# Copyright 2015-2016 Rackspace US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __title__ = 'lambda_uploader' __version__ = '1.2.1' __license__ = 'Apache 2.0' __copyright__ = 'Copyright Rackspace US, Inc. 2015-2016' __url__ = 'https://github.com/rackerlabs/lambda-uploader'
<commit_before># Copyright 2015-2016 Rackspace US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __title__ = 'lambda_uploader' __version__ = '1.2.0' __license__ = 'Apache 2.0' __copyright__ = 'Copyright Rackspace US, Inc. 2015-2016' __url__ = 'https://github.com/rackerlabs/lambda-uploader' <commit_msg>Bump release version in source<commit_after>
# Copyright 2015-2016 Rackspace US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __title__ = 'lambda_uploader' __version__ = '1.2.1' __license__ = 'Apache 2.0' __copyright__ = 'Copyright Rackspace US, Inc. 2015-2016' __url__ = 'https://github.com/rackerlabs/lambda-uploader'
# Copyright 2015-2016 Rackspace US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __title__ = 'lambda_uploader' __version__ = '1.2.0' __license__ = 'Apache 2.0' __copyright__ = 'Copyright Rackspace US, Inc. 2015-2016' __url__ = 'https://github.com/rackerlabs/lambda-uploader' Bump release version in source# Copyright 2015-2016 Rackspace US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __title__ = 'lambda_uploader' __version__ = '1.2.1' __license__ = 'Apache 2.0' __copyright__ = 'Copyright Rackspace US, Inc. 2015-2016' __url__ = 'https://github.com/rackerlabs/lambda-uploader'
<commit_before># Copyright 2015-2016 Rackspace US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __title__ = 'lambda_uploader' __version__ = '1.2.0' __license__ = 'Apache 2.0' __copyright__ = 'Copyright Rackspace US, Inc. 2015-2016' __url__ = 'https://github.com/rackerlabs/lambda-uploader' <commit_msg>Bump release version in source<commit_after># Copyright 2015-2016 Rackspace US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __title__ = 'lambda_uploader' __version__ = '1.2.1' __license__ = 'Apache 2.0' __copyright__ = 'Copyright Rackspace US, Inc. 2015-2016' __url__ = 'https://github.com/rackerlabs/lambda-uploader'
a708645581542822985be2e8778b60f0008d75a6
Lib/whichdb.py
Lib/whichdb.py
"""Guess which db package to use to open a db file.""" import struct def whichdb(filename): """Guess which db package to use to open a db file. Return values: - None if the database file can't be read; - empty string if the file can be read but can't be recognized - the module name (e.g. "dbm" or "gdbm") if recognized. Importing the given module may still fail, and opening the database using that module may still fail. """ # Check for dbm first -- this has a .pag and a .dir file try: f = open(filename + ".pag", "rb") f.close() f = open(filename + ".dir", "rb") f.close() return "dbm" except IOError: pass # See if the file exists, return None if not try: f = open(filename, "rb") except IOError: return None # Read the first 4 bytes of the file -- the magic number s = f.read(4) f.close() # Return "" if not at least 4 bytes if len(s) != 4: return "" # Convert to 4-byte int in native byte order -- return "" if impossible try: (magic,) = struct.unpack("=l", s) except struct.error: return "" # Check for GNU dbm if magic == 0x13579ace: return "gdbm" # Check for BSD hash if magic == 0x061561: return "dbhash" # Unknown return ""
"""Guess which db package to use to open a db file.""" import struct def whichdb(filename): """Guess which db package to use to open a db file. Return values: - None if the database file can't be read; - empty string if the file can be read but can't be recognized - the module name (e.g. "dbm" or "gdbm") if recognized. Importing the given module may still fail, and opening the database using that module may still fail. """ # Check for dbm first -- this has a .pag and a .dir file try: f = open(filename + ".pag", "rb") f.close() f = open(filename + ".dir", "rb") f.close() return "dbm" except IOError: pass # See if the file exists, return None if not try: f = open(filename, "rb") except IOError: return None # Read the first 4 bytes of the file -- the magic number s = f.read(4) f.close() # Return "" if not at least 4 bytes if len(s) != 4: return "" # Convert to 4-byte int in native byte order -- return "" if impossible try: (magic,) = struct.unpack("=l", s) except struct.error: return "" # Check for GNU dbm if magic == 0x13579ace: return "gdbm" # Check for BSD hash if magic in (0x00061561, 0x61150600): return "dbhash" # Unknown return ""
Support byte-swapped dbhash (bsddb) files. Found by Ben Sayer.
Support byte-swapped dbhash (bsddb) files. Found by Ben Sayer.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
"""Guess which db package to use to open a db file.""" import struct def whichdb(filename): """Guess which db package to use to open a db file. Return values: - None if the database file can't be read; - empty string if the file can be read but can't be recognized - the module name (e.g. "dbm" or "gdbm") if recognized. Importing the given module may still fail, and opening the database using that module may still fail. """ # Check for dbm first -- this has a .pag and a .dir file try: f = open(filename + ".pag", "rb") f.close() f = open(filename + ".dir", "rb") f.close() return "dbm" except IOError: pass # See if the file exists, return None if not try: f = open(filename, "rb") except IOError: return None # Read the first 4 bytes of the file -- the magic number s = f.read(4) f.close() # Return "" if not at least 4 bytes if len(s) != 4: return "" # Convert to 4-byte int in native byte order -- return "" if impossible try: (magic,) = struct.unpack("=l", s) except struct.error: return "" # Check for GNU dbm if magic == 0x13579ace: return "gdbm" # Check for BSD hash if magic == 0x061561: return "dbhash" # Unknown return "" Support byte-swapped dbhash (bsddb) files. Found by Ben Sayer.
"""Guess which db package to use to open a db file.""" import struct def whichdb(filename): """Guess which db package to use to open a db file. Return values: - None if the database file can't be read; - empty string if the file can be read but can't be recognized - the module name (e.g. "dbm" or "gdbm") if recognized. Importing the given module may still fail, and opening the database using that module may still fail. """ # Check for dbm first -- this has a .pag and a .dir file try: f = open(filename + ".pag", "rb") f.close() f = open(filename + ".dir", "rb") f.close() return "dbm" except IOError: pass # See if the file exists, return None if not try: f = open(filename, "rb") except IOError: return None # Read the first 4 bytes of the file -- the magic number s = f.read(4) f.close() # Return "" if not at least 4 bytes if len(s) != 4: return "" # Convert to 4-byte int in native byte order -- return "" if impossible try: (magic,) = struct.unpack("=l", s) except struct.error: return "" # Check for GNU dbm if magic == 0x13579ace: return "gdbm" # Check for BSD hash if magic in (0x00061561, 0x61150600): return "dbhash" # Unknown return ""
<commit_before>"""Guess which db package to use to open a db file.""" import struct def whichdb(filename): """Guess which db package to use to open a db file. Return values: - None if the database file can't be read; - empty string if the file can be read but can't be recognized - the module name (e.g. "dbm" or "gdbm") if recognized. Importing the given module may still fail, and opening the database using that module may still fail. """ # Check for dbm first -- this has a .pag and a .dir file try: f = open(filename + ".pag", "rb") f.close() f = open(filename + ".dir", "rb") f.close() return "dbm" except IOError: pass # See if the file exists, return None if not try: f = open(filename, "rb") except IOError: return None # Read the first 4 bytes of the file -- the magic number s = f.read(4) f.close() # Return "" if not at least 4 bytes if len(s) != 4: return "" # Convert to 4-byte int in native byte order -- return "" if impossible try: (magic,) = struct.unpack("=l", s) except struct.error: return "" # Check for GNU dbm if magic == 0x13579ace: return "gdbm" # Check for BSD hash if magic == 0x061561: return "dbhash" # Unknown return "" <commit_msg>Support byte-swapped dbhash (bsddb) files. Found by Ben Sayer.<commit_after>
"""Guess which db package to use to open a db file.""" import struct def whichdb(filename): """Guess which db package to use to open a db file. Return values: - None if the database file can't be read; - empty string if the file can be read but can't be recognized - the module name (e.g. "dbm" or "gdbm") if recognized. Importing the given module may still fail, and opening the database using that module may still fail. """ # Check for dbm first -- this has a .pag and a .dir file try: f = open(filename + ".pag", "rb") f.close() f = open(filename + ".dir", "rb") f.close() return "dbm" except IOError: pass # See if the file exists, return None if not try: f = open(filename, "rb") except IOError: return None # Read the first 4 bytes of the file -- the magic number s = f.read(4) f.close() # Return "" if not at least 4 bytes if len(s) != 4: return "" # Convert to 4-byte int in native byte order -- return "" if impossible try: (magic,) = struct.unpack("=l", s) except struct.error: return "" # Check for GNU dbm if magic == 0x13579ace: return "gdbm" # Check for BSD hash if magic in (0x00061561, 0x61150600): return "dbhash" # Unknown return ""
"""Guess which db package to use to open a db file.""" import struct def whichdb(filename): """Guess which db package to use to open a db file. Return values: - None if the database file can't be read; - empty string if the file can be read but can't be recognized - the module name (e.g. "dbm" or "gdbm") if recognized. Importing the given module may still fail, and opening the database using that module may still fail. """ # Check for dbm first -- this has a .pag and a .dir file try: f = open(filename + ".pag", "rb") f.close() f = open(filename + ".dir", "rb") f.close() return "dbm" except IOError: pass # See if the file exists, return None if not try: f = open(filename, "rb") except IOError: return None # Read the first 4 bytes of the file -- the magic number s = f.read(4) f.close() # Return "" if not at least 4 bytes if len(s) != 4: return "" # Convert to 4-byte int in native byte order -- return "" if impossible try: (magic,) = struct.unpack("=l", s) except struct.error: return "" # Check for GNU dbm if magic == 0x13579ace: return "gdbm" # Check for BSD hash if magic == 0x061561: return "dbhash" # Unknown return "" Support byte-swapped dbhash (bsddb) files. Found by Ben Sayer."""Guess which db package to use to open a db file.""" import struct def whichdb(filename): """Guess which db package to use to open a db file. Return values: - None if the database file can't be read; - empty string if the file can be read but can't be recognized - the module name (e.g. "dbm" or "gdbm") if recognized. Importing the given module may still fail, and opening the database using that module may still fail. """ # Check for dbm first -- this has a .pag and a .dir file try: f = open(filename + ".pag", "rb") f.close() f = open(filename + ".dir", "rb") f.close() return "dbm" except IOError: pass # See if the file exists, return None if not try: f = open(filename, "rb") except IOError: return None # Read the first 4 bytes of the file -- the magic number s = f.read(4) f.close() # Return "" if not at least 4 bytes if len(s) != 4: return "" # Convert to 4-byte int in native byte order -- return "" if impossible try: (magic,) = struct.unpack("=l", s) except struct.error: return "" # Check for GNU dbm if magic == 0x13579ace: return "gdbm" # Check for BSD hash if magic in (0x00061561, 0x61150600): return "dbhash" # Unknown return ""
<commit_before>"""Guess which db package to use to open a db file.""" import struct def whichdb(filename): """Guess which db package to use to open a db file. Return values: - None if the database file can't be read; - empty string if the file can be read but can't be recognized - the module name (e.g. "dbm" or "gdbm") if recognized. Importing the given module may still fail, and opening the database using that module may still fail. """ # Check for dbm first -- this has a .pag and a .dir file try: f = open(filename + ".pag", "rb") f.close() f = open(filename + ".dir", "rb") f.close() return "dbm" except IOError: pass # See if the file exists, return None if not try: f = open(filename, "rb") except IOError: return None # Read the first 4 bytes of the file -- the magic number s = f.read(4) f.close() # Return "" if not at least 4 bytes if len(s) != 4: return "" # Convert to 4-byte int in native byte order -- return "" if impossible try: (magic,) = struct.unpack("=l", s) except struct.error: return "" # Check for GNU dbm if magic == 0x13579ace: return "gdbm" # Check for BSD hash if magic == 0x061561: return "dbhash" # Unknown return "" <commit_msg>Support byte-swapped dbhash (bsddb) files. Found by Ben Sayer.<commit_after>"""Guess which db package to use to open a db file.""" import struct def whichdb(filename): """Guess which db package to use to open a db file. Return values: - None if the database file can't be read; - empty string if the file can be read but can't be recognized - the module name (e.g. "dbm" or "gdbm") if recognized. Importing the given module may still fail, and opening the database using that module may still fail. """ # Check for dbm first -- this has a .pag and a .dir file try: f = open(filename + ".pag", "rb") f.close() f = open(filename + ".dir", "rb") f.close() return "dbm" except IOError: pass # See if the file exists, return None if not try: f = open(filename, "rb") except IOError: return None # Read the first 4 bytes of the file -- the magic number s = f.read(4) f.close() # Return "" if not at least 4 bytes if len(s) != 4: return "" # Convert to 4-byte int in native byte order -- return "" if impossible try: (magic,) = struct.unpack("=l", s) except struct.error: return "" # Check for GNU dbm if magic == 0x13579ace: return "gdbm" # Check for BSD hash if magic in (0x00061561, 0x61150600): return "dbhash" # Unknown return ""
92100c6ea45d4c39afb1134011ad0044cbcab6bd
example/taskworker/tasks.py
example/taskworker/tasks.py
from __future__ import absolute_import from __future__ import print_function import logging from kale import task logger = logging.getLogger(__name__) class FibonacciTask(task.Task): # How many times should taskworker retry if it fails. # If this task shouldn't be retried, set it to None max_retries = 3 # The hard limit for max task running time. # This value should be set between max actual running time and # queue visibility timeout. time_limit = 5 # seconds # The queue name queue = 'default' @staticmethod def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return FibonacciTask.fibonacci(n-1) + FibonacciTask.fibonacci(n-2) def run_task(self, n, *args, **kwargs): print('fibonacci(%d) = %d' % (n, self.fibonacci(n)))
from __future__ import absolute_import from __future__ import print_function import logging from kale import task logger = logging.getLogger(__name__) class FibonacciTask(task.Task): # How many times should taskworker retry if it fails. # If this task shouldn't be retried, set it to None max_retries = 3 # The hard limit for max task running time. # This value should be set between max actual running time and # queue visibility timeout. time_limit = 5 # seconds # The queue name queue = 'default' @staticmethod def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return FibonacciTask.fibonacci(n - 1) + FibonacciTask.fibonacci(n - 2) def run_task(self, n, *args, **kwargs): print('fibonacci(%d) = %d' % (n, self.fibonacci(n)))
Fix flake8 errors for build.
Fix flake8 errors for build.
Python
bsd-2-clause
Nextdoor/ndkale,Nextdoor/ndkale
from __future__ import absolute_import from __future__ import print_function import logging from kale import task logger = logging.getLogger(__name__) class FibonacciTask(task.Task): # How many times should taskworker retry if it fails. # If this task shouldn't be retried, set it to None max_retries = 3 # The hard limit for max task running time. # This value should be set between max actual running time and # queue visibility timeout. time_limit = 5 # seconds # The queue name queue = 'default' @staticmethod def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return FibonacciTask.fibonacci(n-1) + FibonacciTask.fibonacci(n-2) def run_task(self, n, *args, **kwargs): print('fibonacci(%d) = %d' % (n, self.fibonacci(n))) Fix flake8 errors for build.
from __future__ import absolute_import from __future__ import print_function import logging from kale import task logger = logging.getLogger(__name__) class FibonacciTask(task.Task): # How many times should taskworker retry if it fails. # If this task shouldn't be retried, set it to None max_retries = 3 # The hard limit for max task running time. # This value should be set between max actual running time and # queue visibility timeout. time_limit = 5 # seconds # The queue name queue = 'default' @staticmethod def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return FibonacciTask.fibonacci(n - 1) + FibonacciTask.fibonacci(n - 2) def run_task(self, n, *args, **kwargs): print('fibonacci(%d) = %d' % (n, self.fibonacci(n)))
<commit_before>from __future__ import absolute_import from __future__ import print_function import logging from kale import task logger = logging.getLogger(__name__) class FibonacciTask(task.Task): # How many times should taskworker retry if it fails. # If this task shouldn't be retried, set it to None max_retries = 3 # The hard limit for max task running time. # This value should be set between max actual running time and # queue visibility timeout. time_limit = 5 # seconds # The queue name queue = 'default' @staticmethod def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return FibonacciTask.fibonacci(n-1) + FibonacciTask.fibonacci(n-2) def run_task(self, n, *args, **kwargs): print('fibonacci(%d) = %d' % (n, self.fibonacci(n))) <commit_msg>Fix flake8 errors for build.<commit_after>
from __future__ import absolute_import from __future__ import print_function import logging from kale import task logger = logging.getLogger(__name__) class FibonacciTask(task.Task): # How many times should taskworker retry if it fails. # If this task shouldn't be retried, set it to None max_retries = 3 # The hard limit for max task running time. # This value should be set between max actual running time and # queue visibility timeout. time_limit = 5 # seconds # The queue name queue = 'default' @staticmethod def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return FibonacciTask.fibonacci(n - 1) + FibonacciTask.fibonacci(n - 2) def run_task(self, n, *args, **kwargs): print('fibonacci(%d) = %d' % (n, self.fibonacci(n)))
from __future__ import absolute_import from __future__ import print_function import logging from kale import task logger = logging.getLogger(__name__) class FibonacciTask(task.Task): # How many times should taskworker retry if it fails. # If this task shouldn't be retried, set it to None max_retries = 3 # The hard limit for max task running time. # This value should be set between max actual running time and # queue visibility timeout. time_limit = 5 # seconds # The queue name queue = 'default' @staticmethod def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return FibonacciTask.fibonacci(n-1) + FibonacciTask.fibonacci(n-2) def run_task(self, n, *args, **kwargs): print('fibonacci(%d) = %d' % (n, self.fibonacci(n))) Fix flake8 errors for build.from __future__ import absolute_import from __future__ import print_function import logging from kale import task logger = logging.getLogger(__name__) class FibonacciTask(task.Task): # How many times should taskworker retry if it fails. # If this task shouldn't be retried, set it to None max_retries = 3 # The hard limit for max task running time. # This value should be set between max actual running time and # queue visibility timeout. time_limit = 5 # seconds # The queue name queue = 'default' @staticmethod def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return FibonacciTask.fibonacci(n - 1) + FibonacciTask.fibonacci(n - 2) def run_task(self, n, *args, **kwargs): print('fibonacci(%d) = %d' % (n, self.fibonacci(n)))
<commit_before>from __future__ import absolute_import from __future__ import print_function import logging from kale import task logger = logging.getLogger(__name__) class FibonacciTask(task.Task): # How many times should taskworker retry if it fails. # If this task shouldn't be retried, set it to None max_retries = 3 # The hard limit for max task running time. # This value should be set between max actual running time and # queue visibility timeout. time_limit = 5 # seconds # The queue name queue = 'default' @staticmethod def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return FibonacciTask.fibonacci(n-1) + FibonacciTask.fibonacci(n-2) def run_task(self, n, *args, **kwargs): print('fibonacci(%d) = %d' % (n, self.fibonacci(n))) <commit_msg>Fix flake8 errors for build.<commit_after>from __future__ import absolute_import from __future__ import print_function import logging from kale import task logger = logging.getLogger(__name__) class FibonacciTask(task.Task): # How many times should taskworker retry if it fails. # If this task shouldn't be retried, set it to None max_retries = 3 # The hard limit for max task running time. # This value should be set between max actual running time and # queue visibility timeout. time_limit = 5 # seconds # The queue name queue = 'default' @staticmethod def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return FibonacciTask.fibonacci(n - 1) + FibonacciTask.fibonacci(n - 2) def run_task(self, n, *args, **kwargs): print('fibonacci(%d) = %d' % (n, self.fibonacci(n)))
b8cc70280941653dd84982994ca145a6ff56eda9
reindex.py
reindex.py
import sys import argparse from elasticsearch import Elasticsearch from annotator.reindexer import Reindexer description = """ Reindex an elasticsearch index. WARNING: Documents that are created while reindexing may be lost! """ def main(argv): argparser = argparse.ArgumentParser(description=description) argparser.add_argument('old_index', help="Index to read from") argparser.add_argument('new_index', help="Index to write to") argparser.add_argument('--host', help="Elasticsearch server, host[:port]") argparser.add_argument('--alias', help="Alias for the new index") args = argparser.parse_args() host = args.host old_index = args.old_index new_index = args.new_index alias = args.alias conn = Elasticsearch([host]) reindexer = Reindexer(conn, interactive=True) reindexer.reindex(old_index, new_index) if alias: reindexer.alias(new_index, alias) if __name__ == '__main__': main(sys.argv)
import sys import argparse from elasticsearch import Elasticsearch from annotator.reindexer import Reindexer description = """ Reindex an elasticsearch index. WARNING: Documents that are created while reindexing may be lost! """ def main(argv): argparser = argparse.ArgumentParser(description=description) argparser.add_argument('old_index', help="Index to read from") argparser.add_argument('new_index', help="Index to write to") argparser.add_argument('--host', help="Elasticsearch server, host[:port]") argparser.add_argument('--alias', help="Alias for the new index") args = argparser.parse_args() host = args.host old_index = args.old_index new_index = args.new_index alias = args.alias if host: conn = Elasticsearch([host]) else: conn = Elasticsearch() reindexer = Reindexer(conn, interactive=True) reindexer.reindex(old_index, new_index) if alias: reindexer.alias(new_index, alias) if __name__ == '__main__': main(sys.argv)
Use default host when not specified
Use default host when not specified
Python
mit
nobita-isc/annotator-store,nobita-isc/annotator-store,nobita-isc/annotator-store,nobita-isc/annotator-store,openannotation/annotator-store,happybelly/annotator-store,ningyifan/annotator-store
import sys import argparse from elasticsearch import Elasticsearch from annotator.reindexer import Reindexer description = """ Reindex an elasticsearch index. WARNING: Documents that are created while reindexing may be lost! """ def main(argv): argparser = argparse.ArgumentParser(description=description) argparser.add_argument('old_index', help="Index to read from") argparser.add_argument('new_index', help="Index to write to") argparser.add_argument('--host', help="Elasticsearch server, host[:port]") argparser.add_argument('--alias', help="Alias for the new index") args = argparser.parse_args() host = args.host old_index = args.old_index new_index = args.new_index alias = args.alias conn = Elasticsearch([host]) reindexer = Reindexer(conn, interactive=True) reindexer.reindex(old_index, new_index) if alias: reindexer.alias(new_index, alias) if __name__ == '__main__': main(sys.argv) Use default host when not specified
import sys import argparse from elasticsearch import Elasticsearch from annotator.reindexer import Reindexer description = """ Reindex an elasticsearch index. WARNING: Documents that are created while reindexing may be lost! """ def main(argv): argparser = argparse.ArgumentParser(description=description) argparser.add_argument('old_index', help="Index to read from") argparser.add_argument('new_index', help="Index to write to") argparser.add_argument('--host', help="Elasticsearch server, host[:port]") argparser.add_argument('--alias', help="Alias for the new index") args = argparser.parse_args() host = args.host old_index = args.old_index new_index = args.new_index alias = args.alias if host: conn = Elasticsearch([host]) else: conn = Elasticsearch() reindexer = Reindexer(conn, interactive=True) reindexer.reindex(old_index, new_index) if alias: reindexer.alias(new_index, alias) if __name__ == '__main__': main(sys.argv)
<commit_before>import sys import argparse from elasticsearch import Elasticsearch from annotator.reindexer import Reindexer description = """ Reindex an elasticsearch index. WARNING: Documents that are created while reindexing may be lost! """ def main(argv): argparser = argparse.ArgumentParser(description=description) argparser.add_argument('old_index', help="Index to read from") argparser.add_argument('new_index', help="Index to write to") argparser.add_argument('--host', help="Elasticsearch server, host[:port]") argparser.add_argument('--alias', help="Alias for the new index") args = argparser.parse_args() host = args.host old_index = args.old_index new_index = args.new_index alias = args.alias conn = Elasticsearch([host]) reindexer = Reindexer(conn, interactive=True) reindexer.reindex(old_index, new_index) if alias: reindexer.alias(new_index, alias) if __name__ == '__main__': main(sys.argv) <commit_msg>Use default host when not specified<commit_after>
import sys import argparse from elasticsearch import Elasticsearch from annotator.reindexer import Reindexer description = """ Reindex an elasticsearch index. WARNING: Documents that are created while reindexing may be lost! """ def main(argv): argparser = argparse.ArgumentParser(description=description) argparser.add_argument('old_index', help="Index to read from") argparser.add_argument('new_index', help="Index to write to") argparser.add_argument('--host', help="Elasticsearch server, host[:port]") argparser.add_argument('--alias', help="Alias for the new index") args = argparser.parse_args() host = args.host old_index = args.old_index new_index = args.new_index alias = args.alias if host: conn = Elasticsearch([host]) else: conn = Elasticsearch() reindexer = Reindexer(conn, interactive=True) reindexer.reindex(old_index, new_index) if alias: reindexer.alias(new_index, alias) if __name__ == '__main__': main(sys.argv)
import sys import argparse from elasticsearch import Elasticsearch from annotator.reindexer import Reindexer description = """ Reindex an elasticsearch index. WARNING: Documents that are created while reindexing may be lost! """ def main(argv): argparser = argparse.ArgumentParser(description=description) argparser.add_argument('old_index', help="Index to read from") argparser.add_argument('new_index', help="Index to write to") argparser.add_argument('--host', help="Elasticsearch server, host[:port]") argparser.add_argument('--alias', help="Alias for the new index") args = argparser.parse_args() host = args.host old_index = args.old_index new_index = args.new_index alias = args.alias conn = Elasticsearch([host]) reindexer = Reindexer(conn, interactive=True) reindexer.reindex(old_index, new_index) if alias: reindexer.alias(new_index, alias) if __name__ == '__main__': main(sys.argv) Use default host when not specifiedimport sys import argparse from elasticsearch import Elasticsearch from annotator.reindexer import Reindexer description = """ Reindex an elasticsearch index. WARNING: Documents that are created while reindexing may be lost! """ def main(argv): argparser = argparse.ArgumentParser(description=description) argparser.add_argument('old_index', help="Index to read from") argparser.add_argument('new_index', help="Index to write to") argparser.add_argument('--host', help="Elasticsearch server, host[:port]") argparser.add_argument('--alias', help="Alias for the new index") args = argparser.parse_args() host = args.host old_index = args.old_index new_index = args.new_index alias = args.alias if host: conn = Elasticsearch([host]) else: conn = Elasticsearch() reindexer = Reindexer(conn, interactive=True) reindexer.reindex(old_index, new_index) if alias: reindexer.alias(new_index, alias) if __name__ == '__main__': main(sys.argv)
<commit_before>import sys import argparse from elasticsearch import Elasticsearch from annotator.reindexer import Reindexer description = """ Reindex an elasticsearch index. WARNING: Documents that are created while reindexing may be lost! """ def main(argv): argparser = argparse.ArgumentParser(description=description) argparser.add_argument('old_index', help="Index to read from") argparser.add_argument('new_index', help="Index to write to") argparser.add_argument('--host', help="Elasticsearch server, host[:port]") argparser.add_argument('--alias', help="Alias for the new index") args = argparser.parse_args() host = args.host old_index = args.old_index new_index = args.new_index alias = args.alias conn = Elasticsearch([host]) reindexer = Reindexer(conn, interactive=True) reindexer.reindex(old_index, new_index) if alias: reindexer.alias(new_index, alias) if __name__ == '__main__': main(sys.argv) <commit_msg>Use default host when not specified<commit_after>import sys import argparse from elasticsearch import Elasticsearch from annotator.reindexer import Reindexer description = """ Reindex an elasticsearch index. WARNING: Documents that are created while reindexing may be lost! """ def main(argv): argparser = argparse.ArgumentParser(description=description) argparser.add_argument('old_index', help="Index to read from") argparser.add_argument('new_index', help="Index to write to") argparser.add_argument('--host', help="Elasticsearch server, host[:port]") argparser.add_argument('--alias', help="Alias for the new index") args = argparser.parse_args() host = args.host old_index = args.old_index new_index = args.new_index alias = args.alias if host: conn = Elasticsearch([host]) else: conn = Elasticsearch() reindexer = Reindexer(conn, interactive=True) reindexer.reindex(old_index, new_index) if alias: reindexer.alias(new_index, alias) if __name__ == '__main__': main(sys.argv)
3ec325afca110e866a5b60e4e92a38738aee4906
graphene_django_extras/directives/__init__.py
graphene_django_extras/directives/__init__.py
# -*- coding: utf-8 -*- from graphql.type.directives import specified_directives as default_directives from .date import * from .list import * from .numbers import * from .string import * all_directives = ( # date DateGraphQLDirective, # list ShuffleGraphQLDirective, SampleGraphQLDirective, # numbers FloorGraphQLDirective, CeilGraphQLDirective, # string DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = [d() for d in all_directives] + default_directives
# -*- coding: utf-8 -*- from graphql.type.directives import specified_directives as default_directives from .date import DateGraphQLDirective from .list import ShuffleGraphQLDirective, SampleGraphQLDirective from .numbers import FloorGraphQLDirective, CeilGraphQLDirective from .string import ( DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = ( # date DateGraphQLDirective, # list ShuffleGraphQLDirective, SampleGraphQLDirective, # numbers FloorGraphQLDirective, CeilGraphQLDirective, # string DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = [d() for d in all_directives] + default_directives
Make minor improvements for CI.
Make minor improvements for CI.
Python
mit
eamigo86/graphene-django-extras
# -*- coding: utf-8 -*- from graphql.type.directives import specified_directives as default_directives from .date import * from .list import * from .numbers import * from .string import * all_directives = ( # date DateGraphQLDirective, # list ShuffleGraphQLDirective, SampleGraphQLDirective, # numbers FloorGraphQLDirective, CeilGraphQLDirective, # string DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = [d() for d in all_directives] + default_directives Make minor improvements for CI.
# -*- coding: utf-8 -*- from graphql.type.directives import specified_directives as default_directives from .date import DateGraphQLDirective from .list import ShuffleGraphQLDirective, SampleGraphQLDirective from .numbers import FloorGraphQLDirective, CeilGraphQLDirective from .string import ( DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = ( # date DateGraphQLDirective, # list ShuffleGraphQLDirective, SampleGraphQLDirective, # numbers FloorGraphQLDirective, CeilGraphQLDirective, # string DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = [d() for d in all_directives] + default_directives
<commit_before># -*- coding: utf-8 -*- from graphql.type.directives import specified_directives as default_directives from .date import * from .list import * from .numbers import * from .string import * all_directives = ( # date DateGraphQLDirective, # list ShuffleGraphQLDirective, SampleGraphQLDirective, # numbers FloorGraphQLDirective, CeilGraphQLDirective, # string DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = [d() for d in all_directives] + default_directives <commit_msg>Make minor improvements for CI.<commit_after>
# -*- coding: utf-8 -*- from graphql.type.directives import specified_directives as default_directives from .date import DateGraphQLDirective from .list import ShuffleGraphQLDirective, SampleGraphQLDirective from .numbers import FloorGraphQLDirective, CeilGraphQLDirective from .string import ( DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = ( # date DateGraphQLDirective, # list ShuffleGraphQLDirective, SampleGraphQLDirective, # numbers FloorGraphQLDirective, CeilGraphQLDirective, # string DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = [d() for d in all_directives] + default_directives
# -*- coding: utf-8 -*- from graphql.type.directives import specified_directives as default_directives from .date import * from .list import * from .numbers import * from .string import * all_directives = ( # date DateGraphQLDirective, # list ShuffleGraphQLDirective, SampleGraphQLDirective, # numbers FloorGraphQLDirective, CeilGraphQLDirective, # string DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = [d() for d in all_directives] + default_directives Make minor improvements for CI.# -*- coding: utf-8 -*- from graphql.type.directives import specified_directives as default_directives from .date import DateGraphQLDirective from .list import ShuffleGraphQLDirective, SampleGraphQLDirective from .numbers import FloorGraphQLDirective, CeilGraphQLDirective from .string import ( DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = ( # date DateGraphQLDirective, # list ShuffleGraphQLDirective, SampleGraphQLDirective, # numbers FloorGraphQLDirective, CeilGraphQLDirective, # string DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = [d() for d in all_directives] + default_directives
<commit_before># -*- coding: utf-8 -*- from graphql.type.directives import specified_directives as default_directives from .date import * from .list import * from .numbers import * from .string import * all_directives = ( # date DateGraphQLDirective, # list ShuffleGraphQLDirective, SampleGraphQLDirective, # numbers FloorGraphQLDirective, CeilGraphQLDirective, # string DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = [d() for d in all_directives] + default_directives <commit_msg>Make minor improvements for CI.<commit_after># -*- coding: utf-8 -*- from graphql.type.directives import specified_directives as default_directives from .date import DateGraphQLDirective from .list import ShuffleGraphQLDirective, SampleGraphQLDirective from .numbers import FloorGraphQLDirective, CeilGraphQLDirective from .string import ( DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = ( # date DateGraphQLDirective, # list ShuffleGraphQLDirective, SampleGraphQLDirective, # numbers FloorGraphQLDirective, CeilGraphQLDirective, # string DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = [d() for d in all_directives] + default_directives
3b6abde6b7deb662ef2c5b09f99b4a71baa62e4b
stock_planning/models/stock_move.py
stock_planning/models/stock_move.py
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models class StockMove(models.Model): _inherit = 'stock.move' def _find_moves_from_stock_planning( self, company, to_date, from_date=None, category=None, template=None, product=None, location_id=None, location_dest_id=None): cond = [('company_id', '=', company.id), ('date', '<=', to_date), ('state', 'not in', ('done', 'cancel'))] if from_date: cond.append(('date', '=>', from_date)) if product: cond.append(('product_id', '=', product.id)) if location_id: cond.append(('location_id', '=', location_id.id)) if location_dest_id: cond.append(('location_dest_id', '=', location_dest_id.id)) moves = self.search(cond) if category: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.categ_id.id == category.id) if template: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.id == template.id) return moves
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models class StockMove(models.Model): _inherit = 'stock.move' def _find_moves_from_stock_planning( self, company, to_date, from_date=None, category=None, template=None, product=None, location_id=None, location_dest_id=None): cond = [('company_id', '=', company.id), ('date', '<=', to_date), ('state', 'not in', ('done', 'cancel'))] if from_date: cond.append(('date', '>=', from_date)) if product: cond.append(('product_id', '=', product.id)) if location_id: cond.append(('location_id', '=', location_id.id)) if location_dest_id: cond.append(('location_dest_id', '=', location_dest_id.id)) moves = self.search(cond) if category: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.categ_id.id == category.id) if template: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.id == template.id) return moves
Fix condition cond.append(('date', '>=', from_date))
[FIX] stock_planning: Fix condition cond.append(('date', '>=', from_date))
Python
agpl-3.0
agaldona/odoomrp-utils,odoomrp/odoomrp-utils,Endika/odoomrp-utils,ddico/odoomrp-utils,oihane/odoomrp-utils,Eficent/odoomrp-utils,esthermm/odoomrp-utils,diagramsoftware/odoomrp-utils,Antiun/odoomrp-utils,Daniel-CA/odoomrp-utils
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models class StockMove(models.Model): _inherit = 'stock.move' def _find_moves_from_stock_planning( self, company, to_date, from_date=None, category=None, template=None, product=None, location_id=None, location_dest_id=None): cond = [('company_id', '=', company.id), ('date', '<=', to_date), ('state', 'not in', ('done', 'cancel'))] if from_date: cond.append(('date', '=>', from_date)) if product: cond.append(('product_id', '=', product.id)) if location_id: cond.append(('location_id', '=', location_id.id)) if location_dest_id: cond.append(('location_dest_id', '=', location_dest_id.id)) moves = self.search(cond) if category: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.categ_id.id == category.id) if template: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.id == template.id) return moves [FIX] stock_planning: Fix condition cond.append(('date', '>=', from_date))
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models class StockMove(models.Model): _inherit = 'stock.move' def _find_moves_from_stock_planning( self, company, to_date, from_date=None, category=None, template=None, product=None, location_id=None, location_dest_id=None): cond = [('company_id', '=', company.id), ('date', '<=', to_date), ('state', 'not in', ('done', 'cancel'))] if from_date: cond.append(('date', '>=', from_date)) if product: cond.append(('product_id', '=', product.id)) if location_id: cond.append(('location_id', '=', location_id.id)) if location_dest_id: cond.append(('location_dest_id', '=', location_dest_id.id)) moves = self.search(cond) if category: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.categ_id.id == category.id) if template: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.id == template.id) return moves
<commit_before># -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models class StockMove(models.Model): _inherit = 'stock.move' def _find_moves_from_stock_planning( self, company, to_date, from_date=None, category=None, template=None, product=None, location_id=None, location_dest_id=None): cond = [('company_id', '=', company.id), ('date', '<=', to_date), ('state', 'not in', ('done', 'cancel'))] if from_date: cond.append(('date', '=>', from_date)) if product: cond.append(('product_id', '=', product.id)) if location_id: cond.append(('location_id', '=', location_id.id)) if location_dest_id: cond.append(('location_dest_id', '=', location_dest_id.id)) moves = self.search(cond) if category: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.categ_id.id == category.id) if template: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.id == template.id) return moves <commit_msg>[FIX] stock_planning: Fix condition cond.append(('date', '>=', from_date))<commit_after>
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models class StockMove(models.Model): _inherit = 'stock.move' def _find_moves_from_stock_planning( self, company, to_date, from_date=None, category=None, template=None, product=None, location_id=None, location_dest_id=None): cond = [('company_id', '=', company.id), ('date', '<=', to_date), ('state', 'not in', ('done', 'cancel'))] if from_date: cond.append(('date', '>=', from_date)) if product: cond.append(('product_id', '=', product.id)) if location_id: cond.append(('location_id', '=', location_id.id)) if location_dest_id: cond.append(('location_dest_id', '=', location_dest_id.id)) moves = self.search(cond) if category: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.categ_id.id == category.id) if template: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.id == template.id) return moves
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models class StockMove(models.Model): _inherit = 'stock.move' def _find_moves_from_stock_planning( self, company, to_date, from_date=None, category=None, template=None, product=None, location_id=None, location_dest_id=None): cond = [('company_id', '=', company.id), ('date', '<=', to_date), ('state', 'not in', ('done', 'cancel'))] if from_date: cond.append(('date', '=>', from_date)) if product: cond.append(('product_id', '=', product.id)) if location_id: cond.append(('location_id', '=', location_id.id)) if location_dest_id: cond.append(('location_dest_id', '=', location_dest_id.id)) moves = self.search(cond) if category: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.categ_id.id == category.id) if template: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.id == template.id) return moves [FIX] stock_planning: Fix condition cond.append(('date', '>=', from_date))# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models class StockMove(models.Model): _inherit = 'stock.move' def _find_moves_from_stock_planning( self, company, to_date, from_date=None, category=None, template=None, product=None, location_id=None, location_dest_id=None): cond = [('company_id', '=', company.id), ('date', '<=', to_date), ('state', 'not in', ('done', 'cancel'))] if from_date: cond.append(('date', '>=', from_date)) if product: cond.append(('product_id', '=', product.id)) if location_id: cond.append(('location_id', '=', location_id.id)) if location_dest_id: cond.append(('location_dest_id', '=', location_dest_id.id)) moves = self.search(cond) if category: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.categ_id.id == category.id) if template: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.id == template.id) return moves
<commit_before># -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models class StockMove(models.Model): _inherit = 'stock.move' def _find_moves_from_stock_planning( self, company, to_date, from_date=None, category=None, template=None, product=None, location_id=None, location_dest_id=None): cond = [('company_id', '=', company.id), ('date', '<=', to_date), ('state', 'not in', ('done', 'cancel'))] if from_date: cond.append(('date', '=>', from_date)) if product: cond.append(('product_id', '=', product.id)) if location_id: cond.append(('location_id', '=', location_id.id)) if location_dest_id: cond.append(('location_dest_id', '=', location_dest_id.id)) moves = self.search(cond) if category: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.categ_id.id == category.id) if template: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.id == template.id) return moves <commit_msg>[FIX] stock_planning: Fix condition cond.append(('date', '>=', from_date))<commit_after># -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models class StockMove(models.Model): _inherit = 'stock.move' def _find_moves_from_stock_planning( self, company, to_date, from_date=None, category=None, template=None, product=None, location_id=None, location_dest_id=None): cond = [('company_id', '=', company.id), ('date', '<=', to_date), ('state', 'not in', ('done', 'cancel'))] if from_date: cond.append(('date', '>=', from_date)) if product: cond.append(('product_id', '=', product.id)) if location_id: cond.append(('location_id', '=', location_id.id)) if location_dest_id: cond.append(('location_dest_id', '=', location_dest_id.id)) moves = self.search(cond) if category: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.categ_id.id == category.id) if template: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.id == template.id) return moves
097cccec41d4455c73d586ef4506075f8c7c1004
amon/apps/notifications/opsgenie/sender.py
amon/apps/notifications/opsgenie/sender.py
import requests import json from amon.apps.notifications.models import notifications_model def send_opsgenie_notification(message=None, auth=None): sent = False url = "https://api.opsgenie.com/v1/json/alert" # Message is limited to 130 chars data = { 'apiKey': auth.get('api_key'), 'message': message, } data = json.dumps(data) error = None try: r = requests.post(url, data=data, timeout=5) except Exception as e: error = e return error
import requests import json from amon.apps.notifications.models import notifications_model def send_opsgenie_notification(message=None, auth=None): sent = False url = "https://api.opsgenie.com/v2/alerts" headers = { 'Authorization': 'GenieKey '+ auth.get('api_key'), 'Content-Type': 'application/json' } # Message is limited to 130 chars data = { 'message': message, } data = json.dumps(data) error = None try: r = requests.post(url, data=data, timeout=5, headers=headers) except Exception as e: error = e return error
Switch to OpsGenie API V2
Switch to OpsGenie API V2
Python
agpl-3.0
amonapp/amon,amonapp/amon,martinrusev/amonone,martinrusev/amonone,amonapp/amon,amonapp/amon,martinrusev/amonone,amonapp/amon,martinrusev/amonone
import requests import json from amon.apps.notifications.models import notifications_model def send_opsgenie_notification(message=None, auth=None): sent = False url = "https://api.opsgenie.com/v1/json/alert" # Message is limited to 130 chars data = { 'apiKey': auth.get('api_key'), 'message': message, } data = json.dumps(data) error = None try: r = requests.post(url, data=data, timeout=5) except Exception as e: error = e return errorSwitch to OpsGenie API V2
import requests import json from amon.apps.notifications.models import notifications_model def send_opsgenie_notification(message=None, auth=None): sent = False url = "https://api.opsgenie.com/v2/alerts" headers = { 'Authorization': 'GenieKey '+ auth.get('api_key'), 'Content-Type': 'application/json' } # Message is limited to 130 chars data = { 'message': message, } data = json.dumps(data) error = None try: r = requests.post(url, data=data, timeout=5, headers=headers) except Exception as e: error = e return error
<commit_before>import requests import json from amon.apps.notifications.models import notifications_model def send_opsgenie_notification(message=None, auth=None): sent = False url = "https://api.opsgenie.com/v1/json/alert" # Message is limited to 130 chars data = { 'apiKey': auth.get('api_key'), 'message': message, } data = json.dumps(data) error = None try: r = requests.post(url, data=data, timeout=5) except Exception as e: error = e return error<commit_msg>Switch to OpsGenie API V2<commit_after>
import requests import json from amon.apps.notifications.models import notifications_model def send_opsgenie_notification(message=None, auth=None): sent = False url = "https://api.opsgenie.com/v2/alerts" headers = { 'Authorization': 'GenieKey '+ auth.get('api_key'), 'Content-Type': 'application/json' } # Message is limited to 130 chars data = { 'message': message, } data = json.dumps(data) error = None try: r = requests.post(url, data=data, timeout=5, headers=headers) except Exception as e: error = e return error
import requests import json from amon.apps.notifications.models import notifications_model def send_opsgenie_notification(message=None, auth=None): sent = False url = "https://api.opsgenie.com/v1/json/alert" # Message is limited to 130 chars data = { 'apiKey': auth.get('api_key'), 'message': message, } data = json.dumps(data) error = None try: r = requests.post(url, data=data, timeout=5) except Exception as e: error = e return errorSwitch to OpsGenie API V2import requests import json from amon.apps.notifications.models import notifications_model def send_opsgenie_notification(message=None, auth=None): sent = False url = "https://api.opsgenie.com/v2/alerts" headers = { 'Authorization': 'GenieKey '+ auth.get('api_key'), 'Content-Type': 'application/json' } # Message is limited to 130 chars data = { 'message': message, } data = json.dumps(data) error = None try: r = requests.post(url, data=data, timeout=5, headers=headers) except Exception as e: error = e return error
<commit_before>import requests import json from amon.apps.notifications.models import notifications_model def send_opsgenie_notification(message=None, auth=None): sent = False url = "https://api.opsgenie.com/v1/json/alert" # Message is limited to 130 chars data = { 'apiKey': auth.get('api_key'), 'message': message, } data = json.dumps(data) error = None try: r = requests.post(url, data=data, timeout=5) except Exception as e: error = e return error<commit_msg>Switch to OpsGenie API V2<commit_after>import requests import json from amon.apps.notifications.models import notifications_model def send_opsgenie_notification(message=None, auth=None): sent = False url = "https://api.opsgenie.com/v2/alerts" headers = { 'Authorization': 'GenieKey '+ auth.get('api_key'), 'Content-Type': 'application/json' } # Message is limited to 130 chars data = { 'message': message, } data = json.dumps(data) error = None try: r = requests.post(url, data=data, timeout=5, headers=headers) except Exception as e: error = e return error
dc009d03369828cc5147f11a4b385c6959be6286
doitlive/termutils.py
doitlive/termutils.py
# -*- coding: utf-8 -*- import os import sys from contextlib import contextmanager from click._compat import isatty WIN = sys.platform.startswith("win") env = os.environ @contextmanager def raw_mode(): """ Enables terminal raw mode during the context. Note: Currently noop for Windows systems. Usage: :: with raw_mode(): do_some_stuff() """ if WIN: # No implementation for windows yet. yield # needed for the empty context manager to work else: # imports are placed here because this will fail under Windows import tty import termios if not isatty(sys.stdin): f = open("/dev/tty") fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) tty.setraw(fd) except termios.error: pass try: yield finally: # this block sets the terminal to sane mode again, # also in case an exception occured in the context manager try: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) # sys.stdout.flush() # not needed I think. if f is not None: f.close() except termios.error: pass def get_default_shell(): return env.get("DOITLIVE_INTERPRETER") or env.get("SHELL") or "/bin/bash"
# -*- coding: utf-8 -*- import os import sys from contextlib import contextmanager from click._compat import isatty WIN = sys.platform.startswith("win") env = os.environ @contextmanager def raw_mode(): """ Enables terminal raw mode during the context. Note: Currently noop for Windows systems. Usage: :: with raw_mode(): do_some_stuff() """ if WIN: # No implementation for windows yet. yield # needed for the empty context manager to work else: # imports are placed here because this will fail under Windows import tty import termios if not isatty(sys.stdin): f = open("/dev/tty") fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) tty.setraw(fd) except termios.error: pass try: yield finally: # this block sets the terminal to sane mode again, # also in case an exception occurred in the context manager try: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) # sys.stdout.flush() # not needed I think. if f is not None: f.close() except termios.error: pass def get_default_shell(): return env.get("DOITLIVE_INTERPRETER") or env.get("SHELL") or "/bin/bash"
Fix simple typo: occured -> occurred
Fix simple typo: occured -> occurred
Python
mit
sloria/doitlive,sloria/doitlive
# -*- coding: utf-8 -*- import os import sys from contextlib import contextmanager from click._compat import isatty WIN = sys.platform.startswith("win") env = os.environ @contextmanager def raw_mode(): """ Enables terminal raw mode during the context. Note: Currently noop for Windows systems. Usage: :: with raw_mode(): do_some_stuff() """ if WIN: # No implementation for windows yet. yield # needed for the empty context manager to work else: # imports are placed here because this will fail under Windows import tty import termios if not isatty(sys.stdin): f = open("/dev/tty") fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) tty.setraw(fd) except termios.error: pass try: yield finally: # this block sets the terminal to sane mode again, # also in case an exception occured in the context manager try: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) # sys.stdout.flush() # not needed I think. if f is not None: f.close() except termios.error: pass def get_default_shell(): return env.get("DOITLIVE_INTERPRETER") or env.get("SHELL") or "/bin/bash" Fix simple typo: occured -> occurred
# -*- coding: utf-8 -*- import os import sys from contextlib import contextmanager from click._compat import isatty WIN = sys.platform.startswith("win") env = os.environ @contextmanager def raw_mode(): """ Enables terminal raw mode during the context. Note: Currently noop for Windows systems. Usage: :: with raw_mode(): do_some_stuff() """ if WIN: # No implementation for windows yet. yield # needed for the empty context manager to work else: # imports are placed here because this will fail under Windows import tty import termios if not isatty(sys.stdin): f = open("/dev/tty") fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) tty.setraw(fd) except termios.error: pass try: yield finally: # this block sets the terminal to sane mode again, # also in case an exception occurred in the context manager try: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) # sys.stdout.flush() # not needed I think. if f is not None: f.close() except termios.error: pass def get_default_shell(): return env.get("DOITLIVE_INTERPRETER") or env.get("SHELL") or "/bin/bash"
<commit_before># -*- coding: utf-8 -*- import os import sys from contextlib import contextmanager from click._compat import isatty WIN = sys.platform.startswith("win") env = os.environ @contextmanager def raw_mode(): """ Enables terminal raw mode during the context. Note: Currently noop for Windows systems. Usage: :: with raw_mode(): do_some_stuff() """ if WIN: # No implementation for windows yet. yield # needed for the empty context manager to work else: # imports are placed here because this will fail under Windows import tty import termios if not isatty(sys.stdin): f = open("/dev/tty") fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) tty.setraw(fd) except termios.error: pass try: yield finally: # this block sets the terminal to sane mode again, # also in case an exception occured in the context manager try: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) # sys.stdout.flush() # not needed I think. if f is not None: f.close() except termios.error: pass def get_default_shell(): return env.get("DOITLIVE_INTERPRETER") or env.get("SHELL") or "/bin/bash" <commit_msg>Fix simple typo: occured -> occurred<commit_after>
# -*- coding: utf-8 -*- import os import sys from contextlib import contextmanager from click._compat import isatty WIN = sys.platform.startswith("win") env = os.environ @contextmanager def raw_mode(): """ Enables terminal raw mode during the context. Note: Currently noop for Windows systems. Usage: :: with raw_mode(): do_some_stuff() """ if WIN: # No implementation for windows yet. yield # needed for the empty context manager to work else: # imports are placed here because this will fail under Windows import tty import termios if not isatty(sys.stdin): f = open("/dev/tty") fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) tty.setraw(fd) except termios.error: pass try: yield finally: # this block sets the terminal to sane mode again, # also in case an exception occurred in the context manager try: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) # sys.stdout.flush() # not needed I think. if f is not None: f.close() except termios.error: pass def get_default_shell(): return env.get("DOITLIVE_INTERPRETER") or env.get("SHELL") or "/bin/bash"
# -*- coding: utf-8 -*- import os import sys from contextlib import contextmanager from click._compat import isatty WIN = sys.platform.startswith("win") env = os.environ @contextmanager def raw_mode(): """ Enables terminal raw mode during the context. Note: Currently noop for Windows systems. Usage: :: with raw_mode(): do_some_stuff() """ if WIN: # No implementation for windows yet. yield # needed for the empty context manager to work else: # imports are placed here because this will fail under Windows import tty import termios if not isatty(sys.stdin): f = open("/dev/tty") fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) tty.setraw(fd) except termios.error: pass try: yield finally: # this block sets the terminal to sane mode again, # also in case an exception occured in the context manager try: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) # sys.stdout.flush() # not needed I think. if f is not None: f.close() except termios.error: pass def get_default_shell(): return env.get("DOITLIVE_INTERPRETER") or env.get("SHELL") or "/bin/bash" Fix simple typo: occured -> occurred# -*- coding: utf-8 -*- import os import sys from contextlib import contextmanager from click._compat import isatty WIN = sys.platform.startswith("win") env = os.environ @contextmanager def raw_mode(): """ Enables terminal raw mode during the context. Note: Currently noop for Windows systems. Usage: :: with raw_mode(): do_some_stuff() """ if WIN: # No implementation for windows yet. yield # needed for the empty context manager to work else: # imports are placed here because this will fail under Windows import tty import termios if not isatty(sys.stdin): f = open("/dev/tty") fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) tty.setraw(fd) except termios.error: pass try: yield finally: # this block sets the terminal to sane mode again, # also in case an exception occurred in the context manager try: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) # sys.stdout.flush() # not needed I think. if f is not None: f.close() except termios.error: pass def get_default_shell(): return env.get("DOITLIVE_INTERPRETER") or env.get("SHELL") or "/bin/bash"
<commit_before># -*- coding: utf-8 -*- import os import sys from contextlib import contextmanager from click._compat import isatty WIN = sys.platform.startswith("win") env = os.environ @contextmanager def raw_mode(): """ Enables terminal raw mode during the context. Note: Currently noop for Windows systems. Usage: :: with raw_mode(): do_some_stuff() """ if WIN: # No implementation for windows yet. yield # needed for the empty context manager to work else: # imports are placed here because this will fail under Windows import tty import termios if not isatty(sys.stdin): f = open("/dev/tty") fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) tty.setraw(fd) except termios.error: pass try: yield finally: # this block sets the terminal to sane mode again, # also in case an exception occured in the context manager try: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) # sys.stdout.flush() # not needed I think. if f is not None: f.close() except termios.error: pass def get_default_shell(): return env.get("DOITLIVE_INTERPRETER") or env.get("SHELL") or "/bin/bash" <commit_msg>Fix simple typo: occured -> occurred<commit_after># -*- coding: utf-8 -*- import os import sys from contextlib import contextmanager from click._compat import isatty WIN = sys.platform.startswith("win") env = os.environ @contextmanager def raw_mode(): """ Enables terminal raw mode during the context. Note: Currently noop for Windows systems. Usage: :: with raw_mode(): do_some_stuff() """ if WIN: # No implementation for windows yet. yield # needed for the empty context manager to work else: # imports are placed here because this will fail under Windows import tty import termios if not isatty(sys.stdin): f = open("/dev/tty") fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) tty.setraw(fd) except termios.error: pass try: yield finally: # this block sets the terminal to sane mode again, # also in case an exception occurred in the context manager try: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) # sys.stdout.flush() # not needed I think. if f is not None: f.close() except termios.error: pass def get_default_shell(): return env.get("DOITLIVE_INTERPRETER") or env.get("SHELL") or "/bin/bash"
d45620531af6e68b5aad50e6e1ce6f172c79d5fa
l10n_ro_partner_create_by_vat/__manifest__.py
l10n_ro_partner_create_by_vat/__manifest__.py
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Romania - Partner Create by VAT", "category": "Localization", "summary": "Romania - Partner Create by VAT", "depends": ["base"], "data": ["views/res_partner_view.xml"], "license": "AGPL-3", "version": "13.0.1.0.0", "author": "OdooERP Romania," "Forest and Biomass Romania," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-romania", "installable": True, "development_status": "Mature", "maintainers": ["feketemihai"], }
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Romania - Partner Create by VAT", "category": "Localization", "summary": "Romania - Partner Create by VAT", "depends": ["base_vat"], "data": ["views/res_partner_view.xml"], "license": "AGPL-3", "version": "13.0.1.0.0", "author": "OdooERP Romania," "Forest and Biomass Romania," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-romania", "installable": True, "development_status": "Mature", "maintainers": ["feketemihai"], }
Improve code in l10n_ro_vat_on_payment and l10n_ro_stock.
Improve code in l10n_ro_vat_on_payment and l10n_ro_stock.
Python
agpl-3.0
OCA/l10n-romania,OCA/l10n-romania
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Romania - Partner Create by VAT", "category": "Localization", "summary": "Romania - Partner Create by VAT", "depends": ["base"], "data": ["views/res_partner_view.xml"], "license": "AGPL-3", "version": "13.0.1.0.0", "author": "OdooERP Romania," "Forest and Biomass Romania," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-romania", "installable": True, "development_status": "Mature", "maintainers": ["feketemihai"], } Improve code in l10n_ro_vat_on_payment and l10n_ro_stock.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Romania - Partner Create by VAT", "category": "Localization", "summary": "Romania - Partner Create by VAT", "depends": ["base_vat"], "data": ["views/res_partner_view.xml"], "license": "AGPL-3", "version": "13.0.1.0.0", "author": "OdooERP Romania," "Forest and Biomass Romania," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-romania", "installable": True, "development_status": "Mature", "maintainers": ["feketemihai"], }
<commit_before># License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Romania - Partner Create by VAT", "category": "Localization", "summary": "Romania - Partner Create by VAT", "depends": ["base"], "data": ["views/res_partner_view.xml"], "license": "AGPL-3", "version": "13.0.1.0.0", "author": "OdooERP Romania," "Forest and Biomass Romania," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-romania", "installable": True, "development_status": "Mature", "maintainers": ["feketemihai"], } <commit_msg>Improve code in l10n_ro_vat_on_payment and l10n_ro_stock.<commit_after>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Romania - Partner Create by VAT", "category": "Localization", "summary": "Romania - Partner Create by VAT", "depends": ["base_vat"], "data": ["views/res_partner_view.xml"], "license": "AGPL-3", "version": "13.0.1.0.0", "author": "OdooERP Romania," "Forest and Biomass Romania," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-romania", "installable": True, "development_status": "Mature", "maintainers": ["feketemihai"], }
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Romania - Partner Create by VAT", "category": "Localization", "summary": "Romania - Partner Create by VAT", "depends": ["base"], "data": ["views/res_partner_view.xml"], "license": "AGPL-3", "version": "13.0.1.0.0", "author": "OdooERP Romania," "Forest and Biomass Romania," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-romania", "installable": True, "development_status": "Mature", "maintainers": ["feketemihai"], } Improve code in l10n_ro_vat_on_payment and l10n_ro_stock.# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Romania - Partner Create by VAT", "category": "Localization", "summary": "Romania - Partner Create by VAT", "depends": ["base_vat"], "data": ["views/res_partner_view.xml"], "license": "AGPL-3", "version": "13.0.1.0.0", "author": "OdooERP Romania," "Forest and Biomass Romania," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-romania", "installable": True, "development_status": "Mature", "maintainers": ["feketemihai"], }
<commit_before># License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Romania - Partner Create by VAT", "category": "Localization", "summary": "Romania - Partner Create by VAT", "depends": ["base"], "data": ["views/res_partner_view.xml"], "license": "AGPL-3", "version": "13.0.1.0.0", "author": "OdooERP Romania," "Forest and Biomass Romania," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-romania", "installable": True, "development_status": "Mature", "maintainers": ["feketemihai"], } <commit_msg>Improve code in l10n_ro_vat_on_payment and l10n_ro_stock.<commit_after># License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Romania - Partner Create by VAT", "category": "Localization", "summary": "Romania - Partner Create by VAT", "depends": ["base_vat"], "data": ["views/res_partner_view.xml"], "license": "AGPL-3", "version": "13.0.1.0.0", "author": "OdooERP Romania," "Forest and Biomass Romania," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-romania", "installable": True, "development_status": "Mature", "maintainers": ["feketemihai"], }
dfaa49b31e8abd10456761110d0cadc1b7c7640d
zaqar/transport/wsgi/app.py
zaqar/transport/wsgi/app.py
# Copyright (c) 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """WSGI App for WSGI Containers This app should be used by external WSGI containers. For example: $ gunicorn zaqar.transport.wsgi.app:app NOTE: As for external containers, it is necessary to put config files in the standard paths. There's no common way to specify / pass configuration files to the WSGI app when it is called from other apps. """ from oslo_config import cfg from zaqar import bootstrap # Use the global CONF instance conf = cfg.CONF conf(project='zaqar', prog='zaqar-queues', args=[]) boot = bootstrap.Bootstrap(conf) conf.drivers.transport = 'wsgi' app = boot.transport.app
# Copyright (c) 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """WSGI App for WSGI Containers This app should be used by external WSGI containers. For example: $ gunicorn zaqar.transport.wsgi.app:app NOTE: As for external containers, it is necessary to put config files in the standard paths. There's no common way to specify / pass configuration files to the WSGI app when it is called from other apps. """ from oslo_config import cfg from oslo_log import log from zaqar import bootstrap # Use the global CONF instance conf = cfg.CONF log.register_options(conf) conf(project='zaqar', prog='zaqar-queues', args=[]) log.setup(conf, 'zaqar') boot = bootstrap.Bootstrap(conf) conf.drivers.transport = 'wsgi' app = boot.transport.app
Make the log work when deploy Zaqar with uwsgi
Make the log work when deploy Zaqar with uwsgi The zaqar-wsgi runs under uwsgi by devstack can't print any WARNING, DEBUG, ERROR or INFO log now. This path add the log initialization for uwsgi boot. Change-Id: Ifcd6be908442275d2acbde2562e593b2ca87b277 Cloese-bug: #1645492
Python
apache-2.0
openstack/zaqar,openstack/zaqar,openstack/zaqar,openstack/zaqar
# Copyright (c) 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """WSGI App for WSGI Containers This app should be used by external WSGI containers. For example: $ gunicorn zaqar.transport.wsgi.app:app NOTE: As for external containers, it is necessary to put config files in the standard paths. There's no common way to specify / pass configuration files to the WSGI app when it is called from other apps. """ from oslo_config import cfg from zaqar import bootstrap # Use the global CONF instance conf = cfg.CONF conf(project='zaqar', prog='zaqar-queues', args=[]) boot = bootstrap.Bootstrap(conf) conf.drivers.transport = 'wsgi' app = boot.transport.app Make the log work when deploy Zaqar with uwsgi The zaqar-wsgi runs under uwsgi by devstack can't print any WARNING, DEBUG, ERROR or INFO log now. This path add the log initialization for uwsgi boot. Change-Id: Ifcd6be908442275d2acbde2562e593b2ca87b277 Cloese-bug: #1645492
# Copyright (c) 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """WSGI App for WSGI Containers This app should be used by external WSGI containers. For example: $ gunicorn zaqar.transport.wsgi.app:app NOTE: As for external containers, it is necessary to put config files in the standard paths. There's no common way to specify / pass configuration files to the WSGI app when it is called from other apps. """ from oslo_config import cfg from oslo_log import log from zaqar import bootstrap # Use the global CONF instance conf = cfg.CONF log.register_options(conf) conf(project='zaqar', prog='zaqar-queues', args=[]) log.setup(conf, 'zaqar') boot = bootstrap.Bootstrap(conf) conf.drivers.transport = 'wsgi' app = boot.transport.app
<commit_before># Copyright (c) 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """WSGI App for WSGI Containers This app should be used by external WSGI containers. For example: $ gunicorn zaqar.transport.wsgi.app:app NOTE: As for external containers, it is necessary to put config files in the standard paths. There's no common way to specify / pass configuration files to the WSGI app when it is called from other apps. """ from oslo_config import cfg from zaqar import bootstrap # Use the global CONF instance conf = cfg.CONF conf(project='zaqar', prog='zaqar-queues', args=[]) boot = bootstrap.Bootstrap(conf) conf.drivers.transport = 'wsgi' app = boot.transport.app <commit_msg>Make the log work when deploy Zaqar with uwsgi The zaqar-wsgi runs under uwsgi by devstack can't print any WARNING, DEBUG, ERROR or INFO log now. This path add the log initialization for uwsgi boot. Change-Id: Ifcd6be908442275d2acbde2562e593b2ca87b277 Cloese-bug: #1645492<commit_after>
# Copyright (c) 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """WSGI App for WSGI Containers This app should be used by external WSGI containers. For example: $ gunicorn zaqar.transport.wsgi.app:app NOTE: As for external containers, it is necessary to put config files in the standard paths. There's no common way to specify / pass configuration files to the WSGI app when it is called from other apps. """ from oslo_config import cfg from oslo_log import log from zaqar import bootstrap # Use the global CONF instance conf = cfg.CONF log.register_options(conf) conf(project='zaqar', prog='zaqar-queues', args=[]) log.setup(conf, 'zaqar') boot = bootstrap.Bootstrap(conf) conf.drivers.transport = 'wsgi' app = boot.transport.app
# Copyright (c) 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """WSGI App for WSGI Containers This app should be used by external WSGI containers. For example: $ gunicorn zaqar.transport.wsgi.app:app NOTE: As for external containers, it is necessary to put config files in the standard paths. There's no common way to specify / pass configuration files to the WSGI app when it is called from other apps. """ from oslo_config import cfg from zaqar import bootstrap # Use the global CONF instance conf = cfg.CONF conf(project='zaqar', prog='zaqar-queues', args=[]) boot = bootstrap.Bootstrap(conf) conf.drivers.transport = 'wsgi' app = boot.transport.app Make the log work when deploy Zaqar with uwsgi The zaqar-wsgi runs under uwsgi by devstack can't print any WARNING, DEBUG, ERROR or INFO log now. This path add the log initialization for uwsgi boot. Change-Id: Ifcd6be908442275d2acbde2562e593b2ca87b277 Cloese-bug: #1645492# Copyright (c) 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """WSGI App for WSGI Containers This app should be used by external WSGI containers. For example: $ gunicorn zaqar.transport.wsgi.app:app NOTE: As for external containers, it is necessary to put config files in the standard paths. There's no common way to specify / pass configuration files to the WSGI app when it is called from other apps. """ from oslo_config import cfg from oslo_log import log from zaqar import bootstrap # Use the global CONF instance conf = cfg.CONF log.register_options(conf) conf(project='zaqar', prog='zaqar-queues', args=[]) log.setup(conf, 'zaqar') boot = bootstrap.Bootstrap(conf) conf.drivers.transport = 'wsgi' app = boot.transport.app
<commit_before># Copyright (c) 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """WSGI App for WSGI Containers This app should be used by external WSGI containers. For example: $ gunicorn zaqar.transport.wsgi.app:app NOTE: As for external containers, it is necessary to put config files in the standard paths. There's no common way to specify / pass configuration files to the WSGI app when it is called from other apps. """ from oslo_config import cfg from zaqar import bootstrap # Use the global CONF instance conf = cfg.CONF conf(project='zaqar', prog='zaqar-queues', args=[]) boot = bootstrap.Bootstrap(conf) conf.drivers.transport = 'wsgi' app = boot.transport.app <commit_msg>Make the log work when deploy Zaqar with uwsgi The zaqar-wsgi runs under uwsgi by devstack can't print any WARNING, DEBUG, ERROR or INFO log now. This path add the log initialization for uwsgi boot. Change-Id: Ifcd6be908442275d2acbde2562e593b2ca87b277 Cloese-bug: #1645492<commit_after># Copyright (c) 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """WSGI App for WSGI Containers This app should be used by external WSGI containers. For example: $ gunicorn zaqar.transport.wsgi.app:app NOTE: As for external containers, it is necessary to put config files in the standard paths. There's no common way to specify / pass configuration files to the WSGI app when it is called from other apps. """ from oslo_config import cfg from oslo_log import log from zaqar import bootstrap # Use the global CONF instance conf = cfg.CONF log.register_options(conf) conf(project='zaqar', prog='zaqar-queues', args=[]) log.setup(conf, 'zaqar') boot = bootstrap.Bootstrap(conf) conf.drivers.transport = 'wsgi' app = boot.transport.app
a25b03f83c7003ccea2eb554117e8fedc153e4fe
corgi/coerce.py
corgi/coerce.py
def listify(obj): if not isinstance(obj, list): return [obj] return obj def dictify(obj, key): if isinstance(obj, dict): return obj return {key: obj}
def listify(obj): if not isinstance(obj, list): return [obj] return obj def dictify(obj, key): if not isinstance(obj, dict): return {key: obj} return obj
Make dictify similar in flow to listify
Make dictify similar in flow to listify
Python
mit
log0ymxm/corgi
def listify(obj): if not isinstance(obj, list): return [obj] return obj def dictify(obj, key): if isinstance(obj, dict): return obj return {key: obj} Make dictify similar in flow to listify
def listify(obj): if not isinstance(obj, list): return [obj] return obj def dictify(obj, key): if not isinstance(obj, dict): return {key: obj} return obj
<commit_before>def listify(obj): if not isinstance(obj, list): return [obj] return obj def dictify(obj, key): if isinstance(obj, dict): return obj return {key: obj} <commit_msg>Make dictify similar in flow to listify<commit_after>
def listify(obj): if not isinstance(obj, list): return [obj] return obj def dictify(obj, key): if not isinstance(obj, dict): return {key: obj} return obj
def listify(obj): if not isinstance(obj, list): return [obj] return obj def dictify(obj, key): if isinstance(obj, dict): return obj return {key: obj} Make dictify similar in flow to listifydef listify(obj): if not isinstance(obj, list): return [obj] return obj def dictify(obj, key): if not isinstance(obj, dict): return {key: obj} return obj
<commit_before>def listify(obj): if not isinstance(obj, list): return [obj] return obj def dictify(obj, key): if isinstance(obj, dict): return obj return {key: obj} <commit_msg>Make dictify similar in flow to listify<commit_after>def listify(obj): if not isinstance(obj, list): return [obj] return obj def dictify(obj, key): if not isinstance(obj, dict): return {key: obj} return obj
25cd8afdfede8a522f8d0f08ee4678a2e9c46a4b
curious/commands/__init__.py
curious/commands/__init__.py
""" Commands helpers. """ import functools from curious.commands.command import Command def command(*args, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. """ def __inner(func): factory = functools.partial(Command, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func
""" Commands helpers. """ import functools from curious.commands.command import Command def command(*args, klass: type=Command, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. :param klass: The command class type to wrap the object in. """ def __inner(func): factory = functools.partial(klass, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func
Allow changing what object is returned from Command instances.
Allow changing what object is returned from Command instances.
Python
mit
SunDwarf/curious
""" Commands helpers. """ import functools from curious.commands.command import Command def command(*args, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. """ def __inner(func): factory = functools.partial(Command, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func Allow changing what object is returned from Command instances.
""" Commands helpers. """ import functools from curious.commands.command import Command def command(*args, klass: type=Command, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. :param klass: The command class type to wrap the object in. """ def __inner(func): factory = functools.partial(klass, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func
<commit_before>""" Commands helpers. """ import functools from curious.commands.command import Command def command(*args, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. """ def __inner(func): factory = functools.partial(Command, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func <commit_msg>Allow changing what object is returned from Command instances.<commit_after>
""" Commands helpers. """ import functools from curious.commands.command import Command def command(*args, klass: type=Command, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. :param klass: The command class type to wrap the object in. """ def __inner(func): factory = functools.partial(klass, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func
""" Commands helpers. """ import functools from curious.commands.command import Command def command(*args, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. """ def __inner(func): factory = functools.partial(Command, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func Allow changing what object is returned from Command instances.""" Commands helpers. """ import functools from curious.commands.command import Command def command(*args, klass: type=Command, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. :param klass: The command class type to wrap the object in. """ def __inner(func): factory = functools.partial(klass, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func
<commit_before>""" Commands helpers. """ import functools from curious.commands.command import Command def command(*args, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. """ def __inner(func): factory = functools.partial(Command, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func <commit_msg>Allow changing what object is returned from Command instances.<commit_after>""" Commands helpers. """ import functools from curious.commands.command import Command def command(*args, klass: type=Command, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. :param klass: The command class type to wrap the object in. """ def __inner(func): factory = functools.partial(klass, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func
79c449473f5ee0c349df8f4de4577e61776bd337
lily/utils/models/factories.py
lily/utils/models/factories.py
from factory.declarations import LazyAttribute from factory.django import DjangoModelFactory from factory.fuzzy import FuzzyChoice from faker.factory import Factory from .models import EmailAddress, PhoneNumber, Address, PHONE_TYPE_CHOICES, ExternalAppLink from lily.utils.countries import COUNTRIES faker = Factory.create('nl_NL') class PhoneNumberFactory(DjangoModelFactory): number = LazyAttribute(lambda o: faker.phone_number()) type = FuzzyChoice(dict(PHONE_TYPE_CHOICES).keys()) class Meta: model = PhoneNumber class AddressFactory(DjangoModelFactory): address = LazyAttribute(lambda o: faker.street_address()) postal_code = LazyAttribute(lambda o: faker.postcode()) city = LazyAttribute(lambda o: faker.city()) state_province = LazyAttribute(lambda o: faker.province()) country = FuzzyChoice(dict(COUNTRIES).keys()) type = FuzzyChoice(dict(Address.ADDRESS_TYPE_CHOICES).keys()) class Meta: model = Address class EmailAddressFactory(DjangoModelFactory): email_address = LazyAttribute(lambda o: faker.safe_email()) status = EmailAddress.PRIMARY_STATUS class Meta: model = EmailAddress class ExternalAppLinkFactory(DjangoModelFactory): name = LazyAttribute(lambda o: faker.company()) url = LazyAttribute(lambda o: faker.url()) class Meta: model = ExternalAppLink
import unicodedata from factory.declarations import LazyAttribute from factory.django import DjangoModelFactory from factory.fuzzy import FuzzyChoice from faker.factory import Factory from .models import EmailAddress, PhoneNumber, Address, PHONE_TYPE_CHOICES, ExternalAppLink from lily.utils.countries import COUNTRIES faker = Factory.create('nl_NL') class PhoneNumberFactory(DjangoModelFactory): number = LazyAttribute(lambda o: faker.phone_number()) type = FuzzyChoice(dict(PHONE_TYPE_CHOICES).keys()) class Meta: model = PhoneNumber class AddressFactory(DjangoModelFactory): address = LazyAttribute(lambda o: faker.street_address()) postal_code = LazyAttribute(lambda o: faker.postcode()) city = LazyAttribute(lambda o: faker.city()) state_province = LazyAttribute(lambda o: faker.province()) country = FuzzyChoice(dict(COUNTRIES).keys()) type = FuzzyChoice(dict(Address.ADDRESS_TYPE_CHOICES).keys()) class Meta: model = Address class EmailAddressFactory(DjangoModelFactory): email_address = LazyAttribute(lambda o: unicodedata.normalize('NFD', faker.safe_email()).encode('ascii', 'ignore')) status = EmailAddress.PRIMARY_STATUS class Meta: model = EmailAddress class ExternalAppLinkFactory(DjangoModelFactory): name = LazyAttribute(lambda o: faker.company()) url = LazyAttribute(lambda o: faker.url()) class Meta: model = ExternalAppLink
Fix tests generating invalid email addresses
LILY-1809: Fix tests generating invalid email addresses
Python
agpl-3.0
HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily
from factory.declarations import LazyAttribute from factory.django import DjangoModelFactory from factory.fuzzy import FuzzyChoice from faker.factory import Factory from .models import EmailAddress, PhoneNumber, Address, PHONE_TYPE_CHOICES, ExternalAppLink from lily.utils.countries import COUNTRIES faker = Factory.create('nl_NL') class PhoneNumberFactory(DjangoModelFactory): number = LazyAttribute(lambda o: faker.phone_number()) type = FuzzyChoice(dict(PHONE_TYPE_CHOICES).keys()) class Meta: model = PhoneNumber class AddressFactory(DjangoModelFactory): address = LazyAttribute(lambda o: faker.street_address()) postal_code = LazyAttribute(lambda o: faker.postcode()) city = LazyAttribute(lambda o: faker.city()) state_province = LazyAttribute(lambda o: faker.province()) country = FuzzyChoice(dict(COUNTRIES).keys()) type = FuzzyChoice(dict(Address.ADDRESS_TYPE_CHOICES).keys()) class Meta: model = Address class EmailAddressFactory(DjangoModelFactory): email_address = LazyAttribute(lambda o: faker.safe_email()) status = EmailAddress.PRIMARY_STATUS class Meta: model = EmailAddress class ExternalAppLinkFactory(DjangoModelFactory): name = LazyAttribute(lambda o: faker.company()) url = LazyAttribute(lambda o: faker.url()) class Meta: model = ExternalAppLink LILY-1809: Fix tests generating invalid email addresses
import unicodedata from factory.declarations import LazyAttribute from factory.django import DjangoModelFactory from factory.fuzzy import FuzzyChoice from faker.factory import Factory from .models import EmailAddress, PhoneNumber, Address, PHONE_TYPE_CHOICES, ExternalAppLink from lily.utils.countries import COUNTRIES faker = Factory.create('nl_NL') class PhoneNumberFactory(DjangoModelFactory): number = LazyAttribute(lambda o: faker.phone_number()) type = FuzzyChoice(dict(PHONE_TYPE_CHOICES).keys()) class Meta: model = PhoneNumber class AddressFactory(DjangoModelFactory): address = LazyAttribute(lambda o: faker.street_address()) postal_code = LazyAttribute(lambda o: faker.postcode()) city = LazyAttribute(lambda o: faker.city()) state_province = LazyAttribute(lambda o: faker.province()) country = FuzzyChoice(dict(COUNTRIES).keys()) type = FuzzyChoice(dict(Address.ADDRESS_TYPE_CHOICES).keys()) class Meta: model = Address class EmailAddressFactory(DjangoModelFactory): email_address = LazyAttribute(lambda o: unicodedata.normalize('NFD', faker.safe_email()).encode('ascii', 'ignore')) status = EmailAddress.PRIMARY_STATUS class Meta: model = EmailAddress class ExternalAppLinkFactory(DjangoModelFactory): name = LazyAttribute(lambda o: faker.company()) url = LazyAttribute(lambda o: faker.url()) class Meta: model = ExternalAppLink
<commit_before>from factory.declarations import LazyAttribute from factory.django import DjangoModelFactory from factory.fuzzy import FuzzyChoice from faker.factory import Factory from .models import EmailAddress, PhoneNumber, Address, PHONE_TYPE_CHOICES, ExternalAppLink from lily.utils.countries import COUNTRIES faker = Factory.create('nl_NL') class PhoneNumberFactory(DjangoModelFactory): number = LazyAttribute(lambda o: faker.phone_number()) type = FuzzyChoice(dict(PHONE_TYPE_CHOICES).keys()) class Meta: model = PhoneNumber class AddressFactory(DjangoModelFactory): address = LazyAttribute(lambda o: faker.street_address()) postal_code = LazyAttribute(lambda o: faker.postcode()) city = LazyAttribute(lambda o: faker.city()) state_province = LazyAttribute(lambda o: faker.province()) country = FuzzyChoice(dict(COUNTRIES).keys()) type = FuzzyChoice(dict(Address.ADDRESS_TYPE_CHOICES).keys()) class Meta: model = Address class EmailAddressFactory(DjangoModelFactory): email_address = LazyAttribute(lambda o: faker.safe_email()) status = EmailAddress.PRIMARY_STATUS class Meta: model = EmailAddress class ExternalAppLinkFactory(DjangoModelFactory): name = LazyAttribute(lambda o: faker.company()) url = LazyAttribute(lambda o: faker.url()) class Meta: model = ExternalAppLink <commit_msg>LILY-1809: Fix tests generating invalid email addresses<commit_after>
import unicodedata from factory.declarations import LazyAttribute from factory.django import DjangoModelFactory from factory.fuzzy import FuzzyChoice from faker.factory import Factory from .models import EmailAddress, PhoneNumber, Address, PHONE_TYPE_CHOICES, ExternalAppLink from lily.utils.countries import COUNTRIES faker = Factory.create('nl_NL') class PhoneNumberFactory(DjangoModelFactory): number = LazyAttribute(lambda o: faker.phone_number()) type = FuzzyChoice(dict(PHONE_TYPE_CHOICES).keys()) class Meta: model = PhoneNumber class AddressFactory(DjangoModelFactory): address = LazyAttribute(lambda o: faker.street_address()) postal_code = LazyAttribute(lambda o: faker.postcode()) city = LazyAttribute(lambda o: faker.city()) state_province = LazyAttribute(lambda o: faker.province()) country = FuzzyChoice(dict(COUNTRIES).keys()) type = FuzzyChoice(dict(Address.ADDRESS_TYPE_CHOICES).keys()) class Meta: model = Address class EmailAddressFactory(DjangoModelFactory): email_address = LazyAttribute(lambda o: unicodedata.normalize('NFD', faker.safe_email()).encode('ascii', 'ignore')) status = EmailAddress.PRIMARY_STATUS class Meta: model = EmailAddress class ExternalAppLinkFactory(DjangoModelFactory): name = LazyAttribute(lambda o: faker.company()) url = LazyAttribute(lambda o: faker.url()) class Meta: model = ExternalAppLink
from factory.declarations import LazyAttribute from factory.django import DjangoModelFactory from factory.fuzzy import FuzzyChoice from faker.factory import Factory from .models import EmailAddress, PhoneNumber, Address, PHONE_TYPE_CHOICES, ExternalAppLink from lily.utils.countries import COUNTRIES faker = Factory.create('nl_NL') class PhoneNumberFactory(DjangoModelFactory): number = LazyAttribute(lambda o: faker.phone_number()) type = FuzzyChoice(dict(PHONE_TYPE_CHOICES).keys()) class Meta: model = PhoneNumber class AddressFactory(DjangoModelFactory): address = LazyAttribute(lambda o: faker.street_address()) postal_code = LazyAttribute(lambda o: faker.postcode()) city = LazyAttribute(lambda o: faker.city()) state_province = LazyAttribute(lambda o: faker.province()) country = FuzzyChoice(dict(COUNTRIES).keys()) type = FuzzyChoice(dict(Address.ADDRESS_TYPE_CHOICES).keys()) class Meta: model = Address class EmailAddressFactory(DjangoModelFactory): email_address = LazyAttribute(lambda o: faker.safe_email()) status = EmailAddress.PRIMARY_STATUS class Meta: model = EmailAddress class ExternalAppLinkFactory(DjangoModelFactory): name = LazyAttribute(lambda o: faker.company()) url = LazyAttribute(lambda o: faker.url()) class Meta: model = ExternalAppLink LILY-1809: Fix tests generating invalid email addressesimport unicodedata from factory.declarations import LazyAttribute from factory.django import DjangoModelFactory from factory.fuzzy import FuzzyChoice from faker.factory import Factory from .models import EmailAddress, PhoneNumber, Address, PHONE_TYPE_CHOICES, ExternalAppLink from lily.utils.countries import COUNTRIES faker = Factory.create('nl_NL') class PhoneNumberFactory(DjangoModelFactory): number = LazyAttribute(lambda o: faker.phone_number()) type = FuzzyChoice(dict(PHONE_TYPE_CHOICES).keys()) class Meta: model = PhoneNumber class AddressFactory(DjangoModelFactory): address = LazyAttribute(lambda o: faker.street_address()) postal_code = LazyAttribute(lambda o: faker.postcode()) city = LazyAttribute(lambda o: faker.city()) state_province = LazyAttribute(lambda o: faker.province()) country = FuzzyChoice(dict(COUNTRIES).keys()) type = FuzzyChoice(dict(Address.ADDRESS_TYPE_CHOICES).keys()) class Meta: model = Address class EmailAddressFactory(DjangoModelFactory): email_address = LazyAttribute(lambda o: unicodedata.normalize('NFD', faker.safe_email()).encode('ascii', 'ignore')) status = EmailAddress.PRIMARY_STATUS class Meta: model = EmailAddress class ExternalAppLinkFactory(DjangoModelFactory): name = LazyAttribute(lambda o: faker.company()) url = LazyAttribute(lambda o: faker.url()) class Meta: model = ExternalAppLink
<commit_before>from factory.declarations import LazyAttribute from factory.django import DjangoModelFactory from factory.fuzzy import FuzzyChoice from faker.factory import Factory from .models import EmailAddress, PhoneNumber, Address, PHONE_TYPE_CHOICES, ExternalAppLink from lily.utils.countries import COUNTRIES faker = Factory.create('nl_NL') class PhoneNumberFactory(DjangoModelFactory): number = LazyAttribute(lambda o: faker.phone_number()) type = FuzzyChoice(dict(PHONE_TYPE_CHOICES).keys()) class Meta: model = PhoneNumber class AddressFactory(DjangoModelFactory): address = LazyAttribute(lambda o: faker.street_address()) postal_code = LazyAttribute(lambda o: faker.postcode()) city = LazyAttribute(lambda o: faker.city()) state_province = LazyAttribute(lambda o: faker.province()) country = FuzzyChoice(dict(COUNTRIES).keys()) type = FuzzyChoice(dict(Address.ADDRESS_TYPE_CHOICES).keys()) class Meta: model = Address class EmailAddressFactory(DjangoModelFactory): email_address = LazyAttribute(lambda o: faker.safe_email()) status = EmailAddress.PRIMARY_STATUS class Meta: model = EmailAddress class ExternalAppLinkFactory(DjangoModelFactory): name = LazyAttribute(lambda o: faker.company()) url = LazyAttribute(lambda o: faker.url()) class Meta: model = ExternalAppLink <commit_msg>LILY-1809: Fix tests generating invalid email addresses<commit_after>import unicodedata from factory.declarations import LazyAttribute from factory.django import DjangoModelFactory from factory.fuzzy import FuzzyChoice from faker.factory import Factory from .models import EmailAddress, PhoneNumber, Address, PHONE_TYPE_CHOICES, ExternalAppLink from lily.utils.countries import COUNTRIES faker = Factory.create('nl_NL') class PhoneNumberFactory(DjangoModelFactory): number = LazyAttribute(lambda o: faker.phone_number()) type = FuzzyChoice(dict(PHONE_TYPE_CHOICES).keys()) class Meta: model = PhoneNumber class AddressFactory(DjangoModelFactory): address = LazyAttribute(lambda o: faker.street_address()) postal_code = LazyAttribute(lambda o: faker.postcode()) city = LazyAttribute(lambda o: faker.city()) state_province = LazyAttribute(lambda o: faker.province()) country = FuzzyChoice(dict(COUNTRIES).keys()) type = FuzzyChoice(dict(Address.ADDRESS_TYPE_CHOICES).keys()) class Meta: model = Address class EmailAddressFactory(DjangoModelFactory): email_address = LazyAttribute(lambda o: unicodedata.normalize('NFD', faker.safe_email()).encode('ascii', 'ignore')) status = EmailAddress.PRIMARY_STATUS class Meta: model = EmailAddress class ExternalAppLinkFactory(DjangoModelFactory): name = LazyAttribute(lambda o: faker.company()) url = LazyAttribute(lambda o: faker.url()) class Meta: model = ExternalAppLink
b8cacab927c5b98285f15ae4d400b9577dbacef6
openstack_dashboard/dashboards/admin/dashboard.py
openstack_dashboard/dashboards/admin/dashboard.py
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.utils.translation import ugettext_lazy as _ from openstack_auth import utils import horizon from django.conf import settings class Admin(horizon.Dashboard): name = _("Admin") slug = "admin" if getattr(settings, 'POLICY_CHECK_FUNCTION', None): policy_rules = (('identity', 'admin_required'), ('image', 'context_is_admin'), ('volume', 'context_is_admin'), ('compute', 'context_is_admin'), ('network', 'context_is_admin'), ('orchestration', 'context_is_admin'), ('telemetry', 'context_is_admin'),) else: permissions = (tuple(utils.get_admin_permissions()),) horizon.register(Admin)
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.utils.translation import ugettext_lazy as _ from openstack_auth import utils import horizon from django.conf import settings class Admin(horizon.Dashboard): name = _("Admin") slug = "admin" if getattr(settings, 'POLICY_CHECK_FUNCTION', None): policy_rules = (('identity', 'admin_required'), ('image', 'context_is_admin'), ('volume', 'context_is_admin'), ('compute', 'context_is_admin'), ('network', 'context_is_admin'), ('orchestration', 'context_is_admin'),) else: permissions = (tuple(utils.get_admin_permissions()),) horizon.register(Admin)
Remove broken telemetry policy check
Remove broken telemetry policy check The reference to telemetry policy is no longer needed as well as broken causing the admin dashboard to show up inappropriately. Closes-Bug: #1643009 Change-Id: I07406f5d6c23b0fcc34df00a29b573ffc2c900e7
Python
apache-2.0
yeming233/horizon,ChameleonCloud/horizon,noironetworks/horizon,ChameleonCloud/horizon,noironetworks/horizon,NeCTAR-RC/horizon,noironetworks/horizon,BiznetGIO/horizon,BiznetGIO/horizon,yeming233/horizon,NeCTAR-RC/horizon,BiznetGIO/horizon,openstack/horizon,BiznetGIO/horizon,ChameleonCloud/horizon,openstack/horizon,ChameleonCloud/horizon,yeming233/horizon,noironetworks/horizon,NeCTAR-RC/horizon,openstack/horizon,yeming233/horizon,NeCTAR-RC/horizon,openstack/horizon
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.utils.translation import ugettext_lazy as _ from openstack_auth import utils import horizon from django.conf import settings class Admin(horizon.Dashboard): name = _("Admin") slug = "admin" if getattr(settings, 'POLICY_CHECK_FUNCTION', None): policy_rules = (('identity', 'admin_required'), ('image', 'context_is_admin'), ('volume', 'context_is_admin'), ('compute', 'context_is_admin'), ('network', 'context_is_admin'), ('orchestration', 'context_is_admin'), ('telemetry', 'context_is_admin'),) else: permissions = (tuple(utils.get_admin_permissions()),) horizon.register(Admin) Remove broken telemetry policy check The reference to telemetry policy is no longer needed as well as broken causing the admin dashboard to show up inappropriately. Closes-Bug: #1643009 Change-Id: I07406f5d6c23b0fcc34df00a29b573ffc2c900e7
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.utils.translation import ugettext_lazy as _ from openstack_auth import utils import horizon from django.conf import settings class Admin(horizon.Dashboard): name = _("Admin") slug = "admin" if getattr(settings, 'POLICY_CHECK_FUNCTION', None): policy_rules = (('identity', 'admin_required'), ('image', 'context_is_admin'), ('volume', 'context_is_admin'), ('compute', 'context_is_admin'), ('network', 'context_is_admin'), ('orchestration', 'context_is_admin'),) else: permissions = (tuple(utils.get_admin_permissions()),) horizon.register(Admin)
<commit_before># Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.utils.translation import ugettext_lazy as _ from openstack_auth import utils import horizon from django.conf import settings class Admin(horizon.Dashboard): name = _("Admin") slug = "admin" if getattr(settings, 'POLICY_CHECK_FUNCTION', None): policy_rules = (('identity', 'admin_required'), ('image', 'context_is_admin'), ('volume', 'context_is_admin'), ('compute', 'context_is_admin'), ('network', 'context_is_admin'), ('orchestration', 'context_is_admin'), ('telemetry', 'context_is_admin'),) else: permissions = (tuple(utils.get_admin_permissions()),) horizon.register(Admin) <commit_msg>Remove broken telemetry policy check The reference to telemetry policy is no longer needed as well as broken causing the admin dashboard to show up inappropriately. Closes-Bug: #1643009 Change-Id: I07406f5d6c23b0fcc34df00a29b573ffc2c900e7<commit_after>
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.utils.translation import ugettext_lazy as _ from openstack_auth import utils import horizon from django.conf import settings class Admin(horizon.Dashboard): name = _("Admin") slug = "admin" if getattr(settings, 'POLICY_CHECK_FUNCTION', None): policy_rules = (('identity', 'admin_required'), ('image', 'context_is_admin'), ('volume', 'context_is_admin'), ('compute', 'context_is_admin'), ('network', 'context_is_admin'), ('orchestration', 'context_is_admin'),) else: permissions = (tuple(utils.get_admin_permissions()),) horizon.register(Admin)
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.utils.translation import ugettext_lazy as _ from openstack_auth import utils import horizon from django.conf import settings class Admin(horizon.Dashboard): name = _("Admin") slug = "admin" if getattr(settings, 'POLICY_CHECK_FUNCTION', None): policy_rules = (('identity', 'admin_required'), ('image', 'context_is_admin'), ('volume', 'context_is_admin'), ('compute', 'context_is_admin'), ('network', 'context_is_admin'), ('orchestration', 'context_is_admin'), ('telemetry', 'context_is_admin'),) else: permissions = (tuple(utils.get_admin_permissions()),) horizon.register(Admin) Remove broken telemetry policy check The reference to telemetry policy is no longer needed as well as broken causing the admin dashboard to show up inappropriately. Closes-Bug: #1643009 Change-Id: I07406f5d6c23b0fcc34df00a29b573ffc2c900e7# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.utils.translation import ugettext_lazy as _ from openstack_auth import utils import horizon from django.conf import settings class Admin(horizon.Dashboard): name = _("Admin") slug = "admin" if getattr(settings, 'POLICY_CHECK_FUNCTION', None): policy_rules = (('identity', 'admin_required'), ('image', 'context_is_admin'), ('volume', 'context_is_admin'), ('compute', 'context_is_admin'), ('network', 'context_is_admin'), ('orchestration', 'context_is_admin'),) else: permissions = (tuple(utils.get_admin_permissions()),) horizon.register(Admin)
<commit_before># Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.utils.translation import ugettext_lazy as _ from openstack_auth import utils import horizon from django.conf import settings class Admin(horizon.Dashboard): name = _("Admin") slug = "admin" if getattr(settings, 'POLICY_CHECK_FUNCTION', None): policy_rules = (('identity', 'admin_required'), ('image', 'context_is_admin'), ('volume', 'context_is_admin'), ('compute', 'context_is_admin'), ('network', 'context_is_admin'), ('orchestration', 'context_is_admin'), ('telemetry', 'context_is_admin'),) else: permissions = (tuple(utils.get_admin_permissions()),) horizon.register(Admin) <commit_msg>Remove broken telemetry policy check The reference to telemetry policy is no longer needed as well as broken causing the admin dashboard to show up inappropriately. Closes-Bug: #1643009 Change-Id: I07406f5d6c23b0fcc34df00a29b573ffc2c900e7<commit_after># Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.utils.translation import ugettext_lazy as _ from openstack_auth import utils import horizon from django.conf import settings class Admin(horizon.Dashboard): name = _("Admin") slug = "admin" if getattr(settings, 'POLICY_CHECK_FUNCTION', None): policy_rules = (('identity', 'admin_required'), ('image', 'context_is_admin'), ('volume', 'context_is_admin'), ('compute', 'context_is_admin'), ('network', 'context_is_admin'), ('orchestration', 'context_is_admin'),) else: permissions = (tuple(utils.get_admin_permissions()),) horizon.register(Admin)
ce4923461b0f9202ec6ca9ccdbbc5b700018ba18
src/adhocracy/lib/helpers/adhocracy_service.py
src/adhocracy/lib/helpers/adhocracy_service.py
import requests from pylons import config class RESTAPI(object): """Helper to work with the adhocarcy_service rest api (adhocracy_kotti.mediacenter, adhocracy_kotti.staticpages, plone). """ session = requests.Session() def __init__(self): self.api_token = config.get('adhocracy_service.rest_api_token', '') self.api_address = config.get('adhocracy_service.rest_api_address', '') self.headers = {"X-API-Token": self.api_token} def staticpages_get(self, languages): request = requests.Request("GET", url='%s%s' % ( self.api_address, "staticpages", ), params={ 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare()) def staticpage_get(self, path, languages): request = requests.Request("GET", url='%s%s/%s' % ( self.api_address, "staticpages", path, ), params={ 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare())
import requests from pylons import config class RESTAPI(object): """Helper to work with the adhocarcy_service rest api (adhocracy_kotti.mediacenter, adhocracy_kotti.staticpages, plone). """ session = requests.Session() def __init__(self): self.api_token = config.get('adhocracy_service.rest_api_token', '') self.api_address = config.get('adhocracy_service.rest_api_address', '') self.headers = {"X-API-Token": self.api_token} def staticpages_get(self, languages): request = requests.Request("GET", url='%s%s' % ( self.api_address, "staticpages", ), params={ 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare()) def staticpage_get(self, path, languages): request = requests.Request("GET", url='%s%s' % ( self.api_address, 'staticpages/single', ), params={ 'path': path, 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare())
Change API to get single external static page
Adhocracy-service: Change API to get single external static page
Python
agpl-3.0
liqd/adhocracy,alkadis/vcv,phihag/adhocracy,DanielNeugebauer/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,alkadis/vcv,alkadis/vcv,liqd/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,liqd/adhocracy,alkadis/vcv,phihag/adhocracy
import requests from pylons import config class RESTAPI(object): """Helper to work with the adhocarcy_service rest api (adhocracy_kotti.mediacenter, adhocracy_kotti.staticpages, plone). """ session = requests.Session() def __init__(self): self.api_token = config.get('adhocracy_service.rest_api_token', '') self.api_address = config.get('adhocracy_service.rest_api_address', '') self.headers = {"X-API-Token": self.api_token} def staticpages_get(self, languages): request = requests.Request("GET", url='%s%s' % ( self.api_address, "staticpages", ), params={ 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare()) def staticpage_get(self, path, languages): request = requests.Request("GET", url='%s%s/%s' % ( self.api_address, "staticpages", path, ), params={ 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare()) Adhocracy-service: Change API to get single external static page
import requests from pylons import config class RESTAPI(object): """Helper to work with the adhocarcy_service rest api (adhocracy_kotti.mediacenter, adhocracy_kotti.staticpages, plone). """ session = requests.Session() def __init__(self): self.api_token = config.get('adhocracy_service.rest_api_token', '') self.api_address = config.get('adhocracy_service.rest_api_address', '') self.headers = {"X-API-Token": self.api_token} def staticpages_get(self, languages): request = requests.Request("GET", url='%s%s' % ( self.api_address, "staticpages", ), params={ 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare()) def staticpage_get(self, path, languages): request = requests.Request("GET", url='%s%s' % ( self.api_address, 'staticpages/single', ), params={ 'path': path, 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare())
<commit_before>import requests from pylons import config class RESTAPI(object): """Helper to work with the adhocarcy_service rest api (adhocracy_kotti.mediacenter, adhocracy_kotti.staticpages, plone). """ session = requests.Session() def __init__(self): self.api_token = config.get('adhocracy_service.rest_api_token', '') self.api_address = config.get('adhocracy_service.rest_api_address', '') self.headers = {"X-API-Token": self.api_token} def staticpages_get(self, languages): request = requests.Request("GET", url='%s%s' % ( self.api_address, "staticpages", ), params={ 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare()) def staticpage_get(self, path, languages): request = requests.Request("GET", url='%s%s/%s' % ( self.api_address, "staticpages", path, ), params={ 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare()) <commit_msg>Adhocracy-service: Change API to get single external static page<commit_after>
import requests from pylons import config class RESTAPI(object): """Helper to work with the adhocarcy_service rest api (adhocracy_kotti.mediacenter, adhocracy_kotti.staticpages, plone). """ session = requests.Session() def __init__(self): self.api_token = config.get('adhocracy_service.rest_api_token', '') self.api_address = config.get('adhocracy_service.rest_api_address', '') self.headers = {"X-API-Token": self.api_token} def staticpages_get(self, languages): request = requests.Request("GET", url='%s%s' % ( self.api_address, "staticpages", ), params={ 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare()) def staticpage_get(self, path, languages): request = requests.Request("GET", url='%s%s' % ( self.api_address, 'staticpages/single', ), params={ 'path': path, 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare())
import requests from pylons import config class RESTAPI(object): """Helper to work with the adhocarcy_service rest api (adhocracy_kotti.mediacenter, adhocracy_kotti.staticpages, plone). """ session = requests.Session() def __init__(self): self.api_token = config.get('adhocracy_service.rest_api_token', '') self.api_address = config.get('adhocracy_service.rest_api_address', '') self.headers = {"X-API-Token": self.api_token} def staticpages_get(self, languages): request = requests.Request("GET", url='%s%s' % ( self.api_address, "staticpages", ), params={ 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare()) def staticpage_get(self, path, languages): request = requests.Request("GET", url='%s%s/%s' % ( self.api_address, "staticpages", path, ), params={ 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare()) Adhocracy-service: Change API to get single external static pageimport requests from pylons import config class RESTAPI(object): """Helper to work with the adhocarcy_service rest api (adhocracy_kotti.mediacenter, adhocracy_kotti.staticpages, plone). """ session = requests.Session() def __init__(self): self.api_token = config.get('adhocracy_service.rest_api_token', '') self.api_address = config.get('adhocracy_service.rest_api_address', '') self.headers = {"X-API-Token": self.api_token} def staticpages_get(self, languages): request = requests.Request("GET", url='%s%s' % ( self.api_address, "staticpages", ), params={ 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare()) def staticpage_get(self, path, languages): request = requests.Request("GET", url='%s%s' % ( self.api_address, 'staticpages/single', ), params={ 'path': path, 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare())
<commit_before>import requests from pylons import config class RESTAPI(object): """Helper to work with the adhocarcy_service rest api (adhocracy_kotti.mediacenter, adhocracy_kotti.staticpages, plone). """ session = requests.Session() def __init__(self): self.api_token = config.get('adhocracy_service.rest_api_token', '') self.api_address = config.get('adhocracy_service.rest_api_address', '') self.headers = {"X-API-Token": self.api_token} def staticpages_get(self, languages): request = requests.Request("GET", url='%s%s' % ( self.api_address, "staticpages", ), params={ 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare()) def staticpage_get(self, path, languages): request = requests.Request("GET", url='%s%s/%s' % ( self.api_address, "staticpages", path, ), params={ 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare()) <commit_msg>Adhocracy-service: Change API to get single external static page<commit_after>import requests from pylons import config class RESTAPI(object): """Helper to work with the adhocarcy_service rest api (adhocracy_kotti.mediacenter, adhocracy_kotti.staticpages, plone). """ session = requests.Session() def __init__(self): self.api_token = config.get('adhocracy_service.rest_api_token', '') self.api_address = config.get('adhocracy_service.rest_api_address', '') self.headers = {"X-API-Token": self.api_token} def staticpages_get(self, languages): request = requests.Request("GET", url='%s%s' % ( self.api_address, "staticpages", ), params={ 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare()) def staticpage_get(self, path, languages): request = requests.Request("GET", url='%s%s' % ( self.api_address, 'staticpages/single', ), params={ 'path': path, 'lang': languages, }, headers=self.headers) return self.session.send(request.prepare())
d5007da66f8fb179d3cefd1668d767d4e9a3d9d5
TitanicData.py
TitanicData.py
# coding=utf-8 # Import necessary packages (Pandas, NumPy, etc.) import pandas as pd import numpy as np # Set file paths for Titanic data (Source: Kaggle) filepath_train = 'Data/train.csv' filepath_test = 'Data/test.csv' # Load train/test datasets as Pandas DataFrames df_train = pd.read_csv('Data/train.csv', index_col='PassengerId') df_test = pd.read_csv('Data/test.csv', index_col='PassengerId')
# coding=utf-8 # Import necessary packages (Pandas, NumPy, etc.) import pandas as pd import numpy as np # Set file paths for Titanic data (Source: Kaggle) filepath_train = 'Data/train.csv' filepath_test = 'Data/test.csv' # Load train/test datasets as Pandas DataFrames df_train = pd.read_csv('Data/train.csv', index_col='PassengerId') df_test = pd.read_csv('Data/test.csv', index_col='PassengerId') # Assign dataset labels as a new column df_train['Dataset'] = 'Train' df_test['Dataset'] = 'Test' # Create a combined DataFrame by merging train/test sets df_combined = pd.concat([df_train, df_test], axis=0)
Add Combined DataFrame by Merging Train/Test Sets
Add Combined DataFrame by Merging Train/Test Sets Before merging, a new column was assigned to both sets with discrete values ['Train'/'Test'] that correspond to the set an observation is inclusive of.
Python
mit
vnaidu/kaggle-titanic
# coding=utf-8 # Import necessary packages (Pandas, NumPy, etc.) import pandas as pd import numpy as np # Set file paths for Titanic data (Source: Kaggle) filepath_train = 'Data/train.csv' filepath_test = 'Data/test.csv' # Load train/test datasets as Pandas DataFrames df_train = pd.read_csv('Data/train.csv', index_col='PassengerId') df_test = pd.read_csv('Data/test.csv', index_col='PassengerId') Add Combined DataFrame by Merging Train/Test Sets Before merging, a new column was assigned to both sets with discrete values ['Train'/'Test'] that correspond to the set an observation is inclusive of.
# coding=utf-8 # Import necessary packages (Pandas, NumPy, etc.) import pandas as pd import numpy as np # Set file paths for Titanic data (Source: Kaggle) filepath_train = 'Data/train.csv' filepath_test = 'Data/test.csv' # Load train/test datasets as Pandas DataFrames df_train = pd.read_csv('Data/train.csv', index_col='PassengerId') df_test = pd.read_csv('Data/test.csv', index_col='PassengerId') # Assign dataset labels as a new column df_train['Dataset'] = 'Train' df_test['Dataset'] = 'Test' # Create a combined DataFrame by merging train/test sets df_combined = pd.concat([df_train, df_test], axis=0)
<commit_before># coding=utf-8 # Import necessary packages (Pandas, NumPy, etc.) import pandas as pd import numpy as np # Set file paths for Titanic data (Source: Kaggle) filepath_train = 'Data/train.csv' filepath_test = 'Data/test.csv' # Load train/test datasets as Pandas DataFrames df_train = pd.read_csv('Data/train.csv', index_col='PassengerId') df_test = pd.read_csv('Data/test.csv', index_col='PassengerId') <commit_msg>Add Combined DataFrame by Merging Train/Test Sets Before merging, a new column was assigned to both sets with discrete values ['Train'/'Test'] that correspond to the set an observation is inclusive of.<commit_after>
# coding=utf-8 # Import necessary packages (Pandas, NumPy, etc.) import pandas as pd import numpy as np # Set file paths for Titanic data (Source: Kaggle) filepath_train = 'Data/train.csv' filepath_test = 'Data/test.csv' # Load train/test datasets as Pandas DataFrames df_train = pd.read_csv('Data/train.csv', index_col='PassengerId') df_test = pd.read_csv('Data/test.csv', index_col='PassengerId') # Assign dataset labels as a new column df_train['Dataset'] = 'Train' df_test['Dataset'] = 'Test' # Create a combined DataFrame by merging train/test sets df_combined = pd.concat([df_train, df_test], axis=0)
# coding=utf-8 # Import necessary packages (Pandas, NumPy, etc.) import pandas as pd import numpy as np # Set file paths for Titanic data (Source: Kaggle) filepath_train = 'Data/train.csv' filepath_test = 'Data/test.csv' # Load train/test datasets as Pandas DataFrames df_train = pd.read_csv('Data/train.csv', index_col='PassengerId') df_test = pd.read_csv('Data/test.csv', index_col='PassengerId') Add Combined DataFrame by Merging Train/Test Sets Before merging, a new column was assigned to both sets with discrete values ['Train'/'Test'] that correspond to the set an observation is inclusive of.# coding=utf-8 # Import necessary packages (Pandas, NumPy, etc.) import pandas as pd import numpy as np # Set file paths for Titanic data (Source: Kaggle) filepath_train = 'Data/train.csv' filepath_test = 'Data/test.csv' # Load train/test datasets as Pandas DataFrames df_train = pd.read_csv('Data/train.csv', index_col='PassengerId') df_test = pd.read_csv('Data/test.csv', index_col='PassengerId') # Assign dataset labels as a new column df_train['Dataset'] = 'Train' df_test['Dataset'] = 'Test' # Create a combined DataFrame by merging train/test sets df_combined = pd.concat([df_train, df_test], axis=0)
<commit_before># coding=utf-8 # Import necessary packages (Pandas, NumPy, etc.) import pandas as pd import numpy as np # Set file paths for Titanic data (Source: Kaggle) filepath_train = 'Data/train.csv' filepath_test = 'Data/test.csv' # Load train/test datasets as Pandas DataFrames df_train = pd.read_csv('Data/train.csv', index_col='PassengerId') df_test = pd.read_csv('Data/test.csv', index_col='PassengerId') <commit_msg>Add Combined DataFrame by Merging Train/Test Sets Before merging, a new column was assigned to both sets with discrete values ['Train'/'Test'] that correspond to the set an observation is inclusive of.<commit_after># coding=utf-8 # Import necessary packages (Pandas, NumPy, etc.) import pandas as pd import numpy as np # Set file paths for Titanic data (Source: Kaggle) filepath_train = 'Data/train.csv' filepath_test = 'Data/test.csv' # Load train/test datasets as Pandas DataFrames df_train = pd.read_csv('Data/train.csv', index_col='PassengerId') df_test = pd.read_csv('Data/test.csv', index_col='PassengerId') # Assign dataset labels as a new column df_train['Dataset'] = 'Train' df_test['Dataset'] = 'Test' # Create a combined DataFrame by merging train/test sets df_combined = pd.concat([df_train, df_test], axis=0)
ad6d981cfbb9af0b02b40346548eb37631538016
poradnia/users/migrations/0007_migrate_avatars.py
poradnia/users/migrations/0007_migrate_avatars.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def migrate_avatar(apps, schema_editor): Avatar = apps.get_model("avatar", "Avatar") for avatar in Avatar.objects.filter(primary=True).all(): avatar.user.picture = avatar.avatar avatar.user.save() avatar.save() class Migration(migrations.Migration): dependencies = [ ('users', '0006_user_picture'), ('avatar', '0001_initial') ] operations = [ migrations.RunPython(migrate_avatar) ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models, migrations if 'avatar' in settings.INSTALLED_APPS: def migrate_avatar(apps, schema_editor): Avatar = apps.get_model("avatar", "Avatar") for avatar in Avatar.objects.filter(primary=True).all(): avatar.user.picture = avatar.avatar avatar.user.save() avatar.save() class Migration(migrations.Migration): dependencies = [ ('users', '0006_user_picture'), ('avatar', '0001_initial') ] operations = [ migrations.RunPython(migrate_avatar) ] else: class Migration(migrations.Migration): dependencies = [('users', '0006_user_picture'), ] operations = []
Fix migrations after django-avatar drop
Fix migrations after django-avatar drop
Python
mit
watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,watchdogpolska/poradnia,rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def migrate_avatar(apps, schema_editor): Avatar = apps.get_model("avatar", "Avatar") for avatar in Avatar.objects.filter(primary=True).all(): avatar.user.picture = avatar.avatar avatar.user.save() avatar.save() class Migration(migrations.Migration): dependencies = [ ('users', '0006_user_picture'), ('avatar', '0001_initial') ] operations = [ migrations.RunPython(migrate_avatar) ] Fix migrations after django-avatar drop
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models, migrations if 'avatar' in settings.INSTALLED_APPS: def migrate_avatar(apps, schema_editor): Avatar = apps.get_model("avatar", "Avatar") for avatar in Avatar.objects.filter(primary=True).all(): avatar.user.picture = avatar.avatar avatar.user.save() avatar.save() class Migration(migrations.Migration): dependencies = [ ('users', '0006_user_picture'), ('avatar', '0001_initial') ] operations = [ migrations.RunPython(migrate_avatar) ] else: class Migration(migrations.Migration): dependencies = [('users', '0006_user_picture'), ] operations = []
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def migrate_avatar(apps, schema_editor): Avatar = apps.get_model("avatar", "Avatar") for avatar in Avatar.objects.filter(primary=True).all(): avatar.user.picture = avatar.avatar avatar.user.save() avatar.save() class Migration(migrations.Migration): dependencies = [ ('users', '0006_user_picture'), ('avatar', '0001_initial') ] operations = [ migrations.RunPython(migrate_avatar) ] <commit_msg>Fix migrations after django-avatar drop<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models, migrations if 'avatar' in settings.INSTALLED_APPS: def migrate_avatar(apps, schema_editor): Avatar = apps.get_model("avatar", "Avatar") for avatar in Avatar.objects.filter(primary=True).all(): avatar.user.picture = avatar.avatar avatar.user.save() avatar.save() class Migration(migrations.Migration): dependencies = [ ('users', '0006_user_picture'), ('avatar', '0001_initial') ] operations = [ migrations.RunPython(migrate_avatar) ] else: class Migration(migrations.Migration): dependencies = [('users', '0006_user_picture'), ] operations = []
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def migrate_avatar(apps, schema_editor): Avatar = apps.get_model("avatar", "Avatar") for avatar in Avatar.objects.filter(primary=True).all(): avatar.user.picture = avatar.avatar avatar.user.save() avatar.save() class Migration(migrations.Migration): dependencies = [ ('users', '0006_user_picture'), ('avatar', '0001_initial') ] operations = [ migrations.RunPython(migrate_avatar) ] Fix migrations after django-avatar drop# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models, migrations if 'avatar' in settings.INSTALLED_APPS: def migrate_avatar(apps, schema_editor): Avatar = apps.get_model("avatar", "Avatar") for avatar in Avatar.objects.filter(primary=True).all(): avatar.user.picture = avatar.avatar avatar.user.save() avatar.save() class Migration(migrations.Migration): dependencies = [ ('users', '0006_user_picture'), ('avatar', '0001_initial') ] operations = [ migrations.RunPython(migrate_avatar) ] else: class Migration(migrations.Migration): dependencies = [('users', '0006_user_picture'), ] operations = []
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def migrate_avatar(apps, schema_editor): Avatar = apps.get_model("avatar", "Avatar") for avatar in Avatar.objects.filter(primary=True).all(): avatar.user.picture = avatar.avatar avatar.user.save() avatar.save() class Migration(migrations.Migration): dependencies = [ ('users', '0006_user_picture'), ('avatar', '0001_initial') ] operations = [ migrations.RunPython(migrate_avatar) ] <commit_msg>Fix migrations after django-avatar drop<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models, migrations if 'avatar' in settings.INSTALLED_APPS: def migrate_avatar(apps, schema_editor): Avatar = apps.get_model("avatar", "Avatar") for avatar in Avatar.objects.filter(primary=True).all(): avatar.user.picture = avatar.avatar avatar.user.save() avatar.save() class Migration(migrations.Migration): dependencies = [ ('users', '0006_user_picture'), ('avatar', '0001_initial') ] operations = [ migrations.RunPython(migrate_avatar) ] else: class Migration(migrations.Migration): dependencies = [('users', '0006_user_picture'), ] operations = []
9c9a33869747223952b4a999a5a14354ffb3e540
contrib/examples/actions/pythonactions/forloop_parse_github_repos.py
contrib/examples/actions/pythonactions/forloop_parse_github_repos.py
from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: return (False, "Could not parse data: {}".format(e.message)) return (True, output)
from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: raise Exception("Could not parse data: {}".format(e.message)) return (True, output)
Throw exception instead of returning false.
Throw exception instead of returning false.
Python
apache-2.0
StackStorm/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,StackStorm/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2,nzlosh/st2,nzlosh/st2,StackStorm/st2
from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: return (False, "Could not parse data: {}".format(e.message)) return (True, output) Throw exception instead of returning false.
from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: raise Exception("Could not parse data: {}".format(e.message)) return (True, output)
<commit_before>from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: return (False, "Could not parse data: {}".format(e.message)) return (True, output) <commit_msg>Throw exception instead of returning false.<commit_after>
from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: raise Exception("Could not parse data: {}".format(e.message)) return (True, output)
from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: return (False, "Could not parse data: {}".format(e.message)) return (True, output) Throw exception instead of returning false.from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: raise Exception("Could not parse data: {}".format(e.message)) return (True, output)
<commit_before>from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: return (False, "Could not parse data: {}".format(e.message)) return (True, output) <commit_msg>Throw exception instead of returning false.<commit_after>from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: raise Exception("Could not parse data: {}".format(e.message)) return (True, output)
99899f753ff9697f926389efe688c1ae2088c4c4
kpi/management/commands/wait_for_database.py
kpi/management/commands/wait_for_database.py
# coding: utf-8 import time from django.core.management.base import BaseCommand, CommandError from django.db import connection from django.db.utils import OperationalError class Command(BaseCommand): help = ( 'Repeatedly attempt to connect to the default database, exiting ' 'silently once the connection succeeds, or with an error if a ' 'connection cannot be established' ) def add_arguments(self, parser): parser.add_argument( '--retries', default=5, type=int, help=( 'Try this many times before giving up, waiting 2 seconds ' 'between each attempt' ), ) def handle(self, *args, **options): for _ in range(options.get('retries')): try: with connection.cursor() as cursor: return except OperationalError as e: if str(e).strip().endswith('does not exist'): # OK for our purposes if the database doesn't exist; # knowing that proves we were able to connect return time.sleep(2) raise CommandError('Retries exceeded; failed to connect')
# coding: utf-8 import time from django.core.management.base import BaseCommand, CommandError from django.db import connection from django.db.utils import OperationalError class Command(BaseCommand): help = ( 'Repeatedly attempt to connect to the default database, exiting ' 'silently once the connection succeeds, or with an error if a ' 'connection cannot be established' ) def add_arguments(self, parser): parser.add_argument( '--retries', default=5, type=int, help=( 'Try this many times before giving up, waiting 2 seconds ' 'between each attempt' ), ) def handle(self, *args, **options): for _ in range(options.get('retries')): try: with connection.cursor() as cursor: return except OperationalError as e: if str(e).strip().endswith('does not exist'): # OK for our purposes if the database doesn't exist; # knowing that proves we were able to connect return time.sleep(2) raise CommandError( 'Retries exceeded; failed to connect to default database' )
Make database connection error more descriptive
Make database connection error more descriptive
Python
agpl-3.0
kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi
# coding: utf-8 import time from django.core.management.base import BaseCommand, CommandError from django.db import connection from django.db.utils import OperationalError class Command(BaseCommand): help = ( 'Repeatedly attempt to connect to the default database, exiting ' 'silently once the connection succeeds, or with an error if a ' 'connection cannot be established' ) def add_arguments(self, parser): parser.add_argument( '--retries', default=5, type=int, help=( 'Try this many times before giving up, waiting 2 seconds ' 'between each attempt' ), ) def handle(self, *args, **options): for _ in range(options.get('retries')): try: with connection.cursor() as cursor: return except OperationalError as e: if str(e).strip().endswith('does not exist'): # OK for our purposes if the database doesn't exist; # knowing that proves we were able to connect return time.sleep(2) raise CommandError('Retries exceeded; failed to connect') Make database connection error more descriptive
# coding: utf-8 import time from django.core.management.base import BaseCommand, CommandError from django.db import connection from django.db.utils import OperationalError class Command(BaseCommand): help = ( 'Repeatedly attempt to connect to the default database, exiting ' 'silently once the connection succeeds, or with an error if a ' 'connection cannot be established' ) def add_arguments(self, parser): parser.add_argument( '--retries', default=5, type=int, help=( 'Try this many times before giving up, waiting 2 seconds ' 'between each attempt' ), ) def handle(self, *args, **options): for _ in range(options.get('retries')): try: with connection.cursor() as cursor: return except OperationalError as e: if str(e).strip().endswith('does not exist'): # OK for our purposes if the database doesn't exist; # knowing that proves we were able to connect return time.sleep(2) raise CommandError( 'Retries exceeded; failed to connect to default database' )
<commit_before># coding: utf-8 import time from django.core.management.base import BaseCommand, CommandError from django.db import connection from django.db.utils import OperationalError class Command(BaseCommand): help = ( 'Repeatedly attempt to connect to the default database, exiting ' 'silently once the connection succeeds, or with an error if a ' 'connection cannot be established' ) def add_arguments(self, parser): parser.add_argument( '--retries', default=5, type=int, help=( 'Try this many times before giving up, waiting 2 seconds ' 'between each attempt' ), ) def handle(self, *args, **options): for _ in range(options.get('retries')): try: with connection.cursor() as cursor: return except OperationalError as e: if str(e).strip().endswith('does not exist'): # OK for our purposes if the database doesn't exist; # knowing that proves we were able to connect return time.sleep(2) raise CommandError('Retries exceeded; failed to connect') <commit_msg>Make database connection error more descriptive<commit_after>
# coding: utf-8 import time from django.core.management.base import BaseCommand, CommandError from django.db import connection from django.db.utils import OperationalError class Command(BaseCommand): help = ( 'Repeatedly attempt to connect to the default database, exiting ' 'silently once the connection succeeds, or with an error if a ' 'connection cannot be established' ) def add_arguments(self, parser): parser.add_argument( '--retries', default=5, type=int, help=( 'Try this many times before giving up, waiting 2 seconds ' 'between each attempt' ), ) def handle(self, *args, **options): for _ in range(options.get('retries')): try: with connection.cursor() as cursor: return except OperationalError as e: if str(e).strip().endswith('does not exist'): # OK for our purposes if the database doesn't exist; # knowing that proves we were able to connect return time.sleep(2) raise CommandError( 'Retries exceeded; failed to connect to default database' )
# coding: utf-8 import time from django.core.management.base import BaseCommand, CommandError from django.db import connection from django.db.utils import OperationalError class Command(BaseCommand): help = ( 'Repeatedly attempt to connect to the default database, exiting ' 'silently once the connection succeeds, or with an error if a ' 'connection cannot be established' ) def add_arguments(self, parser): parser.add_argument( '--retries', default=5, type=int, help=( 'Try this many times before giving up, waiting 2 seconds ' 'between each attempt' ), ) def handle(self, *args, **options): for _ in range(options.get('retries')): try: with connection.cursor() as cursor: return except OperationalError as e: if str(e).strip().endswith('does not exist'): # OK for our purposes if the database doesn't exist; # knowing that proves we were able to connect return time.sleep(2) raise CommandError('Retries exceeded; failed to connect') Make database connection error more descriptive# coding: utf-8 import time from django.core.management.base import BaseCommand, CommandError from django.db import connection from django.db.utils import OperationalError class Command(BaseCommand): help = ( 'Repeatedly attempt to connect to the default database, exiting ' 'silently once the connection succeeds, or with an error if a ' 'connection cannot be established' ) def add_arguments(self, parser): parser.add_argument( '--retries', default=5, type=int, help=( 'Try this many times before giving up, waiting 2 seconds ' 'between each attempt' ), ) def handle(self, *args, **options): for _ in range(options.get('retries')): try: with connection.cursor() as cursor: return except OperationalError as e: if str(e).strip().endswith('does not exist'): # OK for our purposes if the database doesn't exist; # knowing that proves we were able to connect return time.sleep(2) raise CommandError( 'Retries exceeded; failed to connect to default database' )
<commit_before># coding: utf-8 import time from django.core.management.base import BaseCommand, CommandError from django.db import connection from django.db.utils import OperationalError class Command(BaseCommand): help = ( 'Repeatedly attempt to connect to the default database, exiting ' 'silently once the connection succeeds, or with an error if a ' 'connection cannot be established' ) def add_arguments(self, parser): parser.add_argument( '--retries', default=5, type=int, help=( 'Try this many times before giving up, waiting 2 seconds ' 'between each attempt' ), ) def handle(self, *args, **options): for _ in range(options.get('retries')): try: with connection.cursor() as cursor: return except OperationalError as e: if str(e).strip().endswith('does not exist'): # OK for our purposes if the database doesn't exist; # knowing that proves we were able to connect return time.sleep(2) raise CommandError('Retries exceeded; failed to connect') <commit_msg>Make database connection error more descriptive<commit_after># coding: utf-8 import time from django.core.management.base import BaseCommand, CommandError from django.db import connection from django.db.utils import OperationalError class Command(BaseCommand): help = ( 'Repeatedly attempt to connect to the default database, exiting ' 'silently once the connection succeeds, or with an error if a ' 'connection cannot be established' ) def add_arguments(self, parser): parser.add_argument( '--retries', default=5, type=int, help=( 'Try this many times before giving up, waiting 2 seconds ' 'between each attempt' ), ) def handle(self, *args, **options): for _ in range(options.get('retries')): try: with connection.cursor() as cursor: return except OperationalError as e: if str(e).strip().endswith('does not exist'): # OK for our purposes if the database doesn't exist; # knowing that proves we were able to connect return time.sleep(2) raise CommandError( 'Retries exceeded; failed to connect to default database' )
0da53cf2fcdc37574bebfe538778fffdae58e516
examples/delete_old_files.py
examples/delete_old_files.py
#!/bin/python # installation: # pip install pytz pyuploadcare~=2.1.0 import pytz from datetime import timedelta, datetime import time from pyuploadcare import conf from pyuploadcare.api_resources import FileList, FilesStorage MAX_LIFETIME = 30 # days conf.pub_key = 'demopublickey' conf.secret = 'demoprivatekey' dt_cutoff = datetime.now(pytz.utc) - timedelta(days=MAX_LIFETIME) if __name__ == '__main__': print 'Selecting files to be deleted...' uuid_list = [f.uuid for f in FileList(starting_point=dt_cutoff, stored=True, request_limit=500)] print 'Batch delete of selected files' ts1 = time.time() fs = FilesStorage(uuid_list) fs.delete() ts2 = time.time() print 'Operation completed in %f seconds' % (ts2 - ts1)
#!/bin/python # installation: # pip install pytz pyuploadcare~=2.1.0 import pytz from datetime import timedelta, datetime import time from pyuploadcare import conf from pyuploadcare.api_resources import FileList, FilesStorage MAX_LIFETIME = 30 # days conf.pub_key = 'demopublickey' conf.secret = 'demoprivatekey' dt_cutoff = datetime.now(pytz.utc) - timedelta(days=MAX_LIFETIME) if __name__ == '__main__': print 'Selecting files to be deleted...' uuid_list = [f.uuid for f in FileList(starting_point=dt_cutoff, ordering='-datetime_uploaded', stored=True, request_limit=500)] print 'Batch delete of selected files' ts1 = time.time() fs = FilesStorage(uuid_list) fs.delete() ts2 = time.time() print 'Operation completed in %f seconds' % (ts2 - ts1)
Add file sorting in the example script
Add file sorting in the example script
Python
mit
uploadcare/pyuploadcare
#!/bin/python # installation: # pip install pytz pyuploadcare~=2.1.0 import pytz from datetime import timedelta, datetime import time from pyuploadcare import conf from pyuploadcare.api_resources import FileList, FilesStorage MAX_LIFETIME = 30 # days conf.pub_key = 'demopublickey' conf.secret = 'demoprivatekey' dt_cutoff = datetime.now(pytz.utc) - timedelta(days=MAX_LIFETIME) if __name__ == '__main__': print 'Selecting files to be deleted...' uuid_list = [f.uuid for f in FileList(starting_point=dt_cutoff, stored=True, request_limit=500)] print 'Batch delete of selected files' ts1 = time.time() fs = FilesStorage(uuid_list) fs.delete() ts2 = time.time() print 'Operation completed in %f seconds' % (ts2 - ts1) Add file sorting in the example script
#!/bin/python # installation: # pip install pytz pyuploadcare~=2.1.0 import pytz from datetime import timedelta, datetime import time from pyuploadcare import conf from pyuploadcare.api_resources import FileList, FilesStorage MAX_LIFETIME = 30 # days conf.pub_key = 'demopublickey' conf.secret = 'demoprivatekey' dt_cutoff = datetime.now(pytz.utc) - timedelta(days=MAX_LIFETIME) if __name__ == '__main__': print 'Selecting files to be deleted...' uuid_list = [f.uuid for f in FileList(starting_point=dt_cutoff, ordering='-datetime_uploaded', stored=True, request_limit=500)] print 'Batch delete of selected files' ts1 = time.time() fs = FilesStorage(uuid_list) fs.delete() ts2 = time.time() print 'Operation completed in %f seconds' % (ts2 - ts1)
<commit_before>#!/bin/python # installation: # pip install pytz pyuploadcare~=2.1.0 import pytz from datetime import timedelta, datetime import time from pyuploadcare import conf from pyuploadcare.api_resources import FileList, FilesStorage MAX_LIFETIME = 30 # days conf.pub_key = 'demopublickey' conf.secret = 'demoprivatekey' dt_cutoff = datetime.now(pytz.utc) - timedelta(days=MAX_LIFETIME) if __name__ == '__main__': print 'Selecting files to be deleted...' uuid_list = [f.uuid for f in FileList(starting_point=dt_cutoff, stored=True, request_limit=500)] print 'Batch delete of selected files' ts1 = time.time() fs = FilesStorage(uuid_list) fs.delete() ts2 = time.time() print 'Operation completed in %f seconds' % (ts2 - ts1) <commit_msg>Add file sorting in the example script<commit_after>
#!/bin/python # installation: # pip install pytz pyuploadcare~=2.1.0 import pytz from datetime import timedelta, datetime import time from pyuploadcare import conf from pyuploadcare.api_resources import FileList, FilesStorage MAX_LIFETIME = 30 # days conf.pub_key = 'demopublickey' conf.secret = 'demoprivatekey' dt_cutoff = datetime.now(pytz.utc) - timedelta(days=MAX_LIFETIME) if __name__ == '__main__': print 'Selecting files to be deleted...' uuid_list = [f.uuid for f in FileList(starting_point=dt_cutoff, ordering='-datetime_uploaded', stored=True, request_limit=500)] print 'Batch delete of selected files' ts1 = time.time() fs = FilesStorage(uuid_list) fs.delete() ts2 = time.time() print 'Operation completed in %f seconds' % (ts2 - ts1)
#!/bin/python # installation: # pip install pytz pyuploadcare~=2.1.0 import pytz from datetime import timedelta, datetime import time from pyuploadcare import conf from pyuploadcare.api_resources import FileList, FilesStorage MAX_LIFETIME = 30 # days conf.pub_key = 'demopublickey' conf.secret = 'demoprivatekey' dt_cutoff = datetime.now(pytz.utc) - timedelta(days=MAX_LIFETIME) if __name__ == '__main__': print 'Selecting files to be deleted...' uuid_list = [f.uuid for f in FileList(starting_point=dt_cutoff, stored=True, request_limit=500)] print 'Batch delete of selected files' ts1 = time.time() fs = FilesStorage(uuid_list) fs.delete() ts2 = time.time() print 'Operation completed in %f seconds' % (ts2 - ts1) Add file sorting in the example script#!/bin/python # installation: # pip install pytz pyuploadcare~=2.1.0 import pytz from datetime import timedelta, datetime import time from pyuploadcare import conf from pyuploadcare.api_resources import FileList, FilesStorage MAX_LIFETIME = 30 # days conf.pub_key = 'demopublickey' conf.secret = 'demoprivatekey' dt_cutoff = datetime.now(pytz.utc) - timedelta(days=MAX_LIFETIME) if __name__ == '__main__': print 'Selecting files to be deleted...' uuid_list = [f.uuid for f in FileList(starting_point=dt_cutoff, ordering='-datetime_uploaded', stored=True, request_limit=500)] print 'Batch delete of selected files' ts1 = time.time() fs = FilesStorage(uuid_list) fs.delete() ts2 = time.time() print 'Operation completed in %f seconds' % (ts2 - ts1)
<commit_before>#!/bin/python # installation: # pip install pytz pyuploadcare~=2.1.0 import pytz from datetime import timedelta, datetime import time from pyuploadcare import conf from pyuploadcare.api_resources import FileList, FilesStorage MAX_LIFETIME = 30 # days conf.pub_key = 'demopublickey' conf.secret = 'demoprivatekey' dt_cutoff = datetime.now(pytz.utc) - timedelta(days=MAX_LIFETIME) if __name__ == '__main__': print 'Selecting files to be deleted...' uuid_list = [f.uuid for f in FileList(starting_point=dt_cutoff, stored=True, request_limit=500)] print 'Batch delete of selected files' ts1 = time.time() fs = FilesStorage(uuid_list) fs.delete() ts2 = time.time() print 'Operation completed in %f seconds' % (ts2 - ts1) <commit_msg>Add file sorting in the example script<commit_after>#!/bin/python # installation: # pip install pytz pyuploadcare~=2.1.0 import pytz from datetime import timedelta, datetime import time from pyuploadcare import conf from pyuploadcare.api_resources import FileList, FilesStorage MAX_LIFETIME = 30 # days conf.pub_key = 'demopublickey' conf.secret = 'demoprivatekey' dt_cutoff = datetime.now(pytz.utc) - timedelta(days=MAX_LIFETIME) if __name__ == '__main__': print 'Selecting files to be deleted...' uuid_list = [f.uuid for f in FileList(starting_point=dt_cutoff, ordering='-datetime_uploaded', stored=True, request_limit=500)] print 'Batch delete of selected files' ts1 = time.time() fs = FilesStorage(uuid_list) fs.delete() ts2 = time.time() print 'Operation completed in %f seconds' % (ts2 - ts1)
0599e667625e64acf20ea02853523622f539885d
faker/providers/phone_number/uk_UA/__init__.py
faker/providers/phone_number/uk_UA/__init__.py
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): formats = ( '###-##-##', '### ## ##', '0## ### ## ##', '0## ###-##-##', '+38 ### ###-##-##', '+38 ### ###-##-##', '+38 (###) ###-##-##', '+38 ### ### ## ##', )
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): formats = ( '###-##-##', '### ## ##', '0## ### ## ##', '0## ###-##-##', '+38 0## ###-##-##', '+38 0## ###-##-##', '+38 (0##) ###-##-##', '+38 0## ### ## ##', )
Use a proper international format for Ukrainian phone numbers
Use a proper international format for Ukrainian phone numbers The third digit should always be '0'.
Python
mit
danhuss/faker,joke2k/faker,joke2k/faker
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): formats = ( '###-##-##', '### ## ##', '0## ### ## ##', '0## ###-##-##', '+38 ### ###-##-##', '+38 ### ###-##-##', '+38 (###) ###-##-##', '+38 ### ### ## ##', ) Use a proper international format for Ukrainian phone numbers The third digit should always be '0'.
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): formats = ( '###-##-##', '### ## ##', '0## ### ## ##', '0## ###-##-##', '+38 0## ###-##-##', '+38 0## ###-##-##', '+38 (0##) ###-##-##', '+38 0## ### ## ##', )
<commit_before># coding=utf-8 from __future__ import unicode_literals from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): formats = ( '###-##-##', '### ## ##', '0## ### ## ##', '0## ###-##-##', '+38 ### ###-##-##', '+38 ### ###-##-##', '+38 (###) ###-##-##', '+38 ### ### ## ##', ) <commit_msg>Use a proper international format for Ukrainian phone numbers The third digit should always be '0'.<commit_after>
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): formats = ( '###-##-##', '### ## ##', '0## ### ## ##', '0## ###-##-##', '+38 0## ###-##-##', '+38 0## ###-##-##', '+38 (0##) ###-##-##', '+38 0## ### ## ##', )
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): formats = ( '###-##-##', '### ## ##', '0## ### ## ##', '0## ###-##-##', '+38 ### ###-##-##', '+38 ### ###-##-##', '+38 (###) ###-##-##', '+38 ### ### ## ##', ) Use a proper international format for Ukrainian phone numbers The third digit should always be '0'.# coding=utf-8 from __future__ import unicode_literals from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): formats = ( '###-##-##', '### ## ##', '0## ### ## ##', '0## ###-##-##', '+38 0## ###-##-##', '+38 0## ###-##-##', '+38 (0##) ###-##-##', '+38 0## ### ## ##', )
<commit_before># coding=utf-8 from __future__ import unicode_literals from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): formats = ( '###-##-##', '### ## ##', '0## ### ## ##', '0## ###-##-##', '+38 ### ###-##-##', '+38 ### ###-##-##', '+38 (###) ###-##-##', '+38 ### ### ## ##', ) <commit_msg>Use a proper international format for Ukrainian phone numbers The third digit should always be '0'.<commit_after># coding=utf-8 from __future__ import unicode_literals from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): formats = ( '###-##-##', '### ## ##', '0## ### ## ##', '0## ###-##-##', '+38 0## ###-##-##', '+38 0## ###-##-##', '+38 (0##) ###-##-##', '+38 0## ### ## ##', )
a9de2f3c9a05236c7254a2b1b03049b034fd555e
elections/bf_elections_2015/lib.py
elections/bf_elections_2015/lib.py
from candidates.static_data import ( BaseMapItData, BasePartyData, BaseAreaPostData ) class MapItData(BaseMapItData): pass class PartyData(BasePartyData): def __init__(self): super(PartyData, self).__init__() self.ALL_PARTY_SETS = ( {'slug': 'national', 'name': 'National'}, ) def party_data_to_party_sets(self, party_data): return ['national'] class AreaPostData(BaseAreaPostData): def area_to_post_group(self, area_data): return None def shorten_post_label(self, election, post_label): return post_label def post_id_to_post_group(self, election, post_id): return None def post_id_to_party_set(self, post_id): return 'national'
from candidates.static_data import ( BaseMapItData, BasePartyData, BaseAreaPostData ) class MapItData(BaseMapItData): pass class PartyData(BasePartyData): def __init__(self): super(PartyData, self).__init__() self.ALL_PARTY_SETS = ( {'slug': 'national', 'name': 'National'}, ) def party_data_to_party_sets(self, party_data): return ['national'] class AreaPostData(BaseAreaPostData): def __init__(self, *args, **kwargs): super(AreaPostData, self).__init__(*args, **kwargs) self.ALL_POSSIBLE_POST_GROUPS = [None] def area_to_post_group(self, area_data): return None def shorten_post_label(self, election, post_label): return post_label def post_id_to_post_group(self, election, post_id): return None def post_id_to_party_set(self, post_id): return 'national' def party_to_possible_post_groups(self, party_data): return (None,)
Fix missing post group defaults for Burkina Faso
Fix missing post group defaults for Burkina Faso
Python
agpl-3.0
neavouli/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextrepresentative,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextmp-popit,datamade/yournextmp-popit,mysociety/yournextmp-popit,datamade/yournextmp-popit,mysociety/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative
from candidates.static_data import ( BaseMapItData, BasePartyData, BaseAreaPostData ) class MapItData(BaseMapItData): pass class PartyData(BasePartyData): def __init__(self): super(PartyData, self).__init__() self.ALL_PARTY_SETS = ( {'slug': 'national', 'name': 'National'}, ) def party_data_to_party_sets(self, party_data): return ['national'] class AreaPostData(BaseAreaPostData): def area_to_post_group(self, area_data): return None def shorten_post_label(self, election, post_label): return post_label def post_id_to_post_group(self, election, post_id): return None def post_id_to_party_set(self, post_id): return 'national' Fix missing post group defaults for Burkina Faso
from candidates.static_data import ( BaseMapItData, BasePartyData, BaseAreaPostData ) class MapItData(BaseMapItData): pass class PartyData(BasePartyData): def __init__(self): super(PartyData, self).__init__() self.ALL_PARTY_SETS = ( {'slug': 'national', 'name': 'National'}, ) def party_data_to_party_sets(self, party_data): return ['national'] class AreaPostData(BaseAreaPostData): def __init__(self, *args, **kwargs): super(AreaPostData, self).__init__(*args, **kwargs) self.ALL_POSSIBLE_POST_GROUPS = [None] def area_to_post_group(self, area_data): return None def shorten_post_label(self, election, post_label): return post_label def post_id_to_post_group(self, election, post_id): return None def post_id_to_party_set(self, post_id): return 'national' def party_to_possible_post_groups(self, party_data): return (None,)
<commit_before>from candidates.static_data import ( BaseMapItData, BasePartyData, BaseAreaPostData ) class MapItData(BaseMapItData): pass class PartyData(BasePartyData): def __init__(self): super(PartyData, self).__init__() self.ALL_PARTY_SETS = ( {'slug': 'national', 'name': 'National'}, ) def party_data_to_party_sets(self, party_data): return ['national'] class AreaPostData(BaseAreaPostData): def area_to_post_group(self, area_data): return None def shorten_post_label(self, election, post_label): return post_label def post_id_to_post_group(self, election, post_id): return None def post_id_to_party_set(self, post_id): return 'national' <commit_msg>Fix missing post group defaults for Burkina Faso<commit_after>
from candidates.static_data import ( BaseMapItData, BasePartyData, BaseAreaPostData ) class MapItData(BaseMapItData): pass class PartyData(BasePartyData): def __init__(self): super(PartyData, self).__init__() self.ALL_PARTY_SETS = ( {'slug': 'national', 'name': 'National'}, ) def party_data_to_party_sets(self, party_data): return ['national'] class AreaPostData(BaseAreaPostData): def __init__(self, *args, **kwargs): super(AreaPostData, self).__init__(*args, **kwargs) self.ALL_POSSIBLE_POST_GROUPS = [None] def area_to_post_group(self, area_data): return None def shorten_post_label(self, election, post_label): return post_label def post_id_to_post_group(self, election, post_id): return None def post_id_to_party_set(self, post_id): return 'national' def party_to_possible_post_groups(self, party_data): return (None,)
from candidates.static_data import ( BaseMapItData, BasePartyData, BaseAreaPostData ) class MapItData(BaseMapItData): pass class PartyData(BasePartyData): def __init__(self): super(PartyData, self).__init__() self.ALL_PARTY_SETS = ( {'slug': 'national', 'name': 'National'}, ) def party_data_to_party_sets(self, party_data): return ['national'] class AreaPostData(BaseAreaPostData): def area_to_post_group(self, area_data): return None def shorten_post_label(self, election, post_label): return post_label def post_id_to_post_group(self, election, post_id): return None def post_id_to_party_set(self, post_id): return 'national' Fix missing post group defaults for Burkina Fasofrom candidates.static_data import ( BaseMapItData, BasePartyData, BaseAreaPostData ) class MapItData(BaseMapItData): pass class PartyData(BasePartyData): def __init__(self): super(PartyData, self).__init__() self.ALL_PARTY_SETS = ( {'slug': 'national', 'name': 'National'}, ) def party_data_to_party_sets(self, party_data): return ['national'] class AreaPostData(BaseAreaPostData): def __init__(self, *args, **kwargs): super(AreaPostData, self).__init__(*args, **kwargs) self.ALL_POSSIBLE_POST_GROUPS = [None] def area_to_post_group(self, area_data): return None def shorten_post_label(self, election, post_label): return post_label def post_id_to_post_group(self, election, post_id): return None def post_id_to_party_set(self, post_id): return 'national' def party_to_possible_post_groups(self, party_data): return (None,)
<commit_before>from candidates.static_data import ( BaseMapItData, BasePartyData, BaseAreaPostData ) class MapItData(BaseMapItData): pass class PartyData(BasePartyData): def __init__(self): super(PartyData, self).__init__() self.ALL_PARTY_SETS = ( {'slug': 'national', 'name': 'National'}, ) def party_data_to_party_sets(self, party_data): return ['national'] class AreaPostData(BaseAreaPostData): def area_to_post_group(self, area_data): return None def shorten_post_label(self, election, post_label): return post_label def post_id_to_post_group(self, election, post_id): return None def post_id_to_party_set(self, post_id): return 'national' <commit_msg>Fix missing post group defaults for Burkina Faso<commit_after>from candidates.static_data import ( BaseMapItData, BasePartyData, BaseAreaPostData ) class MapItData(BaseMapItData): pass class PartyData(BasePartyData): def __init__(self): super(PartyData, self).__init__() self.ALL_PARTY_SETS = ( {'slug': 'national', 'name': 'National'}, ) def party_data_to_party_sets(self, party_data): return ['national'] class AreaPostData(BaseAreaPostData): def __init__(self, *args, **kwargs): super(AreaPostData, self).__init__(*args, **kwargs) self.ALL_POSSIBLE_POST_GROUPS = [None] def area_to_post_group(self, area_data): return None def shorten_post_label(self, election, post_label): return post_label def post_id_to_post_group(self, election, post_id): return None def post_id_to_party_set(self, post_id): return 'national' def party_to_possible_post_groups(self, party_data): return (None,)
8b13cd7e19d8f7c8080baa6b3cc532bb6aa79c8a
tests/basics/try_finally_loops.py
tests/basics/try_finally_loops.py
# Test various loop types, some may be implemented/optimized differently while True: try: break finally: print('finally 1') for i in [1, 5, 10]: try: continue finally: print('finally 2') for i in range(3): try: continue finally: print('finally 3') # Multi-level for i in range(4): print(i) try: while True: try: try: break finally: print('finally 1') finally: print('finally 2') print('here') finally: print('finnaly 3') # break from within try-finally, within for-loop for i in [1]: try: print(i) break finally: print('finally 4')
# Test various loop types, some may be implemented/optimized differently while True: try: break finally: print('finally 1') for i in [1, 5, 10]: try: continue finally: print('finally 2') for i in range(3): try: continue finally: print('finally 3') # Multi-level for i in range(4): print(i) try: while True: try: try: break finally: print('finally 1') finally: print('finally 2') print('here') finally: print('finnaly 3') # break from within try-finally, within for-loop for i in [1]: try: print(i) break finally: print('finally 4') # Test unwind-jump where there is nothing in the body of the try or finally. # This checks that the bytecode emitter allocates enough stack for the unwind. for i in [1]: try: break finally: pass # The following test checks that the globals dict is valid after a call to a # function that has an unwind jump. # There was a bug where an unwind jump would trash the globals dict upon return # from a function, because it used the Python-stack incorrectly. def f(): for i in [1]: try: break finally: pass def g(): global global_var f() print(global_var) global_var = 'global' g()
Add more tests for unwind jumps from within a try-finally.
tests/basics: Add more tests for unwind jumps from within a try-finally. These tests excercise cases that are fixed by the previous two commits.
Python
mit
hiway/micropython,henriknelson/micropython,PappaPeppar/micropython,pfalcon/micropython,HenrikSolver/micropython,PappaPeppar/micropython,MrSurly/micropython-esp32,kerneltask/micropython,alex-robbins/micropython,tobbad/micropython,trezor/micropython,Timmenem/micropython,lowRISC/micropython,selste/micropython,deshipu/micropython,adafruit/micropython,MrSurly/micropython-esp32,adafruit/circuitpython,micropython/micropython-esp32,adafruit/micropython,adafruit/circuitpython,swegener/micropython,HenrikSolver/micropython,kerneltask/micropython,deshipu/micropython,selste/micropython,AriZuu/micropython,pfalcon/micropython,tobbad/micropython,oopy/micropython,MrSurly/micropython,kerneltask/micropython,bvernoux/micropython,chrisdearman/micropython,alex-robbins/micropython,MrSurly/micropython,MrSurly/micropython,dmazzella/micropython,swegener/micropython,SHA2017-badge/micropython-esp32,adafruit/micropython,blazewicz/micropython,hiway/micropython,torwag/micropython,lowRISC/micropython,TDAbboud/micropython,micropython/micropython-esp32,tobbad/micropython,micropython/micropython-esp32,torwag/micropython,Timmenem/micropython,torwag/micropython,henriknelson/micropython,pozetroninc/micropython,pramasoul/micropython,adafruit/micropython,MrSurly/micropython,infinnovation/micropython,PappaPeppar/micropython,infinnovation/micropython,trezor/micropython,hiway/micropython,pramasoul/micropython,ryannathans/micropython,blazewicz/micropython,AriZuu/micropython,bvernoux/micropython,henriknelson/micropython,selste/micropython,swegener/micropython,blazewicz/micropython,pfalcon/micropython,chrisdearman/micropython,TDAbboud/micropython,cwyark/micropython,lowRISC/micropython,trezor/micropython,SHA2017-badge/micropython-esp32,adafruit/circuitpython,MrSurly/micropython,bvernoux/micropython,HenrikSolver/micropython,cwyark/micropython,alex-robbins/micropython,ryannathans/micropython,AriZuu/micropython,pramasoul/micropython,tralamazza/micropython,bvernoux/micropython,chrisdearman/micropython,adafruit/circuitpython,trezor/micropython,dmazzella/micropython,adafruit/circuitpython,pfalcon/micropython,tobbad/micropython,dmazzella/micropython,oopy/micropython,micropython/micropython-esp32,cwyark/micropython,hiway/micropython,lowRISC/micropython,cwyark/micropython,AriZuu/micropython,blazewicz/micropython,infinnovation/micropython,hiway/micropython,PappaPeppar/micropython,tobbad/micropython,pozetroninc/micropython,swegener/micropython,HenrikSolver/micropython,ryannathans/micropython,oopy/micropython,pozetroninc/micropython,kerneltask/micropython,pfalcon/micropython,henriknelson/micropython,MrSurly/micropython-esp32,SHA2017-badge/micropython-esp32,torwag/micropython,MrSurly/micropython-esp32,micropython/micropython-esp32,pozetroninc/micropython,Timmenem/micropython,oopy/micropython,cwyark/micropython,selste/micropython,chrisdearman/micropython,adafruit/micropython,TDAbboud/micropython,TDAbboud/micropython,PappaPeppar/micropython,AriZuu/micropython,swegener/micropython,alex-robbins/micropython,oopy/micropython,pozetroninc/micropython,infinnovation/micropython,tralamazza/micropython,ryannathans/micropython,SHA2017-badge/micropython-esp32,Timmenem/micropython,infinnovation/micropython,deshipu/micropython,deshipu/micropython,alex-robbins/micropython,deshipu/micropython,TDAbboud/micropython,henriknelson/micropython,MrSurly/micropython-esp32,torwag/micropython,ryannathans/micropython,lowRISC/micropython,pramasoul/micropython,pramasoul/micropython,SHA2017-badge/micropython-esp32,bvernoux/micropython,chrisdearman/micropython,adafruit/circuitpython,HenrikSolver/micropython,tralamazza/micropython,dmazzella/micropython,kerneltask/micropython,selste/micropython,tralamazza/micropython,trezor/micropython,blazewicz/micropython,Timmenem/micropython
# Test various loop types, some may be implemented/optimized differently while True: try: break finally: print('finally 1') for i in [1, 5, 10]: try: continue finally: print('finally 2') for i in range(3): try: continue finally: print('finally 3') # Multi-level for i in range(4): print(i) try: while True: try: try: break finally: print('finally 1') finally: print('finally 2') print('here') finally: print('finnaly 3') # break from within try-finally, within for-loop for i in [1]: try: print(i) break finally: print('finally 4') tests/basics: Add more tests for unwind jumps from within a try-finally. These tests excercise cases that are fixed by the previous two commits.
# Test various loop types, some may be implemented/optimized differently while True: try: break finally: print('finally 1') for i in [1, 5, 10]: try: continue finally: print('finally 2') for i in range(3): try: continue finally: print('finally 3') # Multi-level for i in range(4): print(i) try: while True: try: try: break finally: print('finally 1') finally: print('finally 2') print('here') finally: print('finnaly 3') # break from within try-finally, within for-loop for i in [1]: try: print(i) break finally: print('finally 4') # Test unwind-jump where there is nothing in the body of the try or finally. # This checks that the bytecode emitter allocates enough stack for the unwind. for i in [1]: try: break finally: pass # The following test checks that the globals dict is valid after a call to a # function that has an unwind jump. # There was a bug where an unwind jump would trash the globals dict upon return # from a function, because it used the Python-stack incorrectly. def f(): for i in [1]: try: break finally: pass def g(): global global_var f() print(global_var) global_var = 'global' g()
<commit_before># Test various loop types, some may be implemented/optimized differently while True: try: break finally: print('finally 1') for i in [1, 5, 10]: try: continue finally: print('finally 2') for i in range(3): try: continue finally: print('finally 3') # Multi-level for i in range(4): print(i) try: while True: try: try: break finally: print('finally 1') finally: print('finally 2') print('here') finally: print('finnaly 3') # break from within try-finally, within for-loop for i in [1]: try: print(i) break finally: print('finally 4') <commit_msg>tests/basics: Add more tests for unwind jumps from within a try-finally. These tests excercise cases that are fixed by the previous two commits.<commit_after>
# Test various loop types, some may be implemented/optimized differently while True: try: break finally: print('finally 1') for i in [1, 5, 10]: try: continue finally: print('finally 2') for i in range(3): try: continue finally: print('finally 3') # Multi-level for i in range(4): print(i) try: while True: try: try: break finally: print('finally 1') finally: print('finally 2') print('here') finally: print('finnaly 3') # break from within try-finally, within for-loop for i in [1]: try: print(i) break finally: print('finally 4') # Test unwind-jump where there is nothing in the body of the try or finally. # This checks that the bytecode emitter allocates enough stack for the unwind. for i in [1]: try: break finally: pass # The following test checks that the globals dict is valid after a call to a # function that has an unwind jump. # There was a bug where an unwind jump would trash the globals dict upon return # from a function, because it used the Python-stack incorrectly. def f(): for i in [1]: try: break finally: pass def g(): global global_var f() print(global_var) global_var = 'global' g()
# Test various loop types, some may be implemented/optimized differently while True: try: break finally: print('finally 1') for i in [1, 5, 10]: try: continue finally: print('finally 2') for i in range(3): try: continue finally: print('finally 3') # Multi-level for i in range(4): print(i) try: while True: try: try: break finally: print('finally 1') finally: print('finally 2') print('here') finally: print('finnaly 3') # break from within try-finally, within for-loop for i in [1]: try: print(i) break finally: print('finally 4') tests/basics: Add more tests for unwind jumps from within a try-finally. These tests excercise cases that are fixed by the previous two commits.# Test various loop types, some may be implemented/optimized differently while True: try: break finally: print('finally 1') for i in [1, 5, 10]: try: continue finally: print('finally 2') for i in range(3): try: continue finally: print('finally 3') # Multi-level for i in range(4): print(i) try: while True: try: try: break finally: print('finally 1') finally: print('finally 2') print('here') finally: print('finnaly 3') # break from within try-finally, within for-loop for i in [1]: try: print(i) break finally: print('finally 4') # Test unwind-jump where there is nothing in the body of the try or finally. # This checks that the bytecode emitter allocates enough stack for the unwind. for i in [1]: try: break finally: pass # The following test checks that the globals dict is valid after a call to a # function that has an unwind jump. # There was a bug where an unwind jump would trash the globals dict upon return # from a function, because it used the Python-stack incorrectly. def f(): for i in [1]: try: break finally: pass def g(): global global_var f() print(global_var) global_var = 'global' g()
<commit_before># Test various loop types, some may be implemented/optimized differently while True: try: break finally: print('finally 1') for i in [1, 5, 10]: try: continue finally: print('finally 2') for i in range(3): try: continue finally: print('finally 3') # Multi-level for i in range(4): print(i) try: while True: try: try: break finally: print('finally 1') finally: print('finally 2') print('here') finally: print('finnaly 3') # break from within try-finally, within for-loop for i in [1]: try: print(i) break finally: print('finally 4') <commit_msg>tests/basics: Add more tests for unwind jumps from within a try-finally. These tests excercise cases that are fixed by the previous two commits.<commit_after># Test various loop types, some may be implemented/optimized differently while True: try: break finally: print('finally 1') for i in [1, 5, 10]: try: continue finally: print('finally 2') for i in range(3): try: continue finally: print('finally 3') # Multi-level for i in range(4): print(i) try: while True: try: try: break finally: print('finally 1') finally: print('finally 2') print('here') finally: print('finnaly 3') # break from within try-finally, within for-loop for i in [1]: try: print(i) break finally: print('finally 4') # Test unwind-jump where there is nothing in the body of the try or finally. # This checks that the bytecode emitter allocates enough stack for the unwind. for i in [1]: try: break finally: pass # The following test checks that the globals dict is valid after a call to a # function that has an unwind jump. # There was a bug where an unwind jump would trash the globals dict upon return # from a function, because it used the Python-stack incorrectly. def f(): for i in [1]: try: break finally: pass def g(): global global_var f() print(global_var) global_var = 'global' g()
f34a6b4ec6b192607f4a3557f6da3f5c119aab04
tests/scoring_engine/unit_test.py
tests/scoring_engine/unit_test.py
from scoring_engine.db import session, engine from scoring_engine.models.base import Base from scoring_engine.models.setting import Setting class UnitTest(object): def setup(self): self.session = session Base.metadata.create_all(engine) self.create_default_settings() def teardown(self): Base.metadata.drop_all(engine) self.session.close_all() def create_default_settings(self): about_page_setting = Setting(name='about_page_content', value='example content value') self.session.add(about_page_setting) welcome_page_setting = Setting(name='welcome_page_content', value='example welcome content <br>here') self.session.add(welcome_page_setting) round_time_sleep_setting = Setting(name='round_time_sleep', value=60) self.session.add(round_time_sleep_setting) worker_refresh_time_setting = Setting(name='worker_refresh_time', value=30) self.session.add(worker_refresh_time_setting) self.session.commit()
from scoring_engine.db import session, engine from scoring_engine.models.base import Base from scoring_engine.models.setting import Setting class UnitTest(object): def setup(self): self.session = session Base.metadata.drop_all(engine) Base.metadata.create_all(engine) self.create_default_settings() def teardown(self): Base.metadata.drop_all(engine) self.session.close_all() def create_default_settings(self): about_page_setting = Setting(name='about_page_content', value='example content value') self.session.add(about_page_setting) welcome_page_setting = Setting(name='welcome_page_content', value='example welcome content <br>here') self.session.add(welcome_page_setting) round_time_sleep_setting = Setting(name='round_time_sleep', value=60) self.session.add(round_time_sleep_setting) worker_refresh_time_setting = Setting(name='worker_refresh_time', value=30) self.session.add(worker_refresh_time_setting) self.session.commit()
Modify unit test framework to delete db during setup
Modify unit test framework to delete db during setup
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
from scoring_engine.db import session, engine from scoring_engine.models.base import Base from scoring_engine.models.setting import Setting class UnitTest(object): def setup(self): self.session = session Base.metadata.create_all(engine) self.create_default_settings() def teardown(self): Base.metadata.drop_all(engine) self.session.close_all() def create_default_settings(self): about_page_setting = Setting(name='about_page_content', value='example content value') self.session.add(about_page_setting) welcome_page_setting = Setting(name='welcome_page_content', value='example welcome content <br>here') self.session.add(welcome_page_setting) round_time_sleep_setting = Setting(name='round_time_sleep', value=60) self.session.add(round_time_sleep_setting) worker_refresh_time_setting = Setting(name='worker_refresh_time', value=30) self.session.add(worker_refresh_time_setting) self.session.commit() Modify unit test framework to delete db during setup
from scoring_engine.db import session, engine from scoring_engine.models.base import Base from scoring_engine.models.setting import Setting class UnitTest(object): def setup(self): self.session = session Base.metadata.drop_all(engine) Base.metadata.create_all(engine) self.create_default_settings() def teardown(self): Base.metadata.drop_all(engine) self.session.close_all() def create_default_settings(self): about_page_setting = Setting(name='about_page_content', value='example content value') self.session.add(about_page_setting) welcome_page_setting = Setting(name='welcome_page_content', value='example welcome content <br>here') self.session.add(welcome_page_setting) round_time_sleep_setting = Setting(name='round_time_sleep', value=60) self.session.add(round_time_sleep_setting) worker_refresh_time_setting = Setting(name='worker_refresh_time', value=30) self.session.add(worker_refresh_time_setting) self.session.commit()
<commit_before>from scoring_engine.db import session, engine from scoring_engine.models.base import Base from scoring_engine.models.setting import Setting class UnitTest(object): def setup(self): self.session = session Base.metadata.create_all(engine) self.create_default_settings() def teardown(self): Base.metadata.drop_all(engine) self.session.close_all() def create_default_settings(self): about_page_setting = Setting(name='about_page_content', value='example content value') self.session.add(about_page_setting) welcome_page_setting = Setting(name='welcome_page_content', value='example welcome content <br>here') self.session.add(welcome_page_setting) round_time_sleep_setting = Setting(name='round_time_sleep', value=60) self.session.add(round_time_sleep_setting) worker_refresh_time_setting = Setting(name='worker_refresh_time', value=30) self.session.add(worker_refresh_time_setting) self.session.commit() <commit_msg>Modify unit test framework to delete db during setup<commit_after>
from scoring_engine.db import session, engine from scoring_engine.models.base import Base from scoring_engine.models.setting import Setting class UnitTest(object): def setup(self): self.session = session Base.metadata.drop_all(engine) Base.metadata.create_all(engine) self.create_default_settings() def teardown(self): Base.metadata.drop_all(engine) self.session.close_all() def create_default_settings(self): about_page_setting = Setting(name='about_page_content', value='example content value') self.session.add(about_page_setting) welcome_page_setting = Setting(name='welcome_page_content', value='example welcome content <br>here') self.session.add(welcome_page_setting) round_time_sleep_setting = Setting(name='round_time_sleep', value=60) self.session.add(round_time_sleep_setting) worker_refresh_time_setting = Setting(name='worker_refresh_time', value=30) self.session.add(worker_refresh_time_setting) self.session.commit()
from scoring_engine.db import session, engine from scoring_engine.models.base import Base from scoring_engine.models.setting import Setting class UnitTest(object): def setup(self): self.session = session Base.metadata.create_all(engine) self.create_default_settings() def teardown(self): Base.metadata.drop_all(engine) self.session.close_all() def create_default_settings(self): about_page_setting = Setting(name='about_page_content', value='example content value') self.session.add(about_page_setting) welcome_page_setting = Setting(name='welcome_page_content', value='example welcome content <br>here') self.session.add(welcome_page_setting) round_time_sleep_setting = Setting(name='round_time_sleep', value=60) self.session.add(round_time_sleep_setting) worker_refresh_time_setting = Setting(name='worker_refresh_time', value=30) self.session.add(worker_refresh_time_setting) self.session.commit() Modify unit test framework to delete db during setupfrom scoring_engine.db import session, engine from scoring_engine.models.base import Base from scoring_engine.models.setting import Setting class UnitTest(object): def setup(self): self.session = session Base.metadata.drop_all(engine) Base.metadata.create_all(engine) self.create_default_settings() def teardown(self): Base.metadata.drop_all(engine) self.session.close_all() def create_default_settings(self): about_page_setting = Setting(name='about_page_content', value='example content value') self.session.add(about_page_setting) welcome_page_setting = Setting(name='welcome_page_content', value='example welcome content <br>here') self.session.add(welcome_page_setting) round_time_sleep_setting = Setting(name='round_time_sleep', value=60) self.session.add(round_time_sleep_setting) worker_refresh_time_setting = Setting(name='worker_refresh_time', value=30) self.session.add(worker_refresh_time_setting) self.session.commit()
<commit_before>from scoring_engine.db import session, engine from scoring_engine.models.base import Base from scoring_engine.models.setting import Setting class UnitTest(object): def setup(self): self.session = session Base.metadata.create_all(engine) self.create_default_settings() def teardown(self): Base.metadata.drop_all(engine) self.session.close_all() def create_default_settings(self): about_page_setting = Setting(name='about_page_content', value='example content value') self.session.add(about_page_setting) welcome_page_setting = Setting(name='welcome_page_content', value='example welcome content <br>here') self.session.add(welcome_page_setting) round_time_sleep_setting = Setting(name='round_time_sleep', value=60) self.session.add(round_time_sleep_setting) worker_refresh_time_setting = Setting(name='worker_refresh_time', value=30) self.session.add(worker_refresh_time_setting) self.session.commit() <commit_msg>Modify unit test framework to delete db during setup<commit_after>from scoring_engine.db import session, engine from scoring_engine.models.base import Base from scoring_engine.models.setting import Setting class UnitTest(object): def setup(self): self.session = session Base.metadata.drop_all(engine) Base.metadata.create_all(engine) self.create_default_settings() def teardown(self): Base.metadata.drop_all(engine) self.session.close_all() def create_default_settings(self): about_page_setting = Setting(name='about_page_content', value='example content value') self.session.add(about_page_setting) welcome_page_setting = Setting(name='welcome_page_content', value='example welcome content <br>here') self.session.add(welcome_page_setting) round_time_sleep_setting = Setting(name='round_time_sleep', value=60) self.session.add(round_time_sleep_setting) worker_refresh_time_setting = Setting(name='worker_refresh_time', value=30) self.session.add(worker_refresh_time_setting) self.session.commit()
2ef0571e5468ac72f712a69180fa5dc18652e8d7
app/applier.py
app/applier.py
import random from collections import namedtuple Rule = namedtuple('Rule', ['changes', 'environments']) sonorization = Rule({'p': 'b', 't': 'd', 'ʈ': 'ɖ', 'c':'ɟ', 'k': 'g', 'q': 'ɢ'}, ['^.', 'V.V']) rules = [sonorization] words = ['potato', 'tobado', 'tabasco'] def choose_rule(words, rules): '''Returns a sound change rule from rules applicable to the given word list.''' filtered_rules = filter_rules_by_phonemes(words, rules) filtered_rules = filter_rules_by_environments(words, filtered_rules) # selected_rule = random.choice(filtered_rules) def filter_rules_by_phonemes(words, rules): '''Returns a list of rules which contain phonemes that are present in the given word list. ''' pass def filter_rules_by_environments(words, rules): '''Returns a list of rules which apply to at least one word in the given word list, taking into account the environments in which the rule applies. ''' pass if __name__ == '__main__': choose_rule(words, rules)
import random from collections import namedtuple Rule = namedtuple('Rule', ['changes', 'environments']) sonorization = Rule({'p': 'b', 't': 'd', 'ʈ': 'ɖ', 'c':'ɟ', 'k': 'g', 'q': 'ɢ'}, ['^.', 'V.V']) rules = [sonorization] words = ['potato', 'tobado', 'tabasco'] def choose_rule(words, rules): '''Returns a sound change rule from rules applicable to the given word list.''' filtered_rules = filter_rules_by_phonemes(words, rules) # filtered_rules = filter_rules_by_environments(words, filtered_rules) # selected_rule = random.choice(filtered_rules) def intersecting(set_1, set_2): '''Return true if the intersection of the two sets isn't empty, false otherwise. ''' return (len(set_1.intersection(set_2)) != 0) def filter_rules_by_phonemes(words, rules): '''Returns a list of rules which contain phonemes that are present in the given word list. ''' word_phonemes = set(''.join(words)) return [rule for rule in rules if intersecting(word_phonemes, set(rule.changes.keys()))] def filter_rules_by_environments(words, rules): '''Returns a list of rules which apply to at least one word in the given word list, taking into account the environments in which the rule applies. ''' pass if __name__ == '__main__': choose_rule(words, rules)
Implement rule filtering by phoneme.
Implement rule filtering by phoneme.
Python
mit
kdelwat/LangEvolve,kdelwat/LangEvolve,kdelwat/LangEvolve
import random from collections import namedtuple Rule = namedtuple('Rule', ['changes', 'environments']) sonorization = Rule({'p': 'b', 't': 'd', 'ʈ': 'ɖ', 'c':'ɟ', 'k': 'g', 'q': 'ɢ'}, ['^.', 'V.V']) rules = [sonorization] words = ['potato', 'tobado', 'tabasco'] def choose_rule(words, rules): '''Returns a sound change rule from rules applicable to the given word list.''' filtered_rules = filter_rules_by_phonemes(words, rules) filtered_rules = filter_rules_by_environments(words, filtered_rules) # selected_rule = random.choice(filtered_rules) def filter_rules_by_phonemes(words, rules): '''Returns a list of rules which contain phonemes that are present in the given word list. ''' pass def filter_rules_by_environments(words, rules): '''Returns a list of rules which apply to at least one word in the given word list, taking into account the environments in which the rule applies. ''' pass if __name__ == '__main__': choose_rule(words, rules) Implement rule filtering by phoneme.
import random from collections import namedtuple Rule = namedtuple('Rule', ['changes', 'environments']) sonorization = Rule({'p': 'b', 't': 'd', 'ʈ': 'ɖ', 'c':'ɟ', 'k': 'g', 'q': 'ɢ'}, ['^.', 'V.V']) rules = [sonorization] words = ['potato', 'tobado', 'tabasco'] def choose_rule(words, rules): '''Returns a sound change rule from rules applicable to the given word list.''' filtered_rules = filter_rules_by_phonemes(words, rules) # filtered_rules = filter_rules_by_environments(words, filtered_rules) # selected_rule = random.choice(filtered_rules) def intersecting(set_1, set_2): '''Return true if the intersection of the two sets isn't empty, false otherwise. ''' return (len(set_1.intersection(set_2)) != 0) def filter_rules_by_phonemes(words, rules): '''Returns a list of rules which contain phonemes that are present in the given word list. ''' word_phonemes = set(''.join(words)) return [rule for rule in rules if intersecting(word_phonemes, set(rule.changes.keys()))] def filter_rules_by_environments(words, rules): '''Returns a list of rules which apply to at least one word in the given word list, taking into account the environments in which the rule applies. ''' pass if __name__ == '__main__': choose_rule(words, rules)
<commit_before>import random from collections import namedtuple Rule = namedtuple('Rule', ['changes', 'environments']) sonorization = Rule({'p': 'b', 't': 'd', 'ʈ': 'ɖ', 'c':'ɟ', 'k': 'g', 'q': 'ɢ'}, ['^.', 'V.V']) rules = [sonorization] words = ['potato', 'tobado', 'tabasco'] def choose_rule(words, rules): '''Returns a sound change rule from rules applicable to the given word list.''' filtered_rules = filter_rules_by_phonemes(words, rules) filtered_rules = filter_rules_by_environments(words, filtered_rules) # selected_rule = random.choice(filtered_rules) def filter_rules_by_phonemes(words, rules): '''Returns a list of rules which contain phonemes that are present in the given word list. ''' pass def filter_rules_by_environments(words, rules): '''Returns a list of rules which apply to at least one word in the given word list, taking into account the environments in which the rule applies. ''' pass if __name__ == '__main__': choose_rule(words, rules) <commit_msg>Implement rule filtering by phoneme.<commit_after>
import random from collections import namedtuple Rule = namedtuple('Rule', ['changes', 'environments']) sonorization = Rule({'p': 'b', 't': 'd', 'ʈ': 'ɖ', 'c':'ɟ', 'k': 'g', 'q': 'ɢ'}, ['^.', 'V.V']) rules = [sonorization] words = ['potato', 'tobado', 'tabasco'] def choose_rule(words, rules): '''Returns a sound change rule from rules applicable to the given word list.''' filtered_rules = filter_rules_by_phonemes(words, rules) # filtered_rules = filter_rules_by_environments(words, filtered_rules) # selected_rule = random.choice(filtered_rules) def intersecting(set_1, set_2): '''Return true if the intersection of the two sets isn't empty, false otherwise. ''' return (len(set_1.intersection(set_2)) != 0) def filter_rules_by_phonemes(words, rules): '''Returns a list of rules which contain phonemes that are present in the given word list. ''' word_phonemes = set(''.join(words)) return [rule for rule in rules if intersecting(word_phonemes, set(rule.changes.keys()))] def filter_rules_by_environments(words, rules): '''Returns a list of rules which apply to at least one word in the given word list, taking into account the environments in which the rule applies. ''' pass if __name__ == '__main__': choose_rule(words, rules)
import random from collections import namedtuple Rule = namedtuple('Rule', ['changes', 'environments']) sonorization = Rule({'p': 'b', 't': 'd', 'ʈ': 'ɖ', 'c':'ɟ', 'k': 'g', 'q': 'ɢ'}, ['^.', 'V.V']) rules = [sonorization] words = ['potato', 'tobado', 'tabasco'] def choose_rule(words, rules): '''Returns a sound change rule from rules applicable to the given word list.''' filtered_rules = filter_rules_by_phonemes(words, rules) filtered_rules = filter_rules_by_environments(words, filtered_rules) # selected_rule = random.choice(filtered_rules) def filter_rules_by_phonemes(words, rules): '''Returns a list of rules which contain phonemes that are present in the given word list. ''' pass def filter_rules_by_environments(words, rules): '''Returns a list of rules which apply to at least one word in the given word list, taking into account the environments in which the rule applies. ''' pass if __name__ == '__main__': choose_rule(words, rules) Implement rule filtering by phoneme.import random from collections import namedtuple Rule = namedtuple('Rule', ['changes', 'environments']) sonorization = Rule({'p': 'b', 't': 'd', 'ʈ': 'ɖ', 'c':'ɟ', 'k': 'g', 'q': 'ɢ'}, ['^.', 'V.V']) rules = [sonorization] words = ['potato', 'tobado', 'tabasco'] def choose_rule(words, rules): '''Returns a sound change rule from rules applicable to the given word list.''' filtered_rules = filter_rules_by_phonemes(words, rules) # filtered_rules = filter_rules_by_environments(words, filtered_rules) # selected_rule = random.choice(filtered_rules) def intersecting(set_1, set_2): '''Return true if the intersection of the two sets isn't empty, false otherwise. ''' return (len(set_1.intersection(set_2)) != 0) def filter_rules_by_phonemes(words, rules): '''Returns a list of rules which contain phonemes that are present in the given word list. ''' word_phonemes = set(''.join(words)) return [rule for rule in rules if intersecting(word_phonemes, set(rule.changes.keys()))] def filter_rules_by_environments(words, rules): '''Returns a list of rules which apply to at least one word in the given word list, taking into account the environments in which the rule applies. ''' pass if __name__ == '__main__': choose_rule(words, rules)
<commit_before>import random from collections import namedtuple Rule = namedtuple('Rule', ['changes', 'environments']) sonorization = Rule({'p': 'b', 't': 'd', 'ʈ': 'ɖ', 'c':'ɟ', 'k': 'g', 'q': 'ɢ'}, ['^.', 'V.V']) rules = [sonorization] words = ['potato', 'tobado', 'tabasco'] def choose_rule(words, rules): '''Returns a sound change rule from rules applicable to the given word list.''' filtered_rules = filter_rules_by_phonemes(words, rules) filtered_rules = filter_rules_by_environments(words, filtered_rules) # selected_rule = random.choice(filtered_rules) def filter_rules_by_phonemes(words, rules): '''Returns a list of rules which contain phonemes that are present in the given word list. ''' pass def filter_rules_by_environments(words, rules): '''Returns a list of rules which apply to at least one word in the given word list, taking into account the environments in which the rule applies. ''' pass if __name__ == '__main__': choose_rule(words, rules) <commit_msg>Implement rule filtering by phoneme.<commit_after>import random from collections import namedtuple Rule = namedtuple('Rule', ['changes', 'environments']) sonorization = Rule({'p': 'b', 't': 'd', 'ʈ': 'ɖ', 'c':'ɟ', 'k': 'g', 'q': 'ɢ'}, ['^.', 'V.V']) rules = [sonorization] words = ['potato', 'tobado', 'tabasco'] def choose_rule(words, rules): '''Returns a sound change rule from rules applicable to the given word list.''' filtered_rules = filter_rules_by_phonemes(words, rules) # filtered_rules = filter_rules_by_environments(words, filtered_rules) # selected_rule = random.choice(filtered_rules) def intersecting(set_1, set_2): '''Return true if the intersection of the two sets isn't empty, false otherwise. ''' return (len(set_1.intersection(set_2)) != 0) def filter_rules_by_phonemes(words, rules): '''Returns a list of rules which contain phonemes that are present in the given word list. ''' word_phonemes = set(''.join(words)) return [rule for rule in rules if intersecting(word_phonemes, set(rule.changes.keys()))] def filter_rules_by_environments(words, rules): '''Returns a list of rules which apply to at least one word in the given word list, taking into account the environments in which the rule applies. ''' pass if __name__ == '__main__': choose_rule(words, rules)
bdbb773f896936e9889617a8d1a21fcc4f17b54e
bot.py
bot.py
#!/usr/bin/env python2.7 # coding: utf-8 import inspect import logging logging.basicConfig() import time import uuid from comicsbot import ComicsBot from dokuwiki import DokuWiki from roomlogger import RoomLogger execfile("config.py") w = DokuWiki() if w.dokuwiki.login(config["dokuwiki"]["username"], config["dokuwiki"]["password"]): welcome_message = "Hello! I've connected to wiki %s version %s, " \ "xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(), w.dokuwiki.getXMLRPCAPIVersion()) else: welcome_message = "Hi! I cannot authorize to the wiki." w = None room_logger = RoomLogger(config["jabber"]["logdir"]) bot = ComicsBot(config["jabber"]["username"], config["jabber"]["password"], wiki=w, room_logger=room_logger, res=uuid.uuid1()) bot.join_room(config["jabber"]["room"], config["jabber"]["nick"]) time.sleep(1) bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat") bot.serve_forever()
#!/usr/bin/env python2.7 # coding: utf-8 import inspect import logging logging.basicConfig(level=logging.DEBUG) import time import uuid from comicsbot import ComicsBot from dokuwiki import DokuWiki from roomlogger import RoomLogger execfile("config.py") w = DokuWiki() if w.dokuwiki.login(config["dokuwiki"]["username"], config["dokuwiki"]["password"]): welcome_message = "Hello! I've connected to wiki %s version %s, " \ "xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(), w.dokuwiki.getXMLRPCAPIVersion()) else: welcome_message = "Hi! I cannot authorize to the wiki." w = None room_logger = RoomLogger(config["jabber"]["logdir"]) bot = ComicsBot(config["jabber"]["username"], config["jabber"]["password"], wiki=w, room_logger=room_logger, res=uuid.uuid1()) bot.join_room(config["jabber"]["room"], config["jabber"]["nick"]) time.sleep(1) bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat") bot.serve_forever()
Enable debug logging for xmpppy
Enable debug logging for xmpppy
Python
mit
dotdoom/comicsbot,dotdoom/comicsbot
#!/usr/bin/env python2.7 # coding: utf-8 import inspect import logging logging.basicConfig() import time import uuid from comicsbot import ComicsBot from dokuwiki import DokuWiki from roomlogger import RoomLogger execfile("config.py") w = DokuWiki() if w.dokuwiki.login(config["dokuwiki"]["username"], config["dokuwiki"]["password"]): welcome_message = "Hello! I've connected to wiki %s version %s, " \ "xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(), w.dokuwiki.getXMLRPCAPIVersion()) else: welcome_message = "Hi! I cannot authorize to the wiki." w = None room_logger = RoomLogger(config["jabber"]["logdir"]) bot = ComicsBot(config["jabber"]["username"], config["jabber"]["password"], wiki=w, room_logger=room_logger, res=uuid.uuid1()) bot.join_room(config["jabber"]["room"], config["jabber"]["nick"]) time.sleep(1) bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat") bot.serve_forever() Enable debug logging for xmpppy
#!/usr/bin/env python2.7 # coding: utf-8 import inspect import logging logging.basicConfig(level=logging.DEBUG) import time import uuid from comicsbot import ComicsBot from dokuwiki import DokuWiki from roomlogger import RoomLogger execfile("config.py") w = DokuWiki() if w.dokuwiki.login(config["dokuwiki"]["username"], config["dokuwiki"]["password"]): welcome_message = "Hello! I've connected to wiki %s version %s, " \ "xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(), w.dokuwiki.getXMLRPCAPIVersion()) else: welcome_message = "Hi! I cannot authorize to the wiki." w = None room_logger = RoomLogger(config["jabber"]["logdir"]) bot = ComicsBot(config["jabber"]["username"], config["jabber"]["password"], wiki=w, room_logger=room_logger, res=uuid.uuid1()) bot.join_room(config["jabber"]["room"], config["jabber"]["nick"]) time.sleep(1) bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat") bot.serve_forever()
<commit_before>#!/usr/bin/env python2.7 # coding: utf-8 import inspect import logging logging.basicConfig() import time import uuid from comicsbot import ComicsBot from dokuwiki import DokuWiki from roomlogger import RoomLogger execfile("config.py") w = DokuWiki() if w.dokuwiki.login(config["dokuwiki"]["username"], config["dokuwiki"]["password"]): welcome_message = "Hello! I've connected to wiki %s version %s, " \ "xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(), w.dokuwiki.getXMLRPCAPIVersion()) else: welcome_message = "Hi! I cannot authorize to the wiki." w = None room_logger = RoomLogger(config["jabber"]["logdir"]) bot = ComicsBot(config["jabber"]["username"], config["jabber"]["password"], wiki=w, room_logger=room_logger, res=uuid.uuid1()) bot.join_room(config["jabber"]["room"], config["jabber"]["nick"]) time.sleep(1) bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat") bot.serve_forever() <commit_msg>Enable debug logging for xmpppy<commit_after>
#!/usr/bin/env python2.7 # coding: utf-8 import inspect import logging logging.basicConfig(level=logging.DEBUG) import time import uuid from comicsbot import ComicsBot from dokuwiki import DokuWiki from roomlogger import RoomLogger execfile("config.py") w = DokuWiki() if w.dokuwiki.login(config["dokuwiki"]["username"], config["dokuwiki"]["password"]): welcome_message = "Hello! I've connected to wiki %s version %s, " \ "xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(), w.dokuwiki.getXMLRPCAPIVersion()) else: welcome_message = "Hi! I cannot authorize to the wiki." w = None room_logger = RoomLogger(config["jabber"]["logdir"]) bot = ComicsBot(config["jabber"]["username"], config["jabber"]["password"], wiki=w, room_logger=room_logger, res=uuid.uuid1()) bot.join_room(config["jabber"]["room"], config["jabber"]["nick"]) time.sleep(1) bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat") bot.serve_forever()
#!/usr/bin/env python2.7 # coding: utf-8 import inspect import logging logging.basicConfig() import time import uuid from comicsbot import ComicsBot from dokuwiki import DokuWiki from roomlogger import RoomLogger execfile("config.py") w = DokuWiki() if w.dokuwiki.login(config["dokuwiki"]["username"], config["dokuwiki"]["password"]): welcome_message = "Hello! I've connected to wiki %s version %s, " \ "xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(), w.dokuwiki.getXMLRPCAPIVersion()) else: welcome_message = "Hi! I cannot authorize to the wiki." w = None room_logger = RoomLogger(config["jabber"]["logdir"]) bot = ComicsBot(config["jabber"]["username"], config["jabber"]["password"], wiki=w, room_logger=room_logger, res=uuid.uuid1()) bot.join_room(config["jabber"]["room"], config["jabber"]["nick"]) time.sleep(1) bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat") bot.serve_forever() Enable debug logging for xmpppy#!/usr/bin/env python2.7 # coding: utf-8 import inspect import logging logging.basicConfig(level=logging.DEBUG) import time import uuid from comicsbot import ComicsBot from dokuwiki import DokuWiki from roomlogger import RoomLogger execfile("config.py") w = DokuWiki() if w.dokuwiki.login(config["dokuwiki"]["username"], config["dokuwiki"]["password"]): welcome_message = "Hello! I've connected to wiki %s version %s, " \ "xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(), w.dokuwiki.getXMLRPCAPIVersion()) else: welcome_message = "Hi! I cannot authorize to the wiki." w = None room_logger = RoomLogger(config["jabber"]["logdir"]) bot = ComicsBot(config["jabber"]["username"], config["jabber"]["password"], wiki=w, room_logger=room_logger, res=uuid.uuid1()) bot.join_room(config["jabber"]["room"], config["jabber"]["nick"]) time.sleep(1) bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat") bot.serve_forever()
<commit_before>#!/usr/bin/env python2.7 # coding: utf-8 import inspect import logging logging.basicConfig() import time import uuid from comicsbot import ComicsBot from dokuwiki import DokuWiki from roomlogger import RoomLogger execfile("config.py") w = DokuWiki() if w.dokuwiki.login(config["dokuwiki"]["username"], config["dokuwiki"]["password"]): welcome_message = "Hello! I've connected to wiki %s version %s, " \ "xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(), w.dokuwiki.getXMLRPCAPIVersion()) else: welcome_message = "Hi! I cannot authorize to the wiki." w = None room_logger = RoomLogger(config["jabber"]["logdir"]) bot = ComicsBot(config["jabber"]["username"], config["jabber"]["password"], wiki=w, room_logger=room_logger, res=uuid.uuid1()) bot.join_room(config["jabber"]["room"], config["jabber"]["nick"]) time.sleep(1) bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat") bot.serve_forever() <commit_msg>Enable debug logging for xmpppy<commit_after>#!/usr/bin/env python2.7 # coding: utf-8 import inspect import logging logging.basicConfig(level=logging.DEBUG) import time import uuid from comicsbot import ComicsBot from dokuwiki import DokuWiki from roomlogger import RoomLogger execfile("config.py") w = DokuWiki() if w.dokuwiki.login(config["dokuwiki"]["username"], config["dokuwiki"]["password"]): welcome_message = "Hello! I've connected to wiki %s version %s, " \ "xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(), w.dokuwiki.getXMLRPCAPIVersion()) else: welcome_message = "Hi! I cannot authorize to the wiki." w = None room_logger = RoomLogger(config["jabber"]["logdir"]) bot = ComicsBot(config["jabber"]["username"], config["jabber"]["password"], wiki=w, room_logger=room_logger, res=uuid.uuid1()) bot.join_room(config["jabber"]["room"], config["jabber"]["nick"]) time.sleep(1) bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat") bot.serve_forever()
556e9f5a9f04b730260268a769cbd7170868f693
opps/__init__.py
opps/__init__.py
# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources pkg_resources.declare_namespace(__name__)
Fix pkg resources declare namespace
Fix pkg resources declare namespace
Python
mit
opps/opps-polls,opps/opps-polls
# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) Fix pkg resources declare namespace
#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources pkg_resources.declare_namespace(__name__)
<commit_before># See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) <commit_msg>Fix pkg resources declare namespace<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources pkg_resources.declare_namespace(__name__)
# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) Fix pkg resources declare namespace#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources pkg_resources.declare_namespace(__name__)
<commit_before># See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) <commit_msg>Fix pkg resources declare namespace<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources pkg_resources.declare_namespace(__name__)
501eb4ee71e47d90c155072b15d8ad840ff01098
voting/management/commands/send_vote_invitation_emails.py
voting/management/commands/send_vote_invitation_emails.py
import datetime from django.core.mail.message import EmailMultiAlternatives from django.core.management.base import BaseCommand from django.template import Context from django.template.loader import get_template from project import settings from voting.models import VoteToken class Command(BaseCommand): def handle(self, *args, **options): voting_enabled = settings.VOTING_ENABLED if not voting_enabled: print 'Voting is disabled' return vote_tokens = VoteToken.objects.filter(token_sent__isnull=True).select_related('user') txt_template = get_template('voting/email/vote_invite.txt') html_template = get_template('voting/email/vote_invite.html') for vote_token in vote_tokens: context = Context({'token': vote_token}) txt = txt_template.render(context) html = html_template.render(context) msg = EmailMultiAlternatives( 'Community voting open', txt, 'WebCamp Zagreb <info@webcampzg.org>', [vote_token.user.email], ) msg.attach_alternative(html, "text/html") msg.send() vote_token.token_sent = datetime.datetime.now() vote_token.save()
import datetime from django.core.mail.message import EmailMultiAlternatives from django.core.management.base import BaseCommand from django.template import Context from django.template.loader import get_template from project import settings from voting.models import VoteToken class Command(BaseCommand): def handle(self, *args, **options): voting_enabled = settings.VOTING_ENABLED if not voting_enabled: print 'Voting is disabled' return vote_tokens = VoteToken.objects.filter(token_sent__isnull=True).select_related('user') txt_template = get_template('voting/email/vote_invite.txt') html_template = get_template('voting/email/vote_invite.html') for vote_token in vote_tokens: context = Context({'token': vote_token}) txt = txt_template.render(context) html = html_template.render(context) msg = EmailMultiAlternatives( 'Community voting open', txt, 'WebCamp Zagreb <info@webcampzg.org>', [vote_token.user.email], ) msg.attach_alternative(html, "text/html") msg.send() print "Voting email sent to %r" % vote_token.user.email vote_token.token_sent = datetime.datetime.now() vote_token.save()
Add print statement to send invite command
Add print statement to send invite command
Python
bsd-3-clause
WebCampZg/conference-web,WebCampZg/conference-web,WebCampZg/conference-web
import datetime from django.core.mail.message import EmailMultiAlternatives from django.core.management.base import BaseCommand from django.template import Context from django.template.loader import get_template from project import settings from voting.models import VoteToken class Command(BaseCommand): def handle(self, *args, **options): voting_enabled = settings.VOTING_ENABLED if not voting_enabled: print 'Voting is disabled' return vote_tokens = VoteToken.objects.filter(token_sent__isnull=True).select_related('user') txt_template = get_template('voting/email/vote_invite.txt') html_template = get_template('voting/email/vote_invite.html') for vote_token in vote_tokens: context = Context({'token': vote_token}) txt = txt_template.render(context) html = html_template.render(context) msg = EmailMultiAlternatives( 'Community voting open', txt, 'WebCamp Zagreb <info@webcampzg.org>', [vote_token.user.email], ) msg.attach_alternative(html, "text/html") msg.send() vote_token.token_sent = datetime.datetime.now() vote_token.save() Add print statement to send invite command
import datetime from django.core.mail.message import EmailMultiAlternatives from django.core.management.base import BaseCommand from django.template import Context from django.template.loader import get_template from project import settings from voting.models import VoteToken class Command(BaseCommand): def handle(self, *args, **options): voting_enabled = settings.VOTING_ENABLED if not voting_enabled: print 'Voting is disabled' return vote_tokens = VoteToken.objects.filter(token_sent__isnull=True).select_related('user') txt_template = get_template('voting/email/vote_invite.txt') html_template = get_template('voting/email/vote_invite.html') for vote_token in vote_tokens: context = Context({'token': vote_token}) txt = txt_template.render(context) html = html_template.render(context) msg = EmailMultiAlternatives( 'Community voting open', txt, 'WebCamp Zagreb <info@webcampzg.org>', [vote_token.user.email], ) msg.attach_alternative(html, "text/html") msg.send() print "Voting email sent to %r" % vote_token.user.email vote_token.token_sent = datetime.datetime.now() vote_token.save()
<commit_before>import datetime from django.core.mail.message import EmailMultiAlternatives from django.core.management.base import BaseCommand from django.template import Context from django.template.loader import get_template from project import settings from voting.models import VoteToken class Command(BaseCommand): def handle(self, *args, **options): voting_enabled = settings.VOTING_ENABLED if not voting_enabled: print 'Voting is disabled' return vote_tokens = VoteToken.objects.filter(token_sent__isnull=True).select_related('user') txt_template = get_template('voting/email/vote_invite.txt') html_template = get_template('voting/email/vote_invite.html') for vote_token in vote_tokens: context = Context({'token': vote_token}) txt = txt_template.render(context) html = html_template.render(context) msg = EmailMultiAlternatives( 'Community voting open', txt, 'WebCamp Zagreb <info@webcampzg.org>', [vote_token.user.email], ) msg.attach_alternative(html, "text/html") msg.send() vote_token.token_sent = datetime.datetime.now() vote_token.save() <commit_msg>Add print statement to send invite command<commit_after>
import datetime from django.core.mail.message import EmailMultiAlternatives from django.core.management.base import BaseCommand from django.template import Context from django.template.loader import get_template from project import settings from voting.models import VoteToken class Command(BaseCommand): def handle(self, *args, **options): voting_enabled = settings.VOTING_ENABLED if not voting_enabled: print 'Voting is disabled' return vote_tokens = VoteToken.objects.filter(token_sent__isnull=True).select_related('user') txt_template = get_template('voting/email/vote_invite.txt') html_template = get_template('voting/email/vote_invite.html') for vote_token in vote_tokens: context = Context({'token': vote_token}) txt = txt_template.render(context) html = html_template.render(context) msg = EmailMultiAlternatives( 'Community voting open', txt, 'WebCamp Zagreb <info@webcampzg.org>', [vote_token.user.email], ) msg.attach_alternative(html, "text/html") msg.send() print "Voting email sent to %r" % vote_token.user.email vote_token.token_sent = datetime.datetime.now() vote_token.save()
import datetime from django.core.mail.message import EmailMultiAlternatives from django.core.management.base import BaseCommand from django.template import Context from django.template.loader import get_template from project import settings from voting.models import VoteToken class Command(BaseCommand): def handle(self, *args, **options): voting_enabled = settings.VOTING_ENABLED if not voting_enabled: print 'Voting is disabled' return vote_tokens = VoteToken.objects.filter(token_sent__isnull=True).select_related('user') txt_template = get_template('voting/email/vote_invite.txt') html_template = get_template('voting/email/vote_invite.html') for vote_token in vote_tokens: context = Context({'token': vote_token}) txt = txt_template.render(context) html = html_template.render(context) msg = EmailMultiAlternatives( 'Community voting open', txt, 'WebCamp Zagreb <info@webcampzg.org>', [vote_token.user.email], ) msg.attach_alternative(html, "text/html") msg.send() vote_token.token_sent = datetime.datetime.now() vote_token.save() Add print statement to send invite commandimport datetime from django.core.mail.message import EmailMultiAlternatives from django.core.management.base import BaseCommand from django.template import Context from django.template.loader import get_template from project import settings from voting.models import VoteToken class Command(BaseCommand): def handle(self, *args, **options): voting_enabled = settings.VOTING_ENABLED if not voting_enabled: print 'Voting is disabled' return vote_tokens = VoteToken.objects.filter(token_sent__isnull=True).select_related('user') txt_template = get_template('voting/email/vote_invite.txt') html_template = get_template('voting/email/vote_invite.html') for vote_token in vote_tokens: context = Context({'token': vote_token}) txt = txt_template.render(context) html = html_template.render(context) msg = EmailMultiAlternatives( 'Community voting open', txt, 'WebCamp Zagreb <info@webcampzg.org>', [vote_token.user.email], ) msg.attach_alternative(html, "text/html") msg.send() print "Voting email sent to %r" % vote_token.user.email vote_token.token_sent = datetime.datetime.now() vote_token.save()
<commit_before>import datetime from django.core.mail.message import EmailMultiAlternatives from django.core.management.base import BaseCommand from django.template import Context from django.template.loader import get_template from project import settings from voting.models import VoteToken class Command(BaseCommand): def handle(self, *args, **options): voting_enabled = settings.VOTING_ENABLED if not voting_enabled: print 'Voting is disabled' return vote_tokens = VoteToken.objects.filter(token_sent__isnull=True).select_related('user') txt_template = get_template('voting/email/vote_invite.txt') html_template = get_template('voting/email/vote_invite.html') for vote_token in vote_tokens: context = Context({'token': vote_token}) txt = txt_template.render(context) html = html_template.render(context) msg = EmailMultiAlternatives( 'Community voting open', txt, 'WebCamp Zagreb <info@webcampzg.org>', [vote_token.user.email], ) msg.attach_alternative(html, "text/html") msg.send() vote_token.token_sent = datetime.datetime.now() vote_token.save() <commit_msg>Add print statement to send invite command<commit_after>import datetime from django.core.mail.message import EmailMultiAlternatives from django.core.management.base import BaseCommand from django.template import Context from django.template.loader import get_template from project import settings from voting.models import VoteToken class Command(BaseCommand): def handle(self, *args, **options): voting_enabled = settings.VOTING_ENABLED if not voting_enabled: print 'Voting is disabled' return vote_tokens = VoteToken.objects.filter(token_sent__isnull=True).select_related('user') txt_template = get_template('voting/email/vote_invite.txt') html_template = get_template('voting/email/vote_invite.html') for vote_token in vote_tokens: context = Context({'token': vote_token}) txt = txt_template.render(context) html = html_template.render(context) msg = EmailMultiAlternatives( 'Community voting open', txt, 'WebCamp Zagreb <info@webcampzg.org>', [vote_token.user.email], ) msg.attach_alternative(html, "text/html") msg.send() print "Voting email sent to %r" % vote_token.user.email vote_token.token_sent = datetime.datetime.now() vote_token.save()
f7a601284d1654671fb87a006cb303bd792e14b4
tracpro/polls/tests/test_utils.py
tracpro/polls/tests/test_utils.py
# coding=utf-8 from __future__ import absolute_import, unicode_literals from tracpro.test.cases import TracProTest from .. import utils class TestExtractWords(TracProTest): def test_extract_words(self): self.assertEqual( utils.extract_words("I think it's good", "eng"), ['think', 'good']) # I and it's are stop words self.assertEqual( utils.extract_words("I think it's good", "kin"), ['think', "it's", 'good']) # no stop words for kin self.assertEqual( utils.extract_words("قلم رصاص", "ara"), ['قلم', 'رصاص'])
# coding=utf-8 from __future__ import absolute_import, unicode_literals from django.test import TestCase from tracpro.test.cases import TracProTest from .. import utils class TestExtractWords(TracProTest): def test_extract_words(self): self.assertEqual( utils.extract_words("I think it's good", "eng"), ['think', 'good']) # I and it's are stop words self.assertEqual( utils.extract_words("I think it's good", "kin"), ['think', "it's", 'good']) # no stop words for kin self.assertEqual( utils.extract_words("قلم رصاص", "ara"), ['قلم', 'رصاص']) class TestCategoryNaturalKey(TestCase): def test_category_sort(self): categories = ['11-20', '1-10', '<100', 'Other', '21-999', '21-99'] categories.sort(key=utils.category_natural_key) self.assertEqual(categories, ['1-10', '11-20', '21-99', '21-999', '<100', 'Other'])
Add test for sorting with category natural key
Add test for sorting with category natural key
Python
bsd-3-clause
xkmato/tracpro,rapidpro/tracpro,rapidpro/tracpro,rapidpro/tracpro,xkmato/tracpro,xkmato/tracpro,xkmato/tracpro
# coding=utf-8 from __future__ import absolute_import, unicode_literals from tracpro.test.cases import TracProTest from .. import utils class TestExtractWords(TracProTest): def test_extract_words(self): self.assertEqual( utils.extract_words("I think it's good", "eng"), ['think', 'good']) # I and it's are stop words self.assertEqual( utils.extract_words("I think it's good", "kin"), ['think', "it's", 'good']) # no stop words for kin self.assertEqual( utils.extract_words("قلم رصاص", "ara"), ['قلم', 'رصاص']) Add test for sorting with category natural key
# coding=utf-8 from __future__ import absolute_import, unicode_literals from django.test import TestCase from tracpro.test.cases import TracProTest from .. import utils class TestExtractWords(TracProTest): def test_extract_words(self): self.assertEqual( utils.extract_words("I think it's good", "eng"), ['think', 'good']) # I and it's are stop words self.assertEqual( utils.extract_words("I think it's good", "kin"), ['think', "it's", 'good']) # no stop words for kin self.assertEqual( utils.extract_words("قلم رصاص", "ara"), ['قلم', 'رصاص']) class TestCategoryNaturalKey(TestCase): def test_category_sort(self): categories = ['11-20', '1-10', '<100', 'Other', '21-999', '21-99'] categories.sort(key=utils.category_natural_key) self.assertEqual(categories, ['1-10', '11-20', '21-99', '21-999', '<100', 'Other'])
<commit_before># coding=utf-8 from __future__ import absolute_import, unicode_literals from tracpro.test.cases import TracProTest from .. import utils class TestExtractWords(TracProTest): def test_extract_words(self): self.assertEqual( utils.extract_words("I think it's good", "eng"), ['think', 'good']) # I and it's are stop words self.assertEqual( utils.extract_words("I think it's good", "kin"), ['think', "it's", 'good']) # no stop words for kin self.assertEqual( utils.extract_words("قلم رصاص", "ara"), ['قلم', 'رصاص']) <commit_msg>Add test for sorting with category natural key<commit_after>
# coding=utf-8 from __future__ import absolute_import, unicode_literals from django.test import TestCase from tracpro.test.cases import TracProTest from .. import utils class TestExtractWords(TracProTest): def test_extract_words(self): self.assertEqual( utils.extract_words("I think it's good", "eng"), ['think', 'good']) # I and it's are stop words self.assertEqual( utils.extract_words("I think it's good", "kin"), ['think', "it's", 'good']) # no stop words for kin self.assertEqual( utils.extract_words("قلم رصاص", "ara"), ['قلم', 'رصاص']) class TestCategoryNaturalKey(TestCase): def test_category_sort(self): categories = ['11-20', '1-10', '<100', 'Other', '21-999', '21-99'] categories.sort(key=utils.category_natural_key) self.assertEqual(categories, ['1-10', '11-20', '21-99', '21-999', '<100', 'Other'])
# coding=utf-8 from __future__ import absolute_import, unicode_literals from tracpro.test.cases import TracProTest from .. import utils class TestExtractWords(TracProTest): def test_extract_words(self): self.assertEqual( utils.extract_words("I think it's good", "eng"), ['think', 'good']) # I and it's are stop words self.assertEqual( utils.extract_words("I think it's good", "kin"), ['think', "it's", 'good']) # no stop words for kin self.assertEqual( utils.extract_words("قلم رصاص", "ara"), ['قلم', 'رصاص']) Add test for sorting with category natural key# coding=utf-8 from __future__ import absolute_import, unicode_literals from django.test import TestCase from tracpro.test.cases import TracProTest from .. import utils class TestExtractWords(TracProTest): def test_extract_words(self): self.assertEqual( utils.extract_words("I think it's good", "eng"), ['think', 'good']) # I and it's are stop words self.assertEqual( utils.extract_words("I think it's good", "kin"), ['think', "it's", 'good']) # no stop words for kin self.assertEqual( utils.extract_words("قلم رصاص", "ara"), ['قلم', 'رصاص']) class TestCategoryNaturalKey(TestCase): def test_category_sort(self): categories = ['11-20', '1-10', '<100', 'Other', '21-999', '21-99'] categories.sort(key=utils.category_natural_key) self.assertEqual(categories, ['1-10', '11-20', '21-99', '21-999', '<100', 'Other'])
<commit_before># coding=utf-8 from __future__ import absolute_import, unicode_literals from tracpro.test.cases import TracProTest from .. import utils class TestExtractWords(TracProTest): def test_extract_words(self): self.assertEqual( utils.extract_words("I think it's good", "eng"), ['think', 'good']) # I and it's are stop words self.assertEqual( utils.extract_words("I think it's good", "kin"), ['think', "it's", 'good']) # no stop words for kin self.assertEqual( utils.extract_words("قلم رصاص", "ara"), ['قلم', 'رصاص']) <commit_msg>Add test for sorting with category natural key<commit_after># coding=utf-8 from __future__ import absolute_import, unicode_literals from django.test import TestCase from tracpro.test.cases import TracProTest from .. import utils class TestExtractWords(TracProTest): def test_extract_words(self): self.assertEqual( utils.extract_words("I think it's good", "eng"), ['think', 'good']) # I and it's are stop words self.assertEqual( utils.extract_words("I think it's good", "kin"), ['think', "it's", 'good']) # no stop words for kin self.assertEqual( utils.extract_words("قلم رصاص", "ara"), ['قلم', 'رصاص']) class TestCategoryNaturalKey(TestCase): def test_category_sort(self): categories = ['11-20', '1-10', '<100', 'Other', '21-999', '21-99'] categories.sort(key=utils.category_natural_key) self.assertEqual(categories, ['1-10', '11-20', '21-99', '21-999', '<100', 'Other'])
e91dc26cc983f98de1efb09cbf687c70ca0f557d
transitions/extensions/locking.py
transitions/extensions/locking.py
from ..core import Machine, Transition, Event from threading import RLock import inspect class LockedMethod: def __init__(self, lock, func): self.lock = lock self.func = func def __call__(self, *args, **kwargs): with self.lock: return self.func(*args, **kwargs) class LockedEvent(Event): def trigger(self, model, *args, **kwargs): with self.machine.rlock: return super(LockedEvent, self).trigger(model, *args, **kwargs) class LockedMachine(Machine): def __init__(self, *args, **kwargs): self.rlock = RLock() super(LockedMachine, self).__init__(*args, **kwargs) def __getattribute__(self, item): f = super(LockedMachine, self).__getattribute__ tmp = f(item) if inspect.ismethod(tmp) and item not in "__getattribute__": return LockedMethod(f('rlock'), tmp) return tmp def __getattr__(self, item): try: return super(LockedMachine, self).__getattribute__(item) except AttributeError: return super(LockedMachine, self).__getattr__(item) @staticmethod def _create_event(*args, **kwargs): return LockedEvent(*args, **kwargs)
from ..core import Machine, Transition, Event, listify from threading import RLock import inspect try: from contextlib import nested # Python 2 except ImportError: from contextlib import ExitStack, contextmanager @contextmanager def nested(*contexts): """ Reimplementation of nested in python 3. """ with ExitStack() as stack: for ctx in contexts: stack.enter_context(ctx) yield contexts class LockedMethod: def __init__(self, context, func): self.context = context self.func = func def __call__(self, *args, **kwargs): with nested(*self.context): return self.func(*args, **kwargs) class LockedEvent(Event): def trigger(self, model, *args, **kwargs): with nested(*self.machine.context): return super(LockedEvent, self).trigger(model, *args, **kwargs) class LockedMachine(Machine): def __init__(self, *args, **kwargs): try: self.context = listify(kwargs.pop('context')) except KeyError: self.context = [RLock()] super(LockedMachine, self).__init__(*args, **kwargs) def __getattribute__(self, item): f = super(LockedMachine, self).__getattribute__ tmp = f(item) if inspect.ismethod(tmp) and item not in "__getattribute__": return LockedMethod(f('context'), tmp) return tmp def __getattr__(self, item): try: return super(LockedMachine, self).__getattribute__(item) except AttributeError: return super(LockedMachine, self).__getattr__(item) @staticmethod def _create_event(*args, **kwargs): return LockedEvent(*args, **kwargs)
Allow injecting a lock, or arbitrary context managers into LockedMachine
Allow injecting a lock, or arbitrary context managers into LockedMachine
Python
mit
pytransitions/transitions,tyarkoni/transitions,pytransitions/transitions
from ..core import Machine, Transition, Event from threading import RLock import inspect class LockedMethod: def __init__(self, lock, func): self.lock = lock self.func = func def __call__(self, *args, **kwargs): with self.lock: return self.func(*args, **kwargs) class LockedEvent(Event): def trigger(self, model, *args, **kwargs): with self.machine.rlock: return super(LockedEvent, self).trigger(model, *args, **kwargs) class LockedMachine(Machine): def __init__(self, *args, **kwargs): self.rlock = RLock() super(LockedMachine, self).__init__(*args, **kwargs) def __getattribute__(self, item): f = super(LockedMachine, self).__getattribute__ tmp = f(item) if inspect.ismethod(tmp) and item not in "__getattribute__": return LockedMethod(f('rlock'), tmp) return tmp def __getattr__(self, item): try: return super(LockedMachine, self).__getattribute__(item) except AttributeError: return super(LockedMachine, self).__getattr__(item) @staticmethod def _create_event(*args, **kwargs): return LockedEvent(*args, **kwargs) Allow injecting a lock, or arbitrary context managers into LockedMachine
from ..core import Machine, Transition, Event, listify from threading import RLock import inspect try: from contextlib import nested # Python 2 except ImportError: from contextlib import ExitStack, contextmanager @contextmanager def nested(*contexts): """ Reimplementation of nested in python 3. """ with ExitStack() as stack: for ctx in contexts: stack.enter_context(ctx) yield contexts class LockedMethod: def __init__(self, context, func): self.context = context self.func = func def __call__(self, *args, **kwargs): with nested(*self.context): return self.func(*args, **kwargs) class LockedEvent(Event): def trigger(self, model, *args, **kwargs): with nested(*self.machine.context): return super(LockedEvent, self).trigger(model, *args, **kwargs) class LockedMachine(Machine): def __init__(self, *args, **kwargs): try: self.context = listify(kwargs.pop('context')) except KeyError: self.context = [RLock()] super(LockedMachine, self).__init__(*args, **kwargs) def __getattribute__(self, item): f = super(LockedMachine, self).__getattribute__ tmp = f(item) if inspect.ismethod(tmp) and item not in "__getattribute__": return LockedMethod(f('context'), tmp) return tmp def __getattr__(self, item): try: return super(LockedMachine, self).__getattribute__(item) except AttributeError: return super(LockedMachine, self).__getattr__(item) @staticmethod def _create_event(*args, **kwargs): return LockedEvent(*args, **kwargs)
<commit_before>from ..core import Machine, Transition, Event from threading import RLock import inspect class LockedMethod: def __init__(self, lock, func): self.lock = lock self.func = func def __call__(self, *args, **kwargs): with self.lock: return self.func(*args, **kwargs) class LockedEvent(Event): def trigger(self, model, *args, **kwargs): with self.machine.rlock: return super(LockedEvent, self).trigger(model, *args, **kwargs) class LockedMachine(Machine): def __init__(self, *args, **kwargs): self.rlock = RLock() super(LockedMachine, self).__init__(*args, **kwargs) def __getattribute__(self, item): f = super(LockedMachine, self).__getattribute__ tmp = f(item) if inspect.ismethod(tmp) and item not in "__getattribute__": return LockedMethod(f('rlock'), tmp) return tmp def __getattr__(self, item): try: return super(LockedMachine, self).__getattribute__(item) except AttributeError: return super(LockedMachine, self).__getattr__(item) @staticmethod def _create_event(*args, **kwargs): return LockedEvent(*args, **kwargs) <commit_msg>Allow injecting a lock, or arbitrary context managers into LockedMachine<commit_after>
from ..core import Machine, Transition, Event, listify from threading import RLock import inspect try: from contextlib import nested # Python 2 except ImportError: from contextlib import ExitStack, contextmanager @contextmanager def nested(*contexts): """ Reimplementation of nested in python 3. """ with ExitStack() as stack: for ctx in contexts: stack.enter_context(ctx) yield contexts class LockedMethod: def __init__(self, context, func): self.context = context self.func = func def __call__(self, *args, **kwargs): with nested(*self.context): return self.func(*args, **kwargs) class LockedEvent(Event): def trigger(self, model, *args, **kwargs): with nested(*self.machine.context): return super(LockedEvent, self).trigger(model, *args, **kwargs) class LockedMachine(Machine): def __init__(self, *args, **kwargs): try: self.context = listify(kwargs.pop('context')) except KeyError: self.context = [RLock()] super(LockedMachine, self).__init__(*args, **kwargs) def __getattribute__(self, item): f = super(LockedMachine, self).__getattribute__ tmp = f(item) if inspect.ismethod(tmp) and item not in "__getattribute__": return LockedMethod(f('context'), tmp) return tmp def __getattr__(self, item): try: return super(LockedMachine, self).__getattribute__(item) except AttributeError: return super(LockedMachine, self).__getattr__(item) @staticmethod def _create_event(*args, **kwargs): return LockedEvent(*args, **kwargs)
from ..core import Machine, Transition, Event from threading import RLock import inspect class LockedMethod: def __init__(self, lock, func): self.lock = lock self.func = func def __call__(self, *args, **kwargs): with self.lock: return self.func(*args, **kwargs) class LockedEvent(Event): def trigger(self, model, *args, **kwargs): with self.machine.rlock: return super(LockedEvent, self).trigger(model, *args, **kwargs) class LockedMachine(Machine): def __init__(self, *args, **kwargs): self.rlock = RLock() super(LockedMachine, self).__init__(*args, **kwargs) def __getattribute__(self, item): f = super(LockedMachine, self).__getattribute__ tmp = f(item) if inspect.ismethod(tmp) and item not in "__getattribute__": return LockedMethod(f('rlock'), tmp) return tmp def __getattr__(self, item): try: return super(LockedMachine, self).__getattribute__(item) except AttributeError: return super(LockedMachine, self).__getattr__(item) @staticmethod def _create_event(*args, **kwargs): return LockedEvent(*args, **kwargs) Allow injecting a lock, or arbitrary context managers into LockedMachinefrom ..core import Machine, Transition, Event, listify from threading import RLock import inspect try: from contextlib import nested # Python 2 except ImportError: from contextlib import ExitStack, contextmanager @contextmanager def nested(*contexts): """ Reimplementation of nested in python 3. """ with ExitStack() as stack: for ctx in contexts: stack.enter_context(ctx) yield contexts class LockedMethod: def __init__(self, context, func): self.context = context self.func = func def __call__(self, *args, **kwargs): with nested(*self.context): return self.func(*args, **kwargs) class LockedEvent(Event): def trigger(self, model, *args, **kwargs): with nested(*self.machine.context): return super(LockedEvent, self).trigger(model, *args, **kwargs) class LockedMachine(Machine): def __init__(self, *args, **kwargs): try: self.context = listify(kwargs.pop('context')) except KeyError: self.context = [RLock()] super(LockedMachine, self).__init__(*args, **kwargs) def __getattribute__(self, item): f = super(LockedMachine, self).__getattribute__ tmp = f(item) if inspect.ismethod(tmp) and item not in "__getattribute__": return LockedMethod(f('context'), tmp) return tmp def __getattr__(self, item): try: return super(LockedMachine, self).__getattribute__(item) except AttributeError: return super(LockedMachine, self).__getattr__(item) @staticmethod def _create_event(*args, **kwargs): return LockedEvent(*args, **kwargs)
<commit_before>from ..core import Machine, Transition, Event from threading import RLock import inspect class LockedMethod: def __init__(self, lock, func): self.lock = lock self.func = func def __call__(self, *args, **kwargs): with self.lock: return self.func(*args, **kwargs) class LockedEvent(Event): def trigger(self, model, *args, **kwargs): with self.machine.rlock: return super(LockedEvent, self).trigger(model, *args, **kwargs) class LockedMachine(Machine): def __init__(self, *args, **kwargs): self.rlock = RLock() super(LockedMachine, self).__init__(*args, **kwargs) def __getattribute__(self, item): f = super(LockedMachine, self).__getattribute__ tmp = f(item) if inspect.ismethod(tmp) and item not in "__getattribute__": return LockedMethod(f('rlock'), tmp) return tmp def __getattr__(self, item): try: return super(LockedMachine, self).__getattribute__(item) except AttributeError: return super(LockedMachine, self).__getattr__(item) @staticmethod def _create_event(*args, **kwargs): return LockedEvent(*args, **kwargs) <commit_msg>Allow injecting a lock, or arbitrary context managers into LockedMachine<commit_after>from ..core import Machine, Transition, Event, listify from threading import RLock import inspect try: from contextlib import nested # Python 2 except ImportError: from contextlib import ExitStack, contextmanager @contextmanager def nested(*contexts): """ Reimplementation of nested in python 3. """ with ExitStack() as stack: for ctx in contexts: stack.enter_context(ctx) yield contexts class LockedMethod: def __init__(self, context, func): self.context = context self.func = func def __call__(self, *args, **kwargs): with nested(*self.context): return self.func(*args, **kwargs) class LockedEvent(Event): def trigger(self, model, *args, **kwargs): with nested(*self.machine.context): return super(LockedEvent, self).trigger(model, *args, **kwargs) class LockedMachine(Machine): def __init__(self, *args, **kwargs): try: self.context = listify(kwargs.pop('context')) except KeyError: self.context = [RLock()] super(LockedMachine, self).__init__(*args, **kwargs) def __getattribute__(self, item): f = super(LockedMachine, self).__getattribute__ tmp = f(item) if inspect.ismethod(tmp) and item not in "__getattribute__": return LockedMethod(f('context'), tmp) return tmp def __getattr__(self, item): try: return super(LockedMachine, self).__getattribute__(item) except AttributeError: return super(LockedMachine, self).__getattr__(item) @staticmethod def _create_event(*args, **kwargs): return LockedEvent(*args, **kwargs)
9839041ca70b40ec37fcd296e4aa8d75e1c72f03
run.py
run.py
from app.plugin import app from app.route import build_route if __name__ == '__main__': build_route(app) app.run()
from app.app import app from app.route import build_route if __name__ == '__main__': build_route(app) app.run()
Use app in app module
Use app in app module
Python
mit
Brok-Bucholtz/CloneTube,Brok-Bucholtz/CloneTube,Brok-Bucholtz/CloneTube
from app.plugin import app from app.route import build_route if __name__ == '__main__': build_route(app) app.run() Use app in app module
from app.app import app from app.route import build_route if __name__ == '__main__': build_route(app) app.run()
<commit_before>from app.plugin import app from app.route import build_route if __name__ == '__main__': build_route(app) app.run() <commit_msg>Use app in app module<commit_after>
from app.app import app from app.route import build_route if __name__ == '__main__': build_route(app) app.run()
from app.plugin import app from app.route import build_route if __name__ == '__main__': build_route(app) app.run() Use app in app modulefrom app.app import app from app.route import build_route if __name__ == '__main__': build_route(app) app.run()
<commit_before>from app.plugin import app from app.route import build_route if __name__ == '__main__': build_route(app) app.run() <commit_msg>Use app in app module<commit_after>from app.app import app from app.route import build_route if __name__ == '__main__': build_route(app) app.run()
954fae8ece0c1f2c36a9f8eace9d060546022b2e
filters/tests/config_test.py
filters/tests/config_test.py
from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs('__main__'), dict) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old)
"""Test configuration utilities.""" from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs(config), dict) def test_get_module_funcs_notempty(self): """Test the return value functions length.""" self.assertGreater(len(config._get_funcs(config).items()), 0) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old)
Remove protected class access, add module docstrings.
Remove protected class access, add module docstrings.
Python
mit
christabor/flask_extras,christabor/jinja2_template_pack,christabor/jinja2_template_pack,christabor/flask_extras
from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs('__main__'), dict) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old) Remove protected class access, add module docstrings.
"""Test configuration utilities.""" from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs(config), dict) def test_get_module_funcs_notempty(self): """Test the return value functions length.""" self.assertGreater(len(config._get_funcs(config).items()), 0) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old)
<commit_before>from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs('__main__'), dict) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old) <commit_msg>Remove protected class access, add module docstrings.<commit_after>
"""Test configuration utilities.""" from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs(config), dict) def test_get_module_funcs_notempty(self): """Test the return value functions length.""" self.assertGreater(len(config._get_funcs(config).items()), 0) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old)
from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs('__main__'), dict) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old) Remove protected class access, add module docstrings."""Test configuration utilities.""" from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs(config), dict) def test_get_module_funcs_notempty(self): """Test the return value functions length.""" self.assertGreater(len(config._get_funcs(config).items()), 0) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old)
<commit_before>from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs('__main__'), dict) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old) <commit_msg>Remove protected class access, add module docstrings.<commit_after>"""Test configuration utilities.""" from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs(config), dict) def test_get_module_funcs_notempty(self): """Test the return value functions length.""" self.assertGreater(len(config._get_funcs(config).items()), 0) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old)
cad1e9bac1694bcb297a962481a18fac5a90bb0e
froide/publicbody/widgets.py
froide/publicbody/widgets.py
import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super(PublicBodySelect, self).get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': pb.as_data() if pb is not None else None } } }) }) return context
import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super(PublicBodySelect, self).get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': [pb.as_data()] if pb is not None else None } } }) }) return context
Return a list for objects on pb widget
Return a list for objects on pb widget
Python
mit
stefanw/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide
import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super(PublicBodySelect, self).get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': pb.as_data() if pb is not None else None } } }) }) return context Return a list for objects on pb widget
import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super(PublicBodySelect, self).get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': [pb.as_data()] if pb is not None else None } } }) }) return context
<commit_before>import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super(PublicBodySelect, self).get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': pb.as_data() if pb is not None else None } } }) }) return context <commit_msg>Return a list for objects on pb widget<commit_after>
import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super(PublicBodySelect, self).get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': [pb.as_data()] if pb is not None else None } } }) }) return context
import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super(PublicBodySelect, self).get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': pb.as_data() if pb is not None else None } } }) }) return context Return a list for objects on pb widgetimport json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super(PublicBodySelect, self).get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': [pb.as_data()] if pb is not None else None } } }) }) return context
<commit_before>import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super(PublicBodySelect, self).get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': pb.as_data() if pb is not None else None } } }) }) return context <commit_msg>Return a list for objects on pb widget<commit_after>import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super(PublicBodySelect, self).get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': [pb.as_data()] if pb is not None else None } } }) }) return context
edca0ed4d7a03c0cd36a0ff132d6a9b89c374203
lizard_auth_server/utils.py
lizard_auth_server/utils.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from random import SystemRandom from django.conf import settings import string # Note: the code in this module must be identical in both lizard-auth-server # and lizard-auth-client! random = SystemRandom() KEY_CHARACTERS = string.letters + string.digits # Keys that can be directly copied from the User object and passed to the # client. SIMPLE_KEYS = [ 'pk', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_superuser', ] def default_gen_secret_key(length=40): return ''.join([random.choice(KEY_CHARACTERS) for _ in range(length)]) def gen_secret_key(length=40): generator = getattr(settings, 'SSO_KEYGENERATOR', default_gen_secret_key) return generator(length)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from random import SystemRandom from django.conf import settings import string # Note: the code in this module must be identical in both lizard-auth-server # and lizard-auth-client! random = SystemRandom() KEY_CHARACTERS = string.letters + string.digits # Keys that can be directly copied from the User object and passed to the # client. SIMPLE_KEYS = [ 'pk', 'username', 'first_name', 'last_name', 'email', 'is_active', 'is_staff', 'is_superuser', ] def default_gen_secret_key(length=40): return ''.join([random.choice(KEY_CHARACTERS) for _ in range(length)]) def gen_secret_key(length=40): generator = getattr(settings, 'SSO_KEYGENERATOR', default_gen_secret_key) return generator(length)
Add is_active to the list of keys to be dumped as json
Add is_active to the list of keys to be dumped as json
Python
mit
lizardsystem/lizard-auth-server,lizardsystem/lizard-auth-server
# -*- coding: utf-8 -*- from __future__ import unicode_literals from random import SystemRandom from django.conf import settings import string # Note: the code in this module must be identical in both lizard-auth-server # and lizard-auth-client! random = SystemRandom() KEY_CHARACTERS = string.letters + string.digits # Keys that can be directly copied from the User object and passed to the # client. SIMPLE_KEYS = [ 'pk', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_superuser', ] def default_gen_secret_key(length=40): return ''.join([random.choice(KEY_CHARACTERS) for _ in range(length)]) def gen_secret_key(length=40): generator = getattr(settings, 'SSO_KEYGENERATOR', default_gen_secret_key) return generator(length) Add is_active to the list of keys to be dumped as json
# -*- coding: utf-8 -*- from __future__ import unicode_literals from random import SystemRandom from django.conf import settings import string # Note: the code in this module must be identical in both lizard-auth-server # and lizard-auth-client! random = SystemRandom() KEY_CHARACTERS = string.letters + string.digits # Keys that can be directly copied from the User object and passed to the # client. SIMPLE_KEYS = [ 'pk', 'username', 'first_name', 'last_name', 'email', 'is_active', 'is_staff', 'is_superuser', ] def default_gen_secret_key(length=40): return ''.join([random.choice(KEY_CHARACTERS) for _ in range(length)]) def gen_secret_key(length=40): generator = getattr(settings, 'SSO_KEYGENERATOR', default_gen_secret_key) return generator(length)
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from random import SystemRandom from django.conf import settings import string # Note: the code in this module must be identical in both lizard-auth-server # and lizard-auth-client! random = SystemRandom() KEY_CHARACTERS = string.letters + string.digits # Keys that can be directly copied from the User object and passed to the # client. SIMPLE_KEYS = [ 'pk', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_superuser', ] def default_gen_secret_key(length=40): return ''.join([random.choice(KEY_CHARACTERS) for _ in range(length)]) def gen_secret_key(length=40): generator = getattr(settings, 'SSO_KEYGENERATOR', default_gen_secret_key) return generator(length) <commit_msg>Add is_active to the list of keys to be dumped as json<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from random import SystemRandom from django.conf import settings import string # Note: the code in this module must be identical in both lizard-auth-server # and lizard-auth-client! random = SystemRandom() KEY_CHARACTERS = string.letters + string.digits # Keys that can be directly copied from the User object and passed to the # client. SIMPLE_KEYS = [ 'pk', 'username', 'first_name', 'last_name', 'email', 'is_active', 'is_staff', 'is_superuser', ] def default_gen_secret_key(length=40): return ''.join([random.choice(KEY_CHARACTERS) for _ in range(length)]) def gen_secret_key(length=40): generator = getattr(settings, 'SSO_KEYGENERATOR', default_gen_secret_key) return generator(length)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from random import SystemRandom from django.conf import settings import string # Note: the code in this module must be identical in both lizard-auth-server # and lizard-auth-client! random = SystemRandom() KEY_CHARACTERS = string.letters + string.digits # Keys that can be directly copied from the User object and passed to the # client. SIMPLE_KEYS = [ 'pk', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_superuser', ] def default_gen_secret_key(length=40): return ''.join([random.choice(KEY_CHARACTERS) for _ in range(length)]) def gen_secret_key(length=40): generator = getattr(settings, 'SSO_KEYGENERATOR', default_gen_secret_key) return generator(length) Add is_active to the list of keys to be dumped as json# -*- coding: utf-8 -*- from __future__ import unicode_literals from random import SystemRandom from django.conf import settings import string # Note: the code in this module must be identical in both lizard-auth-server # and lizard-auth-client! random = SystemRandom() KEY_CHARACTERS = string.letters + string.digits # Keys that can be directly copied from the User object and passed to the # client. SIMPLE_KEYS = [ 'pk', 'username', 'first_name', 'last_name', 'email', 'is_active', 'is_staff', 'is_superuser', ] def default_gen_secret_key(length=40): return ''.join([random.choice(KEY_CHARACTERS) for _ in range(length)]) def gen_secret_key(length=40): generator = getattr(settings, 'SSO_KEYGENERATOR', default_gen_secret_key) return generator(length)
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from random import SystemRandom from django.conf import settings import string # Note: the code in this module must be identical in both lizard-auth-server # and lizard-auth-client! random = SystemRandom() KEY_CHARACTERS = string.letters + string.digits # Keys that can be directly copied from the User object and passed to the # client. SIMPLE_KEYS = [ 'pk', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_superuser', ] def default_gen_secret_key(length=40): return ''.join([random.choice(KEY_CHARACTERS) for _ in range(length)]) def gen_secret_key(length=40): generator = getattr(settings, 'SSO_KEYGENERATOR', default_gen_secret_key) return generator(length) <commit_msg>Add is_active to the list of keys to be dumped as json<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from random import SystemRandom from django.conf import settings import string # Note: the code in this module must be identical in both lizard-auth-server # and lizard-auth-client! random = SystemRandom() KEY_CHARACTERS = string.letters + string.digits # Keys that can be directly copied from the User object and passed to the # client. SIMPLE_KEYS = [ 'pk', 'username', 'first_name', 'last_name', 'email', 'is_active', 'is_staff', 'is_superuser', ] def default_gen_secret_key(length=40): return ''.join([random.choice(KEY_CHARACTERS) for _ in range(length)]) def gen_secret_key(length=40): generator = getattr(settings, 'SSO_KEYGENERATOR', default_gen_secret_key) return generator(length)
5e9dda55d69749eb28c664150a64ad9a6a849b12
tools/grit/grit/extern/FP.py
tools/grit/grit/extern/FP.py
#!/usr/bin/python2.2 # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import md5 """64-bit fingerprint support for strings. Usage: from extern import FP print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!') """ def UnsignedFingerPrint(str, encoding='utf-8'): """Generate a 64-bit fingerprint by taking the first half of the md5 of the string.""" hex128 = md5.new(str).hexdigest() int64 = long(hex128[:16], 16) return int64 def FingerPrint(str, encoding='utf-8'): fp = UnsignedFingerPrint(str, encoding=encoding) # interpret fingerprint as signed longs if fp & 0x8000000000000000L: fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1) return fp
#!/usr/bin/python # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import md5 """64-bit fingerprint support for strings. Usage: from extern import FP print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!') """ def UnsignedFingerPrint(str, encoding='utf-8'): """Generate a 64-bit fingerprint by taking the first half of the md5 of the string.""" hex128 = md5.new(str).hexdigest() int64 = long(hex128[:16], 16) return int64 def FingerPrint(str, encoding='utf-8'): fp = UnsignedFingerPrint(str, encoding=encoding) # interpret fingerprint as signed longs if fp & 0x8000000000000000L: fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1) return fp
Remove version number from Python shebang.
Remove version number from Python shebang. On special request from someone trying to purge python2.2 from code indexed internally at Google. git-svn-id: http://src.chromium.org/svn/trunk/src@7071 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 6b204b6013b516c1f312ac19097dcdc068f85b93
Python
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
#!/usr/bin/python2.2 # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import md5 """64-bit fingerprint support for strings. Usage: from extern import FP print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!') """ def UnsignedFingerPrint(str, encoding='utf-8'): """Generate a 64-bit fingerprint by taking the first half of the md5 of the string.""" hex128 = md5.new(str).hexdigest() int64 = long(hex128[:16], 16) return int64 def FingerPrint(str, encoding='utf-8'): fp = UnsignedFingerPrint(str, encoding=encoding) # interpret fingerprint as signed longs if fp & 0x8000000000000000L: fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1) return fp Remove version number from Python shebang. On special request from someone trying to purge python2.2 from code indexed internally at Google. git-svn-id: http://src.chromium.org/svn/trunk/src@7071 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 6b204b6013b516c1f312ac19097dcdc068f85b93
#!/usr/bin/python # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import md5 """64-bit fingerprint support for strings. Usage: from extern import FP print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!') """ def UnsignedFingerPrint(str, encoding='utf-8'): """Generate a 64-bit fingerprint by taking the first half of the md5 of the string.""" hex128 = md5.new(str).hexdigest() int64 = long(hex128[:16], 16) return int64 def FingerPrint(str, encoding='utf-8'): fp = UnsignedFingerPrint(str, encoding=encoding) # interpret fingerprint as signed longs if fp & 0x8000000000000000L: fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1) return fp
<commit_before>#!/usr/bin/python2.2 # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import md5 """64-bit fingerprint support for strings. Usage: from extern import FP print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!') """ def UnsignedFingerPrint(str, encoding='utf-8'): """Generate a 64-bit fingerprint by taking the first half of the md5 of the string.""" hex128 = md5.new(str).hexdigest() int64 = long(hex128[:16], 16) return int64 def FingerPrint(str, encoding='utf-8'): fp = UnsignedFingerPrint(str, encoding=encoding) # interpret fingerprint as signed longs if fp & 0x8000000000000000L: fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1) return fp <commit_msg>Remove version number from Python shebang. On special request from someone trying to purge python2.2 from code indexed internally at Google. git-svn-id: http://src.chromium.org/svn/trunk/src@7071 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 6b204b6013b516c1f312ac19097dcdc068f85b93<commit_after>
#!/usr/bin/python # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import md5 """64-bit fingerprint support for strings. Usage: from extern import FP print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!') """ def UnsignedFingerPrint(str, encoding='utf-8'): """Generate a 64-bit fingerprint by taking the first half of the md5 of the string.""" hex128 = md5.new(str).hexdigest() int64 = long(hex128[:16], 16) return int64 def FingerPrint(str, encoding='utf-8'): fp = UnsignedFingerPrint(str, encoding=encoding) # interpret fingerprint as signed longs if fp & 0x8000000000000000L: fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1) return fp
#!/usr/bin/python2.2 # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import md5 """64-bit fingerprint support for strings. Usage: from extern import FP print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!') """ def UnsignedFingerPrint(str, encoding='utf-8'): """Generate a 64-bit fingerprint by taking the first half of the md5 of the string.""" hex128 = md5.new(str).hexdigest() int64 = long(hex128[:16], 16) return int64 def FingerPrint(str, encoding='utf-8'): fp = UnsignedFingerPrint(str, encoding=encoding) # interpret fingerprint as signed longs if fp & 0x8000000000000000L: fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1) return fp Remove version number from Python shebang. On special request from someone trying to purge python2.2 from code indexed internally at Google. git-svn-id: http://src.chromium.org/svn/trunk/src@7071 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 6b204b6013b516c1f312ac19097dcdc068f85b93#!/usr/bin/python # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import md5 """64-bit fingerprint support for strings. Usage: from extern import FP print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!') """ def UnsignedFingerPrint(str, encoding='utf-8'): """Generate a 64-bit fingerprint by taking the first half of the md5 of the string.""" hex128 = md5.new(str).hexdigest() int64 = long(hex128[:16], 16) return int64 def FingerPrint(str, encoding='utf-8'): fp = UnsignedFingerPrint(str, encoding=encoding) # interpret fingerprint as signed longs if fp & 0x8000000000000000L: fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1) return fp
<commit_before>#!/usr/bin/python2.2 # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import md5 """64-bit fingerprint support for strings. Usage: from extern import FP print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!') """ def UnsignedFingerPrint(str, encoding='utf-8'): """Generate a 64-bit fingerprint by taking the first half of the md5 of the string.""" hex128 = md5.new(str).hexdigest() int64 = long(hex128[:16], 16) return int64 def FingerPrint(str, encoding='utf-8'): fp = UnsignedFingerPrint(str, encoding=encoding) # interpret fingerprint as signed longs if fp & 0x8000000000000000L: fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1) return fp <commit_msg>Remove version number from Python shebang. On special request from someone trying to purge python2.2 from code indexed internally at Google. git-svn-id: http://src.chromium.org/svn/trunk/src@7071 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 6b204b6013b516c1f312ac19097dcdc068f85b93<commit_after>#!/usr/bin/python # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import md5 """64-bit fingerprint support for strings. Usage: from extern import FP print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!') """ def UnsignedFingerPrint(str, encoding='utf-8'): """Generate a 64-bit fingerprint by taking the first half of the md5 of the string.""" hex128 = md5.new(str).hexdigest() int64 = long(hex128[:16], 16) return int64 def FingerPrint(str, encoding='utf-8'): fp = UnsignedFingerPrint(str, encoding=encoding) # interpret fingerprint as signed longs if fp & 0x8000000000000000L: fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1) return fp
faae5df8648afbfa5921bd67a7f3e082ba626a95
poyo/__init__.py
poyo/__init__.py
# -*- coding: utf-8 -*- __author__ = 'Raphael Pierzina' __email__ = 'raphael@hackebrot.de' __version__ = '0.1.0' from .parser import parse_string __all__ = ['parse_string']
# -*- coding: utf-8 -*- from .parser import parse_string __author__ = 'Raphael Pierzina' __email__ = 'raphael@hackebrot.de' __version__ = '0.1.0' __all__ = ['parse_string']
Move module level import to top of file
Move module level import to top of file
Python
mit
hackebrot/poyo
# -*- coding: utf-8 -*- __author__ = 'Raphael Pierzina' __email__ = 'raphael@hackebrot.de' __version__ = '0.1.0' from .parser import parse_string __all__ = ['parse_string'] Move module level import to top of file
# -*- coding: utf-8 -*- from .parser import parse_string __author__ = 'Raphael Pierzina' __email__ = 'raphael@hackebrot.de' __version__ = '0.1.0' __all__ = ['parse_string']
<commit_before># -*- coding: utf-8 -*- __author__ = 'Raphael Pierzina' __email__ = 'raphael@hackebrot.de' __version__ = '0.1.0' from .parser import parse_string __all__ = ['parse_string'] <commit_msg>Move module level import to top of file<commit_after>
# -*- coding: utf-8 -*- from .parser import parse_string __author__ = 'Raphael Pierzina' __email__ = 'raphael@hackebrot.de' __version__ = '0.1.0' __all__ = ['parse_string']
# -*- coding: utf-8 -*- __author__ = 'Raphael Pierzina' __email__ = 'raphael@hackebrot.de' __version__ = '0.1.0' from .parser import parse_string __all__ = ['parse_string'] Move module level import to top of file# -*- coding: utf-8 -*- from .parser import parse_string __author__ = 'Raphael Pierzina' __email__ = 'raphael@hackebrot.de' __version__ = '0.1.0' __all__ = ['parse_string']
<commit_before># -*- coding: utf-8 -*- __author__ = 'Raphael Pierzina' __email__ = 'raphael@hackebrot.de' __version__ = '0.1.0' from .parser import parse_string __all__ = ['parse_string'] <commit_msg>Move module level import to top of file<commit_after># -*- coding: utf-8 -*- from .parser import parse_string __author__ = 'Raphael Pierzina' __email__ = 'raphael@hackebrot.de' __version__ = '0.1.0' __all__ = ['parse_string']
4c5acfeac467d9323be47da304e6a3e51b28a78d
python/python_condaenv_preamble/time_once.py
python/python_condaenv_preamble/time_once.py
import time class TimeOnce: """Time a sequence of code, allowing access to the time difference in seconds. Example without exception: elapsed = TimeOnce() with elapsed: print('sleeping ...') time.sleep(3) print("elapsed", elapsed) Example with exception: elapsed = TimeOnce() try: with elapsed: print('sleeping ...') time.sleep(3) raise ValueError('foo') print("elapsed inner", elapsed) finally: print("elapsed outer", elapsed) """ def __init__(self): self.t0 = None # An invalid value. def __enter__(self): self.t0 = time.time() def __exit__(self, type, value, traceback): self.dt = time.time() - self.t0 def get_elapsed(self): return self.dt def __str__(self): return str(self.dt)
import time class TimeOnce: """Time a sequence of code, allowing access to the time difference in seconds. Example without exception: elapsed = TimeOnce() with elapsed: print('sleeping ...') time.sleep(3) print("elapsed", elapsed) Example with exception: elapsed = TimeOnce() try: with elapsed: print('sleeping ...') time.sleep(3) raise ValueError('foo') print("elapsed inner", elapsed) finally: print("elapsed outer", elapsed) """ def __init__(self): self.t0 = None # An invalid value. def __enter__(self): self.t0 = time.time() def __exit__(self, type, value, traceback): self.dt = time.time() - self.t0 def get_elapsed(self): return self.dt def __str__(self): return str(self.dt) def __float__(self): return self.dt
Add __float__ operator to TimeOnce
Add __float__ operator to TimeOnce
Python
mit
bgoodr/how-to,bgoodr/how-to
import time class TimeOnce: """Time a sequence of code, allowing access to the time difference in seconds. Example without exception: elapsed = TimeOnce() with elapsed: print('sleeping ...') time.sleep(3) print("elapsed", elapsed) Example with exception: elapsed = TimeOnce() try: with elapsed: print('sleeping ...') time.sleep(3) raise ValueError('foo') print("elapsed inner", elapsed) finally: print("elapsed outer", elapsed) """ def __init__(self): self.t0 = None # An invalid value. def __enter__(self): self.t0 = time.time() def __exit__(self, type, value, traceback): self.dt = time.time() - self.t0 def get_elapsed(self): return self.dt def __str__(self): return str(self.dt) Add __float__ operator to TimeOnce
import time class TimeOnce: """Time a sequence of code, allowing access to the time difference in seconds. Example without exception: elapsed = TimeOnce() with elapsed: print('sleeping ...') time.sleep(3) print("elapsed", elapsed) Example with exception: elapsed = TimeOnce() try: with elapsed: print('sleeping ...') time.sleep(3) raise ValueError('foo') print("elapsed inner", elapsed) finally: print("elapsed outer", elapsed) """ def __init__(self): self.t0 = None # An invalid value. def __enter__(self): self.t0 = time.time() def __exit__(self, type, value, traceback): self.dt = time.time() - self.t0 def get_elapsed(self): return self.dt def __str__(self): return str(self.dt) def __float__(self): return self.dt
<commit_before>import time class TimeOnce: """Time a sequence of code, allowing access to the time difference in seconds. Example without exception: elapsed = TimeOnce() with elapsed: print('sleeping ...') time.sleep(3) print("elapsed", elapsed) Example with exception: elapsed = TimeOnce() try: with elapsed: print('sleeping ...') time.sleep(3) raise ValueError('foo') print("elapsed inner", elapsed) finally: print("elapsed outer", elapsed) """ def __init__(self): self.t0 = None # An invalid value. def __enter__(self): self.t0 = time.time() def __exit__(self, type, value, traceback): self.dt = time.time() - self.t0 def get_elapsed(self): return self.dt def __str__(self): return str(self.dt) <commit_msg>Add __float__ operator to TimeOnce<commit_after>
import time class TimeOnce: """Time a sequence of code, allowing access to the time difference in seconds. Example without exception: elapsed = TimeOnce() with elapsed: print('sleeping ...') time.sleep(3) print("elapsed", elapsed) Example with exception: elapsed = TimeOnce() try: with elapsed: print('sleeping ...') time.sleep(3) raise ValueError('foo') print("elapsed inner", elapsed) finally: print("elapsed outer", elapsed) """ def __init__(self): self.t0 = None # An invalid value. def __enter__(self): self.t0 = time.time() def __exit__(self, type, value, traceback): self.dt = time.time() - self.t0 def get_elapsed(self): return self.dt def __str__(self): return str(self.dt) def __float__(self): return self.dt
import time class TimeOnce: """Time a sequence of code, allowing access to the time difference in seconds. Example without exception: elapsed = TimeOnce() with elapsed: print('sleeping ...') time.sleep(3) print("elapsed", elapsed) Example with exception: elapsed = TimeOnce() try: with elapsed: print('sleeping ...') time.sleep(3) raise ValueError('foo') print("elapsed inner", elapsed) finally: print("elapsed outer", elapsed) """ def __init__(self): self.t0 = None # An invalid value. def __enter__(self): self.t0 = time.time() def __exit__(self, type, value, traceback): self.dt = time.time() - self.t0 def get_elapsed(self): return self.dt def __str__(self): return str(self.dt) Add __float__ operator to TimeOnceimport time class TimeOnce: """Time a sequence of code, allowing access to the time difference in seconds. Example without exception: elapsed = TimeOnce() with elapsed: print('sleeping ...') time.sleep(3) print("elapsed", elapsed) Example with exception: elapsed = TimeOnce() try: with elapsed: print('sleeping ...') time.sleep(3) raise ValueError('foo') print("elapsed inner", elapsed) finally: print("elapsed outer", elapsed) """ def __init__(self): self.t0 = None # An invalid value. def __enter__(self): self.t0 = time.time() def __exit__(self, type, value, traceback): self.dt = time.time() - self.t0 def get_elapsed(self): return self.dt def __str__(self): return str(self.dt) def __float__(self): return self.dt
<commit_before>import time class TimeOnce: """Time a sequence of code, allowing access to the time difference in seconds. Example without exception: elapsed = TimeOnce() with elapsed: print('sleeping ...') time.sleep(3) print("elapsed", elapsed) Example with exception: elapsed = TimeOnce() try: with elapsed: print('sleeping ...') time.sleep(3) raise ValueError('foo') print("elapsed inner", elapsed) finally: print("elapsed outer", elapsed) """ def __init__(self): self.t0 = None # An invalid value. def __enter__(self): self.t0 = time.time() def __exit__(self, type, value, traceback): self.dt = time.time() - self.t0 def get_elapsed(self): return self.dt def __str__(self): return str(self.dt) <commit_msg>Add __float__ operator to TimeOnce<commit_after>import time class TimeOnce: """Time a sequence of code, allowing access to the time difference in seconds. Example without exception: elapsed = TimeOnce() with elapsed: print('sleeping ...') time.sleep(3) print("elapsed", elapsed) Example with exception: elapsed = TimeOnce() try: with elapsed: print('sleeping ...') time.sleep(3) raise ValueError('foo') print("elapsed inner", elapsed) finally: print("elapsed outer", elapsed) """ def __init__(self): self.t0 = None # An invalid value. def __enter__(self): self.t0 = time.time() def __exit__(self, type, value, traceback): self.dt = time.time() - self.t0 def get_elapsed(self): return self.dt def __str__(self): return str(self.dt) def __float__(self): return self.dt
8d80401d19a5635053ceefcbb2bc4cfe8bb7a339
spoppy/config.py
spoppy/config.py
import getpass import os from appdirs import user_cache_dir CONFIG_FILE_NAME = os.path.join( user_cache_dir(appname='spoppy'), '.creds' ) def get_config(): if os.path.exists(CONFIG_FILE_NAME): with open(CONFIG_FILE_NAME, 'r') as f: return [ line.strip() for line in f.readlines() ][:2] return None, None def set_config(username, password): with open(CONFIG_FILE_NAME, 'w') as f: f.write(username) f.write('\n') f.write(password) def get_config_from_user(): username, password = ( input('Username: '), getpass.getpass('Password: ') ) set_config(username, password) return username, password def clear_config(): os.remove(CONFIG_FILE_NAME)
import getpass import os from appdirs import user_cache_dir try: # python2.7 input = raw_input except NameError: pass CONFIG_FILE_NAME = os.path.join( user_cache_dir(appname='spoppy'), '.creds' ) def get_config(): if os.path.exists(CONFIG_FILE_NAME): with open(CONFIG_FILE_NAME, 'r') as f: return [ line.strip() for line in f.readlines() ][:2] return None, None def set_config(username, password): with open(CONFIG_FILE_NAME, 'w') as f: f.write(username) f.write('\n') f.write(password) def get_config_from_user(): username, password = ( input('Username: '), getpass.getpass('Password: ') ) set_config(username, password) return username, password def clear_config(): os.remove(CONFIG_FILE_NAME)
Fix error with saving credentials in python 2.7
Fix error with saving credentials in python 2.7 This fixes #102
Python
mit
sindrig/spoppy,sindrig/spoppy
import getpass import os from appdirs import user_cache_dir CONFIG_FILE_NAME = os.path.join( user_cache_dir(appname='spoppy'), '.creds' ) def get_config(): if os.path.exists(CONFIG_FILE_NAME): with open(CONFIG_FILE_NAME, 'r') as f: return [ line.strip() for line in f.readlines() ][:2] return None, None def set_config(username, password): with open(CONFIG_FILE_NAME, 'w') as f: f.write(username) f.write('\n') f.write(password) def get_config_from_user(): username, password = ( input('Username: '), getpass.getpass('Password: ') ) set_config(username, password) return username, password def clear_config(): os.remove(CONFIG_FILE_NAME) Fix error with saving credentials in python 2.7 This fixes #102
import getpass import os from appdirs import user_cache_dir try: # python2.7 input = raw_input except NameError: pass CONFIG_FILE_NAME = os.path.join( user_cache_dir(appname='spoppy'), '.creds' ) def get_config(): if os.path.exists(CONFIG_FILE_NAME): with open(CONFIG_FILE_NAME, 'r') as f: return [ line.strip() for line in f.readlines() ][:2] return None, None def set_config(username, password): with open(CONFIG_FILE_NAME, 'w') as f: f.write(username) f.write('\n') f.write(password) def get_config_from_user(): username, password = ( input('Username: '), getpass.getpass('Password: ') ) set_config(username, password) return username, password def clear_config(): os.remove(CONFIG_FILE_NAME)
<commit_before>import getpass import os from appdirs import user_cache_dir CONFIG_FILE_NAME = os.path.join( user_cache_dir(appname='spoppy'), '.creds' ) def get_config(): if os.path.exists(CONFIG_FILE_NAME): with open(CONFIG_FILE_NAME, 'r') as f: return [ line.strip() for line in f.readlines() ][:2] return None, None def set_config(username, password): with open(CONFIG_FILE_NAME, 'w') as f: f.write(username) f.write('\n') f.write(password) def get_config_from_user(): username, password = ( input('Username: '), getpass.getpass('Password: ') ) set_config(username, password) return username, password def clear_config(): os.remove(CONFIG_FILE_NAME) <commit_msg>Fix error with saving credentials in python 2.7 This fixes #102<commit_after>
import getpass import os from appdirs import user_cache_dir try: # python2.7 input = raw_input except NameError: pass CONFIG_FILE_NAME = os.path.join( user_cache_dir(appname='spoppy'), '.creds' ) def get_config(): if os.path.exists(CONFIG_FILE_NAME): with open(CONFIG_FILE_NAME, 'r') as f: return [ line.strip() for line in f.readlines() ][:2] return None, None def set_config(username, password): with open(CONFIG_FILE_NAME, 'w') as f: f.write(username) f.write('\n') f.write(password) def get_config_from_user(): username, password = ( input('Username: '), getpass.getpass('Password: ') ) set_config(username, password) return username, password def clear_config(): os.remove(CONFIG_FILE_NAME)
import getpass import os from appdirs import user_cache_dir CONFIG_FILE_NAME = os.path.join( user_cache_dir(appname='spoppy'), '.creds' ) def get_config(): if os.path.exists(CONFIG_FILE_NAME): with open(CONFIG_FILE_NAME, 'r') as f: return [ line.strip() for line in f.readlines() ][:2] return None, None def set_config(username, password): with open(CONFIG_FILE_NAME, 'w') as f: f.write(username) f.write('\n') f.write(password) def get_config_from_user(): username, password = ( input('Username: '), getpass.getpass('Password: ') ) set_config(username, password) return username, password def clear_config(): os.remove(CONFIG_FILE_NAME) Fix error with saving credentials in python 2.7 This fixes #102import getpass import os from appdirs import user_cache_dir try: # python2.7 input = raw_input except NameError: pass CONFIG_FILE_NAME = os.path.join( user_cache_dir(appname='spoppy'), '.creds' ) def get_config(): if os.path.exists(CONFIG_FILE_NAME): with open(CONFIG_FILE_NAME, 'r') as f: return [ line.strip() for line in f.readlines() ][:2] return None, None def set_config(username, password): with open(CONFIG_FILE_NAME, 'w') as f: f.write(username) f.write('\n') f.write(password) def get_config_from_user(): username, password = ( input('Username: '), getpass.getpass('Password: ') ) set_config(username, password) return username, password def clear_config(): os.remove(CONFIG_FILE_NAME)
<commit_before>import getpass import os from appdirs import user_cache_dir CONFIG_FILE_NAME = os.path.join( user_cache_dir(appname='spoppy'), '.creds' ) def get_config(): if os.path.exists(CONFIG_FILE_NAME): with open(CONFIG_FILE_NAME, 'r') as f: return [ line.strip() for line in f.readlines() ][:2] return None, None def set_config(username, password): with open(CONFIG_FILE_NAME, 'w') as f: f.write(username) f.write('\n') f.write(password) def get_config_from_user(): username, password = ( input('Username: '), getpass.getpass('Password: ') ) set_config(username, password) return username, password def clear_config(): os.remove(CONFIG_FILE_NAME) <commit_msg>Fix error with saving credentials in python 2.7 This fixes #102<commit_after>import getpass import os from appdirs import user_cache_dir try: # python2.7 input = raw_input except NameError: pass CONFIG_FILE_NAME = os.path.join( user_cache_dir(appname='spoppy'), '.creds' ) def get_config(): if os.path.exists(CONFIG_FILE_NAME): with open(CONFIG_FILE_NAME, 'r') as f: return [ line.strip() for line in f.readlines() ][:2] return None, None def set_config(username, password): with open(CONFIG_FILE_NAME, 'w') as f: f.write(username) f.write('\n') f.write(password) def get_config_from_user(): username, password = ( input('Username: '), getpass.getpass('Password: ') ) set_config(username, password) return username, password def clear_config(): os.remove(CONFIG_FILE_NAME)
51185cff2c75da068f2f250a61e99472880f11d6
app/duckbot.py
app/duckbot.py
import argparse import discord from discord.ext import commands import config from cmd import general, emotes _DESCRIPTION = '''quack''' def parse_arguments(): parser = argparse.ArgumentParser(description="quack") parser.add_argument('-b', '--botname', required=True, choices=config.bots.keys(), help="Name of bot in config file") return parser.parse_args() args = parse_arguments() bot_info = config.bots[args.botname] CLIENT_ID = bot_info['client_id'] TOKEN = bot_info['token'] bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) # Register commands to bot general.register(bot) emotes.register(bot) @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.oauth_url( CLIENT_ID, permissions=discord.Permissions.text()) print('invite me: %s' % oauth_url) bot.run(TOKEN)
import argparse import discord from discord.ext import commands import config from cmd import general, emotes _DESCRIPTION = '''quack''' def parse_arguments(): parser = argparse.ArgumentParser(description="quack") parser.add_argument('-b', '--botname', required=True, choices=config.bots.keys(), help="Name of bot in config file") return parser.parse_args() def main(): args = parse_arguments() bot_info = config.bots[args.botname] client_id = bot_info['client_id'] token = bot_info['token'] bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) # Register commands to bot general.register(bot) emotes.register(bot) @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.oauth_url( client_id, permissions=discord.Permissions.text()) print('invite me: %s' % oauth_url) bot.run(token) if __name__ == '__main__': main()
Put main bot setup code inside main function
Put main bot setup code inside main function
Python
mit
andrewlin16/duckbot,andrewlin16/duckbot
import argparse import discord from discord.ext import commands import config from cmd import general, emotes _DESCRIPTION = '''quack''' def parse_arguments(): parser = argparse.ArgumentParser(description="quack") parser.add_argument('-b', '--botname', required=True, choices=config.bots.keys(), help="Name of bot in config file") return parser.parse_args() args = parse_arguments() bot_info = config.bots[args.botname] CLIENT_ID = bot_info['client_id'] TOKEN = bot_info['token'] bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) # Register commands to bot general.register(bot) emotes.register(bot) @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.oauth_url( CLIENT_ID, permissions=discord.Permissions.text()) print('invite me: %s' % oauth_url) bot.run(TOKEN) Put main bot setup code inside main function
import argparse import discord from discord.ext import commands import config from cmd import general, emotes _DESCRIPTION = '''quack''' def parse_arguments(): parser = argparse.ArgumentParser(description="quack") parser.add_argument('-b', '--botname', required=True, choices=config.bots.keys(), help="Name of bot in config file") return parser.parse_args() def main(): args = parse_arguments() bot_info = config.bots[args.botname] client_id = bot_info['client_id'] token = bot_info['token'] bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) # Register commands to bot general.register(bot) emotes.register(bot) @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.oauth_url( client_id, permissions=discord.Permissions.text()) print('invite me: %s' % oauth_url) bot.run(token) if __name__ == '__main__': main()
<commit_before>import argparse import discord from discord.ext import commands import config from cmd import general, emotes _DESCRIPTION = '''quack''' def parse_arguments(): parser = argparse.ArgumentParser(description="quack") parser.add_argument('-b', '--botname', required=True, choices=config.bots.keys(), help="Name of bot in config file") return parser.parse_args() args = parse_arguments() bot_info = config.bots[args.botname] CLIENT_ID = bot_info['client_id'] TOKEN = bot_info['token'] bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) # Register commands to bot general.register(bot) emotes.register(bot) @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.oauth_url( CLIENT_ID, permissions=discord.Permissions.text()) print('invite me: %s' % oauth_url) bot.run(TOKEN) <commit_msg>Put main bot setup code inside main function<commit_after>
import argparse import discord from discord.ext import commands import config from cmd import general, emotes _DESCRIPTION = '''quack''' def parse_arguments(): parser = argparse.ArgumentParser(description="quack") parser.add_argument('-b', '--botname', required=True, choices=config.bots.keys(), help="Name of bot in config file") return parser.parse_args() def main(): args = parse_arguments() bot_info = config.bots[args.botname] client_id = bot_info['client_id'] token = bot_info['token'] bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) # Register commands to bot general.register(bot) emotes.register(bot) @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.oauth_url( client_id, permissions=discord.Permissions.text()) print('invite me: %s' % oauth_url) bot.run(token) if __name__ == '__main__': main()
import argparse import discord from discord.ext import commands import config from cmd import general, emotes _DESCRIPTION = '''quack''' def parse_arguments(): parser = argparse.ArgumentParser(description="quack") parser.add_argument('-b', '--botname', required=True, choices=config.bots.keys(), help="Name of bot in config file") return parser.parse_args() args = parse_arguments() bot_info = config.bots[args.botname] CLIENT_ID = bot_info['client_id'] TOKEN = bot_info['token'] bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) # Register commands to bot general.register(bot) emotes.register(bot) @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.oauth_url( CLIENT_ID, permissions=discord.Permissions.text()) print('invite me: %s' % oauth_url) bot.run(TOKEN) Put main bot setup code inside main functionimport argparse import discord from discord.ext import commands import config from cmd import general, emotes _DESCRIPTION = '''quack''' def parse_arguments(): parser = argparse.ArgumentParser(description="quack") parser.add_argument('-b', '--botname', required=True, choices=config.bots.keys(), help="Name of bot in config file") return parser.parse_args() def main(): args = parse_arguments() bot_info = config.bots[args.botname] client_id = bot_info['client_id'] token = bot_info['token'] bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) # Register commands to bot general.register(bot) emotes.register(bot) @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.oauth_url( client_id, permissions=discord.Permissions.text()) print('invite me: %s' % oauth_url) bot.run(token) if __name__ == '__main__': main()
<commit_before>import argparse import discord from discord.ext import commands import config from cmd import general, emotes _DESCRIPTION = '''quack''' def parse_arguments(): parser = argparse.ArgumentParser(description="quack") parser.add_argument('-b', '--botname', required=True, choices=config.bots.keys(), help="Name of bot in config file") return parser.parse_args() args = parse_arguments() bot_info = config.bots[args.botname] CLIENT_ID = bot_info['client_id'] TOKEN = bot_info['token'] bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) # Register commands to bot general.register(bot) emotes.register(bot) @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.oauth_url( CLIENT_ID, permissions=discord.Permissions.text()) print('invite me: %s' % oauth_url) bot.run(TOKEN) <commit_msg>Put main bot setup code inside main function<commit_after>import argparse import discord from discord.ext import commands import config from cmd import general, emotes _DESCRIPTION = '''quack''' def parse_arguments(): parser = argparse.ArgumentParser(description="quack") parser.add_argument('-b', '--botname', required=True, choices=config.bots.keys(), help="Name of bot in config file") return parser.parse_args() def main(): args = parse_arguments() bot_info = config.bots[args.botname] client_id = bot_info['client_id'] token = bot_info['token'] bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) # Register commands to bot general.register(bot) emotes.register(bot) @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.oauth_url( client_id, permissions=discord.Permissions.text()) print('invite me: %s' % oauth_url) bot.run(token) if __name__ == '__main__': main()
4495b28c9483baddcc89097310b0e9699ce13406
app/helpers.py
app/helpers.py
import re import unidecode from datetime import datetime from flask.ext.wtf import regexp is_name = regexp( # not using \w since it allows for unlimited underscores r'^[a-zA-Z0-9]+([ \-\_][a-zA-Z0-9]+)*$', message='Field characters can only be letters and digits with one space, \ underscore or hyphen as separator.' ) def slugify(now, str): """Return slug genereated from date and specified unicoded string.""" date = datetime.date(now) unistr = unidecode.unidecode(str).lower() title = re.sub(r'\W+', '-', unistr).strip('-') return '%i/%i/%i/%s' % (date.year, date.month, date.day, title)
import re import unidecode from datetime import datetime from flask.ext.wtf import regexp is_name = regexp( # not using \w since it allows for unlimited underscores r'^[a-zA-Z0-9]+([ \-\_][a-zA-Z0-9]+)*$', message='Field characters can only be letters and digits with one space, \ underscore or hyphen as separator.' ) def slugify(now, str): """Return slug genereated from date and specified unicoded string.""" date = datetime.date(now) unistr = unidecode.unidecode(str).lower() title = re.sub(r'\W+', '-', unistr).strip('-') return '%i/%i/%i/%s' % (date.year, date.month, date.day, title)
Add row between third party library and standard library import
Add row between third party library and standard library import
Python
mit
thebitstick/Flask-Blog,thebitstick/Flask-Blog
import re import unidecode from datetime import datetime from flask.ext.wtf import regexp is_name = regexp( # not using \w since it allows for unlimited underscores r'^[a-zA-Z0-9]+([ \-\_][a-zA-Z0-9]+)*$', message='Field characters can only be letters and digits with one space, \ underscore or hyphen as separator.' ) def slugify(now, str): """Return slug genereated from date and specified unicoded string.""" date = datetime.date(now) unistr = unidecode.unidecode(str).lower() title = re.sub(r'\W+', '-', unistr).strip('-') return '%i/%i/%i/%s' % (date.year, date.month, date.day, title) Add row between third party library and standard library import
import re import unidecode from datetime import datetime from flask.ext.wtf import regexp is_name = regexp( # not using \w since it allows for unlimited underscores r'^[a-zA-Z0-9]+([ \-\_][a-zA-Z0-9]+)*$', message='Field characters can only be letters and digits with one space, \ underscore or hyphen as separator.' ) def slugify(now, str): """Return slug genereated from date and specified unicoded string.""" date = datetime.date(now) unistr = unidecode.unidecode(str).lower() title = re.sub(r'\W+', '-', unistr).strip('-') return '%i/%i/%i/%s' % (date.year, date.month, date.day, title)
<commit_before>import re import unidecode from datetime import datetime from flask.ext.wtf import regexp is_name = regexp( # not using \w since it allows for unlimited underscores r'^[a-zA-Z0-9]+([ \-\_][a-zA-Z0-9]+)*$', message='Field characters can only be letters and digits with one space, \ underscore or hyphen as separator.' ) def slugify(now, str): """Return slug genereated from date and specified unicoded string.""" date = datetime.date(now) unistr = unidecode.unidecode(str).lower() title = re.sub(r'\W+', '-', unistr).strip('-') return '%i/%i/%i/%s' % (date.year, date.month, date.day, title) <commit_msg>Add row between third party library and standard library import<commit_after>
import re import unidecode from datetime import datetime from flask.ext.wtf import regexp is_name = regexp( # not using \w since it allows for unlimited underscores r'^[a-zA-Z0-9]+([ \-\_][a-zA-Z0-9]+)*$', message='Field characters can only be letters and digits with one space, \ underscore or hyphen as separator.' ) def slugify(now, str): """Return slug genereated from date and specified unicoded string.""" date = datetime.date(now) unistr = unidecode.unidecode(str).lower() title = re.sub(r'\W+', '-', unistr).strip('-') return '%i/%i/%i/%s' % (date.year, date.month, date.day, title)
import re import unidecode from datetime import datetime from flask.ext.wtf import regexp is_name = regexp( # not using \w since it allows for unlimited underscores r'^[a-zA-Z0-9]+([ \-\_][a-zA-Z0-9]+)*$', message='Field characters can only be letters and digits with one space, \ underscore or hyphen as separator.' ) def slugify(now, str): """Return slug genereated from date and specified unicoded string.""" date = datetime.date(now) unistr = unidecode.unidecode(str).lower() title = re.sub(r'\W+', '-', unistr).strip('-') return '%i/%i/%i/%s' % (date.year, date.month, date.day, title) Add row between third party library and standard library importimport re import unidecode from datetime import datetime from flask.ext.wtf import regexp is_name = regexp( # not using \w since it allows for unlimited underscores r'^[a-zA-Z0-9]+([ \-\_][a-zA-Z0-9]+)*$', message='Field characters can only be letters and digits with one space, \ underscore or hyphen as separator.' ) def slugify(now, str): """Return slug genereated from date and specified unicoded string.""" date = datetime.date(now) unistr = unidecode.unidecode(str).lower() title = re.sub(r'\W+', '-', unistr).strip('-') return '%i/%i/%i/%s' % (date.year, date.month, date.day, title)
<commit_before>import re import unidecode from datetime import datetime from flask.ext.wtf import regexp is_name = regexp( # not using \w since it allows for unlimited underscores r'^[a-zA-Z0-9]+([ \-\_][a-zA-Z0-9]+)*$', message='Field characters can only be letters and digits with one space, \ underscore or hyphen as separator.' ) def slugify(now, str): """Return slug genereated from date and specified unicoded string.""" date = datetime.date(now) unistr = unidecode.unidecode(str).lower() title = re.sub(r'\W+', '-', unistr).strip('-') return '%i/%i/%i/%s' % (date.year, date.month, date.day, title) <commit_msg>Add row between third party library and standard library import<commit_after>import re import unidecode from datetime import datetime from flask.ext.wtf import regexp is_name = regexp( # not using \w since it allows for unlimited underscores r'^[a-zA-Z0-9]+([ \-\_][a-zA-Z0-9]+)*$', message='Field characters can only be letters and digits with one space, \ underscore or hyphen as separator.' ) def slugify(now, str): """Return slug genereated from date and specified unicoded string.""" date = datetime.date(now) unistr = unidecode.unidecode(str).lower() title = re.sub(r'\W+', '-', unistr).strip('-') return '%i/%i/%i/%s' % (date.year, date.month, date.day, title)
5a744dc3a27564f0d8c7fe618c6900bff711420a
funnel/forms/usergroup.py
funnel/forms/usergroup.py
# -*- coding: utf-8 -*- from baseframe import __ import baseframe.forms as forms from baseframe.forms.sqlalchemy import AvailableName __all__ = ['UserGroupForm'] class UserGroupForm(forms.Form): name = forms.StringField(__("URL name"), validators=[forms.validators.DataRequired(), forms.validators.ValidName(), AvailableName()]) title = forms.StringField(__("Title"), validators=[forms.validators.DataRequired()]) users = forms.TextAreaField(__("Users"), validators=[forms.validators.DataRequired()], description=__("Usernames or email addresses, one per line"))
# -*- coding: utf-8 -*- from baseframe import __ import baseframe.forms as forms from baseframe.forms.sqlalchemy import AvailableName from ..models import User from .. import lastuser __all__ = ['UserGroupForm'] class UserGroupForm(forms.Form): name = forms.StringField(__("URL name"), validators=[forms.validators.DataRequired(), forms.validators.ValidName(), AvailableName()]) title = forms.StringField(__("Title"), validators=[forms.validators.DataRequired()]) users = forms.UserSelectMultiField(__("Users"), validators=[forms.validators.DataRequired()], usermodel=User, lastuser=lastuser)
Change to user select widget
Change to user select widget
Python
agpl-3.0
hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel
# -*- coding: utf-8 -*- from baseframe import __ import baseframe.forms as forms from baseframe.forms.sqlalchemy import AvailableName __all__ = ['UserGroupForm'] class UserGroupForm(forms.Form): name = forms.StringField(__("URL name"), validators=[forms.validators.DataRequired(), forms.validators.ValidName(), AvailableName()]) title = forms.StringField(__("Title"), validators=[forms.validators.DataRequired()]) users = forms.TextAreaField(__("Users"), validators=[forms.validators.DataRequired()], description=__("Usernames or email addresses, one per line")) Change to user select widget
# -*- coding: utf-8 -*- from baseframe import __ import baseframe.forms as forms from baseframe.forms.sqlalchemy import AvailableName from ..models import User from .. import lastuser __all__ = ['UserGroupForm'] class UserGroupForm(forms.Form): name = forms.StringField(__("URL name"), validators=[forms.validators.DataRequired(), forms.validators.ValidName(), AvailableName()]) title = forms.StringField(__("Title"), validators=[forms.validators.DataRequired()]) users = forms.UserSelectMultiField(__("Users"), validators=[forms.validators.DataRequired()], usermodel=User, lastuser=lastuser)
<commit_before># -*- coding: utf-8 -*- from baseframe import __ import baseframe.forms as forms from baseframe.forms.sqlalchemy import AvailableName __all__ = ['UserGroupForm'] class UserGroupForm(forms.Form): name = forms.StringField(__("URL name"), validators=[forms.validators.DataRequired(), forms.validators.ValidName(), AvailableName()]) title = forms.StringField(__("Title"), validators=[forms.validators.DataRequired()]) users = forms.TextAreaField(__("Users"), validators=[forms.validators.DataRequired()], description=__("Usernames or email addresses, one per line")) <commit_msg>Change to user select widget<commit_after>
# -*- coding: utf-8 -*- from baseframe import __ import baseframe.forms as forms from baseframe.forms.sqlalchemy import AvailableName from ..models import User from .. import lastuser __all__ = ['UserGroupForm'] class UserGroupForm(forms.Form): name = forms.StringField(__("URL name"), validators=[forms.validators.DataRequired(), forms.validators.ValidName(), AvailableName()]) title = forms.StringField(__("Title"), validators=[forms.validators.DataRequired()]) users = forms.UserSelectMultiField(__("Users"), validators=[forms.validators.DataRequired()], usermodel=User, lastuser=lastuser)
# -*- coding: utf-8 -*- from baseframe import __ import baseframe.forms as forms from baseframe.forms.sqlalchemy import AvailableName __all__ = ['UserGroupForm'] class UserGroupForm(forms.Form): name = forms.StringField(__("URL name"), validators=[forms.validators.DataRequired(), forms.validators.ValidName(), AvailableName()]) title = forms.StringField(__("Title"), validators=[forms.validators.DataRequired()]) users = forms.TextAreaField(__("Users"), validators=[forms.validators.DataRequired()], description=__("Usernames or email addresses, one per line")) Change to user select widget# -*- coding: utf-8 -*- from baseframe import __ import baseframe.forms as forms from baseframe.forms.sqlalchemy import AvailableName from ..models import User from .. import lastuser __all__ = ['UserGroupForm'] class UserGroupForm(forms.Form): name = forms.StringField(__("URL name"), validators=[forms.validators.DataRequired(), forms.validators.ValidName(), AvailableName()]) title = forms.StringField(__("Title"), validators=[forms.validators.DataRequired()]) users = forms.UserSelectMultiField(__("Users"), validators=[forms.validators.DataRequired()], usermodel=User, lastuser=lastuser)
<commit_before># -*- coding: utf-8 -*- from baseframe import __ import baseframe.forms as forms from baseframe.forms.sqlalchemy import AvailableName __all__ = ['UserGroupForm'] class UserGroupForm(forms.Form): name = forms.StringField(__("URL name"), validators=[forms.validators.DataRequired(), forms.validators.ValidName(), AvailableName()]) title = forms.StringField(__("Title"), validators=[forms.validators.DataRequired()]) users = forms.TextAreaField(__("Users"), validators=[forms.validators.DataRequired()], description=__("Usernames or email addresses, one per line")) <commit_msg>Change to user select widget<commit_after># -*- coding: utf-8 -*- from baseframe import __ import baseframe.forms as forms from baseframe.forms.sqlalchemy import AvailableName from ..models import User from .. import lastuser __all__ = ['UserGroupForm'] class UserGroupForm(forms.Form): name = forms.StringField(__("URL name"), validators=[forms.validators.DataRequired(), forms.validators.ValidName(), AvailableName()]) title = forms.StringField(__("Title"), validators=[forms.validators.DataRequired()]) users = forms.UserSelectMultiField(__("Users"), validators=[forms.validators.DataRequired()], usermodel=User, lastuser=lastuser)
b75df498fe27aec68460a880b6067d970bead926
alchemist_armet/resources.py
alchemist_armet/resources.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, division from armet.connectors.flask import resources as flask_resources from armet.connectors.sqlalchemy import resources as sqlalchemy_resources from armet import utils from alchemist import db __all__ = [ 'Resource', 'ModelResource', ] class Resource(flask_resources.Resource): @property def session(self): return db.session def route(self, *args, **kwargs): try: # Continue on with the cycle. result = utils.super(Resource, self).route(*args, **kwargs) # Commit the session. db.commit() # Return the result. return result except: # Something occurred; rollback the session. db.rollback() # Re-raise the exception. raise class ModelResource(sqlalchemy_resources.ModelResource): def route(self, *args, **kwargs): return utils.super(sqlalchemy_resources.ModelResource, self).route( *args, **kwargs)
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, division from armet.connectors.flask import resources as flask_resources from armet.connectors.sqlalchemy import resources as sqlalchemy_resources from armet import utils from alchemist import db __all__ = [ 'Resource', 'ModelResource', ] class Resource(flask_resources.Resource): @property def session(self): return db.session def route(self, *args, **kwargs): try: # Continue on with the cycle. result = utils.super(Resource, self).route(*args, **kwargs) # Commit the session. db.session.commit() # Return the result. return result except: # Something occurred; rollback the session. db.session.rollback() # Re-raise the exception. raise class ModelResource(sqlalchemy_resources.ModelResource): def route(self, *args, **kwargs): return utils.super(sqlalchemy_resources.ModelResource, self).route( *args, **kwargs)
Update for changes in alchemist.
Update for changes in alchemist.
Python
mit
concordusapps/alchemist-armet
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, division from armet.connectors.flask import resources as flask_resources from armet.connectors.sqlalchemy import resources as sqlalchemy_resources from armet import utils from alchemist import db __all__ = [ 'Resource', 'ModelResource', ] class Resource(flask_resources.Resource): @property def session(self): return db.session def route(self, *args, **kwargs): try: # Continue on with the cycle. result = utils.super(Resource, self).route(*args, **kwargs) # Commit the session. db.commit() # Return the result. return result except: # Something occurred; rollback the session. db.rollback() # Re-raise the exception. raise class ModelResource(sqlalchemy_resources.ModelResource): def route(self, *args, **kwargs): return utils.super(sqlalchemy_resources.ModelResource, self).route( *args, **kwargs) Update for changes in alchemist.
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, division from armet.connectors.flask import resources as flask_resources from armet.connectors.sqlalchemy import resources as sqlalchemy_resources from armet import utils from alchemist import db __all__ = [ 'Resource', 'ModelResource', ] class Resource(flask_resources.Resource): @property def session(self): return db.session def route(self, *args, **kwargs): try: # Continue on with the cycle. result = utils.super(Resource, self).route(*args, **kwargs) # Commit the session. db.session.commit() # Return the result. return result except: # Something occurred; rollback the session. db.session.rollback() # Re-raise the exception. raise class ModelResource(sqlalchemy_resources.ModelResource): def route(self, *args, **kwargs): return utils.super(sqlalchemy_resources.ModelResource, self).route( *args, **kwargs)
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, division from armet.connectors.flask import resources as flask_resources from armet.connectors.sqlalchemy import resources as sqlalchemy_resources from armet import utils from alchemist import db __all__ = [ 'Resource', 'ModelResource', ] class Resource(flask_resources.Resource): @property def session(self): return db.session def route(self, *args, **kwargs): try: # Continue on with the cycle. result = utils.super(Resource, self).route(*args, **kwargs) # Commit the session. db.commit() # Return the result. return result except: # Something occurred; rollback the session. db.rollback() # Re-raise the exception. raise class ModelResource(sqlalchemy_resources.ModelResource): def route(self, *args, **kwargs): return utils.super(sqlalchemy_resources.ModelResource, self).route( *args, **kwargs) <commit_msg>Update for changes in alchemist.<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, division from armet.connectors.flask import resources as flask_resources from armet.connectors.sqlalchemy import resources as sqlalchemy_resources from armet import utils from alchemist import db __all__ = [ 'Resource', 'ModelResource', ] class Resource(flask_resources.Resource): @property def session(self): return db.session def route(self, *args, **kwargs): try: # Continue on with the cycle. result = utils.super(Resource, self).route(*args, **kwargs) # Commit the session. db.session.commit() # Return the result. return result except: # Something occurred; rollback the session. db.session.rollback() # Re-raise the exception. raise class ModelResource(sqlalchemy_resources.ModelResource): def route(self, *args, **kwargs): return utils.super(sqlalchemy_resources.ModelResource, self).route( *args, **kwargs)
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, division from armet.connectors.flask import resources as flask_resources from armet.connectors.sqlalchemy import resources as sqlalchemy_resources from armet import utils from alchemist import db __all__ = [ 'Resource', 'ModelResource', ] class Resource(flask_resources.Resource): @property def session(self): return db.session def route(self, *args, **kwargs): try: # Continue on with the cycle. result = utils.super(Resource, self).route(*args, **kwargs) # Commit the session. db.commit() # Return the result. return result except: # Something occurred; rollback the session. db.rollback() # Re-raise the exception. raise class ModelResource(sqlalchemy_resources.ModelResource): def route(self, *args, **kwargs): return utils.super(sqlalchemy_resources.ModelResource, self).route( *args, **kwargs) Update for changes in alchemist.# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, division from armet.connectors.flask import resources as flask_resources from armet.connectors.sqlalchemy import resources as sqlalchemy_resources from armet import utils from alchemist import db __all__ = [ 'Resource', 'ModelResource', ] class Resource(flask_resources.Resource): @property def session(self): return db.session def route(self, *args, **kwargs): try: # Continue on with the cycle. result = utils.super(Resource, self).route(*args, **kwargs) # Commit the session. db.session.commit() # Return the result. return result except: # Something occurred; rollback the session. db.session.rollback() # Re-raise the exception. raise class ModelResource(sqlalchemy_resources.ModelResource): def route(self, *args, **kwargs): return utils.super(sqlalchemy_resources.ModelResource, self).route( *args, **kwargs)
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, division from armet.connectors.flask import resources as flask_resources from armet.connectors.sqlalchemy import resources as sqlalchemy_resources from armet import utils from alchemist import db __all__ = [ 'Resource', 'ModelResource', ] class Resource(flask_resources.Resource): @property def session(self): return db.session def route(self, *args, **kwargs): try: # Continue on with the cycle. result = utils.super(Resource, self).route(*args, **kwargs) # Commit the session. db.commit() # Return the result. return result except: # Something occurred; rollback the session. db.rollback() # Re-raise the exception. raise class ModelResource(sqlalchemy_resources.ModelResource): def route(self, *args, **kwargs): return utils.super(sqlalchemy_resources.ModelResource, self).route( *args, **kwargs) <commit_msg>Update for changes in alchemist.<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, division from armet.connectors.flask import resources as flask_resources from armet.connectors.sqlalchemy import resources as sqlalchemy_resources from armet import utils from alchemist import db __all__ = [ 'Resource', 'ModelResource', ] class Resource(flask_resources.Resource): @property def session(self): return db.session def route(self, *args, **kwargs): try: # Continue on with the cycle. result = utils.super(Resource, self).route(*args, **kwargs) # Commit the session. db.session.commit() # Return the result. return result except: # Something occurred; rollback the session. db.session.rollback() # Re-raise the exception. raise class ModelResource(sqlalchemy_resources.ModelResource): def route(self, *args, **kwargs): return utils.super(sqlalchemy_resources.ModelResource, self).route( *args, **kwargs)
469d73255365392a821d701b4df9098d97b7546a
judge/toyojjudge/taskrunner.py
judge/toyojjudge/taskrunner.py
import asyncio import logging logger = logging.getLogger(__name__) class TaskRunner: def __init__(self, sandbox_pool, languages, checkers): self.sandbox_pool = sandbox_pool self.languages = languages self.checkers = checkers async def run(self, task): async with self.sandbox_pool.acquire() as box: logger.debug("Running %s", task) lang = self.languages[task.submission.language_name] check = self.checkers[task.testcase.checker_name] await lang.run_task(box, task) if task.verdict is not None: task.accepted = False else: await check.check(box, task)
import asyncio import logging logger = logging.getLogger(__name__) class TaskRunner: def __init__(self, sandbox_pool, languages, checkers): self.sandbox_pool = sandbox_pool self.languages = languages self.checkers = checkers async def run(self, task): async with self.sandbox_pool.acquire() as box: language_name = task.submission.language_name checker_name = task.testcase.checker_name logger.info("Running %s, language %s, checker %s", task, language_name, checker_name) lang = self.languages[language_name] check = self.checkers[checker_name] await lang.run_task(box, task) if task.verdict is not None: task.accepted = False else: await check.check(box, task)
Print running task, language and checker as INFO
judge: Print running task, language and checker as INFO
Python
agpl-3.0
johnchen902/toyoj,johnchen902/toyoj,johnchen902/toyoj,johnchen902/toyoj,johnchen902/toyoj,johnchen902/toyoj
import asyncio import logging logger = logging.getLogger(__name__) class TaskRunner: def __init__(self, sandbox_pool, languages, checkers): self.sandbox_pool = sandbox_pool self.languages = languages self.checkers = checkers async def run(self, task): async with self.sandbox_pool.acquire() as box: logger.debug("Running %s", task) lang = self.languages[task.submission.language_name] check = self.checkers[task.testcase.checker_name] await lang.run_task(box, task) if task.verdict is not None: task.accepted = False else: await check.check(box, task) judge: Print running task, language and checker as INFO
import asyncio import logging logger = logging.getLogger(__name__) class TaskRunner: def __init__(self, sandbox_pool, languages, checkers): self.sandbox_pool = sandbox_pool self.languages = languages self.checkers = checkers async def run(self, task): async with self.sandbox_pool.acquire() as box: language_name = task.submission.language_name checker_name = task.testcase.checker_name logger.info("Running %s, language %s, checker %s", task, language_name, checker_name) lang = self.languages[language_name] check = self.checkers[checker_name] await lang.run_task(box, task) if task.verdict is not None: task.accepted = False else: await check.check(box, task)
<commit_before>import asyncio import logging logger = logging.getLogger(__name__) class TaskRunner: def __init__(self, sandbox_pool, languages, checkers): self.sandbox_pool = sandbox_pool self.languages = languages self.checkers = checkers async def run(self, task): async with self.sandbox_pool.acquire() as box: logger.debug("Running %s", task) lang = self.languages[task.submission.language_name] check = self.checkers[task.testcase.checker_name] await lang.run_task(box, task) if task.verdict is not None: task.accepted = False else: await check.check(box, task) <commit_msg>judge: Print running task, language and checker as INFO<commit_after>
import asyncio import logging logger = logging.getLogger(__name__) class TaskRunner: def __init__(self, sandbox_pool, languages, checkers): self.sandbox_pool = sandbox_pool self.languages = languages self.checkers = checkers async def run(self, task): async with self.sandbox_pool.acquire() as box: language_name = task.submission.language_name checker_name = task.testcase.checker_name logger.info("Running %s, language %s, checker %s", task, language_name, checker_name) lang = self.languages[language_name] check = self.checkers[checker_name] await lang.run_task(box, task) if task.verdict is not None: task.accepted = False else: await check.check(box, task)
import asyncio import logging logger = logging.getLogger(__name__) class TaskRunner: def __init__(self, sandbox_pool, languages, checkers): self.sandbox_pool = sandbox_pool self.languages = languages self.checkers = checkers async def run(self, task): async with self.sandbox_pool.acquire() as box: logger.debug("Running %s", task) lang = self.languages[task.submission.language_name] check = self.checkers[task.testcase.checker_name] await lang.run_task(box, task) if task.verdict is not None: task.accepted = False else: await check.check(box, task) judge: Print running task, language and checker as INFOimport asyncio import logging logger = logging.getLogger(__name__) class TaskRunner: def __init__(self, sandbox_pool, languages, checkers): self.sandbox_pool = sandbox_pool self.languages = languages self.checkers = checkers async def run(self, task): async with self.sandbox_pool.acquire() as box: language_name = task.submission.language_name checker_name = task.testcase.checker_name logger.info("Running %s, language %s, checker %s", task, language_name, checker_name) lang = self.languages[language_name] check = self.checkers[checker_name] await lang.run_task(box, task) if task.verdict is not None: task.accepted = False else: await check.check(box, task)
<commit_before>import asyncio import logging logger = logging.getLogger(__name__) class TaskRunner: def __init__(self, sandbox_pool, languages, checkers): self.sandbox_pool = sandbox_pool self.languages = languages self.checkers = checkers async def run(self, task): async with self.sandbox_pool.acquire() as box: logger.debug("Running %s", task) lang = self.languages[task.submission.language_name] check = self.checkers[task.testcase.checker_name] await lang.run_task(box, task) if task.verdict is not None: task.accepted = False else: await check.check(box, task) <commit_msg>judge: Print running task, language and checker as INFO<commit_after>import asyncio import logging logger = logging.getLogger(__name__) class TaskRunner: def __init__(self, sandbox_pool, languages, checkers): self.sandbox_pool = sandbox_pool self.languages = languages self.checkers = checkers async def run(self, task): async with self.sandbox_pool.acquire() as box: language_name = task.submission.language_name checker_name = task.testcase.checker_name logger.info("Running %s, language %s, checker %s", task, language_name, checker_name) lang = self.languages[language_name] check = self.checkers[checker_name] await lang.run_task(box, task) if task.verdict is not None: task.accepted = False else: await check.check(box, task)
d794fea9cce98c719caef69b1c50f2783da81b1d
pritunl_node/call_buffer.py
pritunl_node/call_buffer.py
from constants import * import collections import uuid class CallBuffer(): def __init__(self): self.waiters = set() self.cache = collections.deque(maxlen=CALL_CACHE_MAX) self.call_waiters = {} def wait_for_calls(self, callback, cursor=None): if cursor: calls = [] cursor_found = False for call in self.cache: if call['id'] == cursor: cursor_found = True continue if not cursor_found: continue calls.append(call) if calls: callback(calls) return self.waiters.add(callback) def return_call(self, id, response): callback = self.call_waiters.pop(id) if callback: callback(response) def create_call(self, command, args, callback): call_id = uuid.uuid4().hex call = { 'id': call_id, 'command': command, 'args': args, } self.call_waiters[call_id] = callback self.cache.append(call) for callback in self.waiters: callback([call]) self.waiters = set()
from constants import * import collections import uuid class CallBuffer(): def __init__(self): self.waiters = set() self.cache = collections.deque(maxlen=CALL_CACHE_MAX) self.call_waiters = {} def wait_for_calls(self, callback, cursor=None): if cursor: calls = [] cursor_found = False for call in self.cache: if call['id'] == cursor: cursor_found = True continue if not cursor_found: continue calls.append(call) if calls: callback(calls) return self.waiters.add(callback) def return_call(self, id, response): callback = self.call_waiters.pop(id, None) if callback: callback(response) def create_call(self, command, args, callback=None): call_id = uuid.uuid4().hex call = { 'id': call_id, 'command': command, 'args': args, } if callback: self.call_waiters[call_id] = callback self.cache.append(call) for callback in self.waiters: callback([call]) self.waiters = set()
Add optional callbacks for call buffer
Add optional callbacks for call buffer
Python
agpl-3.0
pritunl/pritunl-node,pritunl/pritunl-node
from constants import * import collections import uuid class CallBuffer(): def __init__(self): self.waiters = set() self.cache = collections.deque(maxlen=CALL_CACHE_MAX) self.call_waiters = {} def wait_for_calls(self, callback, cursor=None): if cursor: calls = [] cursor_found = False for call in self.cache: if call['id'] == cursor: cursor_found = True continue if not cursor_found: continue calls.append(call) if calls: callback(calls) return self.waiters.add(callback) def return_call(self, id, response): callback = self.call_waiters.pop(id) if callback: callback(response) def create_call(self, command, args, callback): call_id = uuid.uuid4().hex call = { 'id': call_id, 'command': command, 'args': args, } self.call_waiters[call_id] = callback self.cache.append(call) for callback in self.waiters: callback([call]) self.waiters = set() Add optional callbacks for call buffer
from constants import * import collections import uuid class CallBuffer(): def __init__(self): self.waiters = set() self.cache = collections.deque(maxlen=CALL_CACHE_MAX) self.call_waiters = {} def wait_for_calls(self, callback, cursor=None): if cursor: calls = [] cursor_found = False for call in self.cache: if call['id'] == cursor: cursor_found = True continue if not cursor_found: continue calls.append(call) if calls: callback(calls) return self.waiters.add(callback) def return_call(self, id, response): callback = self.call_waiters.pop(id, None) if callback: callback(response) def create_call(self, command, args, callback=None): call_id = uuid.uuid4().hex call = { 'id': call_id, 'command': command, 'args': args, } if callback: self.call_waiters[call_id] = callback self.cache.append(call) for callback in self.waiters: callback([call]) self.waiters = set()
<commit_before>from constants import * import collections import uuid class CallBuffer(): def __init__(self): self.waiters = set() self.cache = collections.deque(maxlen=CALL_CACHE_MAX) self.call_waiters = {} def wait_for_calls(self, callback, cursor=None): if cursor: calls = [] cursor_found = False for call in self.cache: if call['id'] == cursor: cursor_found = True continue if not cursor_found: continue calls.append(call) if calls: callback(calls) return self.waiters.add(callback) def return_call(self, id, response): callback = self.call_waiters.pop(id) if callback: callback(response) def create_call(self, command, args, callback): call_id = uuid.uuid4().hex call = { 'id': call_id, 'command': command, 'args': args, } self.call_waiters[call_id] = callback self.cache.append(call) for callback in self.waiters: callback([call]) self.waiters = set() <commit_msg>Add optional callbacks for call buffer<commit_after>
from constants import * import collections import uuid class CallBuffer(): def __init__(self): self.waiters = set() self.cache = collections.deque(maxlen=CALL_CACHE_MAX) self.call_waiters = {} def wait_for_calls(self, callback, cursor=None): if cursor: calls = [] cursor_found = False for call in self.cache: if call['id'] == cursor: cursor_found = True continue if not cursor_found: continue calls.append(call) if calls: callback(calls) return self.waiters.add(callback) def return_call(self, id, response): callback = self.call_waiters.pop(id, None) if callback: callback(response) def create_call(self, command, args, callback=None): call_id = uuid.uuid4().hex call = { 'id': call_id, 'command': command, 'args': args, } if callback: self.call_waiters[call_id] = callback self.cache.append(call) for callback in self.waiters: callback([call]) self.waiters = set()
from constants import * import collections import uuid class CallBuffer(): def __init__(self): self.waiters = set() self.cache = collections.deque(maxlen=CALL_CACHE_MAX) self.call_waiters = {} def wait_for_calls(self, callback, cursor=None): if cursor: calls = [] cursor_found = False for call in self.cache: if call['id'] == cursor: cursor_found = True continue if not cursor_found: continue calls.append(call) if calls: callback(calls) return self.waiters.add(callback) def return_call(self, id, response): callback = self.call_waiters.pop(id) if callback: callback(response) def create_call(self, command, args, callback): call_id = uuid.uuid4().hex call = { 'id': call_id, 'command': command, 'args': args, } self.call_waiters[call_id] = callback self.cache.append(call) for callback in self.waiters: callback([call]) self.waiters = set() Add optional callbacks for call bufferfrom constants import * import collections import uuid class CallBuffer(): def __init__(self): self.waiters = set() self.cache = collections.deque(maxlen=CALL_CACHE_MAX) self.call_waiters = {} def wait_for_calls(self, callback, cursor=None): if cursor: calls = [] cursor_found = False for call in self.cache: if call['id'] == cursor: cursor_found = True continue if not cursor_found: continue calls.append(call) if calls: callback(calls) return self.waiters.add(callback) def return_call(self, id, response): callback = self.call_waiters.pop(id, None) if callback: callback(response) def create_call(self, command, args, callback=None): call_id = uuid.uuid4().hex call = { 'id': call_id, 'command': command, 'args': args, } if callback: self.call_waiters[call_id] = callback self.cache.append(call) for callback in self.waiters: callback([call]) self.waiters = set()
<commit_before>from constants import * import collections import uuid class CallBuffer(): def __init__(self): self.waiters = set() self.cache = collections.deque(maxlen=CALL_CACHE_MAX) self.call_waiters = {} def wait_for_calls(self, callback, cursor=None): if cursor: calls = [] cursor_found = False for call in self.cache: if call['id'] == cursor: cursor_found = True continue if not cursor_found: continue calls.append(call) if calls: callback(calls) return self.waiters.add(callback) def return_call(self, id, response): callback = self.call_waiters.pop(id) if callback: callback(response) def create_call(self, command, args, callback): call_id = uuid.uuid4().hex call = { 'id': call_id, 'command': command, 'args': args, } self.call_waiters[call_id] = callback self.cache.append(call) for callback in self.waiters: callback([call]) self.waiters = set() <commit_msg>Add optional callbacks for call buffer<commit_after>from constants import * import collections import uuid class CallBuffer(): def __init__(self): self.waiters = set() self.cache = collections.deque(maxlen=CALL_CACHE_MAX) self.call_waiters = {} def wait_for_calls(self, callback, cursor=None): if cursor: calls = [] cursor_found = False for call in self.cache: if call['id'] == cursor: cursor_found = True continue if not cursor_found: continue calls.append(call) if calls: callback(calls) return self.waiters.add(callback) def return_call(self, id, response): callback = self.call_waiters.pop(id, None) if callback: callback(response) def create_call(self, command, args, callback=None): call_id = uuid.uuid4().hex call = { 'id': call_id, 'command': command, 'args': args, } if callback: self.call_waiters[call_id] = callback self.cache.append(call) for callback in self.waiters: callback([call]) self.waiters = set()
69722d7c2db9869074474373eefacd8b5577cbe6
project/apps/api/signals.py
project/apps/api/signals.py
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) @receiver(post_save, sender=Contest) def contest_post_save(sender, instance=None, created=False, **kwargs): if created: instance.build() instance.save()
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) @receiver(post_save, sender=Contest) def contest_post_save(sender, instance=None, created=False, raw=False, **kwargs): if not raw: if created: instance.build() instance.save()
Add check for fixture loading
Add check for fixture loading
Python
bsd-2-clause
dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore,barberscore/barberscore-api
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) @receiver(post_save, sender=Contest) def contest_post_save(sender, instance=None, created=False, **kwargs): if created: instance.build() instance.save() Add check for fixture loading
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) @receiver(post_save, sender=Contest) def contest_post_save(sender, instance=None, created=False, raw=False, **kwargs): if not raw: if created: instance.build() instance.save()
<commit_before>from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) @receiver(post_save, sender=Contest) def contest_post_save(sender, instance=None, created=False, **kwargs): if created: instance.build() instance.save() <commit_msg>Add check for fixture loading<commit_after>
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) @receiver(post_save, sender=Contest) def contest_post_save(sender, instance=None, created=False, raw=False, **kwargs): if not raw: if created: instance.build() instance.save()
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) @receiver(post_save, sender=Contest) def contest_post_save(sender, instance=None, created=False, **kwargs): if created: instance.build() instance.save() Add check for fixture loadingfrom django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) @receiver(post_save, sender=Contest) def contest_post_save(sender, instance=None, created=False, raw=False, **kwargs): if not raw: if created: instance.build() instance.save()
<commit_before>from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) @receiver(post_save, sender=Contest) def contest_post_save(sender, instance=None, created=False, **kwargs): if created: instance.build() instance.save() <commit_msg>Add check for fixture loading<commit_after>from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) @receiver(post_save, sender=Contest) def contest_post_save(sender, instance=None, created=False, raw=False, **kwargs): if not raw: if created: instance.build() instance.save()
0cff7d25a9d0fc76c723e058652551bb2c43d1fc
benchmarks/test_benchmark.py
benchmarks/test_benchmark.py
import re import urllib import random import unittest from funkload.FunkLoadTestCase import FunkLoadTestCase class Benchmark(FunkLoadTestCase): """This test uses a configuration file Benchmark.conf.""" def setUp(self): self.server_url = self.conf_get('main', 'url') def test_simple(self): server_url = self.server_url if not re.match('https?://', server_url): raise Exception("The `server_url` setting doesn't have a scheme.") username = self.conf_get('test_benchmark', 'username', None) password = self.conf_get('test_benchmark', 'password', None) if username and password: self.post(self.server_url + "/api/user/login", params=[['username', username], ['password', password]], description="Login as %s" % username) nb_times = self.conf_getInt('test_benchmark', 'nb_times') names = self.conf_get('test_benchmark', 'page_names').split(';') for i in range(nb_times): r = random.randint(0, len(names) - 1) url = server_url + '/api/read/' + urllib.quote(names[r]) self.get(url, description='Getting %s' % names[r]) if __name__ in ('main', '__main__'): unittest.main()
import re import urllib.parse import random import unittest from funkload.FunkLoadTestCase import FunkLoadTestCase class Benchmark(FunkLoadTestCase): """This test uses a configuration file Benchmark.conf.""" def setUp(self): self.server_url = self.conf_get('main', 'url') def test_simple(self): server_url = self.server_url if not re.match('https?://', server_url): raise Exception("The `server_url` setting doesn't have a scheme.") username = self.conf_get('test_benchmark', 'username', None) password = self.conf_get('test_benchmark', 'password', None) if username and password: self.post(self.server_url + "/api/user/login", params=[['username', username], ['password', password]], description="Login as %s" % username) nb_times = self.conf_getInt('test_benchmark', 'nb_times') names = self.conf_get('test_benchmark', 'page_names').split(';') for i in range(nb_times): r = random.randint(0, len(names) - 1) url = server_url + '/api/read/' + urllib.parse.quote(names[r]) self.get(url, description='Getting %s' % names[r]) if __name__ in ('main', '__main__'): unittest.main()
Update benchmarks to Pyton 3.
Update benchmarks to Pyton 3.
Python
apache-2.0
ludovicchabant/Wikked,ludovicchabant/Wikked,ludovicchabant/Wikked
import re import urllib import random import unittest from funkload.FunkLoadTestCase import FunkLoadTestCase class Benchmark(FunkLoadTestCase): """This test uses a configuration file Benchmark.conf.""" def setUp(self): self.server_url = self.conf_get('main', 'url') def test_simple(self): server_url = self.server_url if not re.match('https?://', server_url): raise Exception("The `server_url` setting doesn't have a scheme.") username = self.conf_get('test_benchmark', 'username', None) password = self.conf_get('test_benchmark', 'password', None) if username and password: self.post(self.server_url + "/api/user/login", params=[['username', username], ['password', password]], description="Login as %s" % username) nb_times = self.conf_getInt('test_benchmark', 'nb_times') names = self.conf_get('test_benchmark', 'page_names').split(';') for i in range(nb_times): r = random.randint(0, len(names) - 1) url = server_url + '/api/read/' + urllib.quote(names[r]) self.get(url, description='Getting %s' % names[r]) if __name__ in ('main', '__main__'): unittest.main() Update benchmarks to Pyton 3.
import re import urllib.parse import random import unittest from funkload.FunkLoadTestCase import FunkLoadTestCase class Benchmark(FunkLoadTestCase): """This test uses a configuration file Benchmark.conf.""" def setUp(self): self.server_url = self.conf_get('main', 'url') def test_simple(self): server_url = self.server_url if not re.match('https?://', server_url): raise Exception("The `server_url` setting doesn't have a scheme.") username = self.conf_get('test_benchmark', 'username', None) password = self.conf_get('test_benchmark', 'password', None) if username and password: self.post(self.server_url + "/api/user/login", params=[['username', username], ['password', password]], description="Login as %s" % username) nb_times = self.conf_getInt('test_benchmark', 'nb_times') names = self.conf_get('test_benchmark', 'page_names').split(';') for i in range(nb_times): r = random.randint(0, len(names) - 1) url = server_url + '/api/read/' + urllib.parse.quote(names[r]) self.get(url, description='Getting %s' % names[r]) if __name__ in ('main', '__main__'): unittest.main()
<commit_before>import re import urllib import random import unittest from funkload.FunkLoadTestCase import FunkLoadTestCase class Benchmark(FunkLoadTestCase): """This test uses a configuration file Benchmark.conf.""" def setUp(self): self.server_url = self.conf_get('main', 'url') def test_simple(self): server_url = self.server_url if not re.match('https?://', server_url): raise Exception("The `server_url` setting doesn't have a scheme.") username = self.conf_get('test_benchmark', 'username', None) password = self.conf_get('test_benchmark', 'password', None) if username and password: self.post(self.server_url + "/api/user/login", params=[['username', username], ['password', password]], description="Login as %s" % username) nb_times = self.conf_getInt('test_benchmark', 'nb_times') names = self.conf_get('test_benchmark', 'page_names').split(';') for i in range(nb_times): r = random.randint(0, len(names) - 1) url = server_url + '/api/read/' + urllib.quote(names[r]) self.get(url, description='Getting %s' % names[r]) if __name__ in ('main', '__main__'): unittest.main() <commit_msg>Update benchmarks to Pyton 3.<commit_after>
import re import urllib.parse import random import unittest from funkload.FunkLoadTestCase import FunkLoadTestCase class Benchmark(FunkLoadTestCase): """This test uses a configuration file Benchmark.conf.""" def setUp(self): self.server_url = self.conf_get('main', 'url') def test_simple(self): server_url = self.server_url if not re.match('https?://', server_url): raise Exception("The `server_url` setting doesn't have a scheme.") username = self.conf_get('test_benchmark', 'username', None) password = self.conf_get('test_benchmark', 'password', None) if username and password: self.post(self.server_url + "/api/user/login", params=[['username', username], ['password', password]], description="Login as %s" % username) nb_times = self.conf_getInt('test_benchmark', 'nb_times') names = self.conf_get('test_benchmark', 'page_names').split(';') for i in range(nb_times): r = random.randint(0, len(names) - 1) url = server_url + '/api/read/' + urllib.parse.quote(names[r]) self.get(url, description='Getting %s' % names[r]) if __name__ in ('main', '__main__'): unittest.main()
import re import urllib import random import unittest from funkload.FunkLoadTestCase import FunkLoadTestCase class Benchmark(FunkLoadTestCase): """This test uses a configuration file Benchmark.conf.""" def setUp(self): self.server_url = self.conf_get('main', 'url') def test_simple(self): server_url = self.server_url if not re.match('https?://', server_url): raise Exception("The `server_url` setting doesn't have a scheme.") username = self.conf_get('test_benchmark', 'username', None) password = self.conf_get('test_benchmark', 'password', None) if username and password: self.post(self.server_url + "/api/user/login", params=[['username', username], ['password', password]], description="Login as %s" % username) nb_times = self.conf_getInt('test_benchmark', 'nb_times') names = self.conf_get('test_benchmark', 'page_names').split(';') for i in range(nb_times): r = random.randint(0, len(names) - 1) url = server_url + '/api/read/' + urllib.quote(names[r]) self.get(url, description='Getting %s' % names[r]) if __name__ in ('main', '__main__'): unittest.main() Update benchmarks to Pyton 3.import re import urllib.parse import random import unittest from funkload.FunkLoadTestCase import FunkLoadTestCase class Benchmark(FunkLoadTestCase): """This test uses a configuration file Benchmark.conf.""" def setUp(self): self.server_url = self.conf_get('main', 'url') def test_simple(self): server_url = self.server_url if not re.match('https?://', server_url): raise Exception("The `server_url` setting doesn't have a scheme.") username = self.conf_get('test_benchmark', 'username', None) password = self.conf_get('test_benchmark', 'password', None) if username and password: self.post(self.server_url + "/api/user/login", params=[['username', username], ['password', password]], description="Login as %s" % username) nb_times = self.conf_getInt('test_benchmark', 'nb_times') names = self.conf_get('test_benchmark', 'page_names').split(';') for i in range(nb_times): r = random.randint(0, len(names) - 1) url = server_url + '/api/read/' + urllib.parse.quote(names[r]) self.get(url, description='Getting %s' % names[r]) if __name__ in ('main', '__main__'): unittest.main()
<commit_before>import re import urllib import random import unittest from funkload.FunkLoadTestCase import FunkLoadTestCase class Benchmark(FunkLoadTestCase): """This test uses a configuration file Benchmark.conf.""" def setUp(self): self.server_url = self.conf_get('main', 'url') def test_simple(self): server_url = self.server_url if not re.match('https?://', server_url): raise Exception("The `server_url` setting doesn't have a scheme.") username = self.conf_get('test_benchmark', 'username', None) password = self.conf_get('test_benchmark', 'password', None) if username and password: self.post(self.server_url + "/api/user/login", params=[['username', username], ['password', password]], description="Login as %s" % username) nb_times = self.conf_getInt('test_benchmark', 'nb_times') names = self.conf_get('test_benchmark', 'page_names').split(';') for i in range(nb_times): r = random.randint(0, len(names) - 1) url = server_url + '/api/read/' + urllib.quote(names[r]) self.get(url, description='Getting %s' % names[r]) if __name__ in ('main', '__main__'): unittest.main() <commit_msg>Update benchmarks to Pyton 3.<commit_after>import re import urllib.parse import random import unittest from funkload.FunkLoadTestCase import FunkLoadTestCase class Benchmark(FunkLoadTestCase): """This test uses a configuration file Benchmark.conf.""" def setUp(self): self.server_url = self.conf_get('main', 'url') def test_simple(self): server_url = self.server_url if not re.match('https?://', server_url): raise Exception("The `server_url` setting doesn't have a scheme.") username = self.conf_get('test_benchmark', 'username', None) password = self.conf_get('test_benchmark', 'password', None) if username and password: self.post(self.server_url + "/api/user/login", params=[['username', username], ['password', password]], description="Login as %s" % username) nb_times = self.conf_getInt('test_benchmark', 'nb_times') names = self.conf_get('test_benchmark', 'page_names').split(';') for i in range(nb_times): r = random.randint(0, len(names) - 1) url = server_url + '/api/read/' + urllib.parse.quote(names[r]) self.get(url, description='Getting %s' % names[r]) if __name__ in ('main', '__main__'): unittest.main()
215737ef0094f430ca9945841d25fbbaf0301a52
feature_extraction.py
feature_extraction.py
from PIL import Image import glob def _get_masks(): TRAIN_MASKS = './data/train/*_mask.tif' return [Image.open(file_name) for file_name in glob.glob(TRAIN_MASKS)] def _get_rectangle_masks(): rectangle_masks = [] for image in _get_masks(): rectangle_mask = ((0,0), (0,0)) mask_coord = [(i-image.width*(i/image.width), i/image.width) for i, pixel in enumerate(image.getdata()) if pixel != 0] if mask_coord: mask_xs, mask_ys = zip(*mask_coord) rectangle_mask = ((min(mask_xs), mask_ys[0]), (max(mask_xs), mask_ys[len(mask_ys)-1])) rectangle_masks.append(rectangle_mask) return rectangle_masks def run(): print _get_rectangle_masks() if __name__ == '__main__': run()
from PIL import Image import glob def _get_masks(): TRAIN_MASKS = './data/train/*_mask.tif' return [Image.open(file_name) for file_name in glob.glob(TRAIN_MASKS)] def _get_rectangle_masks(): rectangle_masks = [] for image in _get_masks(): rectangle_mask = ((0,0), (0,0)) mask_coord = [(i-image.width*(i/image.width), i/image.width) for i, pixel in enumerate(image.getdata()) if pixel != 0] if mask_coord: mask_xs, mask_ys = zip(*mask_coord) rectangle_mask = (image.filename, ((min(mask_xs), mask_ys[0]), (max(mask_xs), mask_ys[len(mask_ys)-1]))) rectangle_masks.append(rectangle_mask) return rectangle_masks def run(): print _get_rectangle_masks() if __name__ == '__main__': run()
Add filename to square masks
Add filename to square masks
Python
mit
Brok-Bucholtz/Ultrasound-Nerve-Segmentation
from PIL import Image import glob def _get_masks(): TRAIN_MASKS = './data/train/*_mask.tif' return [Image.open(file_name) for file_name in glob.glob(TRAIN_MASKS)] def _get_rectangle_masks(): rectangle_masks = [] for image in _get_masks(): rectangle_mask = ((0,0), (0,0)) mask_coord = [(i-image.width*(i/image.width), i/image.width) for i, pixel in enumerate(image.getdata()) if pixel != 0] if mask_coord: mask_xs, mask_ys = zip(*mask_coord) rectangle_mask = ((min(mask_xs), mask_ys[0]), (max(mask_xs), mask_ys[len(mask_ys)-1])) rectangle_masks.append(rectangle_mask) return rectangle_masks def run(): print _get_rectangle_masks() if __name__ == '__main__': run() Add filename to square masks
from PIL import Image import glob def _get_masks(): TRAIN_MASKS = './data/train/*_mask.tif' return [Image.open(file_name) for file_name in glob.glob(TRAIN_MASKS)] def _get_rectangle_masks(): rectangle_masks = [] for image in _get_masks(): rectangle_mask = ((0,0), (0,0)) mask_coord = [(i-image.width*(i/image.width), i/image.width) for i, pixel in enumerate(image.getdata()) if pixel != 0] if mask_coord: mask_xs, mask_ys = zip(*mask_coord) rectangle_mask = (image.filename, ((min(mask_xs), mask_ys[0]), (max(mask_xs), mask_ys[len(mask_ys)-1]))) rectangle_masks.append(rectangle_mask) return rectangle_masks def run(): print _get_rectangle_masks() if __name__ == '__main__': run()
<commit_before>from PIL import Image import glob def _get_masks(): TRAIN_MASKS = './data/train/*_mask.tif' return [Image.open(file_name) for file_name in glob.glob(TRAIN_MASKS)] def _get_rectangle_masks(): rectangle_masks = [] for image in _get_masks(): rectangle_mask = ((0,0), (0,0)) mask_coord = [(i-image.width*(i/image.width), i/image.width) for i, pixel in enumerate(image.getdata()) if pixel != 0] if mask_coord: mask_xs, mask_ys = zip(*mask_coord) rectangle_mask = ((min(mask_xs), mask_ys[0]), (max(mask_xs), mask_ys[len(mask_ys)-1])) rectangle_masks.append(rectangle_mask) return rectangle_masks def run(): print _get_rectangle_masks() if __name__ == '__main__': run() <commit_msg>Add filename to square masks<commit_after>
from PIL import Image import glob def _get_masks(): TRAIN_MASKS = './data/train/*_mask.tif' return [Image.open(file_name) for file_name in glob.glob(TRAIN_MASKS)] def _get_rectangle_masks(): rectangle_masks = [] for image in _get_masks(): rectangle_mask = ((0,0), (0,0)) mask_coord = [(i-image.width*(i/image.width), i/image.width) for i, pixel in enumerate(image.getdata()) if pixel != 0] if mask_coord: mask_xs, mask_ys = zip(*mask_coord) rectangle_mask = (image.filename, ((min(mask_xs), mask_ys[0]), (max(mask_xs), mask_ys[len(mask_ys)-1]))) rectangle_masks.append(rectangle_mask) return rectangle_masks def run(): print _get_rectangle_masks() if __name__ == '__main__': run()
from PIL import Image import glob def _get_masks(): TRAIN_MASKS = './data/train/*_mask.tif' return [Image.open(file_name) for file_name in glob.glob(TRAIN_MASKS)] def _get_rectangle_masks(): rectangle_masks = [] for image in _get_masks(): rectangle_mask = ((0,0), (0,0)) mask_coord = [(i-image.width*(i/image.width), i/image.width) for i, pixel in enumerate(image.getdata()) if pixel != 0] if mask_coord: mask_xs, mask_ys = zip(*mask_coord) rectangle_mask = ((min(mask_xs), mask_ys[0]), (max(mask_xs), mask_ys[len(mask_ys)-1])) rectangle_masks.append(rectangle_mask) return rectangle_masks def run(): print _get_rectangle_masks() if __name__ == '__main__': run() Add filename to square masksfrom PIL import Image import glob def _get_masks(): TRAIN_MASKS = './data/train/*_mask.tif' return [Image.open(file_name) for file_name in glob.glob(TRAIN_MASKS)] def _get_rectangle_masks(): rectangle_masks = [] for image in _get_masks(): rectangle_mask = ((0,0), (0,0)) mask_coord = [(i-image.width*(i/image.width), i/image.width) for i, pixel in enumerate(image.getdata()) if pixel != 0] if mask_coord: mask_xs, mask_ys = zip(*mask_coord) rectangle_mask = (image.filename, ((min(mask_xs), mask_ys[0]), (max(mask_xs), mask_ys[len(mask_ys)-1]))) rectangle_masks.append(rectangle_mask) return rectangle_masks def run(): print _get_rectangle_masks() if __name__ == '__main__': run()
<commit_before>from PIL import Image import glob def _get_masks(): TRAIN_MASKS = './data/train/*_mask.tif' return [Image.open(file_name) for file_name in glob.glob(TRAIN_MASKS)] def _get_rectangle_masks(): rectangle_masks = [] for image in _get_masks(): rectangle_mask = ((0,0), (0,0)) mask_coord = [(i-image.width*(i/image.width), i/image.width) for i, pixel in enumerate(image.getdata()) if pixel != 0] if mask_coord: mask_xs, mask_ys = zip(*mask_coord) rectangle_mask = ((min(mask_xs), mask_ys[0]), (max(mask_xs), mask_ys[len(mask_ys)-1])) rectangle_masks.append(rectangle_mask) return rectangle_masks def run(): print _get_rectangle_masks() if __name__ == '__main__': run() <commit_msg>Add filename to square masks<commit_after>from PIL import Image import glob def _get_masks(): TRAIN_MASKS = './data/train/*_mask.tif' return [Image.open(file_name) for file_name in glob.glob(TRAIN_MASKS)] def _get_rectangle_masks(): rectangle_masks = [] for image in _get_masks(): rectangle_mask = ((0,0), (0,0)) mask_coord = [(i-image.width*(i/image.width), i/image.width) for i, pixel in enumerate(image.getdata()) if pixel != 0] if mask_coord: mask_xs, mask_ys = zip(*mask_coord) rectangle_mask = (image.filename, ((min(mask_xs), mask_ys[0]), (max(mask_xs), mask_ys[len(mask_ys)-1]))) rectangle_masks.append(rectangle_mask) return rectangle_masks def run(): print _get_rectangle_masks() if __name__ == '__main__': run()
4ca1aeb4b0fd3e8d3406d5b5152eb382e32abc1f
app/main/views.py
app/main/views.py
import importlib from flask import render_template from werkzeug.exceptions import NotFound from . import main DATA_QUALITY_ROUTE = '/data-quality/' @main.route('/') def index(): return render_template('index.html') @main.route('/data-quality/<path:page>') def data_quality_page(page): """Serve a data quality page. page must be a directory path relative to /app/main/pages, and the corresponding directory must be a package. Params: ------- page: str Path of the directory containing the page content. """ page = page.replace('/', '.') # turn directory path into package name try: dq = importlib.import_module('app.main.pages.' + page, __package__) except ImportError: raise NotFound return render_template('data_quality/data_quality_page.html', title=dq.title(), content=dq.content())
import importlib from flask import render_template from werkzeug.exceptions import NotFound from . import main DATA_QUALITY_ROUTE = '/data-quality/' @main.route('/') def index(): return render_template('index.html') @main.route('/data-quality/<path:page>') def data_quality_page(page): """Serve a data quality page. page must be a directory path relative to /app/main/pages, and the corresponding directory must be a package. Params: ------- page: str Path of the directory containing the page content. """ page = page.strip('/') page = page.replace('/', '.') # turn directory path into package name try: dq = importlib.import_module('app.main.pages.' + page, __package__) except ImportError: raise NotFound return render_template('data_quality/data_quality_page.html', title=dq.title(), content=dq.content())
Allow trailing slash in URL
Allow trailing slash in URL
Python
mit
saltastro/salt-data-quality-site,saltastro/salt-data-quality-site,saltastro/salt-data-quality-site,saltastro/salt-data-quality-site
import importlib from flask import render_template from werkzeug.exceptions import NotFound from . import main DATA_QUALITY_ROUTE = '/data-quality/' @main.route('/') def index(): return render_template('index.html') @main.route('/data-quality/<path:page>') def data_quality_page(page): """Serve a data quality page. page must be a directory path relative to /app/main/pages, and the corresponding directory must be a package. Params: ------- page: str Path of the directory containing the page content. """ page = page.replace('/', '.') # turn directory path into package name try: dq = importlib.import_module('app.main.pages.' + page, __package__) except ImportError: raise NotFound return render_template('data_quality/data_quality_page.html', title=dq.title(), content=dq.content()) Allow trailing slash in URL
import importlib from flask import render_template from werkzeug.exceptions import NotFound from . import main DATA_QUALITY_ROUTE = '/data-quality/' @main.route('/') def index(): return render_template('index.html') @main.route('/data-quality/<path:page>') def data_quality_page(page): """Serve a data quality page. page must be a directory path relative to /app/main/pages, and the corresponding directory must be a package. Params: ------- page: str Path of the directory containing the page content. """ page = page.strip('/') page = page.replace('/', '.') # turn directory path into package name try: dq = importlib.import_module('app.main.pages.' + page, __package__) except ImportError: raise NotFound return render_template('data_quality/data_quality_page.html', title=dq.title(), content=dq.content())
<commit_before>import importlib from flask import render_template from werkzeug.exceptions import NotFound from . import main DATA_QUALITY_ROUTE = '/data-quality/' @main.route('/') def index(): return render_template('index.html') @main.route('/data-quality/<path:page>') def data_quality_page(page): """Serve a data quality page. page must be a directory path relative to /app/main/pages, and the corresponding directory must be a package. Params: ------- page: str Path of the directory containing the page content. """ page = page.replace('/', '.') # turn directory path into package name try: dq = importlib.import_module('app.main.pages.' + page, __package__) except ImportError: raise NotFound return render_template('data_quality/data_quality_page.html', title=dq.title(), content=dq.content()) <commit_msg>Allow trailing slash in URL<commit_after>
import importlib from flask import render_template from werkzeug.exceptions import NotFound from . import main DATA_QUALITY_ROUTE = '/data-quality/' @main.route('/') def index(): return render_template('index.html') @main.route('/data-quality/<path:page>') def data_quality_page(page): """Serve a data quality page. page must be a directory path relative to /app/main/pages, and the corresponding directory must be a package. Params: ------- page: str Path of the directory containing the page content. """ page = page.strip('/') page = page.replace('/', '.') # turn directory path into package name try: dq = importlib.import_module('app.main.pages.' + page, __package__) except ImportError: raise NotFound return render_template('data_quality/data_quality_page.html', title=dq.title(), content=dq.content())
import importlib from flask import render_template from werkzeug.exceptions import NotFound from . import main DATA_QUALITY_ROUTE = '/data-quality/' @main.route('/') def index(): return render_template('index.html') @main.route('/data-quality/<path:page>') def data_quality_page(page): """Serve a data quality page. page must be a directory path relative to /app/main/pages, and the corresponding directory must be a package. Params: ------- page: str Path of the directory containing the page content. """ page = page.replace('/', '.') # turn directory path into package name try: dq = importlib.import_module('app.main.pages.' + page, __package__) except ImportError: raise NotFound return render_template('data_quality/data_quality_page.html', title=dq.title(), content=dq.content()) Allow trailing slash in URLimport importlib from flask import render_template from werkzeug.exceptions import NotFound from . import main DATA_QUALITY_ROUTE = '/data-quality/' @main.route('/') def index(): return render_template('index.html') @main.route('/data-quality/<path:page>') def data_quality_page(page): """Serve a data quality page. page must be a directory path relative to /app/main/pages, and the corresponding directory must be a package. Params: ------- page: str Path of the directory containing the page content. """ page = page.strip('/') page = page.replace('/', '.') # turn directory path into package name try: dq = importlib.import_module('app.main.pages.' + page, __package__) except ImportError: raise NotFound return render_template('data_quality/data_quality_page.html', title=dq.title(), content=dq.content())
<commit_before>import importlib from flask import render_template from werkzeug.exceptions import NotFound from . import main DATA_QUALITY_ROUTE = '/data-quality/' @main.route('/') def index(): return render_template('index.html') @main.route('/data-quality/<path:page>') def data_quality_page(page): """Serve a data quality page. page must be a directory path relative to /app/main/pages, and the corresponding directory must be a package. Params: ------- page: str Path of the directory containing the page content. """ page = page.replace('/', '.') # turn directory path into package name try: dq = importlib.import_module('app.main.pages.' + page, __package__) except ImportError: raise NotFound return render_template('data_quality/data_quality_page.html', title=dq.title(), content=dq.content()) <commit_msg>Allow trailing slash in URL<commit_after>import importlib from flask import render_template from werkzeug.exceptions import NotFound from . import main DATA_QUALITY_ROUTE = '/data-quality/' @main.route('/') def index(): return render_template('index.html') @main.route('/data-quality/<path:page>') def data_quality_page(page): """Serve a data quality page. page must be a directory path relative to /app/main/pages, and the corresponding directory must be a package. Params: ------- page: str Path of the directory containing the page content. """ page = page.strip('/') page = page.replace('/', '.') # turn directory path into package name try: dq = importlib.import_module('app.main.pages.' + page, __package__) except ImportError: raise NotFound return render_template('data_quality/data_quality_page.html', title=dq.title(), content=dq.content())
21efcb7c0793533ff7e4ed52f09573463f0fb1f0
scripts/configuration.py
scripts/configuration.py
import subprocess def load_configuration(environment): configuration = { "project": "nimp", "project_version": { "identifier": "0.9.6" }, "distribution": "nimp-cli", } revision = subprocess.run([ environment["git_executable"], "rev-parse", "--short=10", "HEAD" ], check = True, capture_output = True).stdout.decode("utf-8").strip() branch = subprocess.run([ environment["git_executable"], "rev-parse", "--abbrev-ref", "HEAD" ], check = True, capture_output = True).stdout.decode("utf-8").strip() configuration["project_version"]["revision"] = revision configuration["project_version"]["branch"] = branch configuration["project_version"]["numeric"] = "{identifier}".format(**configuration["project_version"]) configuration["project_version"]["full"] = "{identifier}+{revision}".format(**configuration["project_version"]) return configuration
import subprocess def load_configuration(environment): configuration = { "project": "nimp", "project_version": { "identifier": "0.9.6" }, "distribution": "nimp-cli", } configuration["project_version"]["revision"] = subprocess.check_output([ environment["git_executable"], "rev-parse", "--short=10", "HEAD" ]).decode("utf-8").strip() configuration["project_version"]["branch"] = subprocess.check_output([ environment["git_executable"], "rev-parse", "--abbrev-ref", "HEAD" ]).decode("utf-8").strip() configuration["project_version"]["numeric"] = "{identifier}".format(**configuration["project_version"]) configuration["project_version"]["full"] = "{identifier}+{revision}".format(**configuration["project_version"]) return configuration
Change distribution script to support python 3.5
Change distribution script to support python 3.5
Python
mit
dontnod/nimp
import subprocess def load_configuration(environment): configuration = { "project": "nimp", "project_version": { "identifier": "0.9.6" }, "distribution": "nimp-cli", } revision = subprocess.run([ environment["git_executable"], "rev-parse", "--short=10", "HEAD" ], check = True, capture_output = True).stdout.decode("utf-8").strip() branch = subprocess.run([ environment["git_executable"], "rev-parse", "--abbrev-ref", "HEAD" ], check = True, capture_output = True).stdout.decode("utf-8").strip() configuration["project_version"]["revision"] = revision configuration["project_version"]["branch"] = branch configuration["project_version"]["numeric"] = "{identifier}".format(**configuration["project_version"]) configuration["project_version"]["full"] = "{identifier}+{revision}".format(**configuration["project_version"]) return configuration Change distribution script to support python 3.5
import subprocess def load_configuration(environment): configuration = { "project": "nimp", "project_version": { "identifier": "0.9.6" }, "distribution": "nimp-cli", } configuration["project_version"]["revision"] = subprocess.check_output([ environment["git_executable"], "rev-parse", "--short=10", "HEAD" ]).decode("utf-8").strip() configuration["project_version"]["branch"] = subprocess.check_output([ environment["git_executable"], "rev-parse", "--abbrev-ref", "HEAD" ]).decode("utf-8").strip() configuration["project_version"]["numeric"] = "{identifier}".format(**configuration["project_version"]) configuration["project_version"]["full"] = "{identifier}+{revision}".format(**configuration["project_version"]) return configuration
<commit_before>import subprocess def load_configuration(environment): configuration = { "project": "nimp", "project_version": { "identifier": "0.9.6" }, "distribution": "nimp-cli", } revision = subprocess.run([ environment["git_executable"], "rev-parse", "--short=10", "HEAD" ], check = True, capture_output = True).stdout.decode("utf-8").strip() branch = subprocess.run([ environment["git_executable"], "rev-parse", "--abbrev-ref", "HEAD" ], check = True, capture_output = True).stdout.decode("utf-8").strip() configuration["project_version"]["revision"] = revision configuration["project_version"]["branch"] = branch configuration["project_version"]["numeric"] = "{identifier}".format(**configuration["project_version"]) configuration["project_version"]["full"] = "{identifier}+{revision}".format(**configuration["project_version"]) return configuration <commit_msg>Change distribution script to support python 3.5<commit_after>
import subprocess def load_configuration(environment): configuration = { "project": "nimp", "project_version": { "identifier": "0.9.6" }, "distribution": "nimp-cli", } configuration["project_version"]["revision"] = subprocess.check_output([ environment["git_executable"], "rev-parse", "--short=10", "HEAD" ]).decode("utf-8").strip() configuration["project_version"]["branch"] = subprocess.check_output([ environment["git_executable"], "rev-parse", "--abbrev-ref", "HEAD" ]).decode("utf-8").strip() configuration["project_version"]["numeric"] = "{identifier}".format(**configuration["project_version"]) configuration["project_version"]["full"] = "{identifier}+{revision}".format(**configuration["project_version"]) return configuration
import subprocess def load_configuration(environment): configuration = { "project": "nimp", "project_version": { "identifier": "0.9.6" }, "distribution": "nimp-cli", } revision = subprocess.run([ environment["git_executable"], "rev-parse", "--short=10", "HEAD" ], check = True, capture_output = True).stdout.decode("utf-8").strip() branch = subprocess.run([ environment["git_executable"], "rev-parse", "--abbrev-ref", "HEAD" ], check = True, capture_output = True).stdout.decode("utf-8").strip() configuration["project_version"]["revision"] = revision configuration["project_version"]["branch"] = branch configuration["project_version"]["numeric"] = "{identifier}".format(**configuration["project_version"]) configuration["project_version"]["full"] = "{identifier}+{revision}".format(**configuration["project_version"]) return configuration Change distribution script to support python 3.5import subprocess def load_configuration(environment): configuration = { "project": "nimp", "project_version": { "identifier": "0.9.6" }, "distribution": "nimp-cli", } configuration["project_version"]["revision"] = subprocess.check_output([ environment["git_executable"], "rev-parse", "--short=10", "HEAD" ]).decode("utf-8").strip() configuration["project_version"]["branch"] = subprocess.check_output([ environment["git_executable"], "rev-parse", "--abbrev-ref", "HEAD" ]).decode("utf-8").strip() configuration["project_version"]["numeric"] = "{identifier}".format(**configuration["project_version"]) configuration["project_version"]["full"] = "{identifier}+{revision}".format(**configuration["project_version"]) return configuration
<commit_before>import subprocess def load_configuration(environment): configuration = { "project": "nimp", "project_version": { "identifier": "0.9.6" }, "distribution": "nimp-cli", } revision = subprocess.run([ environment["git_executable"], "rev-parse", "--short=10", "HEAD" ], check = True, capture_output = True).stdout.decode("utf-8").strip() branch = subprocess.run([ environment["git_executable"], "rev-parse", "--abbrev-ref", "HEAD" ], check = True, capture_output = True).stdout.decode("utf-8").strip() configuration["project_version"]["revision"] = revision configuration["project_version"]["branch"] = branch configuration["project_version"]["numeric"] = "{identifier}".format(**configuration["project_version"]) configuration["project_version"]["full"] = "{identifier}+{revision}".format(**configuration["project_version"]) return configuration <commit_msg>Change distribution script to support python 3.5<commit_after>import subprocess def load_configuration(environment): configuration = { "project": "nimp", "project_version": { "identifier": "0.9.6" }, "distribution": "nimp-cli", } configuration["project_version"]["revision"] = subprocess.check_output([ environment["git_executable"], "rev-parse", "--short=10", "HEAD" ]).decode("utf-8").strip() configuration["project_version"]["branch"] = subprocess.check_output([ environment["git_executable"], "rev-parse", "--abbrev-ref", "HEAD" ]).decode("utf-8").strip() configuration["project_version"]["numeric"] = "{identifier}".format(**configuration["project_version"]) configuration["project_version"]["full"] = "{identifier}+{revision}".format(**configuration["project_version"]) return configuration
d2674e1ce5a6baaabf82b96c9a551457bb87d718
headlines/__init__.py
headlines/__init__.py
# -*- coding: utf-8 -*- """ headlines ~~~~~~~~~ A Flask powered news aggregation web app. :copyright: (c) 2017, John Alcher :license: MIT, see LICENSE for more info. """ from flask import Flask app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile("appconfig.py") SOURCES = { "bbc": "bbc-news", "cnn": "cnn", "hackernews": "hacker-news" } DEFAULTS = { "source": "bbc", "city": "Malolos", "currency_from": "USD", "currency_to": "PHP" } from . import views
# -*- coding: utf-8 -*- """ headlines ~~~~~~~~~ A Flask powered news aggregation web app. :copyright: (c) 2017, John Alcher :license: MIT, see LICENSE for more info. """ from flask import Flask app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile("appconfig.py") SOURCES = { "bbc": "bbc-news", "cnn": "cnn", "hackernews": "hacker-news" } DEFAULTS = { "source": "bbc", "city": "Malolos", "currency_from": "USD", "currency_to": "PHP" } from . import views
Add newline in docstring to separate summary.
Add newline in docstring to separate summary.
Python
mit
alchermd/headlines,alchermd/headlines
# -*- coding: utf-8 -*- """ headlines ~~~~~~~~~ A Flask powered news aggregation web app. :copyright: (c) 2017, John Alcher :license: MIT, see LICENSE for more info. """ from flask import Flask app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile("appconfig.py") SOURCES = { "bbc": "bbc-news", "cnn": "cnn", "hackernews": "hacker-news" } DEFAULTS = { "source": "bbc", "city": "Malolos", "currency_from": "USD", "currency_to": "PHP" } from . import viewsAdd newline in docstring to separate summary.
# -*- coding: utf-8 -*- """ headlines ~~~~~~~~~ A Flask powered news aggregation web app. :copyright: (c) 2017, John Alcher :license: MIT, see LICENSE for more info. """ from flask import Flask app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile("appconfig.py") SOURCES = { "bbc": "bbc-news", "cnn": "cnn", "hackernews": "hacker-news" } DEFAULTS = { "source": "bbc", "city": "Malolos", "currency_from": "USD", "currency_to": "PHP" } from . import views
<commit_before># -*- coding: utf-8 -*- """ headlines ~~~~~~~~~ A Flask powered news aggregation web app. :copyright: (c) 2017, John Alcher :license: MIT, see LICENSE for more info. """ from flask import Flask app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile("appconfig.py") SOURCES = { "bbc": "bbc-news", "cnn": "cnn", "hackernews": "hacker-news" } DEFAULTS = { "source": "bbc", "city": "Malolos", "currency_from": "USD", "currency_to": "PHP" } from . import views<commit_msg>Add newline in docstring to separate summary.<commit_after>
# -*- coding: utf-8 -*- """ headlines ~~~~~~~~~ A Flask powered news aggregation web app. :copyright: (c) 2017, John Alcher :license: MIT, see LICENSE for more info. """ from flask import Flask app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile("appconfig.py") SOURCES = { "bbc": "bbc-news", "cnn": "cnn", "hackernews": "hacker-news" } DEFAULTS = { "source": "bbc", "city": "Malolos", "currency_from": "USD", "currency_to": "PHP" } from . import views
# -*- coding: utf-8 -*- """ headlines ~~~~~~~~~ A Flask powered news aggregation web app. :copyright: (c) 2017, John Alcher :license: MIT, see LICENSE for more info. """ from flask import Flask app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile("appconfig.py") SOURCES = { "bbc": "bbc-news", "cnn": "cnn", "hackernews": "hacker-news" } DEFAULTS = { "source": "bbc", "city": "Malolos", "currency_from": "USD", "currency_to": "PHP" } from . import viewsAdd newline in docstring to separate summary.# -*- coding: utf-8 -*- """ headlines ~~~~~~~~~ A Flask powered news aggregation web app. :copyright: (c) 2017, John Alcher :license: MIT, see LICENSE for more info. """ from flask import Flask app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile("appconfig.py") SOURCES = { "bbc": "bbc-news", "cnn": "cnn", "hackernews": "hacker-news" } DEFAULTS = { "source": "bbc", "city": "Malolos", "currency_from": "USD", "currency_to": "PHP" } from . import views
<commit_before># -*- coding: utf-8 -*- """ headlines ~~~~~~~~~ A Flask powered news aggregation web app. :copyright: (c) 2017, John Alcher :license: MIT, see LICENSE for more info. """ from flask import Flask app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile("appconfig.py") SOURCES = { "bbc": "bbc-news", "cnn": "cnn", "hackernews": "hacker-news" } DEFAULTS = { "source": "bbc", "city": "Malolos", "currency_from": "USD", "currency_to": "PHP" } from . import views<commit_msg>Add newline in docstring to separate summary.<commit_after># -*- coding: utf-8 -*- """ headlines ~~~~~~~~~ A Flask powered news aggregation web app. :copyright: (c) 2017, John Alcher :license: MIT, see LICENSE for more info. """ from flask import Flask app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile("appconfig.py") SOURCES = { "bbc": "bbc-news", "cnn": "cnn", "hackernews": "hacker-news" } DEFAULTS = { "source": "bbc", "city": "Malolos", "currency_from": "USD", "currency_to": "PHP" } from . import views
46359266de70275a53cc9d82d3387ca6c0266f3b
jwst_lib/models/dynamicdq.py
jwst_lib/models/dynamicdq.py
import numpy as np from . import dqflags def dynamic_mask(input_model): # # Return a mask model given a mask with dynamic DQ flags # Dynamic flags define what each plane refers to using the DQ_DEF extension dq_table = input_model.dq_def # Get the DQ array and the flag definitions if dq_table is not None: # # Make an empty mask dqmask = np.zeros(input_model.dq.shape, dtype=input_model.dq.dtype) for record in dq_table: bitplane = record['VALUE'] dqname = record['NAME'].strip() try: standard_bitvalue = dqflags.pixel[dqname] except KeyError: print 'Keyword %s does not correspond to an existing DQ mnemonic, so will be ignored' % (dqname) continue just_this_bit = np.bitwise_and(input_model.dq, bitplane) pixels = np.where(just_this_bit != 0) dqmask[pixels] = np.bitwise_or(dqmask[pixels], standard_bitvalue) else: dqmask = input_model.dq return dqmask
import numpy as np from . import dqflags def dynamic_mask(input_model): # # Return a mask model given a mask with dynamic DQ flags # Dynamic flags define what each plane refers to using the DQ_DEF extension dq_table = input_model.dq_def # Get the DQ array and the flag definitions if dq_table is not None and len(dq_table) > 0: # # Make an empty mask dqmask = np.zeros(input_model.dq.shape, dtype=input_model.dq.dtype) for record in dq_table: bitplane = record['VALUE'] dqname = record['NAME'].strip() try: standard_bitvalue = dqflags.pixel[dqname] except KeyError: print 'Keyword %s does not correspond to an existing DQ mnemonic, so will be ignored' % (dqname) continue just_this_bit = np.bitwise_and(input_model.dq, bitplane) pixels = np.where(just_this_bit != 0) dqmask[pixels] = np.bitwise_or(dqmask[pixels], standard_bitvalue) else: dqmask = input_model.dq return dqmask
Fix bug that appears when a reference file model is created from scratch where the dq_def member exists, but has no rows.
Fix bug that appears when a reference file model is created from scratch where the dq_def member exists, but has no rows. git-svn-id: 7ab1303e5df1b63f74144546e35d3203cc1d26c5@3127 560b4ebf-6bc0-4cc5-b8e0-b136f69d22d4
Python
bsd-3-clause
mdboom/jwst_lib.models
import numpy as np from . import dqflags def dynamic_mask(input_model): # # Return a mask model given a mask with dynamic DQ flags # Dynamic flags define what each plane refers to using the DQ_DEF extension dq_table = input_model.dq_def # Get the DQ array and the flag definitions if dq_table is not None: # # Make an empty mask dqmask = np.zeros(input_model.dq.shape, dtype=input_model.dq.dtype) for record in dq_table: bitplane = record['VALUE'] dqname = record['NAME'].strip() try: standard_bitvalue = dqflags.pixel[dqname] except KeyError: print 'Keyword %s does not correspond to an existing DQ mnemonic, so will be ignored' % (dqname) continue just_this_bit = np.bitwise_and(input_model.dq, bitplane) pixels = np.where(just_this_bit != 0) dqmask[pixels] = np.bitwise_or(dqmask[pixels], standard_bitvalue) else: dqmask = input_model.dq return dqmask Fix bug that appears when a reference file model is created from scratch where the dq_def member exists, but has no rows. git-svn-id: 7ab1303e5df1b63f74144546e35d3203cc1d26c5@3127 560b4ebf-6bc0-4cc5-b8e0-b136f69d22d4
import numpy as np from . import dqflags def dynamic_mask(input_model): # # Return a mask model given a mask with dynamic DQ flags # Dynamic flags define what each plane refers to using the DQ_DEF extension dq_table = input_model.dq_def # Get the DQ array and the flag definitions if dq_table is not None and len(dq_table) > 0: # # Make an empty mask dqmask = np.zeros(input_model.dq.shape, dtype=input_model.dq.dtype) for record in dq_table: bitplane = record['VALUE'] dqname = record['NAME'].strip() try: standard_bitvalue = dqflags.pixel[dqname] except KeyError: print 'Keyword %s does not correspond to an existing DQ mnemonic, so will be ignored' % (dqname) continue just_this_bit = np.bitwise_and(input_model.dq, bitplane) pixels = np.where(just_this_bit != 0) dqmask[pixels] = np.bitwise_or(dqmask[pixels], standard_bitvalue) else: dqmask = input_model.dq return dqmask
<commit_before>import numpy as np from . import dqflags def dynamic_mask(input_model): # # Return a mask model given a mask with dynamic DQ flags # Dynamic flags define what each plane refers to using the DQ_DEF extension dq_table = input_model.dq_def # Get the DQ array and the flag definitions if dq_table is not None: # # Make an empty mask dqmask = np.zeros(input_model.dq.shape, dtype=input_model.dq.dtype) for record in dq_table: bitplane = record['VALUE'] dqname = record['NAME'].strip() try: standard_bitvalue = dqflags.pixel[dqname] except KeyError: print 'Keyword %s does not correspond to an existing DQ mnemonic, so will be ignored' % (dqname) continue just_this_bit = np.bitwise_and(input_model.dq, bitplane) pixels = np.where(just_this_bit != 0) dqmask[pixels] = np.bitwise_or(dqmask[pixels], standard_bitvalue) else: dqmask = input_model.dq return dqmask <commit_msg>Fix bug that appears when a reference file model is created from scratch where the dq_def member exists, but has no rows. git-svn-id: 7ab1303e5df1b63f74144546e35d3203cc1d26c5@3127 560b4ebf-6bc0-4cc5-b8e0-b136f69d22d4<commit_after>
import numpy as np from . import dqflags def dynamic_mask(input_model): # # Return a mask model given a mask with dynamic DQ flags # Dynamic flags define what each plane refers to using the DQ_DEF extension dq_table = input_model.dq_def # Get the DQ array and the flag definitions if dq_table is not None and len(dq_table) > 0: # # Make an empty mask dqmask = np.zeros(input_model.dq.shape, dtype=input_model.dq.dtype) for record in dq_table: bitplane = record['VALUE'] dqname = record['NAME'].strip() try: standard_bitvalue = dqflags.pixel[dqname] except KeyError: print 'Keyword %s does not correspond to an existing DQ mnemonic, so will be ignored' % (dqname) continue just_this_bit = np.bitwise_and(input_model.dq, bitplane) pixels = np.where(just_this_bit != 0) dqmask[pixels] = np.bitwise_or(dqmask[pixels], standard_bitvalue) else: dqmask = input_model.dq return dqmask
import numpy as np from . import dqflags def dynamic_mask(input_model): # # Return a mask model given a mask with dynamic DQ flags # Dynamic flags define what each plane refers to using the DQ_DEF extension dq_table = input_model.dq_def # Get the DQ array and the flag definitions if dq_table is not None: # # Make an empty mask dqmask = np.zeros(input_model.dq.shape, dtype=input_model.dq.dtype) for record in dq_table: bitplane = record['VALUE'] dqname = record['NAME'].strip() try: standard_bitvalue = dqflags.pixel[dqname] except KeyError: print 'Keyword %s does not correspond to an existing DQ mnemonic, so will be ignored' % (dqname) continue just_this_bit = np.bitwise_and(input_model.dq, bitplane) pixels = np.where(just_this_bit != 0) dqmask[pixels] = np.bitwise_or(dqmask[pixels], standard_bitvalue) else: dqmask = input_model.dq return dqmask Fix bug that appears when a reference file model is created from scratch where the dq_def member exists, but has no rows. git-svn-id: 7ab1303e5df1b63f74144546e35d3203cc1d26c5@3127 560b4ebf-6bc0-4cc5-b8e0-b136f69d22d4import numpy as np from . import dqflags def dynamic_mask(input_model): # # Return a mask model given a mask with dynamic DQ flags # Dynamic flags define what each plane refers to using the DQ_DEF extension dq_table = input_model.dq_def # Get the DQ array and the flag definitions if dq_table is not None and len(dq_table) > 0: # # Make an empty mask dqmask = np.zeros(input_model.dq.shape, dtype=input_model.dq.dtype) for record in dq_table: bitplane = record['VALUE'] dqname = record['NAME'].strip() try: standard_bitvalue = dqflags.pixel[dqname] except KeyError: print 'Keyword %s does not correspond to an existing DQ mnemonic, so will be ignored' % (dqname) continue just_this_bit = np.bitwise_and(input_model.dq, bitplane) pixels = np.where(just_this_bit != 0) dqmask[pixels] = np.bitwise_or(dqmask[pixels], standard_bitvalue) else: dqmask = input_model.dq return dqmask
<commit_before>import numpy as np from . import dqflags def dynamic_mask(input_model): # # Return a mask model given a mask with dynamic DQ flags # Dynamic flags define what each plane refers to using the DQ_DEF extension dq_table = input_model.dq_def # Get the DQ array and the flag definitions if dq_table is not None: # # Make an empty mask dqmask = np.zeros(input_model.dq.shape, dtype=input_model.dq.dtype) for record in dq_table: bitplane = record['VALUE'] dqname = record['NAME'].strip() try: standard_bitvalue = dqflags.pixel[dqname] except KeyError: print 'Keyword %s does not correspond to an existing DQ mnemonic, so will be ignored' % (dqname) continue just_this_bit = np.bitwise_and(input_model.dq, bitplane) pixels = np.where(just_this_bit != 0) dqmask[pixels] = np.bitwise_or(dqmask[pixels], standard_bitvalue) else: dqmask = input_model.dq return dqmask <commit_msg>Fix bug that appears when a reference file model is created from scratch where the dq_def member exists, but has no rows. git-svn-id: 7ab1303e5df1b63f74144546e35d3203cc1d26c5@3127 560b4ebf-6bc0-4cc5-b8e0-b136f69d22d4<commit_after>import numpy as np from . import dqflags def dynamic_mask(input_model): # # Return a mask model given a mask with dynamic DQ flags # Dynamic flags define what each plane refers to using the DQ_DEF extension dq_table = input_model.dq_def # Get the DQ array and the flag definitions if dq_table is not None and len(dq_table) > 0: # # Make an empty mask dqmask = np.zeros(input_model.dq.shape, dtype=input_model.dq.dtype) for record in dq_table: bitplane = record['VALUE'] dqname = record['NAME'].strip() try: standard_bitvalue = dqflags.pixel[dqname] except KeyError: print 'Keyword %s does not correspond to an existing DQ mnemonic, so will be ignored' % (dqname) continue just_this_bit = np.bitwise_and(input_model.dq, bitplane) pixels = np.where(just_this_bit != 0) dqmask[pixels] = np.bitwise_or(dqmask[pixels], standard_bitvalue) else: dqmask = input_model.dq return dqmask
a691946e7321ce7d2db55642b99eecbc61fceb82
kpi/utils/private_storage.py
kpi/utils/private_storage.py
# coding: utf-8 from rest_framework.request import Request as DRFRequest from rest_framework.settings import api_settings def superuser_or_username_matches_prefix(private_file): """ You can create a custom function, and use that instead. The function receives a private_storate.models.PrivateFile object, which has the following fields: request: the Django request. storage: the storage engine used to retrieve the file. relative_name: the file name in the storage. full_path: the full file system path. exists(): whether the file exists. content_type: the HTTP content type. (See https://github.com/edoburu/django-private-storage) """ user = private_file.request.user if not user.is_authenticated(): # Try all the DRF authentication methods before giving up request = DRFRequest( private_file.request, authenticators=[ auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES ] ) user = request.user if not user.is_authenticated(): return False if user.is_superuser: return True if private_file.relative_name.startswith( '{}/'.format(user.username) ): return True return False
# coding: utf-8 from rest_framework.request import Request as DRFRequest from rest_framework.settings import api_settings def superuser_or_username_matches_prefix(private_file): """ You can create a custom function, and use that instead. The function receives a private_storate.models.PrivateFile object, which has the following fields: request: the Django request. storage: the storage engine used to retrieve the file. relative_name: the file name in the storage. full_path: the full file system path. exists(): whether the file exists. content_type: the HTTP content type. (See https://github.com/edoburu/django-private-storage) """ user = private_file.request.user if not user.is_authenticated: # Try all the DRF authentication methods before giving up request = DRFRequest( private_file.request, authenticators=[ auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES ] ) user = request.user if not user.is_authenticated: return False if user.is_superuser: return True if private_file.relative_name.startswith( '{}/'.format(user.username) ): return True return False
Fix `TypeError: 'bool' object is not callable`
Fix `TypeError: 'bool' object is not callable` …when attempting to download an export
Python
agpl-3.0
kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi
# coding: utf-8 from rest_framework.request import Request as DRFRequest from rest_framework.settings import api_settings def superuser_or_username_matches_prefix(private_file): """ You can create a custom function, and use that instead. The function receives a private_storate.models.PrivateFile object, which has the following fields: request: the Django request. storage: the storage engine used to retrieve the file. relative_name: the file name in the storage. full_path: the full file system path. exists(): whether the file exists. content_type: the HTTP content type. (See https://github.com/edoburu/django-private-storage) """ user = private_file.request.user if not user.is_authenticated(): # Try all the DRF authentication methods before giving up request = DRFRequest( private_file.request, authenticators=[ auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES ] ) user = request.user if not user.is_authenticated(): return False if user.is_superuser: return True if private_file.relative_name.startswith( '{}/'.format(user.username) ): return True return False Fix `TypeError: 'bool' object is not callable` …when attempting to download an export
# coding: utf-8 from rest_framework.request import Request as DRFRequest from rest_framework.settings import api_settings def superuser_or_username_matches_prefix(private_file): """ You can create a custom function, and use that instead. The function receives a private_storate.models.PrivateFile object, which has the following fields: request: the Django request. storage: the storage engine used to retrieve the file. relative_name: the file name in the storage. full_path: the full file system path. exists(): whether the file exists. content_type: the HTTP content type. (See https://github.com/edoburu/django-private-storage) """ user = private_file.request.user if not user.is_authenticated: # Try all the DRF authentication methods before giving up request = DRFRequest( private_file.request, authenticators=[ auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES ] ) user = request.user if not user.is_authenticated: return False if user.is_superuser: return True if private_file.relative_name.startswith( '{}/'.format(user.username) ): return True return False
<commit_before># coding: utf-8 from rest_framework.request import Request as DRFRequest from rest_framework.settings import api_settings def superuser_or_username_matches_prefix(private_file): """ You can create a custom function, and use that instead. The function receives a private_storate.models.PrivateFile object, which has the following fields: request: the Django request. storage: the storage engine used to retrieve the file. relative_name: the file name in the storage. full_path: the full file system path. exists(): whether the file exists. content_type: the HTTP content type. (See https://github.com/edoburu/django-private-storage) """ user = private_file.request.user if not user.is_authenticated(): # Try all the DRF authentication methods before giving up request = DRFRequest( private_file.request, authenticators=[ auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES ] ) user = request.user if not user.is_authenticated(): return False if user.is_superuser: return True if private_file.relative_name.startswith( '{}/'.format(user.username) ): return True return False <commit_msg>Fix `TypeError: 'bool' object is not callable` …when attempting to download an export<commit_after>
# coding: utf-8 from rest_framework.request import Request as DRFRequest from rest_framework.settings import api_settings def superuser_or_username_matches_prefix(private_file): """ You can create a custom function, and use that instead. The function receives a private_storate.models.PrivateFile object, which has the following fields: request: the Django request. storage: the storage engine used to retrieve the file. relative_name: the file name in the storage. full_path: the full file system path. exists(): whether the file exists. content_type: the HTTP content type. (See https://github.com/edoburu/django-private-storage) """ user = private_file.request.user if not user.is_authenticated: # Try all the DRF authentication methods before giving up request = DRFRequest( private_file.request, authenticators=[ auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES ] ) user = request.user if not user.is_authenticated: return False if user.is_superuser: return True if private_file.relative_name.startswith( '{}/'.format(user.username) ): return True return False
# coding: utf-8 from rest_framework.request import Request as DRFRequest from rest_framework.settings import api_settings def superuser_or_username_matches_prefix(private_file): """ You can create a custom function, and use that instead. The function receives a private_storate.models.PrivateFile object, which has the following fields: request: the Django request. storage: the storage engine used to retrieve the file. relative_name: the file name in the storage. full_path: the full file system path. exists(): whether the file exists. content_type: the HTTP content type. (See https://github.com/edoburu/django-private-storage) """ user = private_file.request.user if not user.is_authenticated(): # Try all the DRF authentication methods before giving up request = DRFRequest( private_file.request, authenticators=[ auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES ] ) user = request.user if not user.is_authenticated(): return False if user.is_superuser: return True if private_file.relative_name.startswith( '{}/'.format(user.username) ): return True return False Fix `TypeError: 'bool' object is not callable` …when attempting to download an export# coding: utf-8 from rest_framework.request import Request as DRFRequest from rest_framework.settings import api_settings def superuser_or_username_matches_prefix(private_file): """ You can create a custom function, and use that instead. The function receives a private_storate.models.PrivateFile object, which has the following fields: request: the Django request. storage: the storage engine used to retrieve the file. relative_name: the file name in the storage. full_path: the full file system path. exists(): whether the file exists. content_type: the HTTP content type. (See https://github.com/edoburu/django-private-storage) """ user = private_file.request.user if not user.is_authenticated: # Try all the DRF authentication methods before giving up request = DRFRequest( private_file.request, authenticators=[ auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES ] ) user = request.user if not user.is_authenticated: return False if user.is_superuser: return True if private_file.relative_name.startswith( '{}/'.format(user.username) ): return True return False
<commit_before># coding: utf-8 from rest_framework.request import Request as DRFRequest from rest_framework.settings import api_settings def superuser_or_username_matches_prefix(private_file): """ You can create a custom function, and use that instead. The function receives a private_storate.models.PrivateFile object, which has the following fields: request: the Django request. storage: the storage engine used to retrieve the file. relative_name: the file name in the storage. full_path: the full file system path. exists(): whether the file exists. content_type: the HTTP content type. (See https://github.com/edoburu/django-private-storage) """ user = private_file.request.user if not user.is_authenticated(): # Try all the DRF authentication methods before giving up request = DRFRequest( private_file.request, authenticators=[ auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES ] ) user = request.user if not user.is_authenticated(): return False if user.is_superuser: return True if private_file.relative_name.startswith( '{}/'.format(user.username) ): return True return False <commit_msg>Fix `TypeError: 'bool' object is not callable` …when attempting to download an export<commit_after># coding: utf-8 from rest_framework.request import Request as DRFRequest from rest_framework.settings import api_settings def superuser_or_username_matches_prefix(private_file): """ You can create a custom function, and use that instead. The function receives a private_storate.models.PrivateFile object, which has the following fields: request: the Django request. storage: the storage engine used to retrieve the file. relative_name: the file name in the storage. full_path: the full file system path. exists(): whether the file exists. content_type: the HTTP content type. (See https://github.com/edoburu/django-private-storage) """ user = private_file.request.user if not user.is_authenticated: # Try all the DRF authentication methods before giving up request = DRFRequest( private_file.request, authenticators=[ auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES ] ) user = request.user if not user.is_authenticated: return False if user.is_superuser: return True if private_file.relative_name.startswith( '{}/'.format(user.username) ): return True return False
73399a7cf86d20a3cda4336cb37f64bcc0508274
masters/master.client.skia/master_site_config.py
masters/master.client.skia/master_site_config.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 10115 slave_port = 10116 master_port_alt = 10117 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 8053 slave_port = 8153 master_port_alt = 8253 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None
Change Skia master ports again
Change Skia master ports again BUG=393690 Review URL: https://codereview.chromium.org/390903004 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@283235 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 10115 slave_port = 10116 master_port_alt = 10117 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None Change Skia master ports again BUG=393690 Review URL: https://codereview.chromium.org/390903004 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@283235 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 8053 slave_port = 8153 master_port_alt = 8253 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None
<commit_before># Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 10115 slave_port = 10116 master_port_alt = 10117 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None <commit_msg>Change Skia master ports again BUG=393690 Review URL: https://codereview.chromium.org/390903004 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@283235 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 8053 slave_port = 8153 master_port_alt = 8253 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 10115 slave_port = 10116 master_port_alt = 10117 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None Change Skia master ports again BUG=393690 Review URL: https://codereview.chromium.org/390903004 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@283235 0039d316-1c4b-4281-b951-d872f2087c98# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 8053 slave_port = 8153 master_port_alt = 8253 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None
<commit_before># Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 10115 slave_port = 10116 master_port_alt = 10117 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None <commit_msg>Change Skia master ports again BUG=393690 Review URL: https://codereview.chromium.org/390903004 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@283235 0039d316-1c4b-4281-b951-d872f2087c98<commit_after># Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 8053 slave_port = 8153 master_port_alt = 8253 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None
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 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 Add absolute imports in init
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
<commit_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 <commit_msg>Add absolute imports in init<commit_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 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 Add absolute imports in initfrom 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
<commit_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 <commit_msg>Add absolute imports in init<commit_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
0d27c83861106c275113cf8018806a5c22c73579
cio/plugins/md.py
cio/plugins/md.py
from .txt import TextPlugin class MarkdownPlugin(TextPlugin): ext = 'md' def render(self, data): # TODO: Handle markdown import error import markdown if data: return markdown.markdown(data)
from .txt import TextPlugin class MarkdownPlugin(TextPlugin): ext = 'md' def render(self, data): # TODO: Handle markdown import error import markdown if data: extensions = self.settings.get('EXTENSIONS', []) return markdown.markdown(data, extensions=extensions)
Add support for Markdown extensions via plugin settings.
Add support for Markdown extensions via plugin settings.
Python
bsd-3-clause
5monkeys/content-io
from .txt import TextPlugin class MarkdownPlugin(TextPlugin): ext = 'md' def render(self, data): # TODO: Handle markdown import error import markdown if data: return markdown.markdown(data) Add support for Markdown extensions via plugin settings.
from .txt import TextPlugin class MarkdownPlugin(TextPlugin): ext = 'md' def render(self, data): # TODO: Handle markdown import error import markdown if data: extensions = self.settings.get('EXTENSIONS', []) return markdown.markdown(data, extensions=extensions)
<commit_before>from .txt import TextPlugin class MarkdownPlugin(TextPlugin): ext = 'md' def render(self, data): # TODO: Handle markdown import error import markdown if data: return markdown.markdown(data) <commit_msg>Add support for Markdown extensions via plugin settings.<commit_after>
from .txt import TextPlugin class MarkdownPlugin(TextPlugin): ext = 'md' def render(self, data): # TODO: Handle markdown import error import markdown if data: extensions = self.settings.get('EXTENSIONS', []) return markdown.markdown(data, extensions=extensions)
from .txt import TextPlugin class MarkdownPlugin(TextPlugin): ext = 'md' def render(self, data): # TODO: Handle markdown import error import markdown if data: return markdown.markdown(data) Add support for Markdown extensions via plugin settings.from .txt import TextPlugin class MarkdownPlugin(TextPlugin): ext = 'md' def render(self, data): # TODO: Handle markdown import error import markdown if data: extensions = self.settings.get('EXTENSIONS', []) return markdown.markdown(data, extensions=extensions)
<commit_before>from .txt import TextPlugin class MarkdownPlugin(TextPlugin): ext = 'md' def render(self, data): # TODO: Handle markdown import error import markdown if data: return markdown.markdown(data) <commit_msg>Add support for Markdown extensions via plugin settings.<commit_after>from .txt import TextPlugin class MarkdownPlugin(TextPlugin): ext = 'md' def render(self, data): # TODO: Handle markdown import error import markdown if data: extensions = self.settings.get('EXTENSIONS', []) return markdown.markdown(data, extensions=extensions)
6ae95c747b7b1e96423fab3de59b52c2bbddd884
sklearn_porter/utils/Logger.py
sklearn_porter/utils/Logger.py
# -*- coding: utf-8 -*- from pathlib import Path import logging from logging.config import fileConfig class Logger: loggers = {} @staticmethod def get_logger(name: str = '') -> logging.Logger: if name not in Logger.loggers.keys(): config_path = Path(__file__).parent / 'logging.ini' fileConfig(config_path) Logger.loggers[name] = logging.getLogger(name) return Logger.loggers.get(name) @staticmethod def set_level(level: int): for name, logger in Logger.loggers.items(): logger.setLevel(level) def get_logger(name: str = '') -> logging.Logger: return Logger.get_logger(name) def set_level(level: int): Logger.set_level(level)
# -*- coding: utf-8 -*- from pathlib import Path import logging from logging.config import fileConfig class Logger: loggers = {} @staticmethod def get_logger(name: str = '') -> logging.Logger: if name not in Logger.loggers.keys(): config_path = Path(__file__).parent / 'logging.ini' config_path = str(config_path) # for Python 3.5 fileConfig(config_path) Logger.loggers[name] = logging.getLogger(name) return Logger.loggers.get(name) @staticmethod def set_level(level: int): for name, logger in Logger.loggers.items(): logger.setLevel(level) def get_logger(name: str = '') -> logging.Logger: return Logger.get_logger(name) def set_level(level: int): Logger.set_level(level)
Fix and cast path to `str`
feature/oop-api-refactoring: Fix and cast path to `str`
Python
bsd-3-clause
nok/sklearn-porter
# -*- coding: utf-8 -*- from pathlib import Path import logging from logging.config import fileConfig class Logger: loggers = {} @staticmethod def get_logger(name: str = '') -> logging.Logger: if name not in Logger.loggers.keys(): config_path = Path(__file__).parent / 'logging.ini' fileConfig(config_path) Logger.loggers[name] = logging.getLogger(name) return Logger.loggers.get(name) @staticmethod def set_level(level: int): for name, logger in Logger.loggers.items(): logger.setLevel(level) def get_logger(name: str = '') -> logging.Logger: return Logger.get_logger(name) def set_level(level: int): Logger.set_level(level) feature/oop-api-refactoring: Fix and cast path to `str`
# -*- coding: utf-8 -*- from pathlib import Path import logging from logging.config import fileConfig class Logger: loggers = {} @staticmethod def get_logger(name: str = '') -> logging.Logger: if name not in Logger.loggers.keys(): config_path = Path(__file__).parent / 'logging.ini' config_path = str(config_path) # for Python 3.5 fileConfig(config_path) Logger.loggers[name] = logging.getLogger(name) return Logger.loggers.get(name) @staticmethod def set_level(level: int): for name, logger in Logger.loggers.items(): logger.setLevel(level) def get_logger(name: str = '') -> logging.Logger: return Logger.get_logger(name) def set_level(level: int): Logger.set_level(level)
<commit_before># -*- coding: utf-8 -*- from pathlib import Path import logging from logging.config import fileConfig class Logger: loggers = {} @staticmethod def get_logger(name: str = '') -> logging.Logger: if name not in Logger.loggers.keys(): config_path = Path(__file__).parent / 'logging.ini' fileConfig(config_path) Logger.loggers[name] = logging.getLogger(name) return Logger.loggers.get(name) @staticmethod def set_level(level: int): for name, logger in Logger.loggers.items(): logger.setLevel(level) def get_logger(name: str = '') -> logging.Logger: return Logger.get_logger(name) def set_level(level: int): Logger.set_level(level) <commit_msg>feature/oop-api-refactoring: Fix and cast path to `str`<commit_after>
# -*- coding: utf-8 -*- from pathlib import Path import logging from logging.config import fileConfig class Logger: loggers = {} @staticmethod def get_logger(name: str = '') -> logging.Logger: if name not in Logger.loggers.keys(): config_path = Path(__file__).parent / 'logging.ini' config_path = str(config_path) # for Python 3.5 fileConfig(config_path) Logger.loggers[name] = logging.getLogger(name) return Logger.loggers.get(name) @staticmethod def set_level(level: int): for name, logger in Logger.loggers.items(): logger.setLevel(level) def get_logger(name: str = '') -> logging.Logger: return Logger.get_logger(name) def set_level(level: int): Logger.set_level(level)
# -*- coding: utf-8 -*- from pathlib import Path import logging from logging.config import fileConfig class Logger: loggers = {} @staticmethod def get_logger(name: str = '') -> logging.Logger: if name not in Logger.loggers.keys(): config_path = Path(__file__).parent / 'logging.ini' fileConfig(config_path) Logger.loggers[name] = logging.getLogger(name) return Logger.loggers.get(name) @staticmethod def set_level(level: int): for name, logger in Logger.loggers.items(): logger.setLevel(level) def get_logger(name: str = '') -> logging.Logger: return Logger.get_logger(name) def set_level(level: int): Logger.set_level(level) feature/oop-api-refactoring: Fix and cast path to `str`# -*- coding: utf-8 -*- from pathlib import Path import logging from logging.config import fileConfig class Logger: loggers = {} @staticmethod def get_logger(name: str = '') -> logging.Logger: if name not in Logger.loggers.keys(): config_path = Path(__file__).parent / 'logging.ini' config_path = str(config_path) # for Python 3.5 fileConfig(config_path) Logger.loggers[name] = logging.getLogger(name) return Logger.loggers.get(name) @staticmethod def set_level(level: int): for name, logger in Logger.loggers.items(): logger.setLevel(level) def get_logger(name: str = '') -> logging.Logger: return Logger.get_logger(name) def set_level(level: int): Logger.set_level(level)
<commit_before># -*- coding: utf-8 -*- from pathlib import Path import logging from logging.config import fileConfig class Logger: loggers = {} @staticmethod def get_logger(name: str = '') -> logging.Logger: if name not in Logger.loggers.keys(): config_path = Path(__file__).parent / 'logging.ini' fileConfig(config_path) Logger.loggers[name] = logging.getLogger(name) return Logger.loggers.get(name) @staticmethod def set_level(level: int): for name, logger in Logger.loggers.items(): logger.setLevel(level) def get_logger(name: str = '') -> logging.Logger: return Logger.get_logger(name) def set_level(level: int): Logger.set_level(level) <commit_msg>feature/oop-api-refactoring: Fix and cast path to `str`<commit_after># -*- coding: utf-8 -*- from pathlib import Path import logging from logging.config import fileConfig class Logger: loggers = {} @staticmethod def get_logger(name: str = '') -> logging.Logger: if name not in Logger.loggers.keys(): config_path = Path(__file__).parent / 'logging.ini' config_path = str(config_path) # for Python 3.5 fileConfig(config_path) Logger.loggers[name] = logging.getLogger(name) return Logger.loggers.get(name) @staticmethod def set_level(level: int): for name, logger in Logger.loggers.items(): logger.setLevel(level) def get_logger(name: str = '') -> logging.Logger: return Logger.get_logger(name) def set_level(level: int): Logger.set_level(level)
e82ed9fcaa6745f849dfb65968ed44da30f6065b
src/plugins/spikeProbability.py
src/plugins/spikeProbability.py
### Spike Probability SpikeDB.plotClear() files = SpikeDB.getFiles(True) for f in files: means = [] err = [] x = [] raw = [] for t in f['trials']: count = [] x.append(t['xvalue']) for p in t['passes']: if len(p) > 0: count.append(1) else: count.append(0) means.append(SpikeDB.mean(count)) err.append(SpikeDB.stddev(count)) SpikeDB.plotXLabel(f['xvar']) SpikeDB.plotYLabel('Spike Probability') SpikeDB.plotYMin(0) SpikeDB.plotYMax(1.0000001) SpikeDB.plotLine(x,means,err)
### Spike Probability SpikeDB.plotClear() files = SpikeDB.getFiles(True) for f in files: means = [] err = [] x = [] raw = [] for t in f['trials']: count = [] x.append(t['xvalue']) for p in t['passes']: if len(p) > 0: count.append(1) else: count.append(0) means.append(SpikeDB.mean(count)) err.append(SpikeDB.stddev(count)) SpikeDB.plotXLabel(f['xvar']) SpikeDB.plotYLabel('Spike Probability') SpikeDB.plotYMin(0) SpikeDB.plotYMax(1.0000001) SpikeDB.plotLine(x,means,err) SpikeDB.plotSetRGBA(0,0,0,0.25); SpikeDB.plotSetPointSize(0); SpikeDB.plotSetLineWidth(4); SpikeDB.plotLine([x[first_index],x[-1]], [0.5,0.5], [])
Add line to spike prob
Add line to spike prob
Python
bsd-3-clause
baubie/SpikeDB,baubie/SpikeDB,baubie/SpikeDB,baubie/SpikeDB
### Spike Probability SpikeDB.plotClear() files = SpikeDB.getFiles(True) for f in files: means = [] err = [] x = [] raw = [] for t in f['trials']: count = [] x.append(t['xvalue']) for p in t['passes']: if len(p) > 0: count.append(1) else: count.append(0) means.append(SpikeDB.mean(count)) err.append(SpikeDB.stddev(count)) SpikeDB.plotXLabel(f['xvar']) SpikeDB.plotYLabel('Spike Probability') SpikeDB.plotYMin(0) SpikeDB.plotYMax(1.0000001) SpikeDB.plotLine(x,means,err) Add line to spike prob
### Spike Probability SpikeDB.plotClear() files = SpikeDB.getFiles(True) for f in files: means = [] err = [] x = [] raw = [] for t in f['trials']: count = [] x.append(t['xvalue']) for p in t['passes']: if len(p) > 0: count.append(1) else: count.append(0) means.append(SpikeDB.mean(count)) err.append(SpikeDB.stddev(count)) SpikeDB.plotXLabel(f['xvar']) SpikeDB.plotYLabel('Spike Probability') SpikeDB.plotYMin(0) SpikeDB.plotYMax(1.0000001) SpikeDB.plotLine(x,means,err) SpikeDB.plotSetRGBA(0,0,0,0.25); SpikeDB.plotSetPointSize(0); SpikeDB.plotSetLineWidth(4); SpikeDB.plotLine([x[first_index],x[-1]], [0.5,0.5], [])
<commit_before>### Spike Probability SpikeDB.plotClear() files = SpikeDB.getFiles(True) for f in files: means = [] err = [] x = [] raw = [] for t in f['trials']: count = [] x.append(t['xvalue']) for p in t['passes']: if len(p) > 0: count.append(1) else: count.append(0) means.append(SpikeDB.mean(count)) err.append(SpikeDB.stddev(count)) SpikeDB.plotXLabel(f['xvar']) SpikeDB.plotYLabel('Spike Probability') SpikeDB.plotYMin(0) SpikeDB.plotYMax(1.0000001) SpikeDB.plotLine(x,means,err) <commit_msg>Add line to spike prob<commit_after>
### Spike Probability SpikeDB.plotClear() files = SpikeDB.getFiles(True) for f in files: means = [] err = [] x = [] raw = [] for t in f['trials']: count = [] x.append(t['xvalue']) for p in t['passes']: if len(p) > 0: count.append(1) else: count.append(0) means.append(SpikeDB.mean(count)) err.append(SpikeDB.stddev(count)) SpikeDB.plotXLabel(f['xvar']) SpikeDB.plotYLabel('Spike Probability') SpikeDB.plotYMin(0) SpikeDB.plotYMax(1.0000001) SpikeDB.plotLine(x,means,err) SpikeDB.plotSetRGBA(0,0,0,0.25); SpikeDB.plotSetPointSize(0); SpikeDB.plotSetLineWidth(4); SpikeDB.plotLine([x[first_index],x[-1]], [0.5,0.5], [])
### Spike Probability SpikeDB.plotClear() files = SpikeDB.getFiles(True) for f in files: means = [] err = [] x = [] raw = [] for t in f['trials']: count = [] x.append(t['xvalue']) for p in t['passes']: if len(p) > 0: count.append(1) else: count.append(0) means.append(SpikeDB.mean(count)) err.append(SpikeDB.stddev(count)) SpikeDB.plotXLabel(f['xvar']) SpikeDB.plotYLabel('Spike Probability') SpikeDB.plotYMin(0) SpikeDB.plotYMax(1.0000001) SpikeDB.plotLine(x,means,err) Add line to spike prob### Spike Probability SpikeDB.plotClear() files = SpikeDB.getFiles(True) for f in files: means = [] err = [] x = [] raw = [] for t in f['trials']: count = [] x.append(t['xvalue']) for p in t['passes']: if len(p) > 0: count.append(1) else: count.append(0) means.append(SpikeDB.mean(count)) err.append(SpikeDB.stddev(count)) SpikeDB.plotXLabel(f['xvar']) SpikeDB.plotYLabel('Spike Probability') SpikeDB.plotYMin(0) SpikeDB.plotYMax(1.0000001) SpikeDB.plotLine(x,means,err) SpikeDB.plotSetRGBA(0,0,0,0.25); SpikeDB.plotSetPointSize(0); SpikeDB.plotSetLineWidth(4); SpikeDB.plotLine([x[first_index],x[-1]], [0.5,0.5], [])
<commit_before>### Spike Probability SpikeDB.plotClear() files = SpikeDB.getFiles(True) for f in files: means = [] err = [] x = [] raw = [] for t in f['trials']: count = [] x.append(t['xvalue']) for p in t['passes']: if len(p) > 0: count.append(1) else: count.append(0) means.append(SpikeDB.mean(count)) err.append(SpikeDB.stddev(count)) SpikeDB.plotXLabel(f['xvar']) SpikeDB.plotYLabel('Spike Probability') SpikeDB.plotYMin(0) SpikeDB.plotYMax(1.0000001) SpikeDB.plotLine(x,means,err) <commit_msg>Add line to spike prob<commit_after>### Spike Probability SpikeDB.plotClear() files = SpikeDB.getFiles(True) for f in files: means = [] err = [] x = [] raw = [] for t in f['trials']: count = [] x.append(t['xvalue']) for p in t['passes']: if len(p) > 0: count.append(1) else: count.append(0) means.append(SpikeDB.mean(count)) err.append(SpikeDB.stddev(count)) SpikeDB.plotXLabel(f['xvar']) SpikeDB.plotYLabel('Spike Probability') SpikeDB.plotYMin(0) SpikeDB.plotYMax(1.0000001) SpikeDB.plotLine(x,means,err) SpikeDB.plotSetRGBA(0,0,0,0.25); SpikeDB.plotSetPointSize(0); SpikeDB.plotSetLineWidth(4); SpikeDB.plotLine([x[first_index],x[-1]], [0.5,0.5], [])
effd1010abb7dbe920e11627fe555bacecced194
rst2pdf/utils.py
rst2pdf/utils.py
#$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
# -*- coding: utf-8 -*- #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
Fix encoding (thanks to Yasushi Masuda)
Fix encoding (thanks to Yasushi Masuda) git-svn-id: 305ad3fa995f01f9ce4b4f46c2a806ba00a97020@433 3777fadb-0f44-0410-9e7f-9d8fa6171d72
Python
mit
aquavitae/rst2pdf-py3-dev,tonioo/rst2pdf,sychen/rst2pdf,tonioo/rst2pdf,aquavitae/rst2pdf,sychen/rst2pdf,openpolis/rst2pdf-patched-docutils-0.8,aquavitae/rst2pdf-py3-dev,aquavitae/rst2pdf,openpolis/rst2pdf-patched-docutils-0.8
#$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent) Fix encoding (thanks to Yasushi Masuda) git-svn-id: 305ad3fa995f01f9ce4b4f46c2a806ba00a97020@433 3777fadb-0f44-0410-9e7f-9d8fa6171d72
# -*- coding: utf-8 -*- #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
<commit_before>#$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent) <commit_msg>Fix encoding (thanks to Yasushi Masuda) git-svn-id: 305ad3fa995f01f9ce4b4f46c2a806ba00a97020@433 3777fadb-0f44-0410-9e7f-9d8fa6171d72<commit_after>
# -*- coding: utf-8 -*- #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
#$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent) Fix encoding (thanks to Yasushi Masuda) git-svn-id: 305ad3fa995f01f9ce4b4f46c2a806ba00a97020@433 3777fadb-0f44-0410-9e7f-9d8fa6171d72# -*- coding: utf-8 -*- #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
<commit_before>#$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent) <commit_msg>Fix encoding (thanks to Yasushi Masuda) git-svn-id: 305ad3fa995f01f9ce4b4f46c2a806ba00a97020@433 3777fadb-0f44-0410-9e7f-9d8fa6171d72<commit_after># -*- coding: utf-8 -*- #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
dafd7689eaca4705ace7b462a1f039982d47cd71
panoply/errors.py
panoply/errors.py
class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable
class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable class IncorrectParamError(Exception): def __init__(self, msg: str = "Incorrect input parametr"): super().__init__(msg)
Add new exception class for ssh tunnel logic
Add new exception class for ssh tunnel logic
Python
mit
panoplyio/panoply-python-sdk
class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable Add new exception class for ssh tunnel logic
class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable class IncorrectParamError(Exception): def __init__(self, msg: str = "Incorrect input parametr"): super().__init__(msg)
<commit_before>class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable <commit_msg>Add new exception class for ssh tunnel logic<commit_after>
class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable class IncorrectParamError(Exception): def __init__(self, msg: str = "Incorrect input parametr"): super().__init__(msg)
class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable Add new exception class for ssh tunnel logicclass PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable class IncorrectParamError(Exception): def __init__(self, msg: str = "Incorrect input parametr"): super().__init__(msg)
<commit_before>class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable <commit_msg>Add new exception class for ssh tunnel logic<commit_after>class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable class IncorrectParamError(Exception): def __init__(self, msg: str = "Incorrect input parametr"): super().__init__(msg)
d9cb41e12b3f64e71d64dc32fcdc133813897e0b
core/data/DataTransformer.py
core/data/DataTransformer.py
""" DataTransformer :Authors: Berend Klein Haneveld """ from vtk import vtkImageReslice class DataTransformer(object): """DataTransformer is a class that can transform a given dataset""" def __init__(self): super(DataTransformer, self).__init__() def TransformImageData(self, imageData, transform): """ :type imageData: vtkImageData :type transform: vtkTransform """ reslicer = vtkImageReslice() reslicer.SetInterpolationModeToCubic() range = imageData.GetScalarRange() reslicer.SetBackgroundLevel(range[0]) # reslicer.SetAutoCropOutput(1) # Not sure if this is what we want reslicer.SetInputData(imageData) reslicer.SetResliceTransform(transform.GetInverse()) reslicer.Update() return reslicer.GetOutput()
""" DataTransformer :Authors: Berend Klein Haneveld """ from vtk import vtkImageReslice class DataTransformer(object): """DataTransformer is a class that can transform a given dataset""" def __init__(self): super(DataTransformer, self).__init__() def TransformImageData(self, imageData, transform): """ :type imageData: vtkImageData :type transform: vtkTransform """ range = imageData.GetScalarRange() reslicer = vtkImageReslice() reslicer.SetInterpolationModeToCubic() reslicer.SetBackgroundLevel(range[0]) reslicer.AutoCropOutputOff() reslicer.SetInputData(imageData) reslicer.SetResliceTransform(transform.GetInverse()) reslicer.Update() return reslicer.GetOutput()
Make sure that the reslicer does not ommit any image data.
Make sure that the reslicer does not ommit any image data.
Python
mit
berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop
""" DataTransformer :Authors: Berend Klein Haneveld """ from vtk import vtkImageReslice class DataTransformer(object): """DataTransformer is a class that can transform a given dataset""" def __init__(self): super(DataTransformer, self).__init__() def TransformImageData(self, imageData, transform): """ :type imageData: vtkImageData :type transform: vtkTransform """ reslicer = vtkImageReslice() reslicer.SetInterpolationModeToCubic() range = imageData.GetScalarRange() reslicer.SetBackgroundLevel(range[0]) # reslicer.SetAutoCropOutput(1) # Not sure if this is what we want reslicer.SetInputData(imageData) reslicer.SetResliceTransform(transform.GetInverse()) reslicer.Update() return reslicer.GetOutput() Make sure that the reslicer does not ommit any image data.
""" DataTransformer :Authors: Berend Klein Haneveld """ from vtk import vtkImageReslice class DataTransformer(object): """DataTransformer is a class that can transform a given dataset""" def __init__(self): super(DataTransformer, self).__init__() def TransformImageData(self, imageData, transform): """ :type imageData: vtkImageData :type transform: vtkTransform """ range = imageData.GetScalarRange() reslicer = vtkImageReslice() reslicer.SetInterpolationModeToCubic() reslicer.SetBackgroundLevel(range[0]) reslicer.AutoCropOutputOff() reslicer.SetInputData(imageData) reslicer.SetResliceTransform(transform.GetInverse()) reslicer.Update() return reslicer.GetOutput()
<commit_before>""" DataTransformer :Authors: Berend Klein Haneveld """ from vtk import vtkImageReslice class DataTransformer(object): """DataTransformer is a class that can transform a given dataset""" def __init__(self): super(DataTransformer, self).__init__() def TransformImageData(self, imageData, transform): """ :type imageData: vtkImageData :type transform: vtkTransform """ reslicer = vtkImageReslice() reslicer.SetInterpolationModeToCubic() range = imageData.GetScalarRange() reslicer.SetBackgroundLevel(range[0]) # reslicer.SetAutoCropOutput(1) # Not sure if this is what we want reslicer.SetInputData(imageData) reslicer.SetResliceTransform(transform.GetInverse()) reslicer.Update() return reslicer.GetOutput() <commit_msg>Make sure that the reslicer does not ommit any image data.<commit_after>
""" DataTransformer :Authors: Berend Klein Haneveld """ from vtk import vtkImageReslice class DataTransformer(object): """DataTransformer is a class that can transform a given dataset""" def __init__(self): super(DataTransformer, self).__init__() def TransformImageData(self, imageData, transform): """ :type imageData: vtkImageData :type transform: vtkTransform """ range = imageData.GetScalarRange() reslicer = vtkImageReslice() reslicer.SetInterpolationModeToCubic() reslicer.SetBackgroundLevel(range[0]) reslicer.AutoCropOutputOff() reslicer.SetInputData(imageData) reslicer.SetResliceTransform(transform.GetInverse()) reslicer.Update() return reslicer.GetOutput()
""" DataTransformer :Authors: Berend Klein Haneveld """ from vtk import vtkImageReslice class DataTransformer(object): """DataTransformer is a class that can transform a given dataset""" def __init__(self): super(DataTransformer, self).__init__() def TransformImageData(self, imageData, transform): """ :type imageData: vtkImageData :type transform: vtkTransform """ reslicer = vtkImageReslice() reslicer.SetInterpolationModeToCubic() range = imageData.GetScalarRange() reslicer.SetBackgroundLevel(range[0]) # reslicer.SetAutoCropOutput(1) # Not sure if this is what we want reslicer.SetInputData(imageData) reslicer.SetResliceTransform(transform.GetInverse()) reslicer.Update() return reslicer.GetOutput() Make sure that the reslicer does not ommit any image data.""" DataTransformer :Authors: Berend Klein Haneveld """ from vtk import vtkImageReslice class DataTransformer(object): """DataTransformer is a class that can transform a given dataset""" def __init__(self): super(DataTransformer, self).__init__() def TransformImageData(self, imageData, transform): """ :type imageData: vtkImageData :type transform: vtkTransform """ range = imageData.GetScalarRange() reslicer = vtkImageReslice() reslicer.SetInterpolationModeToCubic() reslicer.SetBackgroundLevel(range[0]) reslicer.AutoCropOutputOff() reslicer.SetInputData(imageData) reslicer.SetResliceTransform(transform.GetInverse()) reslicer.Update() return reslicer.GetOutput()
<commit_before>""" DataTransformer :Authors: Berend Klein Haneveld """ from vtk import vtkImageReslice class DataTransformer(object): """DataTransformer is a class that can transform a given dataset""" def __init__(self): super(DataTransformer, self).__init__() def TransformImageData(self, imageData, transform): """ :type imageData: vtkImageData :type transform: vtkTransform """ reslicer = vtkImageReslice() reslicer.SetInterpolationModeToCubic() range = imageData.GetScalarRange() reslicer.SetBackgroundLevel(range[0]) # reslicer.SetAutoCropOutput(1) # Not sure if this is what we want reslicer.SetInputData(imageData) reslicer.SetResliceTransform(transform.GetInverse()) reslicer.Update() return reslicer.GetOutput() <commit_msg>Make sure that the reslicer does not ommit any image data.<commit_after>""" DataTransformer :Authors: Berend Klein Haneveld """ from vtk import vtkImageReslice class DataTransformer(object): """DataTransformer is a class that can transform a given dataset""" def __init__(self): super(DataTransformer, self).__init__() def TransformImageData(self, imageData, transform): """ :type imageData: vtkImageData :type transform: vtkTransform """ range = imageData.GetScalarRange() reslicer = vtkImageReslice() reslicer.SetInterpolationModeToCubic() reslicer.SetBackgroundLevel(range[0]) reslicer.AutoCropOutputOff() reslicer.SetInputData(imageData) reslicer.SetResliceTransform(transform.GetInverse()) reslicer.Update() return reslicer.GetOutput()
58fb8460b58e99b26abe9f3f279f87459f8b7ac4
patrol_mission.py
patrol_mission.py
#!/usr/bin/python """ Cyril Robin -- LAAS-CNRS -- 2014 TODO Descriptif """ from mission import * from constant import * from sys import argv, exit from timer import Timer if __name__ == "__main__": with Timer('Loading mission file'): json_mission = loaded_mission(argv[1]) mission = Mission ( json_mission ) print "Starting Loop !" #mission.loop_once('Perception-based TSP') #mission.loop(10,True,'Perception-based TSP') #mission.decentralized_loop_once() mission.decentralized_loop(5,False,'Perception-based TSP') print "Updating..." mission.update() mission.dump_situation() #for robot in mission.team: #robot.display_weighted_map() mission.display_situation() mission.print_metrics() print "Done."
#!/usr/bin/python """ Cyril Robin -- LAAS-CNRS -- 2014 TODO Descriptif """ from mission import * from constant import * from sys import argv, exit from timer import Timer if __name__ == "__main__": with Timer('Loading mission file'): json_mission = loaded_mission(argv[1]) mission = Mission ( json_mission ) print "Starting Loop !" #mission.loop(20,False,'Perception-based TSP') #mission.loop(10,False,'Perception-based TOP') mission.decentralized_loop(20,False,'Perception-based TSP') #mission.sample_objective() #mission.sample_all_positions() #for robot in mission.team: #robot.display_weighted_map() #mission.display_situation() print "Last update..." mission.update() mission.dump_situation() mission.display_situation() mission.print_metrics() print "Done."
Update patrol launcher to recent changes
Update patrol launcher to recent changes
Python
bsd-3-clause
cyrobin/patrolling,cyrobin/patrolling
#!/usr/bin/python """ Cyril Robin -- LAAS-CNRS -- 2014 TODO Descriptif """ from mission import * from constant import * from sys import argv, exit from timer import Timer if __name__ == "__main__": with Timer('Loading mission file'): json_mission = loaded_mission(argv[1]) mission = Mission ( json_mission ) print "Starting Loop !" #mission.loop_once('Perception-based TSP') #mission.loop(10,True,'Perception-based TSP') #mission.decentralized_loop_once() mission.decentralized_loop(5,False,'Perception-based TSP') print "Updating..." mission.update() mission.dump_situation() #for robot in mission.team: #robot.display_weighted_map() mission.display_situation() mission.print_metrics() print "Done." Update patrol launcher to recent changes
#!/usr/bin/python """ Cyril Robin -- LAAS-CNRS -- 2014 TODO Descriptif """ from mission import * from constant import * from sys import argv, exit from timer import Timer if __name__ == "__main__": with Timer('Loading mission file'): json_mission = loaded_mission(argv[1]) mission = Mission ( json_mission ) print "Starting Loop !" #mission.loop(20,False,'Perception-based TSP') #mission.loop(10,False,'Perception-based TOP') mission.decentralized_loop(20,False,'Perception-based TSP') #mission.sample_objective() #mission.sample_all_positions() #for robot in mission.team: #robot.display_weighted_map() #mission.display_situation() print "Last update..." mission.update() mission.dump_situation() mission.display_situation() mission.print_metrics() print "Done."
<commit_before>#!/usr/bin/python """ Cyril Robin -- LAAS-CNRS -- 2014 TODO Descriptif """ from mission import * from constant import * from sys import argv, exit from timer import Timer if __name__ == "__main__": with Timer('Loading mission file'): json_mission = loaded_mission(argv[1]) mission = Mission ( json_mission ) print "Starting Loop !" #mission.loop_once('Perception-based TSP') #mission.loop(10,True,'Perception-based TSP') #mission.decentralized_loop_once() mission.decentralized_loop(5,False,'Perception-based TSP') print "Updating..." mission.update() mission.dump_situation() #for robot in mission.team: #robot.display_weighted_map() mission.display_situation() mission.print_metrics() print "Done." <commit_msg>Update patrol launcher to recent changes<commit_after>
#!/usr/bin/python """ Cyril Robin -- LAAS-CNRS -- 2014 TODO Descriptif """ from mission import * from constant import * from sys import argv, exit from timer import Timer if __name__ == "__main__": with Timer('Loading mission file'): json_mission = loaded_mission(argv[1]) mission = Mission ( json_mission ) print "Starting Loop !" #mission.loop(20,False,'Perception-based TSP') #mission.loop(10,False,'Perception-based TOP') mission.decentralized_loop(20,False,'Perception-based TSP') #mission.sample_objective() #mission.sample_all_positions() #for robot in mission.team: #robot.display_weighted_map() #mission.display_situation() print "Last update..." mission.update() mission.dump_situation() mission.display_situation() mission.print_metrics() print "Done."
#!/usr/bin/python """ Cyril Robin -- LAAS-CNRS -- 2014 TODO Descriptif """ from mission import * from constant import * from sys import argv, exit from timer import Timer if __name__ == "__main__": with Timer('Loading mission file'): json_mission = loaded_mission(argv[1]) mission = Mission ( json_mission ) print "Starting Loop !" #mission.loop_once('Perception-based TSP') #mission.loop(10,True,'Perception-based TSP') #mission.decentralized_loop_once() mission.decentralized_loop(5,False,'Perception-based TSP') print "Updating..." mission.update() mission.dump_situation() #for robot in mission.team: #robot.display_weighted_map() mission.display_situation() mission.print_metrics() print "Done." Update patrol launcher to recent changes#!/usr/bin/python """ Cyril Robin -- LAAS-CNRS -- 2014 TODO Descriptif """ from mission import * from constant import * from sys import argv, exit from timer import Timer if __name__ == "__main__": with Timer('Loading mission file'): json_mission = loaded_mission(argv[1]) mission = Mission ( json_mission ) print "Starting Loop !" #mission.loop(20,False,'Perception-based TSP') #mission.loop(10,False,'Perception-based TOP') mission.decentralized_loop(20,False,'Perception-based TSP') #mission.sample_objective() #mission.sample_all_positions() #for robot in mission.team: #robot.display_weighted_map() #mission.display_situation() print "Last update..." mission.update() mission.dump_situation() mission.display_situation() mission.print_metrics() print "Done."
<commit_before>#!/usr/bin/python """ Cyril Robin -- LAAS-CNRS -- 2014 TODO Descriptif """ from mission import * from constant import * from sys import argv, exit from timer import Timer if __name__ == "__main__": with Timer('Loading mission file'): json_mission = loaded_mission(argv[1]) mission = Mission ( json_mission ) print "Starting Loop !" #mission.loop_once('Perception-based TSP') #mission.loop(10,True,'Perception-based TSP') #mission.decentralized_loop_once() mission.decentralized_loop(5,False,'Perception-based TSP') print "Updating..." mission.update() mission.dump_situation() #for robot in mission.team: #robot.display_weighted_map() mission.display_situation() mission.print_metrics() print "Done." <commit_msg>Update patrol launcher to recent changes<commit_after>#!/usr/bin/python """ Cyril Robin -- LAAS-CNRS -- 2014 TODO Descriptif """ from mission import * from constant import * from sys import argv, exit from timer import Timer if __name__ == "__main__": with Timer('Loading mission file'): json_mission = loaded_mission(argv[1]) mission = Mission ( json_mission ) print "Starting Loop !" #mission.loop(20,False,'Perception-based TSP') #mission.loop(10,False,'Perception-based TOP') mission.decentralized_loop(20,False,'Perception-based TSP') #mission.sample_objective() #mission.sample_all_positions() #for robot in mission.team: #robot.display_weighted_map() #mission.display_situation() print "Last update..." mission.update() mission.dump_situation() mission.display_situation() mission.print_metrics() print "Done."
65d7ff9fc275bd6186484236d7a0d03c65cc62d7
peerinst/admin.py
peerinst/admin.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}), (_('Secondary image or video'), { 'fields': ['secondary_image', 'secondary_video_url'], 'classes': ['collapse'], 'description': _( 'Choose either a video or image to include on the first page of the question, ' 'where students select concept tags. This is only used if you want the question ' 'to be hidden when students select concept tags; instead, a preliminary video or ' 'image can be displayed. The main question image will be displayed on all ' 'subsequent pages.' ), }), (_('Answers'), {'fields': [ 'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer' ]}), (None, {'fields': ['example_rationale']}), ] @admin.register(models.Assignment) class AssignmentAdmin(admin.ModelAdmin): pass
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}), (_('Secondary image or video'), { 'fields': ['secondary_image', 'secondary_video_url'], 'classes': ['collapse'], 'description': _( 'Choose either a video or image to include on the first page of the question, ' 'where students select concept tags. This is only used if you want the question ' 'to be hidden when students select concept tags; instead, a preliminary video or ' 'image can be displayed. The main question image will be displayed on all ' 'subsequent pages.' ), }), (_('Answers'), {'fields': [ 'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer' ]}), (None, {'fields': ['example_rationale']}), ] @admin.register(models.Assignment) class AssignmentAdmin(admin.ModelAdmin): filter_horizontal = ['questions']
Use nifty filter widget for selecting questions for an assignment.
Use nifty filter widget for selecting questions for an assignment.
Python
agpl-3.0
open-craft/dalite-ng,open-craft/dalite-ng,open-craft/dalite-ng
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}), (_('Secondary image or video'), { 'fields': ['secondary_image', 'secondary_video_url'], 'classes': ['collapse'], 'description': _( 'Choose either a video or image to include on the first page of the question, ' 'where students select concept tags. This is only used if you want the question ' 'to be hidden when students select concept tags; instead, a preliminary video or ' 'image can be displayed. The main question image will be displayed on all ' 'subsequent pages.' ), }), (_('Answers'), {'fields': [ 'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer' ]}), (None, {'fields': ['example_rationale']}), ] @admin.register(models.Assignment) class AssignmentAdmin(admin.ModelAdmin): pass Use nifty filter widget for selecting questions for an assignment.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}), (_('Secondary image or video'), { 'fields': ['secondary_image', 'secondary_video_url'], 'classes': ['collapse'], 'description': _( 'Choose either a video or image to include on the first page of the question, ' 'where students select concept tags. This is only used if you want the question ' 'to be hidden when students select concept tags; instead, a preliminary video or ' 'image can be displayed. The main question image will be displayed on all ' 'subsequent pages.' ), }), (_('Answers'), {'fields': [ 'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer' ]}), (None, {'fields': ['example_rationale']}), ] @admin.register(models.Assignment) class AssignmentAdmin(admin.ModelAdmin): filter_horizontal = ['questions']
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}), (_('Secondary image or video'), { 'fields': ['secondary_image', 'secondary_video_url'], 'classes': ['collapse'], 'description': _( 'Choose either a video or image to include on the first page of the question, ' 'where students select concept tags. This is only used if you want the question ' 'to be hidden when students select concept tags; instead, a preliminary video or ' 'image can be displayed. The main question image will be displayed on all ' 'subsequent pages.' ), }), (_('Answers'), {'fields': [ 'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer' ]}), (None, {'fields': ['example_rationale']}), ] @admin.register(models.Assignment) class AssignmentAdmin(admin.ModelAdmin): pass <commit_msg>Use nifty filter widget for selecting questions for an assignment.<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}), (_('Secondary image or video'), { 'fields': ['secondary_image', 'secondary_video_url'], 'classes': ['collapse'], 'description': _( 'Choose either a video or image to include on the first page of the question, ' 'where students select concept tags. This is only used if you want the question ' 'to be hidden when students select concept tags; instead, a preliminary video or ' 'image can be displayed. The main question image will be displayed on all ' 'subsequent pages.' ), }), (_('Answers'), {'fields': [ 'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer' ]}), (None, {'fields': ['example_rationale']}), ] @admin.register(models.Assignment) class AssignmentAdmin(admin.ModelAdmin): filter_horizontal = ['questions']
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}), (_('Secondary image or video'), { 'fields': ['secondary_image', 'secondary_video_url'], 'classes': ['collapse'], 'description': _( 'Choose either a video or image to include on the first page of the question, ' 'where students select concept tags. This is only used if you want the question ' 'to be hidden when students select concept tags; instead, a preliminary video or ' 'image can be displayed. The main question image will be displayed on all ' 'subsequent pages.' ), }), (_('Answers'), {'fields': [ 'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer' ]}), (None, {'fields': ['example_rationale']}), ] @admin.register(models.Assignment) class AssignmentAdmin(admin.ModelAdmin): pass Use nifty filter widget for selecting questions for an assignment.# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}), (_('Secondary image or video'), { 'fields': ['secondary_image', 'secondary_video_url'], 'classes': ['collapse'], 'description': _( 'Choose either a video or image to include on the first page of the question, ' 'where students select concept tags. This is only used if you want the question ' 'to be hidden when students select concept tags; instead, a preliminary video or ' 'image can be displayed. The main question image will be displayed on all ' 'subsequent pages.' ), }), (_('Answers'), {'fields': [ 'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer' ]}), (None, {'fields': ['example_rationale']}), ] @admin.register(models.Assignment) class AssignmentAdmin(admin.ModelAdmin): filter_horizontal = ['questions']
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}), (_('Secondary image or video'), { 'fields': ['secondary_image', 'secondary_video_url'], 'classes': ['collapse'], 'description': _( 'Choose either a video or image to include on the first page of the question, ' 'where students select concept tags. This is only used if you want the question ' 'to be hidden when students select concept tags; instead, a preliminary video or ' 'image can be displayed. The main question image will be displayed on all ' 'subsequent pages.' ), }), (_('Answers'), {'fields': [ 'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer' ]}), (None, {'fields': ['example_rationale']}), ] @admin.register(models.Assignment) class AssignmentAdmin(admin.ModelAdmin): pass <commit_msg>Use nifty filter widget for selecting questions for an assignment.<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}), (_('Secondary image or video'), { 'fields': ['secondary_image', 'secondary_video_url'], 'classes': ['collapse'], 'description': _( 'Choose either a video or image to include on the first page of the question, ' 'where students select concept tags. This is only used if you want the question ' 'to be hidden when students select concept tags; instead, a preliminary video or ' 'image can be displayed. The main question image will be displayed on all ' 'subsequent pages.' ), }), (_('Answers'), {'fields': [ 'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer' ]}), (None, {'fields': ['example_rationale']}), ] @admin.register(models.Assignment) class AssignmentAdmin(admin.ModelAdmin): filter_horizontal = ['questions']
83f6a1eaf41cb45f7e2d705966e269dcb514f9be
coinrpc.py
coinrpc.py
import bottle, jsonrpc, sys def with_rpc(orig_func): '''Function decorator to provide RPC service proxy''' def wrapped_func(*arg, **kwarg): app = bottle.default_app() svc = app.config['coinrpc.svc'] return orig_func(svc, *arg, **kwarg) return wrapped_func @bottle.get('/help') @with_rpc def help(rpc): hdoc = rpc.help() return hdoc.replace('\n', '<br>') if __name__ == '__main__': app = bottle.default_app() try: conf_file = sys.argv[1] except IndexError: conf_file = 'coin.conf' config = app.config.load_config(conf_file) url = 'http://%s:%s@%s:%s' % ( config['coinrpc.user'], config['coinrpc.pass'], config['coinrpc.host'], config['coinrpc.port'], ) svc = jsonrpc.ServiceProxy(url) config['coinrpc.svc'] = svc app.run(**config)
import bottle, jsonrpc, sys def with_coinrpc(*items): '''Function decorator to provide coinrpc config items''' def wrap_func(orig_func): app = bottle.default_app() keys = tuple(['coinrpc.' + i for i in items]) def wrapped_func(*arg, **kwarg): config_items = tuple([app.config[k] for k in keys]) arg = config_items + arg return orig_func(*arg, **kwarg) return wrapped_func return wrap_func @bottle.get('/help') @with_coinrpc('svc') def help(svc): hdoc = svc.help() return hdoc.replace('\n', '<br>') if __name__ == '__main__': app = bottle.default_app() try: conf_file = sys.argv[1] except IndexError: conf_file = 'coin.conf' config = app.config.load_config(conf_file) url = 'http://%s:%s@%s:%s' % ( config['coinrpc.user'], config['coinrpc.pass'], config['coinrpc.host'], config['coinrpc.port'], ) svc = jsonrpc.ServiceProxy(url) config['coinrpc.svc'] = svc app.run(**config)
Make config-helper decorator more generic
Make config-helper decorator more generic Instead of only pulling 'coinrpc.svc' from app.config, pull out any number of items.
Python
mit
grantisu/Sericata
import bottle, jsonrpc, sys def with_rpc(orig_func): '''Function decorator to provide RPC service proxy''' def wrapped_func(*arg, **kwarg): app = bottle.default_app() svc = app.config['coinrpc.svc'] return orig_func(svc, *arg, **kwarg) return wrapped_func @bottle.get('/help') @with_rpc def help(rpc): hdoc = rpc.help() return hdoc.replace('\n', '<br>') if __name__ == '__main__': app = bottle.default_app() try: conf_file = sys.argv[1] except IndexError: conf_file = 'coin.conf' config = app.config.load_config(conf_file) url = 'http://%s:%s@%s:%s' % ( config['coinrpc.user'], config['coinrpc.pass'], config['coinrpc.host'], config['coinrpc.port'], ) svc = jsonrpc.ServiceProxy(url) config['coinrpc.svc'] = svc app.run(**config) Make config-helper decorator more generic Instead of only pulling 'coinrpc.svc' from app.config, pull out any number of items.
import bottle, jsonrpc, sys def with_coinrpc(*items): '''Function decorator to provide coinrpc config items''' def wrap_func(orig_func): app = bottle.default_app() keys = tuple(['coinrpc.' + i for i in items]) def wrapped_func(*arg, **kwarg): config_items = tuple([app.config[k] for k in keys]) arg = config_items + arg return orig_func(*arg, **kwarg) return wrapped_func return wrap_func @bottle.get('/help') @with_coinrpc('svc') def help(svc): hdoc = svc.help() return hdoc.replace('\n', '<br>') if __name__ == '__main__': app = bottle.default_app() try: conf_file = sys.argv[1] except IndexError: conf_file = 'coin.conf' config = app.config.load_config(conf_file) url = 'http://%s:%s@%s:%s' % ( config['coinrpc.user'], config['coinrpc.pass'], config['coinrpc.host'], config['coinrpc.port'], ) svc = jsonrpc.ServiceProxy(url) config['coinrpc.svc'] = svc app.run(**config)
<commit_before>import bottle, jsonrpc, sys def with_rpc(orig_func): '''Function decorator to provide RPC service proxy''' def wrapped_func(*arg, **kwarg): app = bottle.default_app() svc = app.config['coinrpc.svc'] return orig_func(svc, *arg, **kwarg) return wrapped_func @bottle.get('/help') @with_rpc def help(rpc): hdoc = rpc.help() return hdoc.replace('\n', '<br>') if __name__ == '__main__': app = bottle.default_app() try: conf_file = sys.argv[1] except IndexError: conf_file = 'coin.conf' config = app.config.load_config(conf_file) url = 'http://%s:%s@%s:%s' % ( config['coinrpc.user'], config['coinrpc.pass'], config['coinrpc.host'], config['coinrpc.port'], ) svc = jsonrpc.ServiceProxy(url) config['coinrpc.svc'] = svc app.run(**config) <commit_msg>Make config-helper decorator more generic Instead of only pulling 'coinrpc.svc' from app.config, pull out any number of items.<commit_after>
import bottle, jsonrpc, sys def with_coinrpc(*items): '''Function decorator to provide coinrpc config items''' def wrap_func(orig_func): app = bottle.default_app() keys = tuple(['coinrpc.' + i for i in items]) def wrapped_func(*arg, **kwarg): config_items = tuple([app.config[k] for k in keys]) arg = config_items + arg return orig_func(*arg, **kwarg) return wrapped_func return wrap_func @bottle.get('/help') @with_coinrpc('svc') def help(svc): hdoc = svc.help() return hdoc.replace('\n', '<br>') if __name__ == '__main__': app = bottle.default_app() try: conf_file = sys.argv[1] except IndexError: conf_file = 'coin.conf' config = app.config.load_config(conf_file) url = 'http://%s:%s@%s:%s' % ( config['coinrpc.user'], config['coinrpc.pass'], config['coinrpc.host'], config['coinrpc.port'], ) svc = jsonrpc.ServiceProxy(url) config['coinrpc.svc'] = svc app.run(**config)
import bottle, jsonrpc, sys def with_rpc(orig_func): '''Function decorator to provide RPC service proxy''' def wrapped_func(*arg, **kwarg): app = bottle.default_app() svc = app.config['coinrpc.svc'] return orig_func(svc, *arg, **kwarg) return wrapped_func @bottle.get('/help') @with_rpc def help(rpc): hdoc = rpc.help() return hdoc.replace('\n', '<br>') if __name__ == '__main__': app = bottle.default_app() try: conf_file = sys.argv[1] except IndexError: conf_file = 'coin.conf' config = app.config.load_config(conf_file) url = 'http://%s:%s@%s:%s' % ( config['coinrpc.user'], config['coinrpc.pass'], config['coinrpc.host'], config['coinrpc.port'], ) svc = jsonrpc.ServiceProxy(url) config['coinrpc.svc'] = svc app.run(**config) Make config-helper decorator more generic Instead of only pulling 'coinrpc.svc' from app.config, pull out any number of items.import bottle, jsonrpc, sys def with_coinrpc(*items): '''Function decorator to provide coinrpc config items''' def wrap_func(orig_func): app = bottle.default_app() keys = tuple(['coinrpc.' + i for i in items]) def wrapped_func(*arg, **kwarg): config_items = tuple([app.config[k] for k in keys]) arg = config_items + arg return orig_func(*arg, **kwarg) return wrapped_func return wrap_func @bottle.get('/help') @with_coinrpc('svc') def help(svc): hdoc = svc.help() return hdoc.replace('\n', '<br>') if __name__ == '__main__': app = bottle.default_app() try: conf_file = sys.argv[1] except IndexError: conf_file = 'coin.conf' config = app.config.load_config(conf_file) url = 'http://%s:%s@%s:%s' % ( config['coinrpc.user'], config['coinrpc.pass'], config['coinrpc.host'], config['coinrpc.port'], ) svc = jsonrpc.ServiceProxy(url) config['coinrpc.svc'] = svc app.run(**config)
<commit_before>import bottle, jsonrpc, sys def with_rpc(orig_func): '''Function decorator to provide RPC service proxy''' def wrapped_func(*arg, **kwarg): app = bottle.default_app() svc = app.config['coinrpc.svc'] return orig_func(svc, *arg, **kwarg) return wrapped_func @bottle.get('/help') @with_rpc def help(rpc): hdoc = rpc.help() return hdoc.replace('\n', '<br>') if __name__ == '__main__': app = bottle.default_app() try: conf_file = sys.argv[1] except IndexError: conf_file = 'coin.conf' config = app.config.load_config(conf_file) url = 'http://%s:%s@%s:%s' % ( config['coinrpc.user'], config['coinrpc.pass'], config['coinrpc.host'], config['coinrpc.port'], ) svc = jsonrpc.ServiceProxy(url) config['coinrpc.svc'] = svc app.run(**config) <commit_msg>Make config-helper decorator more generic Instead of only pulling 'coinrpc.svc' from app.config, pull out any number of items.<commit_after>import bottle, jsonrpc, sys def with_coinrpc(*items): '''Function decorator to provide coinrpc config items''' def wrap_func(orig_func): app = bottle.default_app() keys = tuple(['coinrpc.' + i for i in items]) def wrapped_func(*arg, **kwarg): config_items = tuple([app.config[k] for k in keys]) arg = config_items + arg return orig_func(*arg, **kwarg) return wrapped_func return wrap_func @bottle.get('/help') @with_coinrpc('svc') def help(svc): hdoc = svc.help() return hdoc.replace('\n', '<br>') if __name__ == '__main__': app = bottle.default_app() try: conf_file = sys.argv[1] except IndexError: conf_file = 'coin.conf' config = app.config.load_config(conf_file) url = 'http://%s:%s@%s:%s' % ( config['coinrpc.user'], config['coinrpc.pass'], config['coinrpc.host'], config['coinrpc.port'], ) svc = jsonrpc.ServiceProxy(url) config['coinrpc.svc'] = svc app.run(**config)
0e593183ccf9fe719d8dc6ced05a9967698f5c7d
api/app.py
api/app.py
from flask import Flask from flask import request from flask import jsonify from y_text_recommender_system.recommender import recommend app = Flask(__name__) class InvalidUsage(Exception): status_code = 400 def __init__(self, message, payload=None): Exception.__init__(self) self.message = message self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/recommender/', methods=['GET', 'POST']) def recommender(): content = request.get_json() if content is not None: doc = content.get('doc', {}) docs = content.get('docs', []) if doc == {}: msg = 'The parameter `doc` is missing or empty' raise InvalidUsage(msg) if len(docs) == 0: msg = 'The parameter `docs` is missing or empty' raise InvalidUsage(msg) result = recommend(doc, docs) return jsonify(result) else: msg = 'You need to send the parameters: doc and docs' raise InvalidUsage(msg)
from flask import Flask from flask import request from flask import jsonify from y_text_recommender_system.recommender import recommend app = Flask(__name__) class InvalidUsage(Exception): status_code = 400 def __init__(self, message, payload=None): Exception.__init__(self) self.message = message self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/recommender/', methods=['POST']) def recommender(): content = request.get_json() if content is not None: doc = content.get('doc', {}) docs = content.get('docs', []) if doc == {}: msg = 'The parameter `doc` is missing or empty' raise InvalidUsage(msg) if len(docs) == 0: msg = 'The parameter `docs` is missing or empty' raise InvalidUsage(msg) result = recommend(doc, docs) return jsonify(result) else: msg = 'You need to send the parameters: doc and docs' raise InvalidUsage(msg)
Remove GET options in url
Remove GET options in url
Python
mit
joaojunior/y_text_recommender_system
from flask import Flask from flask import request from flask import jsonify from y_text_recommender_system.recommender import recommend app = Flask(__name__) class InvalidUsage(Exception): status_code = 400 def __init__(self, message, payload=None): Exception.__init__(self) self.message = message self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/recommender/', methods=['GET', 'POST']) def recommender(): content = request.get_json() if content is not None: doc = content.get('doc', {}) docs = content.get('docs', []) if doc == {}: msg = 'The parameter `doc` is missing or empty' raise InvalidUsage(msg) if len(docs) == 0: msg = 'The parameter `docs` is missing or empty' raise InvalidUsage(msg) result = recommend(doc, docs) return jsonify(result) else: msg = 'You need to send the parameters: doc and docs' raise InvalidUsage(msg) Remove GET options in url
from flask import Flask from flask import request from flask import jsonify from y_text_recommender_system.recommender import recommend app = Flask(__name__) class InvalidUsage(Exception): status_code = 400 def __init__(self, message, payload=None): Exception.__init__(self) self.message = message self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/recommender/', methods=['POST']) def recommender(): content = request.get_json() if content is not None: doc = content.get('doc', {}) docs = content.get('docs', []) if doc == {}: msg = 'The parameter `doc` is missing or empty' raise InvalidUsage(msg) if len(docs) == 0: msg = 'The parameter `docs` is missing or empty' raise InvalidUsage(msg) result = recommend(doc, docs) return jsonify(result) else: msg = 'You need to send the parameters: doc and docs' raise InvalidUsage(msg)
<commit_before>from flask import Flask from flask import request from flask import jsonify from y_text_recommender_system.recommender import recommend app = Flask(__name__) class InvalidUsage(Exception): status_code = 400 def __init__(self, message, payload=None): Exception.__init__(self) self.message = message self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/recommender/', methods=['GET', 'POST']) def recommender(): content = request.get_json() if content is not None: doc = content.get('doc', {}) docs = content.get('docs', []) if doc == {}: msg = 'The parameter `doc` is missing or empty' raise InvalidUsage(msg) if len(docs) == 0: msg = 'The parameter `docs` is missing or empty' raise InvalidUsage(msg) result = recommend(doc, docs) return jsonify(result) else: msg = 'You need to send the parameters: doc and docs' raise InvalidUsage(msg) <commit_msg>Remove GET options in url<commit_after>
from flask import Flask from flask import request from flask import jsonify from y_text_recommender_system.recommender import recommend app = Flask(__name__) class InvalidUsage(Exception): status_code = 400 def __init__(self, message, payload=None): Exception.__init__(self) self.message = message self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/recommender/', methods=['POST']) def recommender(): content = request.get_json() if content is not None: doc = content.get('doc', {}) docs = content.get('docs', []) if doc == {}: msg = 'The parameter `doc` is missing or empty' raise InvalidUsage(msg) if len(docs) == 0: msg = 'The parameter `docs` is missing or empty' raise InvalidUsage(msg) result = recommend(doc, docs) return jsonify(result) else: msg = 'You need to send the parameters: doc and docs' raise InvalidUsage(msg)
from flask import Flask from flask import request from flask import jsonify from y_text_recommender_system.recommender import recommend app = Flask(__name__) class InvalidUsage(Exception): status_code = 400 def __init__(self, message, payload=None): Exception.__init__(self) self.message = message self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/recommender/', methods=['GET', 'POST']) def recommender(): content = request.get_json() if content is not None: doc = content.get('doc', {}) docs = content.get('docs', []) if doc == {}: msg = 'The parameter `doc` is missing or empty' raise InvalidUsage(msg) if len(docs) == 0: msg = 'The parameter `docs` is missing or empty' raise InvalidUsage(msg) result = recommend(doc, docs) return jsonify(result) else: msg = 'You need to send the parameters: doc and docs' raise InvalidUsage(msg) Remove GET options in urlfrom flask import Flask from flask import request from flask import jsonify from y_text_recommender_system.recommender import recommend app = Flask(__name__) class InvalidUsage(Exception): status_code = 400 def __init__(self, message, payload=None): Exception.__init__(self) self.message = message self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/recommender/', methods=['POST']) def recommender(): content = request.get_json() if content is not None: doc = content.get('doc', {}) docs = content.get('docs', []) if doc == {}: msg = 'The parameter `doc` is missing or empty' raise InvalidUsage(msg) if len(docs) == 0: msg = 'The parameter `docs` is missing or empty' raise InvalidUsage(msg) result = recommend(doc, docs) return jsonify(result) else: msg = 'You need to send the parameters: doc and docs' raise InvalidUsage(msg)
<commit_before>from flask import Flask from flask import request from flask import jsonify from y_text_recommender_system.recommender import recommend app = Flask(__name__) class InvalidUsage(Exception): status_code = 400 def __init__(self, message, payload=None): Exception.__init__(self) self.message = message self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/recommender/', methods=['GET', 'POST']) def recommender(): content = request.get_json() if content is not None: doc = content.get('doc', {}) docs = content.get('docs', []) if doc == {}: msg = 'The parameter `doc` is missing or empty' raise InvalidUsage(msg) if len(docs) == 0: msg = 'The parameter `docs` is missing or empty' raise InvalidUsage(msg) result = recommend(doc, docs) return jsonify(result) else: msg = 'You need to send the parameters: doc and docs' raise InvalidUsage(msg) <commit_msg>Remove GET options in url<commit_after>from flask import Flask from flask import request from flask import jsonify from y_text_recommender_system.recommender import recommend app = Flask(__name__) class InvalidUsage(Exception): status_code = 400 def __init__(self, message, payload=None): Exception.__init__(self) self.message = message self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/recommender/', methods=['POST']) def recommender(): content = request.get_json() if content is not None: doc = content.get('doc', {}) docs = content.get('docs', []) if doc == {}: msg = 'The parameter `doc` is missing or empty' raise InvalidUsage(msg) if len(docs) == 0: msg = 'The parameter `docs` is missing or empty' raise InvalidUsage(msg) result = recommend(doc, docs) return jsonify(result) else: msg = 'You need to send the parameters: doc and docs' raise InvalidUsage(msg)
51cddfb654370aa57bd069dbbbf03638482c2e45
attributes/community/main.py
attributes/community/main.py
import sys from core import Tokenizer from utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM projects WHERE id = {0} '''.format(project_id)) record = cursor.fetchone() tokenizer = Tokenizer() full_url = tokenizer.tokenize(record[0].rstrip()) json_response = url_to_json(full_url) subscribers_count = json_response['subscribers_count'] stargazers_count = json_response['stargazers_count'] forks = json_response['forks'] result = False if ( (subscribers_count >= t_sub and stargazers_count >= t_star) or (stargazers_count >= t_star and forks >= t_forks) or (subscribers_count >= t_sub and forks >= t_forks) ): result = True return ( result, { 'sub': subscribers_count, 'star': stargazers_count, 'forks': forks } ) if __name__ == '__main__': print('Attribute plugins are not meant to be executed directly.') sys.exit(1)
import sys from lib.core import Tokenizer from lib.utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM projects WHERE id = {0} '''.format(project_id)) record = cursor.fetchone() tokenizer = Tokenizer() full_url = tokenizer.tokenize(record[0].rstrip()) json_response = url_to_json(full_url) subscribers_count = json_response['subscribers_count'] stargazers_count = json_response['stargazers_count'] forks = json_response['forks'] result = False if ( (subscribers_count >= t_sub and stargazers_count >= t_star) or (stargazers_count >= t_star and forks >= t_forks) or (subscribers_count >= t_sub and forks >= t_forks) ): result = True return ( result, { 'sub': subscribers_count, 'star': stargazers_count, 'forks': forks } ) if __name__ == '__main__': print('Attribute plugins are not meant to be executed directly.') sys.exit(1)
Update community to use new lib namespace
Update community to use new lib namespace
Python
apache-2.0
RepoReapers/reaper,RepoReapers/reaper,RepoReapers/reaper,RepoReapers/reaper
import sys from core import Tokenizer from utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM projects WHERE id = {0} '''.format(project_id)) record = cursor.fetchone() tokenizer = Tokenizer() full_url = tokenizer.tokenize(record[0].rstrip()) json_response = url_to_json(full_url) subscribers_count = json_response['subscribers_count'] stargazers_count = json_response['stargazers_count'] forks = json_response['forks'] result = False if ( (subscribers_count >= t_sub and stargazers_count >= t_star) or (stargazers_count >= t_star and forks >= t_forks) or (subscribers_count >= t_sub and forks >= t_forks) ): result = True return ( result, { 'sub': subscribers_count, 'star': stargazers_count, 'forks': forks } ) if __name__ == '__main__': print('Attribute plugins are not meant to be executed directly.') sys.exit(1) Update community to use new lib namespace
import sys from lib.core import Tokenizer from lib.utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM projects WHERE id = {0} '''.format(project_id)) record = cursor.fetchone() tokenizer = Tokenizer() full_url = tokenizer.tokenize(record[0].rstrip()) json_response = url_to_json(full_url) subscribers_count = json_response['subscribers_count'] stargazers_count = json_response['stargazers_count'] forks = json_response['forks'] result = False if ( (subscribers_count >= t_sub and stargazers_count >= t_star) or (stargazers_count >= t_star and forks >= t_forks) or (subscribers_count >= t_sub and forks >= t_forks) ): result = True return ( result, { 'sub': subscribers_count, 'star': stargazers_count, 'forks': forks } ) if __name__ == '__main__': print('Attribute plugins are not meant to be executed directly.') sys.exit(1)
<commit_before>import sys from core import Tokenizer from utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM projects WHERE id = {0} '''.format(project_id)) record = cursor.fetchone() tokenizer = Tokenizer() full_url = tokenizer.tokenize(record[0].rstrip()) json_response = url_to_json(full_url) subscribers_count = json_response['subscribers_count'] stargazers_count = json_response['stargazers_count'] forks = json_response['forks'] result = False if ( (subscribers_count >= t_sub and stargazers_count >= t_star) or (stargazers_count >= t_star and forks >= t_forks) or (subscribers_count >= t_sub and forks >= t_forks) ): result = True return ( result, { 'sub': subscribers_count, 'star': stargazers_count, 'forks': forks } ) if __name__ == '__main__': print('Attribute plugins are not meant to be executed directly.') sys.exit(1) <commit_msg>Update community to use new lib namespace<commit_after>
import sys from lib.core import Tokenizer from lib.utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM projects WHERE id = {0} '''.format(project_id)) record = cursor.fetchone() tokenizer = Tokenizer() full_url = tokenizer.tokenize(record[0].rstrip()) json_response = url_to_json(full_url) subscribers_count = json_response['subscribers_count'] stargazers_count = json_response['stargazers_count'] forks = json_response['forks'] result = False if ( (subscribers_count >= t_sub and stargazers_count >= t_star) or (stargazers_count >= t_star and forks >= t_forks) or (subscribers_count >= t_sub and forks >= t_forks) ): result = True return ( result, { 'sub': subscribers_count, 'star': stargazers_count, 'forks': forks } ) if __name__ == '__main__': print('Attribute plugins are not meant to be executed directly.') sys.exit(1)
import sys from core import Tokenizer from utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM projects WHERE id = {0} '''.format(project_id)) record = cursor.fetchone() tokenizer = Tokenizer() full_url = tokenizer.tokenize(record[0].rstrip()) json_response = url_to_json(full_url) subscribers_count = json_response['subscribers_count'] stargazers_count = json_response['stargazers_count'] forks = json_response['forks'] result = False if ( (subscribers_count >= t_sub and stargazers_count >= t_star) or (stargazers_count >= t_star and forks >= t_forks) or (subscribers_count >= t_sub and forks >= t_forks) ): result = True return ( result, { 'sub': subscribers_count, 'star': stargazers_count, 'forks': forks } ) if __name__ == '__main__': print('Attribute plugins are not meant to be executed directly.') sys.exit(1) Update community to use new lib namespaceimport sys from lib.core import Tokenizer from lib.utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM projects WHERE id = {0} '''.format(project_id)) record = cursor.fetchone() tokenizer = Tokenizer() full_url = tokenizer.tokenize(record[0].rstrip()) json_response = url_to_json(full_url) subscribers_count = json_response['subscribers_count'] stargazers_count = json_response['stargazers_count'] forks = json_response['forks'] result = False if ( (subscribers_count >= t_sub and stargazers_count >= t_star) or (stargazers_count >= t_star and forks >= t_forks) or (subscribers_count >= t_sub and forks >= t_forks) ): result = True return ( result, { 'sub': subscribers_count, 'star': stargazers_count, 'forks': forks } ) if __name__ == '__main__': print('Attribute plugins are not meant to be executed directly.') sys.exit(1)
<commit_before>import sys from core import Tokenizer from utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM projects WHERE id = {0} '''.format(project_id)) record = cursor.fetchone() tokenizer = Tokenizer() full_url = tokenizer.tokenize(record[0].rstrip()) json_response = url_to_json(full_url) subscribers_count = json_response['subscribers_count'] stargazers_count = json_response['stargazers_count'] forks = json_response['forks'] result = False if ( (subscribers_count >= t_sub and stargazers_count >= t_star) or (stargazers_count >= t_star and forks >= t_forks) or (subscribers_count >= t_sub and forks >= t_forks) ): result = True return ( result, { 'sub': subscribers_count, 'star': stargazers_count, 'forks': forks } ) if __name__ == '__main__': print('Attribute plugins are not meant to be executed directly.') sys.exit(1) <commit_msg>Update community to use new lib namespace<commit_after>import sys from lib.core import Tokenizer from lib.utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM projects WHERE id = {0} '''.format(project_id)) record = cursor.fetchone() tokenizer = Tokenizer() full_url = tokenizer.tokenize(record[0].rstrip()) json_response = url_to_json(full_url) subscribers_count = json_response['subscribers_count'] stargazers_count = json_response['stargazers_count'] forks = json_response['forks'] result = False if ( (subscribers_count >= t_sub and stargazers_count >= t_star) or (stargazers_count >= t_star and forks >= t_forks) or (subscribers_count >= t_sub and forks >= t_forks) ): result = True return ( result, { 'sub': subscribers_count, 'star': stargazers_count, 'forks': forks } ) if __name__ == '__main__': print('Attribute plugins are not meant to be executed directly.') sys.exit(1)
2405fd2619633e390343984d02763e037a736ef5
openstack/common/messaging/drivers/__init__.py
openstack/common/messaging/drivers/__init__.py
# Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. NAMESPACE = 'openstack.common.messaging.drivers' def _driver(module, name): return '%s.%s.%s' % (NAMESPACE, module, name) _RABBIT_DRIVER = _driver('rabbit', RabbitDriver) _QPID_DRIVER = _driver('qpid', QpidDriver) _ZMQ_DRIVER = _driver('zmq', ZmqDriver) TRANSPORT_DRIVERS = [ 'rabbit = ' + _RABBIT_DRIVER, 'qpid = ' + _QPID_DRIVER, 'zmq = ' + _ZMQ_DRIVER, # To avoid confusion 'kombu = ' + _RABBIT_DRIVER, # For backwards compat 'openstack.common.rpc.impl_kombu = ' + _RABBIT_DRIVER, 'openstack.common.rpc.impl_qpid = ' + _QPID_DRIVER, 'openstack.common.rpc.impl_zmq = ' + _ZMQ_DRIVER, ]
# Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. NAMESPACE = 'openstack.common.messaging.drivers' def _driver(module, name): return '%s.%s:%s' % (NAMESPACE, module, name) _RABBIT_DRIVER = _driver('rabbit', 'RabbitDriver') _QPID_DRIVER = _driver('qpid', 'QpidDriver') _ZMQ_DRIVER = _driver('zmq', 'ZmqDriver') TRANSPORT_DRIVERS = [ 'rabbit = ' + _RABBIT_DRIVER, 'qpid = ' + _QPID_DRIVER, 'zmq = ' + _ZMQ_DRIVER, # To avoid confusion 'kombu = ' + _RABBIT_DRIVER, # For backwards compat 'openstack.common.rpc.impl_kombu = ' + _RABBIT_DRIVER, 'openstack.common.rpc.impl_qpid = ' + _QPID_DRIVER, 'openstack.common.rpc.impl_zmq = ' + _ZMQ_DRIVER, ]
Use : for loading classes in entry_points
Use : for loading classes in entry_points
Python
apache-2.0
isyippee/oslo.messaging,JioCloud/oslo.messaging,isyippee/oslo.messaging,dims/oslo.messaging,dukhlov/oslo.messaging,redhat-openstack/oslo.messaging,apporc/oslo.messaging,markmc/oslo.messaging,magic0704/oslo.messaging,hkumarmk/oslo.messaging,ozamiatin/oslo.messaging,citrix-openstack-build/oslo.messaging,redhat-openstack/oslo.messaging,eayunstack/oslo.messaging,zhurongze/oslo.messaging,dims/oslo.messaging,dukhlov/oslo.messaging,markmc/oslo.messaging,apporc/oslo.messaging,stevei101/oslo.messaging,ozamiatin/oslo.messaging,stevei101/oslo.messaging,hkumarmk/oslo.messaging,magic0704/oslo.messaging,zhurongze/oslo.messaging,viggates/oslo.messaging
# Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. NAMESPACE = 'openstack.common.messaging.drivers' def _driver(module, name): return '%s.%s.%s' % (NAMESPACE, module, name) _RABBIT_DRIVER = _driver('rabbit', RabbitDriver) _QPID_DRIVER = _driver('qpid', QpidDriver) _ZMQ_DRIVER = _driver('zmq', ZmqDriver) TRANSPORT_DRIVERS = [ 'rabbit = ' + _RABBIT_DRIVER, 'qpid = ' + _QPID_DRIVER, 'zmq = ' + _ZMQ_DRIVER, # To avoid confusion 'kombu = ' + _RABBIT_DRIVER, # For backwards compat 'openstack.common.rpc.impl_kombu = ' + _RABBIT_DRIVER, 'openstack.common.rpc.impl_qpid = ' + _QPID_DRIVER, 'openstack.common.rpc.impl_zmq = ' + _ZMQ_DRIVER, ] Use : for loading classes in entry_points
# Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. NAMESPACE = 'openstack.common.messaging.drivers' def _driver(module, name): return '%s.%s:%s' % (NAMESPACE, module, name) _RABBIT_DRIVER = _driver('rabbit', 'RabbitDriver') _QPID_DRIVER = _driver('qpid', 'QpidDriver') _ZMQ_DRIVER = _driver('zmq', 'ZmqDriver') TRANSPORT_DRIVERS = [ 'rabbit = ' + _RABBIT_DRIVER, 'qpid = ' + _QPID_DRIVER, 'zmq = ' + _ZMQ_DRIVER, # To avoid confusion 'kombu = ' + _RABBIT_DRIVER, # For backwards compat 'openstack.common.rpc.impl_kombu = ' + _RABBIT_DRIVER, 'openstack.common.rpc.impl_qpid = ' + _QPID_DRIVER, 'openstack.common.rpc.impl_zmq = ' + _ZMQ_DRIVER, ]
<commit_before> # Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. NAMESPACE = 'openstack.common.messaging.drivers' def _driver(module, name): return '%s.%s.%s' % (NAMESPACE, module, name) _RABBIT_DRIVER = _driver('rabbit', RabbitDriver) _QPID_DRIVER = _driver('qpid', QpidDriver) _ZMQ_DRIVER = _driver('zmq', ZmqDriver) TRANSPORT_DRIVERS = [ 'rabbit = ' + _RABBIT_DRIVER, 'qpid = ' + _QPID_DRIVER, 'zmq = ' + _ZMQ_DRIVER, # To avoid confusion 'kombu = ' + _RABBIT_DRIVER, # For backwards compat 'openstack.common.rpc.impl_kombu = ' + _RABBIT_DRIVER, 'openstack.common.rpc.impl_qpid = ' + _QPID_DRIVER, 'openstack.common.rpc.impl_zmq = ' + _ZMQ_DRIVER, ] <commit_msg>Use : for loading classes in entry_points<commit_after>
# Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. NAMESPACE = 'openstack.common.messaging.drivers' def _driver(module, name): return '%s.%s:%s' % (NAMESPACE, module, name) _RABBIT_DRIVER = _driver('rabbit', 'RabbitDriver') _QPID_DRIVER = _driver('qpid', 'QpidDriver') _ZMQ_DRIVER = _driver('zmq', 'ZmqDriver') TRANSPORT_DRIVERS = [ 'rabbit = ' + _RABBIT_DRIVER, 'qpid = ' + _QPID_DRIVER, 'zmq = ' + _ZMQ_DRIVER, # To avoid confusion 'kombu = ' + _RABBIT_DRIVER, # For backwards compat 'openstack.common.rpc.impl_kombu = ' + _RABBIT_DRIVER, 'openstack.common.rpc.impl_qpid = ' + _QPID_DRIVER, 'openstack.common.rpc.impl_zmq = ' + _ZMQ_DRIVER, ]
# Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. NAMESPACE = 'openstack.common.messaging.drivers' def _driver(module, name): return '%s.%s.%s' % (NAMESPACE, module, name) _RABBIT_DRIVER = _driver('rabbit', RabbitDriver) _QPID_DRIVER = _driver('qpid', QpidDriver) _ZMQ_DRIVER = _driver('zmq', ZmqDriver) TRANSPORT_DRIVERS = [ 'rabbit = ' + _RABBIT_DRIVER, 'qpid = ' + _QPID_DRIVER, 'zmq = ' + _ZMQ_DRIVER, # To avoid confusion 'kombu = ' + _RABBIT_DRIVER, # For backwards compat 'openstack.common.rpc.impl_kombu = ' + _RABBIT_DRIVER, 'openstack.common.rpc.impl_qpid = ' + _QPID_DRIVER, 'openstack.common.rpc.impl_zmq = ' + _ZMQ_DRIVER, ] Use : for loading classes in entry_points # Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. NAMESPACE = 'openstack.common.messaging.drivers' def _driver(module, name): return '%s.%s:%s' % (NAMESPACE, module, name) _RABBIT_DRIVER = _driver('rabbit', 'RabbitDriver') _QPID_DRIVER = _driver('qpid', 'QpidDriver') _ZMQ_DRIVER = _driver('zmq', 'ZmqDriver') TRANSPORT_DRIVERS = [ 'rabbit = ' + _RABBIT_DRIVER, 'qpid = ' + _QPID_DRIVER, 'zmq = ' + _ZMQ_DRIVER, # To avoid confusion 'kombu = ' + _RABBIT_DRIVER, # For backwards compat 'openstack.common.rpc.impl_kombu = ' + _RABBIT_DRIVER, 'openstack.common.rpc.impl_qpid = ' + _QPID_DRIVER, 'openstack.common.rpc.impl_zmq = ' + _ZMQ_DRIVER, ]
<commit_before> # Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. NAMESPACE = 'openstack.common.messaging.drivers' def _driver(module, name): return '%s.%s.%s' % (NAMESPACE, module, name) _RABBIT_DRIVER = _driver('rabbit', RabbitDriver) _QPID_DRIVER = _driver('qpid', QpidDriver) _ZMQ_DRIVER = _driver('zmq', ZmqDriver) TRANSPORT_DRIVERS = [ 'rabbit = ' + _RABBIT_DRIVER, 'qpid = ' + _QPID_DRIVER, 'zmq = ' + _ZMQ_DRIVER, # To avoid confusion 'kombu = ' + _RABBIT_DRIVER, # For backwards compat 'openstack.common.rpc.impl_kombu = ' + _RABBIT_DRIVER, 'openstack.common.rpc.impl_qpid = ' + _QPID_DRIVER, 'openstack.common.rpc.impl_zmq = ' + _ZMQ_DRIVER, ] <commit_msg>Use : for loading classes in entry_points<commit_after> # Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. NAMESPACE = 'openstack.common.messaging.drivers' def _driver(module, name): return '%s.%s:%s' % (NAMESPACE, module, name) _RABBIT_DRIVER = _driver('rabbit', 'RabbitDriver') _QPID_DRIVER = _driver('qpid', 'QpidDriver') _ZMQ_DRIVER = _driver('zmq', 'ZmqDriver') TRANSPORT_DRIVERS = [ 'rabbit = ' + _RABBIT_DRIVER, 'qpid = ' + _QPID_DRIVER, 'zmq = ' + _ZMQ_DRIVER, # To avoid confusion 'kombu = ' + _RABBIT_DRIVER, # For backwards compat 'openstack.common.rpc.impl_kombu = ' + _RABBIT_DRIVER, 'openstack.common.rpc.impl_qpid = ' + _QPID_DRIVER, 'openstack.common.rpc.impl_zmq = ' + _ZMQ_DRIVER, ]
887ad6280df9c6e88a036783097f87626436ca9f
Lib/importlib/test/import_/util.py
Lib/importlib/test/import_/util.py
import functools import importlib import importlib._bootstrap import unittest using___import__ = False def import_(*args, **kwargs): """Delegate to allow for injecting different implementations of import.""" if using___import__: return __import__(*args, **kwargs) else: return importlib.__import__(*args, **kwargs) importlib_only = unittest.skipIf(using___import__, "importlib-specific test") def mock_path_hook(*entries, importer): """A mock sys.path_hooks entry.""" def hook(entry): if entry not in entries: raise ImportError return importer return hook
import functools import importlib import importlib._bootstrap import unittest using___import__ = False def import_(*args, **kwargs): """Delegate to allow for injecting different implementations of import.""" if using___import__: return __import__(*args, **kwargs) else: return importlib.__import__(*args, **kwargs) def importlib_only(fxn): """Decorator to skip a test if using __builtins__.__import__.""" return unittest.skipIf(using___import__, "importlib-specific test")(fxn) def mock_path_hook(*entries, importer): """A mock sys.path_hooks entry.""" def hook(entry): if entry not in entries: raise ImportError return importer return hook
Fix the importlib_only test decorator to work again; don't capture the flag variable as it might change later.
Fix the importlib_only test decorator to work again; don't capture the flag variable as it might change later.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
import functools import importlib import importlib._bootstrap import unittest using___import__ = False def import_(*args, **kwargs): """Delegate to allow for injecting different implementations of import.""" if using___import__: return __import__(*args, **kwargs) else: return importlib.__import__(*args, **kwargs) importlib_only = unittest.skipIf(using___import__, "importlib-specific test") def mock_path_hook(*entries, importer): """A mock sys.path_hooks entry.""" def hook(entry): if entry not in entries: raise ImportError return importer return hook Fix the importlib_only test decorator to work again; don't capture the flag variable as it might change later.
import functools import importlib import importlib._bootstrap import unittest using___import__ = False def import_(*args, **kwargs): """Delegate to allow for injecting different implementations of import.""" if using___import__: return __import__(*args, **kwargs) else: return importlib.__import__(*args, **kwargs) def importlib_only(fxn): """Decorator to skip a test if using __builtins__.__import__.""" return unittest.skipIf(using___import__, "importlib-specific test")(fxn) def mock_path_hook(*entries, importer): """A mock sys.path_hooks entry.""" def hook(entry): if entry not in entries: raise ImportError return importer return hook
<commit_before>import functools import importlib import importlib._bootstrap import unittest using___import__ = False def import_(*args, **kwargs): """Delegate to allow for injecting different implementations of import.""" if using___import__: return __import__(*args, **kwargs) else: return importlib.__import__(*args, **kwargs) importlib_only = unittest.skipIf(using___import__, "importlib-specific test") def mock_path_hook(*entries, importer): """A mock sys.path_hooks entry.""" def hook(entry): if entry not in entries: raise ImportError return importer return hook <commit_msg>Fix the importlib_only test decorator to work again; don't capture the flag variable as it might change later.<commit_after>
import functools import importlib import importlib._bootstrap import unittest using___import__ = False def import_(*args, **kwargs): """Delegate to allow for injecting different implementations of import.""" if using___import__: return __import__(*args, **kwargs) else: return importlib.__import__(*args, **kwargs) def importlib_only(fxn): """Decorator to skip a test if using __builtins__.__import__.""" return unittest.skipIf(using___import__, "importlib-specific test")(fxn) def mock_path_hook(*entries, importer): """A mock sys.path_hooks entry.""" def hook(entry): if entry not in entries: raise ImportError return importer return hook
import functools import importlib import importlib._bootstrap import unittest using___import__ = False def import_(*args, **kwargs): """Delegate to allow for injecting different implementations of import.""" if using___import__: return __import__(*args, **kwargs) else: return importlib.__import__(*args, **kwargs) importlib_only = unittest.skipIf(using___import__, "importlib-specific test") def mock_path_hook(*entries, importer): """A mock sys.path_hooks entry.""" def hook(entry): if entry not in entries: raise ImportError return importer return hook Fix the importlib_only test decorator to work again; don't capture the flag variable as it might change later.import functools import importlib import importlib._bootstrap import unittest using___import__ = False def import_(*args, **kwargs): """Delegate to allow for injecting different implementations of import.""" if using___import__: return __import__(*args, **kwargs) else: return importlib.__import__(*args, **kwargs) def importlib_only(fxn): """Decorator to skip a test if using __builtins__.__import__.""" return unittest.skipIf(using___import__, "importlib-specific test")(fxn) def mock_path_hook(*entries, importer): """A mock sys.path_hooks entry.""" def hook(entry): if entry not in entries: raise ImportError return importer return hook
<commit_before>import functools import importlib import importlib._bootstrap import unittest using___import__ = False def import_(*args, **kwargs): """Delegate to allow for injecting different implementations of import.""" if using___import__: return __import__(*args, **kwargs) else: return importlib.__import__(*args, **kwargs) importlib_only = unittest.skipIf(using___import__, "importlib-specific test") def mock_path_hook(*entries, importer): """A mock sys.path_hooks entry.""" def hook(entry): if entry not in entries: raise ImportError return importer return hook <commit_msg>Fix the importlib_only test decorator to work again; don't capture the flag variable as it might change later.<commit_after>import functools import importlib import importlib._bootstrap import unittest using___import__ = False def import_(*args, **kwargs): """Delegate to allow for injecting different implementations of import.""" if using___import__: return __import__(*args, **kwargs) else: return importlib.__import__(*args, **kwargs) def importlib_only(fxn): """Decorator to skip a test if using __builtins__.__import__.""" return unittest.skipIf(using___import__, "importlib-specific test")(fxn) def mock_path_hook(*entries, importer): """A mock sys.path_hooks entry.""" def hook(entry): if entry not in entries: raise ImportError return importer return hook
802ffff14c7636b80073debfe2159a9fa71abe15
numba/tests/test_vectorization_type_inference.py
numba/tests/test_vectorization_type_inference.py
from __future__ import print_function from numba import vectorize, jit, bool_, double, int_, float_, typeof, int8 import numba.unittest_support as unittest import numpy as np def add(a, b): return a + b def func(dtypeA, dtypeB): A = np.arange(10, dtype=dtypeA) B = np.arange(10, dtype=dtypeB) return typeof(vector_add(A, B)) class TestVectTypeInfer(unittest.TestCase): def test_type_inference(self): global vector_add vector_add = vectorize([ bool_(double, int_), double(double, double), float_(double, float_), ])(add) cfunc = jit(func) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype('i')), int8[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float64)), double[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float32)), float_[:]) if __name__ == '__main__': unittest.main()
from __future__ import print_function from numba import vectorize, jit, bool_, double, int_, float_, typeof, int8 import numba.unittest_support as unittest import numpy as np def add(a, b): return a + b def func(dtypeA, dtypeB): A = np.arange(10, dtype=dtypeA) B = np.arange(10, dtype=dtypeB) return typeof(vector_add(A, B)) class TestVectTypeInfer(unittest.TestCase): @unittest.expectedFailure def test_type_inference(self): global vector_add vector_add = vectorize([ bool_(double, int_), double(double, double), float_(double, float_), ])(add) cfunc = jit(func) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype('i')), int8[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float64)), double[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float32)), float_[:]) if __name__ == '__main__': unittest.main()
Mark test_type_inference test as expected failure
Mark test_type_inference test as expected failure
Python
bsd-2-clause
gdementen/numba,stefanseefeld/numba,pombredanne/numba,stuartarchibald/numba,seibert/numba,pitrou/numba,stuartarchibald/numba,stefanseefeld/numba,seibert/numba,cpcloud/numba,gmarkall/numba,sklam/numba,seibert/numba,cpcloud/numba,jriehl/numba,stonebig/numba,ssarangi/numba,jriehl/numba,gmarkall/numba,stonebig/numba,stonebig/numba,jriehl/numba,ssarangi/numba,IntelLabs/numba,pombredanne/numba,GaZ3ll3/numba,numba/numba,IntelLabs/numba,numba/numba,stefanseefeld/numba,sklam/numba,cpcloud/numba,gdementen/numba,pitrou/numba,pitrou/numba,ssarangi/numba,numba/numba,IntelLabs/numba,stefanseefeld/numba,gmarkall/numba,numba/numba,numba/numba,cpcloud/numba,seibert/numba,stonebig/numba,gdementen/numba,jriehl/numba,gdementen/numba,stonebig/numba,ssarangi/numba,GaZ3ll3/numba,pombredanne/numba,sklam/numba,stuartarchibald/numba,GaZ3ll3/numba,gdementen/numba,sklam/numba,IntelLabs/numba,stuartarchibald/numba,jriehl/numba,pombredanne/numba,pitrou/numba,sklam/numba,gmarkall/numba,pitrou/numba,pombredanne/numba,stuartarchibald/numba,ssarangi/numba,cpcloud/numba,seibert/numba,gmarkall/numba,stefanseefeld/numba,GaZ3ll3/numba,IntelLabs/numba,GaZ3ll3/numba
from __future__ import print_function from numba import vectorize, jit, bool_, double, int_, float_, typeof, int8 import numba.unittest_support as unittest import numpy as np def add(a, b): return a + b def func(dtypeA, dtypeB): A = np.arange(10, dtype=dtypeA) B = np.arange(10, dtype=dtypeB) return typeof(vector_add(A, B)) class TestVectTypeInfer(unittest.TestCase): def test_type_inference(self): global vector_add vector_add = vectorize([ bool_(double, int_), double(double, double), float_(double, float_), ])(add) cfunc = jit(func) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype('i')), int8[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float64)), double[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float32)), float_[:]) if __name__ == '__main__': unittest.main() Mark test_type_inference test as expected failure
from __future__ import print_function from numba import vectorize, jit, bool_, double, int_, float_, typeof, int8 import numba.unittest_support as unittest import numpy as np def add(a, b): return a + b def func(dtypeA, dtypeB): A = np.arange(10, dtype=dtypeA) B = np.arange(10, dtype=dtypeB) return typeof(vector_add(A, B)) class TestVectTypeInfer(unittest.TestCase): @unittest.expectedFailure def test_type_inference(self): global vector_add vector_add = vectorize([ bool_(double, int_), double(double, double), float_(double, float_), ])(add) cfunc = jit(func) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype('i')), int8[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float64)), double[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float32)), float_[:]) if __name__ == '__main__': unittest.main()
<commit_before>from __future__ import print_function from numba import vectorize, jit, bool_, double, int_, float_, typeof, int8 import numba.unittest_support as unittest import numpy as np def add(a, b): return a + b def func(dtypeA, dtypeB): A = np.arange(10, dtype=dtypeA) B = np.arange(10, dtype=dtypeB) return typeof(vector_add(A, B)) class TestVectTypeInfer(unittest.TestCase): def test_type_inference(self): global vector_add vector_add = vectorize([ bool_(double, int_), double(double, double), float_(double, float_), ])(add) cfunc = jit(func) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype('i')), int8[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float64)), double[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float32)), float_[:]) if __name__ == '__main__': unittest.main() <commit_msg>Mark test_type_inference test as expected failure<commit_after>
from __future__ import print_function from numba import vectorize, jit, bool_, double, int_, float_, typeof, int8 import numba.unittest_support as unittest import numpy as np def add(a, b): return a + b def func(dtypeA, dtypeB): A = np.arange(10, dtype=dtypeA) B = np.arange(10, dtype=dtypeB) return typeof(vector_add(A, B)) class TestVectTypeInfer(unittest.TestCase): @unittest.expectedFailure def test_type_inference(self): global vector_add vector_add = vectorize([ bool_(double, int_), double(double, double), float_(double, float_), ])(add) cfunc = jit(func) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype('i')), int8[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float64)), double[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float32)), float_[:]) if __name__ == '__main__': unittest.main()
from __future__ import print_function from numba import vectorize, jit, bool_, double, int_, float_, typeof, int8 import numba.unittest_support as unittest import numpy as np def add(a, b): return a + b def func(dtypeA, dtypeB): A = np.arange(10, dtype=dtypeA) B = np.arange(10, dtype=dtypeB) return typeof(vector_add(A, B)) class TestVectTypeInfer(unittest.TestCase): def test_type_inference(self): global vector_add vector_add = vectorize([ bool_(double, int_), double(double, double), float_(double, float_), ])(add) cfunc = jit(func) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype('i')), int8[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float64)), double[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float32)), float_[:]) if __name__ == '__main__': unittest.main() Mark test_type_inference test as expected failurefrom __future__ import print_function from numba import vectorize, jit, bool_, double, int_, float_, typeof, int8 import numba.unittest_support as unittest import numpy as np def add(a, b): return a + b def func(dtypeA, dtypeB): A = np.arange(10, dtype=dtypeA) B = np.arange(10, dtype=dtypeB) return typeof(vector_add(A, B)) class TestVectTypeInfer(unittest.TestCase): @unittest.expectedFailure def test_type_inference(self): global vector_add vector_add = vectorize([ bool_(double, int_), double(double, double), float_(double, float_), ])(add) cfunc = jit(func) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype('i')), int8[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float64)), double[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float32)), float_[:]) if __name__ == '__main__': unittest.main()
<commit_before>from __future__ import print_function from numba import vectorize, jit, bool_, double, int_, float_, typeof, int8 import numba.unittest_support as unittest import numpy as np def add(a, b): return a + b def func(dtypeA, dtypeB): A = np.arange(10, dtype=dtypeA) B = np.arange(10, dtype=dtypeB) return typeof(vector_add(A, B)) class TestVectTypeInfer(unittest.TestCase): def test_type_inference(self): global vector_add vector_add = vectorize([ bool_(double, int_), double(double, double), float_(double, float_), ])(add) cfunc = jit(func) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype('i')), int8[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float64)), double[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float32)), float_[:]) if __name__ == '__main__': unittest.main() <commit_msg>Mark test_type_inference test as expected failure<commit_after>from __future__ import print_function from numba import vectorize, jit, bool_, double, int_, float_, typeof, int8 import numba.unittest_support as unittest import numpy as np def add(a, b): return a + b def func(dtypeA, dtypeB): A = np.arange(10, dtype=dtypeA) B = np.arange(10, dtype=dtypeB) return typeof(vector_add(A, B)) class TestVectTypeInfer(unittest.TestCase): @unittest.expectedFailure def test_type_inference(self): global vector_add vector_add = vectorize([ bool_(double, int_), double(double, double), float_(double, float_), ])(add) cfunc = jit(func) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype('i')), int8[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float64)), double[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float32)), float_[:]) if __name__ == '__main__': unittest.main()
7019a211ae083d1b99d1c3ab580e6b8c0357b4f9
mne/commands/mne_coreg.py
mne/commands/mne_coreg.py
#!/usr/bin/env python # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> """ Open the coregistration GUI. example usage: $ mne coreg """ import os import sys import mne if __name__ == '__main__': os.environ['ETS_TOOLKIT'] = 'qt4' mne.gui.coregistration() sys.exit(0)
#!/usr/bin/env python # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> """ Open the coregistration GUI. example usage: $ mne coreg """ import os import sys import mne if __name__ == '__main__': from mne.commands.utils import get_optparser parser = get_optparser(__file__) options, args = parser.parse_args() os.environ['ETS_TOOLKIT'] = 'qt4' mne.gui.coregistration() sys.exit(0)
FIX coreg bin: add parser
FIX coreg bin: add parser
Python
bsd-3-clause
jaeilepp/mne-python,mne-tools/mne-python,pravsripad/mne-python,wmvanvliet/mne-python,dimkal/mne-python,trachelr/mne-python,jmontoyam/mne-python,effigies/mne-python,ARudiuk/mne-python,teonlamont/mne-python,lorenzo-desantis/mne-python,jniediek/mne-python,olafhauk/mne-python,mne-tools/mne-python,Odingod/mne-python,kingjr/mne-python,pravsripad/mne-python,wmvanvliet/mne-python,aestrivex/mne-python,antiface/mne-python,adykstra/mne-python,andyh616/mne-python,larsoner/mne-python,rkmaddox/mne-python,Eric89GXL/mne-python,mne-tools/mne-python,Odingod/mne-python,alexandrebarachant/mne-python,larsoner/mne-python,leggitta/mne-python,dgwakeman/mne-python,wronk/mne-python,pravsripad/mne-python,drammock/mne-python,alexandrebarachant/mne-python,kambysese/mne-python,leggitta/mne-python,Teekuningas/mne-python,kingjr/mne-python,yousrabk/mne-python,trachelr/mne-python,jmontoyam/mne-python,drammock/mne-python,nicproulx/mne-python,olafhauk/mne-python,olafhauk/mne-python,cjayb/mne-python,aestrivex/mne-python,cmoutard/mne-python,dgwakeman/mne-python,rkmaddox/mne-python,Teekuningas/mne-python,Teekuningas/mne-python,bloyl/mne-python,wmvanvliet/mne-python,yousrabk/mne-python,drammock/mne-python,lorenzo-desantis/mne-python,dimkal/mne-python,matthew-tucker/mne-python,andyh616/mne-python,jniediek/mne-python,bloyl/mne-python,kambysese/mne-python,jaeilepp/mne-python,effigies/mne-python,ARudiuk/mne-python,teonlamont/mne-python,larsoner/mne-python,cjayb/mne-python,cmoutard/mne-python,agramfort/mne-python,matthew-tucker/mne-python,wronk/mne-python,nicproulx/mne-python,kingjr/mne-python,antiface/mne-python,agramfort/mne-python,adykstra/mne-python,Eric89GXL/mne-python
#!/usr/bin/env python # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> """ Open the coregistration GUI. example usage: $ mne coreg """ import os import sys import mne if __name__ == '__main__': os.environ['ETS_TOOLKIT'] = 'qt4' mne.gui.coregistration() sys.exit(0) FIX coreg bin: add parser
#!/usr/bin/env python # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> """ Open the coregistration GUI. example usage: $ mne coreg """ import os import sys import mne if __name__ == '__main__': from mne.commands.utils import get_optparser parser = get_optparser(__file__) options, args = parser.parse_args() os.environ['ETS_TOOLKIT'] = 'qt4' mne.gui.coregistration() sys.exit(0)
<commit_before>#!/usr/bin/env python # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> """ Open the coregistration GUI. example usage: $ mne coreg """ import os import sys import mne if __name__ == '__main__': os.environ['ETS_TOOLKIT'] = 'qt4' mne.gui.coregistration() sys.exit(0) <commit_msg>FIX coreg bin: add parser<commit_after>
#!/usr/bin/env python # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> """ Open the coregistration GUI. example usage: $ mne coreg """ import os import sys import mne if __name__ == '__main__': from mne.commands.utils import get_optparser parser = get_optparser(__file__) options, args = parser.parse_args() os.environ['ETS_TOOLKIT'] = 'qt4' mne.gui.coregistration() sys.exit(0)
#!/usr/bin/env python # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> """ Open the coregistration GUI. example usage: $ mne coreg """ import os import sys import mne if __name__ == '__main__': os.environ['ETS_TOOLKIT'] = 'qt4' mne.gui.coregistration() sys.exit(0) FIX coreg bin: add parser#!/usr/bin/env python # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> """ Open the coregistration GUI. example usage: $ mne coreg """ import os import sys import mne if __name__ == '__main__': from mne.commands.utils import get_optparser parser = get_optparser(__file__) options, args = parser.parse_args() os.environ['ETS_TOOLKIT'] = 'qt4' mne.gui.coregistration() sys.exit(0)
<commit_before>#!/usr/bin/env python # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> """ Open the coregistration GUI. example usage: $ mne coreg """ import os import sys import mne if __name__ == '__main__': os.environ['ETS_TOOLKIT'] = 'qt4' mne.gui.coregistration() sys.exit(0) <commit_msg>FIX coreg bin: add parser<commit_after>#!/usr/bin/env python # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> """ Open the coregistration GUI. example usage: $ mne coreg """ import os import sys import mne if __name__ == '__main__': from mne.commands.utils import get_optparser parser = get_optparser(__file__) options, args = parser.parse_args() os.environ['ETS_TOOLKIT'] = 'qt4' mne.gui.coregistration() sys.exit(0)
c2abe8cee63def90846f2f5663e647133480946f
launch_control/models/test_case.py
launch_control/models/test_case.py
""" Module with the TestCase model. """ from launch_control.utils.json.pod import PlainOldData class TestCase(PlainOldData): """ TestCase model. Currently contains just two fields: - test_case_id (test-case specific ID) - name (human readable) """ __slots__ = ('test_case_id', 'name') def __init__(self, test_case_id, desc): self.test_case_id = test_case_id self.name = name
""" Module with the TestCase model. """ from launch_control.utils.json.pod import PlainOldData class TestCase(PlainOldData): """ TestCase model. Currently contains just two fields: - test_case_id (test-case specific ID) - name (human readable) """ __slots__ = ('test_case_id', 'name') def __init__(self, test_case_id, name): self.test_case_id = test_case_id self.name = name
Fix argument name in TestCase constructor
Fix argument name in TestCase constructor
Python
agpl-3.0
Linaro/lava-server,OSSystems/lava-server,OSSystems/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server
""" Module with the TestCase model. """ from launch_control.utils.json.pod import PlainOldData class TestCase(PlainOldData): """ TestCase model. Currently contains just two fields: - test_case_id (test-case specific ID) - name (human readable) """ __slots__ = ('test_case_id', 'name') def __init__(self, test_case_id, desc): self.test_case_id = test_case_id self.name = name Fix argument name in TestCase constructor
""" Module with the TestCase model. """ from launch_control.utils.json.pod import PlainOldData class TestCase(PlainOldData): """ TestCase model. Currently contains just two fields: - test_case_id (test-case specific ID) - name (human readable) """ __slots__ = ('test_case_id', 'name') def __init__(self, test_case_id, name): self.test_case_id = test_case_id self.name = name
<commit_before>""" Module with the TestCase model. """ from launch_control.utils.json.pod import PlainOldData class TestCase(PlainOldData): """ TestCase model. Currently contains just two fields: - test_case_id (test-case specific ID) - name (human readable) """ __slots__ = ('test_case_id', 'name') def __init__(self, test_case_id, desc): self.test_case_id = test_case_id self.name = name <commit_msg>Fix argument name in TestCase constructor<commit_after>
""" Module with the TestCase model. """ from launch_control.utils.json.pod import PlainOldData class TestCase(PlainOldData): """ TestCase model. Currently contains just two fields: - test_case_id (test-case specific ID) - name (human readable) """ __slots__ = ('test_case_id', 'name') def __init__(self, test_case_id, name): self.test_case_id = test_case_id self.name = name
""" Module with the TestCase model. """ from launch_control.utils.json.pod import PlainOldData class TestCase(PlainOldData): """ TestCase model. Currently contains just two fields: - test_case_id (test-case specific ID) - name (human readable) """ __slots__ = ('test_case_id', 'name') def __init__(self, test_case_id, desc): self.test_case_id = test_case_id self.name = name Fix argument name in TestCase constructor""" Module with the TestCase model. """ from launch_control.utils.json.pod import PlainOldData class TestCase(PlainOldData): """ TestCase model. Currently contains just two fields: - test_case_id (test-case specific ID) - name (human readable) """ __slots__ = ('test_case_id', 'name') def __init__(self, test_case_id, name): self.test_case_id = test_case_id self.name = name
<commit_before>""" Module with the TestCase model. """ from launch_control.utils.json.pod import PlainOldData class TestCase(PlainOldData): """ TestCase model. Currently contains just two fields: - test_case_id (test-case specific ID) - name (human readable) """ __slots__ = ('test_case_id', 'name') def __init__(self, test_case_id, desc): self.test_case_id = test_case_id self.name = name <commit_msg>Fix argument name in TestCase constructor<commit_after>""" Module with the TestCase model. """ from launch_control.utils.json.pod import PlainOldData class TestCase(PlainOldData): """ TestCase model. Currently contains just two fields: - test_case_id (test-case specific ID) - name (human readable) """ __slots__ = ('test_case_id', 'name') def __init__(self, test_case_id, name): self.test_case_id = test_case_id self.name = name
274222aade5438448a05989bf2973e349d33fb04
skald/geometry.py
skald/geometry.py
# -*- coding: utf-8 -*- from collections import namedtuple Size = namedtuple("Size", ["width", "height"]) class Rectangle(namedtuple("Rectangle", ["x0", "y0", "x1", "y1"])): def __contains__(self, other): """Check if this rectangle and `other` overlaps eachother. Essentially this is a bit of a hack to be able to write `rect1 in rect2`. """ if self.x0 < other.x0 and self.x1 > other.x1 and \ self.y0 < other.y0 and self.y1 > other.y1: return True return False class Point(namedtuple("Point", ["x", "y"])): """Point in a two-dimensional space. Named tuple implementation that allows for addition and subtraction. """ __slots__ = () def __add__(self, other): x = self.x + other.x y = self.y + other.y return Point(x, y) def __sub__(self, other): x = self.x - other.x y = self.y - other.y return Point(x, y) class Box(namedtuple("Box", ["point", "size"])): __slots__ = () @property def rectangle(self): return Rectangle( x0=self.point.x, y0=self.point.y, x1=self.point.x+self.size.width, y1=self.point.y+self.size.height )
# -*- coding: utf-8 -*- from collections import namedtuple Size = namedtuple("Size", ["width", "height"]) class Rectangle(namedtuple("Rectangle", ["x0", "y0", "x1", "y1"])): def __contains__(self, other): """Check if this rectangle and `other` overlaps eachother. Essentially this is a bit of a hack to be able to write `rect1 in rect2`. """ if self.x0 < other.x1 and self.x1 > other.x0 and \ self.y0 < other.y1 and self.y1 > other.y0: return True return False class Point(namedtuple("Point", ["x", "y"])): """Point in a two-dimensional space. Named tuple implementation that allows for addition and subtraction. """ __slots__ = () def __add__(self, other): x = self.x + other.x y = self.y + other.y return Point(x, y) def __sub__(self, other): x = self.x - other.x y = self.y - other.y return Point(x, y) class Box(namedtuple("Box", ["point", "size"])): __slots__ = () @property def rectangle(self): return Rectangle( x0=self.point.x, y0=self.point.y, x1=self.point.x+self.size.width, y1=self.point.y+self.size.height )
Fix implementation of overlapping rectangles
Fix implementation of overlapping rectangles
Python
mit
bjornarg/skald,bjornarg/skald
# -*- coding: utf-8 -*- from collections import namedtuple Size = namedtuple("Size", ["width", "height"]) class Rectangle(namedtuple("Rectangle", ["x0", "y0", "x1", "y1"])): def __contains__(self, other): """Check if this rectangle and `other` overlaps eachother. Essentially this is a bit of a hack to be able to write `rect1 in rect2`. """ if self.x0 < other.x0 and self.x1 > other.x1 and \ self.y0 < other.y0 and self.y1 > other.y1: return True return False class Point(namedtuple("Point", ["x", "y"])): """Point in a two-dimensional space. Named tuple implementation that allows for addition and subtraction. """ __slots__ = () def __add__(self, other): x = self.x + other.x y = self.y + other.y return Point(x, y) def __sub__(self, other): x = self.x - other.x y = self.y - other.y return Point(x, y) class Box(namedtuple("Box", ["point", "size"])): __slots__ = () @property def rectangle(self): return Rectangle( x0=self.point.x, y0=self.point.y, x1=self.point.x+self.size.width, y1=self.point.y+self.size.height ) Fix implementation of overlapping rectangles
# -*- coding: utf-8 -*- from collections import namedtuple Size = namedtuple("Size", ["width", "height"]) class Rectangle(namedtuple("Rectangle", ["x0", "y0", "x1", "y1"])): def __contains__(self, other): """Check if this rectangle and `other` overlaps eachother. Essentially this is a bit of a hack to be able to write `rect1 in rect2`. """ if self.x0 < other.x1 and self.x1 > other.x0 and \ self.y0 < other.y1 and self.y1 > other.y0: return True return False class Point(namedtuple("Point", ["x", "y"])): """Point in a two-dimensional space. Named tuple implementation that allows for addition and subtraction. """ __slots__ = () def __add__(self, other): x = self.x + other.x y = self.y + other.y return Point(x, y) def __sub__(self, other): x = self.x - other.x y = self.y - other.y return Point(x, y) class Box(namedtuple("Box", ["point", "size"])): __slots__ = () @property def rectangle(self): return Rectangle( x0=self.point.x, y0=self.point.y, x1=self.point.x+self.size.width, y1=self.point.y+self.size.height )
<commit_before># -*- coding: utf-8 -*- from collections import namedtuple Size = namedtuple("Size", ["width", "height"]) class Rectangle(namedtuple("Rectangle", ["x0", "y0", "x1", "y1"])): def __contains__(self, other): """Check if this rectangle and `other` overlaps eachother. Essentially this is a bit of a hack to be able to write `rect1 in rect2`. """ if self.x0 < other.x0 and self.x1 > other.x1 and \ self.y0 < other.y0 and self.y1 > other.y1: return True return False class Point(namedtuple("Point", ["x", "y"])): """Point in a two-dimensional space. Named tuple implementation that allows for addition and subtraction. """ __slots__ = () def __add__(self, other): x = self.x + other.x y = self.y + other.y return Point(x, y) def __sub__(self, other): x = self.x - other.x y = self.y - other.y return Point(x, y) class Box(namedtuple("Box", ["point", "size"])): __slots__ = () @property def rectangle(self): return Rectangle( x0=self.point.x, y0=self.point.y, x1=self.point.x+self.size.width, y1=self.point.y+self.size.height ) <commit_msg>Fix implementation of overlapping rectangles<commit_after>
# -*- coding: utf-8 -*- from collections import namedtuple Size = namedtuple("Size", ["width", "height"]) class Rectangle(namedtuple("Rectangle", ["x0", "y0", "x1", "y1"])): def __contains__(self, other): """Check if this rectangle and `other` overlaps eachother. Essentially this is a bit of a hack to be able to write `rect1 in rect2`. """ if self.x0 < other.x1 and self.x1 > other.x0 and \ self.y0 < other.y1 and self.y1 > other.y0: return True return False class Point(namedtuple("Point", ["x", "y"])): """Point in a two-dimensional space. Named tuple implementation that allows for addition and subtraction. """ __slots__ = () def __add__(self, other): x = self.x + other.x y = self.y + other.y return Point(x, y) def __sub__(self, other): x = self.x - other.x y = self.y - other.y return Point(x, y) class Box(namedtuple("Box", ["point", "size"])): __slots__ = () @property def rectangle(self): return Rectangle( x0=self.point.x, y0=self.point.y, x1=self.point.x+self.size.width, y1=self.point.y+self.size.height )
# -*- coding: utf-8 -*- from collections import namedtuple Size = namedtuple("Size", ["width", "height"]) class Rectangle(namedtuple("Rectangle", ["x0", "y0", "x1", "y1"])): def __contains__(self, other): """Check if this rectangle and `other` overlaps eachother. Essentially this is a bit of a hack to be able to write `rect1 in rect2`. """ if self.x0 < other.x0 and self.x1 > other.x1 and \ self.y0 < other.y0 and self.y1 > other.y1: return True return False class Point(namedtuple("Point", ["x", "y"])): """Point in a two-dimensional space. Named tuple implementation that allows for addition and subtraction. """ __slots__ = () def __add__(self, other): x = self.x + other.x y = self.y + other.y return Point(x, y) def __sub__(self, other): x = self.x - other.x y = self.y - other.y return Point(x, y) class Box(namedtuple("Box", ["point", "size"])): __slots__ = () @property def rectangle(self): return Rectangle( x0=self.point.x, y0=self.point.y, x1=self.point.x+self.size.width, y1=self.point.y+self.size.height ) Fix implementation of overlapping rectangles# -*- coding: utf-8 -*- from collections import namedtuple Size = namedtuple("Size", ["width", "height"]) class Rectangle(namedtuple("Rectangle", ["x0", "y0", "x1", "y1"])): def __contains__(self, other): """Check if this rectangle and `other` overlaps eachother. Essentially this is a bit of a hack to be able to write `rect1 in rect2`. """ if self.x0 < other.x1 and self.x1 > other.x0 and \ self.y0 < other.y1 and self.y1 > other.y0: return True return False class Point(namedtuple("Point", ["x", "y"])): """Point in a two-dimensional space. Named tuple implementation that allows for addition and subtraction. """ __slots__ = () def __add__(self, other): x = self.x + other.x y = self.y + other.y return Point(x, y) def __sub__(self, other): x = self.x - other.x y = self.y - other.y return Point(x, y) class Box(namedtuple("Box", ["point", "size"])): __slots__ = () @property def rectangle(self): return Rectangle( x0=self.point.x, y0=self.point.y, x1=self.point.x+self.size.width, y1=self.point.y+self.size.height )
<commit_before># -*- coding: utf-8 -*- from collections import namedtuple Size = namedtuple("Size", ["width", "height"]) class Rectangle(namedtuple("Rectangle", ["x0", "y0", "x1", "y1"])): def __contains__(self, other): """Check if this rectangle and `other` overlaps eachother. Essentially this is a bit of a hack to be able to write `rect1 in rect2`. """ if self.x0 < other.x0 and self.x1 > other.x1 and \ self.y0 < other.y0 and self.y1 > other.y1: return True return False class Point(namedtuple("Point", ["x", "y"])): """Point in a two-dimensional space. Named tuple implementation that allows for addition and subtraction. """ __slots__ = () def __add__(self, other): x = self.x + other.x y = self.y + other.y return Point(x, y) def __sub__(self, other): x = self.x - other.x y = self.y - other.y return Point(x, y) class Box(namedtuple("Box", ["point", "size"])): __slots__ = () @property def rectangle(self): return Rectangle( x0=self.point.x, y0=self.point.y, x1=self.point.x+self.size.width, y1=self.point.y+self.size.height ) <commit_msg>Fix implementation of overlapping rectangles<commit_after># -*- coding: utf-8 -*- from collections import namedtuple Size = namedtuple("Size", ["width", "height"]) class Rectangle(namedtuple("Rectangle", ["x0", "y0", "x1", "y1"])): def __contains__(self, other): """Check if this rectangle and `other` overlaps eachother. Essentially this is a bit of a hack to be able to write `rect1 in rect2`. """ if self.x0 < other.x1 and self.x1 > other.x0 and \ self.y0 < other.y1 and self.y1 > other.y0: return True return False class Point(namedtuple("Point", ["x", "y"])): """Point in a two-dimensional space. Named tuple implementation that allows for addition and subtraction. """ __slots__ = () def __add__(self, other): x = self.x + other.x y = self.y + other.y return Point(x, y) def __sub__(self, other): x = self.x - other.x y = self.y - other.y return Point(x, y) class Box(namedtuple("Box", ["point", "size"])): __slots__ = () @property def rectangle(self): return Rectangle( x0=self.point.x, y0=self.point.y, x1=self.point.x+self.size.width, y1=self.point.y+self.size.height )
f20e7abc1672b3814062357add9f3adc1ca300f9
editorsnotes/main/migrations/0021_populate_display_name.py
editorsnotes/main/migrations/0021_populate_display_name.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): user.display_name = user._get_display_name() user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): if user.first_name or user.last_name: display_name = user.first_name + ' ' + user.last_name display_name = display_name.strip().rstrip() else: display_name = user.username user.display_name = display_name user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ]
Fix data migration for user display names
Fix data migration for user display names
Python
agpl-3.0
editorsnotes/editorsnotes,editorsnotes/editorsnotes
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): user.display_name = user._get_display_name() user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ] Fix data migration for user display names
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): if user.first_name or user.last_name: display_name = user.first_name + ' ' + user.last_name display_name = display_name.strip().rstrip() else: display_name = user.username user.display_name = display_name user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): user.display_name = user._get_display_name() user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ] <commit_msg>Fix data migration for user display names<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): if user.first_name or user.last_name: display_name = user.first_name + ' ' + user.last_name display_name = display_name.strip().rstrip() else: display_name = user.username user.display_name = display_name user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): user.display_name = user._get_display_name() user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ] Fix data migration for user display names# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): if user.first_name or user.last_name: display_name = user.first_name + ' ' + user.last_name display_name = display_name.strip().rstrip() else: display_name = user.username user.display_name = display_name user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): user.display_name = user._get_display_name() user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ] <commit_msg>Fix data migration for user display names<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): if user.first_name or user.last_name: display_name = user.first_name + ' ' + user.last_name display_name = display_name.strip().rstrip() else: display_name = user.username user.display_name = display_name user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ]
7c65017fa16632f21eb94896a3d7c8d2cce989dd
user/admin.py
user/admin.py
from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'get_date_joined', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',) def get_date_joined(self, user): return user.profile.joined get_date_joined.short_description = 'Joined' get_date_joined.admin_order_field = ( 'profile__joined')
from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'get_name', 'email', 'get_date_joined', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',) def get_date_joined(self, user): return user.profile.joined get_date_joined.short_description = 'Joined' get_date_joined.admin_order_field = ( 'profile__joined') def get_name(self, user): return user.profile.name get_name.short_description = 'Name' get_name.admin_order_field = 'profile__name'
Add Profile name to UserAdmin list.
Ch23: Add Profile name to UserAdmin list.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'get_date_joined', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',) def get_date_joined(self, user): return user.profile.joined get_date_joined.short_description = 'Joined' get_date_joined.admin_order_field = ( 'profile__joined') Ch23: Add Profile name to UserAdmin list.
from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'get_name', 'email', 'get_date_joined', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',) def get_date_joined(self, user): return user.profile.joined get_date_joined.short_description = 'Joined' get_date_joined.admin_order_field = ( 'profile__joined') def get_name(self, user): return user.profile.name get_name.short_description = 'Name' get_name.admin_order_field = 'profile__name'
<commit_before>from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'get_date_joined', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',) def get_date_joined(self, user): return user.profile.joined get_date_joined.short_description = 'Joined' get_date_joined.admin_order_field = ( 'profile__joined') <commit_msg>Ch23: Add Profile name to UserAdmin list.<commit_after>
from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'get_name', 'email', 'get_date_joined', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',) def get_date_joined(self, user): return user.profile.joined get_date_joined.short_description = 'Joined' get_date_joined.admin_order_field = ( 'profile__joined') def get_name(self, user): return user.profile.name get_name.short_description = 'Name' get_name.admin_order_field = 'profile__name'
from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'get_date_joined', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',) def get_date_joined(self, user): return user.profile.joined get_date_joined.short_description = 'Joined' get_date_joined.admin_order_field = ( 'profile__joined') Ch23: Add Profile name to UserAdmin list.from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'get_name', 'email', 'get_date_joined', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',) def get_date_joined(self, user): return user.profile.joined get_date_joined.short_description = 'Joined' get_date_joined.admin_order_field = ( 'profile__joined') def get_name(self, user): return user.profile.name get_name.short_description = 'Name' get_name.admin_order_field = 'profile__name'
<commit_before>from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'get_date_joined', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',) def get_date_joined(self, user): return user.profile.joined get_date_joined.short_description = 'Joined' get_date_joined.admin_order_field = ( 'profile__joined') <commit_msg>Ch23: Add Profile name to UserAdmin list.<commit_after>from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'get_name', 'email', 'get_date_joined', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',) def get_date_joined(self, user): return user.profile.joined get_date_joined.short_description = 'Joined' get_date_joined.admin_order_field = ( 'profile__joined') def get_name(self, user): return user.profile.name get_name.short_description = 'Name' get_name.admin_order_field = 'profile__name'
c58e3c207ad5f534ea8a7e17cb13f6a1a1b8c714
multi_schema/admin.py
multi_schema/admin.py
from django.contrib import admin from models import Schema class SchemaAdmin(admin.ModelAdmin): pass admin.site.register(Schema, SchemaAdmin)
from django.contrib import admin, auth from models import Schema, UserSchema class SchemaAdmin(admin.ModelAdmin): def get_readonly_fields(self, request, obj=None): if obj is not None: return ('schema',) return () admin.site.register(Schema, SchemaAdmin) class SchemaInline(admin.StackedInline): model = UserSchema # Inject SchemeInline into UserAdmin UserAdmin = admin.site._registry[auth.models.User].__class__ class SchemaUserAdmin(UserAdmin): inlines = UserAdmin.inlines + [SchemaInline] admin.site.unregister(auth.models.User) admin.site.register(auth.models.User, SchemaUserAdmin)
Make 'schema' value readonly after creation. Inject SchemaUser into UserAdmin inlines.
Make 'schema' value readonly after creation. Inject SchemaUser into UserAdmin inlines.
Python
bsd-3-clause
schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse
from django.contrib import admin from models import Schema class SchemaAdmin(admin.ModelAdmin): pass admin.site.register(Schema, SchemaAdmin)Make 'schema' value readonly after creation. Inject SchemaUser into UserAdmin inlines.
from django.contrib import admin, auth from models import Schema, UserSchema class SchemaAdmin(admin.ModelAdmin): def get_readonly_fields(self, request, obj=None): if obj is not None: return ('schema',) return () admin.site.register(Schema, SchemaAdmin) class SchemaInline(admin.StackedInline): model = UserSchema # Inject SchemeInline into UserAdmin UserAdmin = admin.site._registry[auth.models.User].__class__ class SchemaUserAdmin(UserAdmin): inlines = UserAdmin.inlines + [SchemaInline] admin.site.unregister(auth.models.User) admin.site.register(auth.models.User, SchemaUserAdmin)
<commit_before>from django.contrib import admin from models import Schema class SchemaAdmin(admin.ModelAdmin): pass admin.site.register(Schema, SchemaAdmin)<commit_msg>Make 'schema' value readonly after creation. Inject SchemaUser into UserAdmin inlines.<commit_after>
from django.contrib import admin, auth from models import Schema, UserSchema class SchemaAdmin(admin.ModelAdmin): def get_readonly_fields(self, request, obj=None): if obj is not None: return ('schema',) return () admin.site.register(Schema, SchemaAdmin) class SchemaInline(admin.StackedInline): model = UserSchema # Inject SchemeInline into UserAdmin UserAdmin = admin.site._registry[auth.models.User].__class__ class SchemaUserAdmin(UserAdmin): inlines = UserAdmin.inlines + [SchemaInline] admin.site.unregister(auth.models.User) admin.site.register(auth.models.User, SchemaUserAdmin)
from django.contrib import admin from models import Schema class SchemaAdmin(admin.ModelAdmin): pass admin.site.register(Schema, SchemaAdmin)Make 'schema' value readonly after creation. Inject SchemaUser into UserAdmin inlines.from django.contrib import admin, auth from models import Schema, UserSchema class SchemaAdmin(admin.ModelAdmin): def get_readonly_fields(self, request, obj=None): if obj is not None: return ('schema',) return () admin.site.register(Schema, SchemaAdmin) class SchemaInline(admin.StackedInline): model = UserSchema # Inject SchemeInline into UserAdmin UserAdmin = admin.site._registry[auth.models.User].__class__ class SchemaUserAdmin(UserAdmin): inlines = UserAdmin.inlines + [SchemaInline] admin.site.unregister(auth.models.User) admin.site.register(auth.models.User, SchemaUserAdmin)
<commit_before>from django.contrib import admin from models import Schema class SchemaAdmin(admin.ModelAdmin): pass admin.site.register(Schema, SchemaAdmin)<commit_msg>Make 'schema' value readonly after creation. Inject SchemaUser into UserAdmin inlines.<commit_after>from django.contrib import admin, auth from models import Schema, UserSchema class SchemaAdmin(admin.ModelAdmin): def get_readonly_fields(self, request, obj=None): if obj is not None: return ('schema',) return () admin.site.register(Schema, SchemaAdmin) class SchemaInline(admin.StackedInline): model = UserSchema # Inject SchemeInline into UserAdmin UserAdmin = admin.site._registry[auth.models.User].__class__ class SchemaUserAdmin(UserAdmin): inlines = UserAdmin.inlines + [SchemaInline] admin.site.unregister(auth.models.User) admin.site.register(auth.models.User, SchemaUserAdmin)
c5eb0358e763d626f503fa45228752da10b7c70d
openfisca_core/commons.py
openfisca_core/commons.py
# -*- coding: utf-8 -*- # The following two variables and the is_unicode function are there to bridge string types across Python 2 & 3 unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return unicode(string, 'utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None'
# -*- coding: utf-8 -*- # The following two variables and the is_unicode function are there to bridge string types across Python 2 & 3 unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return string.decode('utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None'
Make to_unicode work in Python 3
Make to_unicode work in Python 3
Python
agpl-3.0
openfisca/openfisca-core,openfisca/openfisca-core
# -*- coding: utf-8 -*- # The following two variables and the is_unicode function are there to bridge string types across Python 2 & 3 unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return unicode(string, 'utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None' Make to_unicode work in Python 3
# -*- coding: utf-8 -*- # The following two variables and the is_unicode function are there to bridge string types across Python 2 & 3 unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return string.decode('utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None'
<commit_before># -*- coding: utf-8 -*- # The following two variables and the is_unicode function are there to bridge string types across Python 2 & 3 unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return unicode(string, 'utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None' <commit_msg>Make to_unicode work in Python 3<commit_after>
# -*- coding: utf-8 -*- # The following two variables and the is_unicode function are there to bridge string types across Python 2 & 3 unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return string.decode('utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None'
# -*- coding: utf-8 -*- # The following two variables and the is_unicode function are there to bridge string types across Python 2 & 3 unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return unicode(string, 'utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None' Make to_unicode work in Python 3# -*- coding: utf-8 -*- # The following two variables and the is_unicode function are there to bridge string types across Python 2 & 3 unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return string.decode('utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None'
<commit_before># -*- coding: utf-8 -*- # The following two variables and the is_unicode function are there to bridge string types across Python 2 & 3 unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return unicode(string, 'utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None' <commit_msg>Make to_unicode work in Python 3<commit_after># -*- coding: utf-8 -*- # The following two variables and the is_unicode function are there to bridge string types across Python 2 & 3 unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return string.decode('utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None'
7c953b71cbcb01ce1fc2d7d1a476a33dffb8999e
fabfile.py
fabfile.py
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('chown -R www-data:www-data logs') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')
Remove log chown step from post-deployment process.
Remove log chown step from post-deployment process.
Python
agpl-3.0
coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('chown -R www-data:www-data logs') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development') Remove log chown step from post-deployment process.
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')
<commit_before>import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('chown -R www-data:www-data logs') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development') <commit_msg>Remove log chown step from post-deployment process.<commit_after>
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('chown -R www-data:www-data logs') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development') Remove log chown step from post-deployment process.import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')
<commit_before>import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('chown -R www-data:www-data logs') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development') <commit_msg>Remove log chown step from post-deployment process.<commit_after>import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')
e72fa5ab59a8c904d525a33652424b0acf5c9de4
cms/widgets.py
cms/widgets.py
## # Copyright (C) 2017 Jessica Tallon & Matt Molyneaux # # This file is part of Inboxen. # # Inboxen 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. # # Inboxen 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 Inboxen. If not, see <http://www.gnu.org/licenses/>. ## from django.forms.widgets import TextInput class RichTextInput(TextInput): template_name = 'cms/forms/widgets/rich_text.html'
## # Copyright (C) 2017 Jessica Tallon & Matt Molyneaux # # This file is part of Inboxen. # # Inboxen 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. # # Inboxen 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 Inboxen. If not, see <http://www.gnu.org/licenses/>. ## from django.forms.widgets import Textarea class RichTextInput(Textarea): template_name = 'cms/forms/widgets/rich_text.html'
Switch TextInput for Textarea for RichText widget base class
Switch TextInput for Textarea for RichText widget base class
Python
agpl-3.0
Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen
## # Copyright (C) 2017 Jessica Tallon & Matt Molyneaux # # This file is part of Inboxen. # # Inboxen 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. # # Inboxen 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 Inboxen. If not, see <http://www.gnu.org/licenses/>. ## from django.forms.widgets import TextInput class RichTextInput(TextInput): template_name = 'cms/forms/widgets/rich_text.html' Switch TextInput for Textarea for RichText widget base class
## # Copyright (C) 2017 Jessica Tallon & Matt Molyneaux # # This file is part of Inboxen. # # Inboxen 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. # # Inboxen 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 Inboxen. If not, see <http://www.gnu.org/licenses/>. ## from django.forms.widgets import Textarea class RichTextInput(Textarea): template_name = 'cms/forms/widgets/rich_text.html'
<commit_before>## # Copyright (C) 2017 Jessica Tallon & Matt Molyneaux # # This file is part of Inboxen. # # Inboxen 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. # # Inboxen 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 Inboxen. If not, see <http://www.gnu.org/licenses/>. ## from django.forms.widgets import TextInput class RichTextInput(TextInput): template_name = 'cms/forms/widgets/rich_text.html' <commit_msg>Switch TextInput for Textarea for RichText widget base class<commit_after>
## # Copyright (C) 2017 Jessica Tallon & Matt Molyneaux # # This file is part of Inboxen. # # Inboxen 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. # # Inboxen 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 Inboxen. If not, see <http://www.gnu.org/licenses/>. ## from django.forms.widgets import Textarea class RichTextInput(Textarea): template_name = 'cms/forms/widgets/rich_text.html'
## # Copyright (C) 2017 Jessica Tallon & Matt Molyneaux # # This file is part of Inboxen. # # Inboxen 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. # # Inboxen 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 Inboxen. If not, see <http://www.gnu.org/licenses/>. ## from django.forms.widgets import TextInput class RichTextInput(TextInput): template_name = 'cms/forms/widgets/rich_text.html' Switch TextInput for Textarea for RichText widget base class## # Copyright (C) 2017 Jessica Tallon & Matt Molyneaux # # This file is part of Inboxen. # # Inboxen 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. # # Inboxen 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 Inboxen. If not, see <http://www.gnu.org/licenses/>. ## from django.forms.widgets import Textarea class RichTextInput(Textarea): template_name = 'cms/forms/widgets/rich_text.html'
<commit_before>## # Copyright (C) 2017 Jessica Tallon & Matt Molyneaux # # This file is part of Inboxen. # # Inboxen 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. # # Inboxen 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 Inboxen. If not, see <http://www.gnu.org/licenses/>. ## from django.forms.widgets import TextInput class RichTextInput(TextInput): template_name = 'cms/forms/widgets/rich_text.html' <commit_msg>Switch TextInput for Textarea for RichText widget base class<commit_after>## # Copyright (C) 2017 Jessica Tallon & Matt Molyneaux # # This file is part of Inboxen. # # Inboxen 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. # # Inboxen 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 Inboxen. If not, see <http://www.gnu.org/licenses/>. ## from django.forms.widgets import Textarea class RichTextInput(Textarea): template_name = 'cms/forms/widgets/rich_text.html'
0392e4e26b5affee2de648084198fa3375a7bdd3
src/zeit/brightcove/json/tests/test_update.py
src/zeit/brightcove/json/tests/test_update.py
import mock import zeit.brightcove.convert import zeit.brightcove.testing import zeit.cms.testing import zope.testbrowser.testing class NotificationTest(zeit.cms.testing.BrowserTestCase): layer = zeit.brightcove.testing.LAYER def test_runs_import_as_system_user(self): # View is available without authentication b = zope.testbrowser.testing.Browser() with mock.patch.object( zeit.brightcove.update.import_video_async, '__call__') as import_video: b.post('http://localhost/@@update_video', '{"event": "video-change", "video": "myvid"}', 'application/x-javascript') self.assertEqual('myvid', import_video.call_args[0][0]) self.assertEqual( 'zope.user', import_video.call_args[1]['_principal_id_']) def create_video(self): bc = zeit.brightcove.convert.Video() bc.data = { 'id': 'myvid', 'created_at': '2017-05-15T08:24:55.916Z', 'state': 'INACTIVE', } return bc
import mock import zeit.brightcove.convert import zeit.brightcove.testing import zeit.cms.testing class NotificationTest(zeit.cms.testing.BrowserTestCase): layer = zeit.brightcove.testing.LAYER def test_runs_import_as_system_user(self): # View is available without authentication b = zeit.cms.testing.Browser() with mock.patch.object( zeit.brightcove.update.import_video_async, '__call__') as import_video: b.post('http://localhost/@@update_video', '{"event": "video-change", "video": "myvid"}', 'application/x-javascript') self.assertEqual('myvid', import_video.call_args[0][0]) self.assertEqual( 'zope.user', import_video.call_args[1]['_principal_id_']) def create_video(self): bc = zeit.brightcove.convert.Video() bc.data = { 'id': 'myvid', 'created_at': '2017-05-15T08:24:55.916Z', 'state': 'INACTIVE', } return bc
Update to changed zeit.cms test browser setup API
MAINT: Update to changed zeit.cms test browser setup API
Python
bsd-3-clause
ZeitOnline/zeit.brightcove
import mock import zeit.brightcove.convert import zeit.brightcove.testing import zeit.cms.testing import zope.testbrowser.testing class NotificationTest(zeit.cms.testing.BrowserTestCase): layer = zeit.brightcove.testing.LAYER def test_runs_import_as_system_user(self): # View is available without authentication b = zope.testbrowser.testing.Browser() with mock.patch.object( zeit.brightcove.update.import_video_async, '__call__') as import_video: b.post('http://localhost/@@update_video', '{"event": "video-change", "video": "myvid"}', 'application/x-javascript') self.assertEqual('myvid', import_video.call_args[0][0]) self.assertEqual( 'zope.user', import_video.call_args[1]['_principal_id_']) def create_video(self): bc = zeit.brightcove.convert.Video() bc.data = { 'id': 'myvid', 'created_at': '2017-05-15T08:24:55.916Z', 'state': 'INACTIVE', } return bc MAINT: Update to changed zeit.cms test browser setup API
import mock import zeit.brightcove.convert import zeit.brightcove.testing import zeit.cms.testing class NotificationTest(zeit.cms.testing.BrowserTestCase): layer = zeit.brightcove.testing.LAYER def test_runs_import_as_system_user(self): # View is available without authentication b = zeit.cms.testing.Browser() with mock.patch.object( zeit.brightcove.update.import_video_async, '__call__') as import_video: b.post('http://localhost/@@update_video', '{"event": "video-change", "video": "myvid"}', 'application/x-javascript') self.assertEqual('myvid', import_video.call_args[0][0]) self.assertEqual( 'zope.user', import_video.call_args[1]['_principal_id_']) def create_video(self): bc = zeit.brightcove.convert.Video() bc.data = { 'id': 'myvid', 'created_at': '2017-05-15T08:24:55.916Z', 'state': 'INACTIVE', } return bc
<commit_before>import mock import zeit.brightcove.convert import zeit.brightcove.testing import zeit.cms.testing import zope.testbrowser.testing class NotificationTest(zeit.cms.testing.BrowserTestCase): layer = zeit.brightcove.testing.LAYER def test_runs_import_as_system_user(self): # View is available without authentication b = zope.testbrowser.testing.Browser() with mock.patch.object( zeit.brightcove.update.import_video_async, '__call__') as import_video: b.post('http://localhost/@@update_video', '{"event": "video-change", "video": "myvid"}', 'application/x-javascript') self.assertEqual('myvid', import_video.call_args[0][0]) self.assertEqual( 'zope.user', import_video.call_args[1]['_principal_id_']) def create_video(self): bc = zeit.brightcove.convert.Video() bc.data = { 'id': 'myvid', 'created_at': '2017-05-15T08:24:55.916Z', 'state': 'INACTIVE', } return bc <commit_msg>MAINT: Update to changed zeit.cms test browser setup API<commit_after>
import mock import zeit.brightcove.convert import zeit.brightcove.testing import zeit.cms.testing class NotificationTest(zeit.cms.testing.BrowserTestCase): layer = zeit.brightcove.testing.LAYER def test_runs_import_as_system_user(self): # View is available without authentication b = zeit.cms.testing.Browser() with mock.patch.object( zeit.brightcove.update.import_video_async, '__call__') as import_video: b.post('http://localhost/@@update_video', '{"event": "video-change", "video": "myvid"}', 'application/x-javascript') self.assertEqual('myvid', import_video.call_args[0][0]) self.assertEqual( 'zope.user', import_video.call_args[1]['_principal_id_']) def create_video(self): bc = zeit.brightcove.convert.Video() bc.data = { 'id': 'myvid', 'created_at': '2017-05-15T08:24:55.916Z', 'state': 'INACTIVE', } return bc
import mock import zeit.brightcove.convert import zeit.brightcove.testing import zeit.cms.testing import zope.testbrowser.testing class NotificationTest(zeit.cms.testing.BrowserTestCase): layer = zeit.brightcove.testing.LAYER def test_runs_import_as_system_user(self): # View is available without authentication b = zope.testbrowser.testing.Browser() with mock.patch.object( zeit.brightcove.update.import_video_async, '__call__') as import_video: b.post('http://localhost/@@update_video', '{"event": "video-change", "video": "myvid"}', 'application/x-javascript') self.assertEqual('myvid', import_video.call_args[0][0]) self.assertEqual( 'zope.user', import_video.call_args[1]['_principal_id_']) def create_video(self): bc = zeit.brightcove.convert.Video() bc.data = { 'id': 'myvid', 'created_at': '2017-05-15T08:24:55.916Z', 'state': 'INACTIVE', } return bc MAINT: Update to changed zeit.cms test browser setup APIimport mock import zeit.brightcove.convert import zeit.brightcove.testing import zeit.cms.testing class NotificationTest(zeit.cms.testing.BrowserTestCase): layer = zeit.brightcove.testing.LAYER def test_runs_import_as_system_user(self): # View is available without authentication b = zeit.cms.testing.Browser() with mock.patch.object( zeit.brightcove.update.import_video_async, '__call__') as import_video: b.post('http://localhost/@@update_video', '{"event": "video-change", "video": "myvid"}', 'application/x-javascript') self.assertEqual('myvid', import_video.call_args[0][0]) self.assertEqual( 'zope.user', import_video.call_args[1]['_principal_id_']) def create_video(self): bc = zeit.brightcove.convert.Video() bc.data = { 'id': 'myvid', 'created_at': '2017-05-15T08:24:55.916Z', 'state': 'INACTIVE', } return bc
<commit_before>import mock import zeit.brightcove.convert import zeit.brightcove.testing import zeit.cms.testing import zope.testbrowser.testing class NotificationTest(zeit.cms.testing.BrowserTestCase): layer = zeit.brightcove.testing.LAYER def test_runs_import_as_system_user(self): # View is available without authentication b = zope.testbrowser.testing.Browser() with mock.patch.object( zeit.brightcove.update.import_video_async, '__call__') as import_video: b.post('http://localhost/@@update_video', '{"event": "video-change", "video": "myvid"}', 'application/x-javascript') self.assertEqual('myvid', import_video.call_args[0][0]) self.assertEqual( 'zope.user', import_video.call_args[1]['_principal_id_']) def create_video(self): bc = zeit.brightcove.convert.Video() bc.data = { 'id': 'myvid', 'created_at': '2017-05-15T08:24:55.916Z', 'state': 'INACTIVE', } return bc <commit_msg>MAINT: Update to changed zeit.cms test browser setup API<commit_after>import mock import zeit.brightcove.convert import zeit.brightcove.testing import zeit.cms.testing class NotificationTest(zeit.cms.testing.BrowserTestCase): layer = zeit.brightcove.testing.LAYER def test_runs_import_as_system_user(self): # View is available without authentication b = zeit.cms.testing.Browser() with mock.patch.object( zeit.brightcove.update.import_video_async, '__call__') as import_video: b.post('http://localhost/@@update_video', '{"event": "video-change", "video": "myvid"}', 'application/x-javascript') self.assertEqual('myvid', import_video.call_args[0][0]) self.assertEqual( 'zope.user', import_video.call_args[1]['_principal_id_']) def create_video(self): bc = zeit.brightcove.convert.Video() bc.data = { 'id': 'myvid', 'created_at': '2017-05-15T08:24:55.916Z', 'state': 'INACTIVE', } return bc
999688f963c2737fc699bd1a97d91e79eb125c38
test/test_path_utilities.py
test/test_path_utilities.py
import pytest from girder.utility import path @pytest.mark.parametrize('raw,encoded', [ ('abcd', 'abcd'), ('/', '\/'), ('\\', '\\\\'), ('/\\', '\/\\\\'), ('\\//\\', '\\\\\/\/\\\\'), ('a\\\\b//c\\d', 'a\\\\\\\\b\/\/c\\\\d') ]) def testCodec(raw, encoded): assert path.encode(raw) == encoded assert path.decode(encoded) == raw @pytest.mark.parametrize('pth,tokens', [ ('abcd', ['abcd']), ('/abcd', ['', 'abcd']), ('/ab/cd/ef/gh', ['', 'ab', 'cd', 'ef', 'gh']), ('/ab/cd//', ['', 'ab', 'cd', '', '']), ('ab\\/cd', ['ab/cd']), ('ab\/c/d', ['ab/c', 'd']), ('ab\//cd', ['ab/', 'cd']), ('ab/\/cd', ['ab', '/cd']), ('ab\\\\/cd', ['ab\\', 'cd']), ('ab\\\\/\\\\cd', ['ab\\', '\\cd']), ('ab\\\\\\/\\\\cd', ['ab\\/\\cd']), ('/\\\\abcd\\\\/', ['', '\\abcd\\', '']), ('/\\\\\\\\/\\//\\\\', ['', '\\\\', '/', '\\']) ]) def testSplitAndJoin(pth, tokens): assert path.split(pth) == tokens assert path.join(tokens) == pth
import pytest from girder.utility import path @pytest.mark.parametrize('raw,encoded', [ ('abcd', 'abcd'), ('/', '\\/'), ('\\', '\\\\'), ('/\\', '\\/\\\\'), ('\\//\\', '\\\\\\/\\/\\\\'), ('a\\\\b//c\\d', 'a\\\\\\\\b\\/\\/c\\\\d') ]) def testCodec(raw, encoded): assert path.encode(raw) == encoded assert path.decode(encoded) == raw @pytest.mark.parametrize('pth,tokens', [ ('abcd', ['abcd']), ('/abcd', ['', 'abcd']), ('/ab/cd/ef/gh', ['', 'ab', 'cd', 'ef', 'gh']), ('/ab/cd//', ['', 'ab', 'cd', '', '']), ('ab\\/cd', ['ab/cd']), ('ab\\/c/d', ['ab/c', 'd']), ('ab\\//cd', ['ab/', 'cd']), ('ab/\\/cd', ['ab', '/cd']), ('ab\\\\/cd', ['ab\\', 'cd']), ('ab\\\\/\\\\cd', ['ab\\', '\\cd']), ('ab\\\\\\/\\\\cd', ['ab\\/\\cd']), ('/\\\\abcd\\\\/', ['', '\\abcd\\', '']), ('/\\\\\\\\/\\//\\\\', ['', '\\\\', '/', '\\']) ]) def testSplitAndJoin(pth, tokens): assert path.split(pth) == tokens assert path.join(tokens) == pth
Fix escape sequence formatting linter errors
Fix escape sequence formatting linter errors
Python
apache-2.0
RafaelPalomar/girder,RafaelPalomar/girder,jbeezley/girder,manthey/girder,jbeezley/girder,Kitware/girder,girder/girder,RafaelPalomar/girder,girder/girder,Kitware/girder,manthey/girder,jbeezley/girder,RafaelPalomar/girder,girder/girder,Kitware/girder,manthey/girder,girder/girder,RafaelPalomar/girder,jbeezley/girder,Kitware/girder,manthey/girder
import pytest from girder.utility import path @pytest.mark.parametrize('raw,encoded', [ ('abcd', 'abcd'), ('/', '\/'), ('\\', '\\\\'), ('/\\', '\/\\\\'), ('\\//\\', '\\\\\/\/\\\\'), ('a\\\\b//c\\d', 'a\\\\\\\\b\/\/c\\\\d') ]) def testCodec(raw, encoded): assert path.encode(raw) == encoded assert path.decode(encoded) == raw @pytest.mark.parametrize('pth,tokens', [ ('abcd', ['abcd']), ('/abcd', ['', 'abcd']), ('/ab/cd/ef/gh', ['', 'ab', 'cd', 'ef', 'gh']), ('/ab/cd//', ['', 'ab', 'cd', '', '']), ('ab\\/cd', ['ab/cd']), ('ab\/c/d', ['ab/c', 'd']), ('ab\//cd', ['ab/', 'cd']), ('ab/\/cd', ['ab', '/cd']), ('ab\\\\/cd', ['ab\\', 'cd']), ('ab\\\\/\\\\cd', ['ab\\', '\\cd']), ('ab\\\\\\/\\\\cd', ['ab\\/\\cd']), ('/\\\\abcd\\\\/', ['', '\\abcd\\', '']), ('/\\\\\\\\/\\//\\\\', ['', '\\\\', '/', '\\']) ]) def testSplitAndJoin(pth, tokens): assert path.split(pth) == tokens assert path.join(tokens) == pth Fix escape sequence formatting linter errors
import pytest from girder.utility import path @pytest.mark.parametrize('raw,encoded', [ ('abcd', 'abcd'), ('/', '\\/'), ('\\', '\\\\'), ('/\\', '\\/\\\\'), ('\\//\\', '\\\\\\/\\/\\\\'), ('a\\\\b//c\\d', 'a\\\\\\\\b\\/\\/c\\\\d') ]) def testCodec(raw, encoded): assert path.encode(raw) == encoded assert path.decode(encoded) == raw @pytest.mark.parametrize('pth,tokens', [ ('abcd', ['abcd']), ('/abcd', ['', 'abcd']), ('/ab/cd/ef/gh', ['', 'ab', 'cd', 'ef', 'gh']), ('/ab/cd//', ['', 'ab', 'cd', '', '']), ('ab\\/cd', ['ab/cd']), ('ab\\/c/d', ['ab/c', 'd']), ('ab\\//cd', ['ab/', 'cd']), ('ab/\\/cd', ['ab', '/cd']), ('ab\\\\/cd', ['ab\\', 'cd']), ('ab\\\\/\\\\cd', ['ab\\', '\\cd']), ('ab\\\\\\/\\\\cd', ['ab\\/\\cd']), ('/\\\\abcd\\\\/', ['', '\\abcd\\', '']), ('/\\\\\\\\/\\//\\\\', ['', '\\\\', '/', '\\']) ]) def testSplitAndJoin(pth, tokens): assert path.split(pth) == tokens assert path.join(tokens) == pth
<commit_before>import pytest from girder.utility import path @pytest.mark.parametrize('raw,encoded', [ ('abcd', 'abcd'), ('/', '\/'), ('\\', '\\\\'), ('/\\', '\/\\\\'), ('\\//\\', '\\\\\/\/\\\\'), ('a\\\\b//c\\d', 'a\\\\\\\\b\/\/c\\\\d') ]) def testCodec(raw, encoded): assert path.encode(raw) == encoded assert path.decode(encoded) == raw @pytest.mark.parametrize('pth,tokens', [ ('abcd', ['abcd']), ('/abcd', ['', 'abcd']), ('/ab/cd/ef/gh', ['', 'ab', 'cd', 'ef', 'gh']), ('/ab/cd//', ['', 'ab', 'cd', '', '']), ('ab\\/cd', ['ab/cd']), ('ab\/c/d', ['ab/c', 'd']), ('ab\//cd', ['ab/', 'cd']), ('ab/\/cd', ['ab', '/cd']), ('ab\\\\/cd', ['ab\\', 'cd']), ('ab\\\\/\\\\cd', ['ab\\', '\\cd']), ('ab\\\\\\/\\\\cd', ['ab\\/\\cd']), ('/\\\\abcd\\\\/', ['', '\\abcd\\', '']), ('/\\\\\\\\/\\//\\\\', ['', '\\\\', '/', '\\']) ]) def testSplitAndJoin(pth, tokens): assert path.split(pth) == tokens assert path.join(tokens) == pth <commit_msg>Fix escape sequence formatting linter errors<commit_after>
import pytest from girder.utility import path @pytest.mark.parametrize('raw,encoded', [ ('abcd', 'abcd'), ('/', '\\/'), ('\\', '\\\\'), ('/\\', '\\/\\\\'), ('\\//\\', '\\\\\\/\\/\\\\'), ('a\\\\b//c\\d', 'a\\\\\\\\b\\/\\/c\\\\d') ]) def testCodec(raw, encoded): assert path.encode(raw) == encoded assert path.decode(encoded) == raw @pytest.mark.parametrize('pth,tokens', [ ('abcd', ['abcd']), ('/abcd', ['', 'abcd']), ('/ab/cd/ef/gh', ['', 'ab', 'cd', 'ef', 'gh']), ('/ab/cd//', ['', 'ab', 'cd', '', '']), ('ab\\/cd', ['ab/cd']), ('ab\\/c/d', ['ab/c', 'd']), ('ab\\//cd', ['ab/', 'cd']), ('ab/\\/cd', ['ab', '/cd']), ('ab\\\\/cd', ['ab\\', 'cd']), ('ab\\\\/\\\\cd', ['ab\\', '\\cd']), ('ab\\\\\\/\\\\cd', ['ab\\/\\cd']), ('/\\\\abcd\\\\/', ['', '\\abcd\\', '']), ('/\\\\\\\\/\\//\\\\', ['', '\\\\', '/', '\\']) ]) def testSplitAndJoin(pth, tokens): assert path.split(pth) == tokens assert path.join(tokens) == pth
import pytest from girder.utility import path @pytest.mark.parametrize('raw,encoded', [ ('abcd', 'abcd'), ('/', '\/'), ('\\', '\\\\'), ('/\\', '\/\\\\'), ('\\//\\', '\\\\\/\/\\\\'), ('a\\\\b//c\\d', 'a\\\\\\\\b\/\/c\\\\d') ]) def testCodec(raw, encoded): assert path.encode(raw) == encoded assert path.decode(encoded) == raw @pytest.mark.parametrize('pth,tokens', [ ('abcd', ['abcd']), ('/abcd', ['', 'abcd']), ('/ab/cd/ef/gh', ['', 'ab', 'cd', 'ef', 'gh']), ('/ab/cd//', ['', 'ab', 'cd', '', '']), ('ab\\/cd', ['ab/cd']), ('ab\/c/d', ['ab/c', 'd']), ('ab\//cd', ['ab/', 'cd']), ('ab/\/cd', ['ab', '/cd']), ('ab\\\\/cd', ['ab\\', 'cd']), ('ab\\\\/\\\\cd', ['ab\\', '\\cd']), ('ab\\\\\\/\\\\cd', ['ab\\/\\cd']), ('/\\\\abcd\\\\/', ['', '\\abcd\\', '']), ('/\\\\\\\\/\\//\\\\', ['', '\\\\', '/', '\\']) ]) def testSplitAndJoin(pth, tokens): assert path.split(pth) == tokens assert path.join(tokens) == pth Fix escape sequence formatting linter errorsimport pytest from girder.utility import path @pytest.mark.parametrize('raw,encoded', [ ('abcd', 'abcd'), ('/', '\\/'), ('\\', '\\\\'), ('/\\', '\\/\\\\'), ('\\//\\', '\\\\\\/\\/\\\\'), ('a\\\\b//c\\d', 'a\\\\\\\\b\\/\\/c\\\\d') ]) def testCodec(raw, encoded): assert path.encode(raw) == encoded assert path.decode(encoded) == raw @pytest.mark.parametrize('pth,tokens', [ ('abcd', ['abcd']), ('/abcd', ['', 'abcd']), ('/ab/cd/ef/gh', ['', 'ab', 'cd', 'ef', 'gh']), ('/ab/cd//', ['', 'ab', 'cd', '', '']), ('ab\\/cd', ['ab/cd']), ('ab\\/c/d', ['ab/c', 'd']), ('ab\\//cd', ['ab/', 'cd']), ('ab/\\/cd', ['ab', '/cd']), ('ab\\\\/cd', ['ab\\', 'cd']), ('ab\\\\/\\\\cd', ['ab\\', '\\cd']), ('ab\\\\\\/\\\\cd', ['ab\\/\\cd']), ('/\\\\abcd\\\\/', ['', '\\abcd\\', '']), ('/\\\\\\\\/\\//\\\\', ['', '\\\\', '/', '\\']) ]) def testSplitAndJoin(pth, tokens): assert path.split(pth) == tokens assert path.join(tokens) == pth
<commit_before>import pytest from girder.utility import path @pytest.mark.parametrize('raw,encoded', [ ('abcd', 'abcd'), ('/', '\/'), ('\\', '\\\\'), ('/\\', '\/\\\\'), ('\\//\\', '\\\\\/\/\\\\'), ('a\\\\b//c\\d', 'a\\\\\\\\b\/\/c\\\\d') ]) def testCodec(raw, encoded): assert path.encode(raw) == encoded assert path.decode(encoded) == raw @pytest.mark.parametrize('pth,tokens', [ ('abcd', ['abcd']), ('/abcd', ['', 'abcd']), ('/ab/cd/ef/gh', ['', 'ab', 'cd', 'ef', 'gh']), ('/ab/cd//', ['', 'ab', 'cd', '', '']), ('ab\\/cd', ['ab/cd']), ('ab\/c/d', ['ab/c', 'd']), ('ab\//cd', ['ab/', 'cd']), ('ab/\/cd', ['ab', '/cd']), ('ab\\\\/cd', ['ab\\', 'cd']), ('ab\\\\/\\\\cd', ['ab\\', '\\cd']), ('ab\\\\\\/\\\\cd', ['ab\\/\\cd']), ('/\\\\abcd\\\\/', ['', '\\abcd\\', '']), ('/\\\\\\\\/\\//\\\\', ['', '\\\\', '/', '\\']) ]) def testSplitAndJoin(pth, tokens): assert path.split(pth) == tokens assert path.join(tokens) == pth <commit_msg>Fix escape sequence formatting linter errors<commit_after>import pytest from girder.utility import path @pytest.mark.parametrize('raw,encoded', [ ('abcd', 'abcd'), ('/', '\\/'), ('\\', '\\\\'), ('/\\', '\\/\\\\'), ('\\//\\', '\\\\\\/\\/\\\\'), ('a\\\\b//c\\d', 'a\\\\\\\\b\\/\\/c\\\\d') ]) def testCodec(raw, encoded): assert path.encode(raw) == encoded assert path.decode(encoded) == raw @pytest.mark.parametrize('pth,tokens', [ ('abcd', ['abcd']), ('/abcd', ['', 'abcd']), ('/ab/cd/ef/gh', ['', 'ab', 'cd', 'ef', 'gh']), ('/ab/cd//', ['', 'ab', 'cd', '', '']), ('ab\\/cd', ['ab/cd']), ('ab\\/c/d', ['ab/c', 'd']), ('ab\\//cd', ['ab/', 'cd']), ('ab/\\/cd', ['ab', '/cd']), ('ab\\\\/cd', ['ab\\', 'cd']), ('ab\\\\/\\\\cd', ['ab\\', '\\cd']), ('ab\\\\\\/\\\\cd', ['ab\\/\\cd']), ('/\\\\abcd\\\\/', ['', '\\abcd\\', '']), ('/\\\\\\\\/\\//\\\\', ['', '\\\\', '/', '\\']) ]) def testSplitAndJoin(pth, tokens): assert path.split(pth) == tokens assert path.join(tokens) == pth
e89b1de0669dd54fb1c3e2153f0539f5f5559d74
readmore/content/helpers.py
readmore/content/helpers.py
from django.core.urlresolvers import reverse from bs4 import BeautifulSoup def process_wiki_page_html(html): """Process the html of a wikipedia page to be used in ReadMore.""" #TODO: Write BeautifullSoup code to remove Edit links #TODO: Write BeautifullSoup code to alter local links, # use: reverse('wikipedia_article', args=(identifier,)) for new link # see also: https://docs.djangoproject.com/en/1.6/ref/urlresolvers/#django.core.urlresolvers.reverse soup = BeautifulSoup(html) #Find and remove all edit links edits = soup.find_all("span", class_="mw-editsection") for edit in edits: edit.extract() #Find and edit all internal links internal = soup.find_all("a") for link in internal: source = link.get('href') if source[0:5] == "/wiki": link['href'] = reverse('wikipedia_article', args=(source[6:],)) + "?type=title" #Find all external links and add target="_blank" external = soup.find_all("a", class_="external text") for link in external: link['target'] = '_blank' return str(soup) def stripped(title): if(title[:10] == "Categorie:"): return title[10:] return title
from django.core.urlresolvers import reverse from bs4 import BeautifulSoup def process_wiki_page_html(html): """Process the html of a wikipedia page to be used in ReadMore.""" #TODO: Write BeautifullSoup code to remove Edit links #TODO: Write BeautifullSoup code to alter local links, # use: reverse('wikipedia_article', args=(identifier,)) for new link # see also: https://docs.djangoproject.com/en/1.6/ref/urlresolvers/#django.core.urlresolvers.reverse soup = BeautifulSoup(html) #Find and remove all edit links edits = soup.find_all("span", class_="mw-editsection") for edit in edits: edit.extract() #Find and edit all internal links internal = soup.find_all("a") for link in internal: source = link.get('href') if source[0:5] == "/wiki": link['href'] = reverse('wikipedia_article', args=(source[6:],)) + "?type=title" #Find all external links and add target="_blank" external = soup.find_all("a", class_="external text") for link in external: link['target'] = '_blank' #Get all info-tables and delete them infoTables = soup.find_all("table", class_="infobox") for table in infoTables: table.extract() return str(soup) def stripped(title): if(title[:10] == "Categorie:"): return title[10:] return title
Remove infobox, can be re-added if necessary
Remove infobox, can be re-added if necessary
Python
agpl-3.0
PerceptumNL/ReadMore,PerceptumNL/ReadMore,PerceptumNL/ReadMore,PerceptumNL/ReadMore
from django.core.urlresolvers import reverse from bs4 import BeautifulSoup def process_wiki_page_html(html): """Process the html of a wikipedia page to be used in ReadMore.""" #TODO: Write BeautifullSoup code to remove Edit links #TODO: Write BeautifullSoup code to alter local links, # use: reverse('wikipedia_article', args=(identifier,)) for new link # see also: https://docs.djangoproject.com/en/1.6/ref/urlresolvers/#django.core.urlresolvers.reverse soup = BeautifulSoup(html) #Find and remove all edit links edits = soup.find_all("span", class_="mw-editsection") for edit in edits: edit.extract() #Find and edit all internal links internal = soup.find_all("a") for link in internal: source = link.get('href') if source[0:5] == "/wiki": link['href'] = reverse('wikipedia_article', args=(source[6:],)) + "?type=title" #Find all external links and add target="_blank" external = soup.find_all("a", class_="external text") for link in external: link['target'] = '_blank' return str(soup) def stripped(title): if(title[:10] == "Categorie:"): return title[10:] return title Remove infobox, can be re-added if necessary
from django.core.urlresolvers import reverse from bs4 import BeautifulSoup def process_wiki_page_html(html): """Process the html of a wikipedia page to be used in ReadMore.""" #TODO: Write BeautifullSoup code to remove Edit links #TODO: Write BeautifullSoup code to alter local links, # use: reverse('wikipedia_article', args=(identifier,)) for new link # see also: https://docs.djangoproject.com/en/1.6/ref/urlresolvers/#django.core.urlresolvers.reverse soup = BeautifulSoup(html) #Find and remove all edit links edits = soup.find_all("span", class_="mw-editsection") for edit in edits: edit.extract() #Find and edit all internal links internal = soup.find_all("a") for link in internal: source = link.get('href') if source[0:5] == "/wiki": link['href'] = reverse('wikipedia_article', args=(source[6:],)) + "?type=title" #Find all external links and add target="_blank" external = soup.find_all("a", class_="external text") for link in external: link['target'] = '_blank' #Get all info-tables and delete them infoTables = soup.find_all("table", class_="infobox") for table in infoTables: table.extract() return str(soup) def stripped(title): if(title[:10] == "Categorie:"): return title[10:] return title
<commit_before>from django.core.urlresolvers import reverse from bs4 import BeautifulSoup def process_wiki_page_html(html): """Process the html of a wikipedia page to be used in ReadMore.""" #TODO: Write BeautifullSoup code to remove Edit links #TODO: Write BeautifullSoup code to alter local links, # use: reverse('wikipedia_article', args=(identifier,)) for new link # see also: https://docs.djangoproject.com/en/1.6/ref/urlresolvers/#django.core.urlresolvers.reverse soup = BeautifulSoup(html) #Find and remove all edit links edits = soup.find_all("span", class_="mw-editsection") for edit in edits: edit.extract() #Find and edit all internal links internal = soup.find_all("a") for link in internal: source = link.get('href') if source[0:5] == "/wiki": link['href'] = reverse('wikipedia_article', args=(source[6:],)) + "?type=title" #Find all external links and add target="_blank" external = soup.find_all("a", class_="external text") for link in external: link['target'] = '_blank' return str(soup) def stripped(title): if(title[:10] == "Categorie:"): return title[10:] return title <commit_msg>Remove infobox, can be re-added if necessary<commit_after>
from django.core.urlresolvers import reverse from bs4 import BeautifulSoup def process_wiki_page_html(html): """Process the html of a wikipedia page to be used in ReadMore.""" #TODO: Write BeautifullSoup code to remove Edit links #TODO: Write BeautifullSoup code to alter local links, # use: reverse('wikipedia_article', args=(identifier,)) for new link # see also: https://docs.djangoproject.com/en/1.6/ref/urlresolvers/#django.core.urlresolvers.reverse soup = BeautifulSoup(html) #Find and remove all edit links edits = soup.find_all("span", class_="mw-editsection") for edit in edits: edit.extract() #Find and edit all internal links internal = soup.find_all("a") for link in internal: source = link.get('href') if source[0:5] == "/wiki": link['href'] = reverse('wikipedia_article', args=(source[6:],)) + "?type=title" #Find all external links and add target="_blank" external = soup.find_all("a", class_="external text") for link in external: link['target'] = '_blank' #Get all info-tables and delete them infoTables = soup.find_all("table", class_="infobox") for table in infoTables: table.extract() return str(soup) def stripped(title): if(title[:10] == "Categorie:"): return title[10:] return title
from django.core.urlresolvers import reverse from bs4 import BeautifulSoup def process_wiki_page_html(html): """Process the html of a wikipedia page to be used in ReadMore.""" #TODO: Write BeautifullSoup code to remove Edit links #TODO: Write BeautifullSoup code to alter local links, # use: reverse('wikipedia_article', args=(identifier,)) for new link # see also: https://docs.djangoproject.com/en/1.6/ref/urlresolvers/#django.core.urlresolvers.reverse soup = BeautifulSoup(html) #Find and remove all edit links edits = soup.find_all("span", class_="mw-editsection") for edit in edits: edit.extract() #Find and edit all internal links internal = soup.find_all("a") for link in internal: source = link.get('href') if source[0:5] == "/wiki": link['href'] = reverse('wikipedia_article', args=(source[6:],)) + "?type=title" #Find all external links and add target="_blank" external = soup.find_all("a", class_="external text") for link in external: link['target'] = '_blank' return str(soup) def stripped(title): if(title[:10] == "Categorie:"): return title[10:] return title Remove infobox, can be re-added if necessaryfrom django.core.urlresolvers import reverse from bs4 import BeautifulSoup def process_wiki_page_html(html): """Process the html of a wikipedia page to be used in ReadMore.""" #TODO: Write BeautifullSoup code to remove Edit links #TODO: Write BeautifullSoup code to alter local links, # use: reverse('wikipedia_article', args=(identifier,)) for new link # see also: https://docs.djangoproject.com/en/1.6/ref/urlresolvers/#django.core.urlresolvers.reverse soup = BeautifulSoup(html) #Find and remove all edit links edits = soup.find_all("span", class_="mw-editsection") for edit in edits: edit.extract() #Find and edit all internal links internal = soup.find_all("a") for link in internal: source = link.get('href') if source[0:5] == "/wiki": link['href'] = reverse('wikipedia_article', args=(source[6:],)) + "?type=title" #Find all external links and add target="_blank" external = soup.find_all("a", class_="external text") for link in external: link['target'] = '_blank' #Get all info-tables and delete them infoTables = soup.find_all("table", class_="infobox") for table in infoTables: table.extract() return str(soup) def stripped(title): if(title[:10] == "Categorie:"): return title[10:] return title
<commit_before>from django.core.urlresolvers import reverse from bs4 import BeautifulSoup def process_wiki_page_html(html): """Process the html of a wikipedia page to be used in ReadMore.""" #TODO: Write BeautifullSoup code to remove Edit links #TODO: Write BeautifullSoup code to alter local links, # use: reverse('wikipedia_article', args=(identifier,)) for new link # see also: https://docs.djangoproject.com/en/1.6/ref/urlresolvers/#django.core.urlresolvers.reverse soup = BeautifulSoup(html) #Find and remove all edit links edits = soup.find_all("span", class_="mw-editsection") for edit in edits: edit.extract() #Find and edit all internal links internal = soup.find_all("a") for link in internal: source = link.get('href') if source[0:5] == "/wiki": link['href'] = reverse('wikipedia_article', args=(source[6:],)) + "?type=title" #Find all external links and add target="_blank" external = soup.find_all("a", class_="external text") for link in external: link['target'] = '_blank' return str(soup) def stripped(title): if(title[:10] == "Categorie:"): return title[10:] return title <commit_msg>Remove infobox, can be re-added if necessary<commit_after>from django.core.urlresolvers import reverse from bs4 import BeautifulSoup def process_wiki_page_html(html): """Process the html of a wikipedia page to be used in ReadMore.""" #TODO: Write BeautifullSoup code to remove Edit links #TODO: Write BeautifullSoup code to alter local links, # use: reverse('wikipedia_article', args=(identifier,)) for new link # see also: https://docs.djangoproject.com/en/1.6/ref/urlresolvers/#django.core.urlresolvers.reverse soup = BeautifulSoup(html) #Find and remove all edit links edits = soup.find_all("span", class_="mw-editsection") for edit in edits: edit.extract() #Find and edit all internal links internal = soup.find_all("a") for link in internal: source = link.get('href') if source[0:5] == "/wiki": link['href'] = reverse('wikipedia_article', args=(source[6:],)) + "?type=title" #Find all external links and add target="_blank" external = soup.find_all("a", class_="external text") for link in external: link['target'] = '_blank' #Get all info-tables and delete them infoTables = soup.find_all("table", class_="infobox") for table in infoTables: table.extract() return str(soup) def stripped(title): if(title[:10] == "Categorie:"): return title[10:] return title
a75a6e071e532d981fe8e11bf3c1d33a3356578d
astropy/io/misc/tests/test_pandas.py
astropy/io/misc/tests/test_pandas.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst from io import StringIO import pytest import numpy as np from astropy.io import ascii from astropy.table import Table, QTable from astropy import units as u from astropy.coordinates import SkyCoord from astropy.io.misc.pandas.connect import PANDAS_FMTS pandas = pytest.importorskip("pandas") WRITE_FMTS = [fmt for fmt in PANDAS_FMTS if 'write' in PANDAS_FMTS[fmt]] @pytest.mark.parametrize('fmt', WRITE_FMTS) def test_read_write_format(fmt): """ Test round-trip through pandas write/read for supported formats. :param fmt: format name, e.g. csv, html, json :return: """ pandas_fmt = 'pandas.' + fmt t = Table([[1, 2, 3], [1.0, 2.5, 5.0], ['a', 'b', 'c']]) buf = StringIO() t.write(buf, format=pandas_fmt) buf.seek(0) t2 = Table.read(buf, format=pandas_fmt) assert t.colnames == t2.colnames assert np.all(t == t2) def test_read_fixed_width_format(): """Test reading with pandas read_fwf() """ tbl = """\ a b c 1 2.0 a 2 3.0 b""" buf = StringIO() buf.write(tbl) t = Table.read(tbl, format='ascii', guess=False) buf.seek(0) t2 = Table.read(buf, format='pandas.fwf') assert t.colnames == t2.colnames assert np.all(t == t2) def test_write_with_mixins(): """Writing a table with mixins just drops them via to_pandas() This also tests passing a kwarg to pandas read and write. """ sc = SkyCoord([1, 2], [3, 4], unit='deg') q = [5, 6] * u.m qt = QTable([[1, 2], q, sc], names=['i', 'q', 'sc']) buf = StringIO() qt.write(buf, format='pandas.csv', sep=' ') exp = ['i q sc.ra sc.dec', '1 5.0 1.0 3.0', '2 6.0 2.0 4.0'] assert buf.getvalue().splitlines() == exp # Read it back buf.seek(0) qt2 = Table.read(buf, format='pandas.csv', sep=' ') exp_t = ascii.read(exp) assert qt2.colnames == exp_t.colnames assert np.all(qt2 == exp_t)
Add tests of pandas backend
Add tests of pandas backend
Python
bsd-3-clause
stargaser/astropy,astropy/astropy,lpsinger/astropy,StuartLittlefair/astropy,bsipocz/astropy,astropy/astropy,aleksandr-bakanov/astropy,bsipocz/astropy,MSeifert04/astropy,pllim/astropy,stargaser/astropy,MSeifert04/astropy,aleksandr-bakanov/astropy,stargaser/astropy,saimn/astropy,lpsinger/astropy,pllim/astropy,lpsinger/astropy,MSeifert04/astropy,stargaser/astropy,MSeifert04/astropy,larrybradley/astropy,pllim/astropy,aleksandr-bakanov/astropy,saimn/astropy,saimn/astropy,mhvk/astropy,aleksandr-bakanov/astropy,lpsinger/astropy,saimn/astropy,mhvk/astropy,StuartLittlefair/astropy,dhomeier/astropy,larrybradley/astropy,mhvk/astropy,dhomeier/astropy,mhvk/astropy,larrybradley/astropy,StuartLittlefair/astropy,dhomeier/astropy,larrybradley/astropy,astropy/astropy,pllim/astropy,bsipocz/astropy,pllim/astropy,StuartLittlefair/astropy,dhomeier/astropy,bsipocz/astropy,mhvk/astropy,astropy/astropy,dhomeier/astropy,lpsinger/astropy,larrybradley/astropy,saimn/astropy,astropy/astropy,StuartLittlefair/astropy
Add tests of pandas backend
# Licensed under a 3-clause BSD style license - see LICENSE.rst from io import StringIO import pytest import numpy as np from astropy.io import ascii from astropy.table import Table, QTable from astropy import units as u from astropy.coordinates import SkyCoord from astropy.io.misc.pandas.connect import PANDAS_FMTS pandas = pytest.importorskip("pandas") WRITE_FMTS = [fmt for fmt in PANDAS_FMTS if 'write' in PANDAS_FMTS[fmt]] @pytest.mark.parametrize('fmt', WRITE_FMTS) def test_read_write_format(fmt): """ Test round-trip through pandas write/read for supported formats. :param fmt: format name, e.g. csv, html, json :return: """ pandas_fmt = 'pandas.' + fmt t = Table([[1, 2, 3], [1.0, 2.5, 5.0], ['a', 'b', 'c']]) buf = StringIO() t.write(buf, format=pandas_fmt) buf.seek(0) t2 = Table.read(buf, format=pandas_fmt) assert t.colnames == t2.colnames assert np.all(t == t2) def test_read_fixed_width_format(): """Test reading with pandas read_fwf() """ tbl = """\ a b c 1 2.0 a 2 3.0 b""" buf = StringIO() buf.write(tbl) t = Table.read(tbl, format='ascii', guess=False) buf.seek(0) t2 = Table.read(buf, format='pandas.fwf') assert t.colnames == t2.colnames assert np.all(t == t2) def test_write_with_mixins(): """Writing a table with mixins just drops them via to_pandas() This also tests passing a kwarg to pandas read and write. """ sc = SkyCoord([1, 2], [3, 4], unit='deg') q = [5, 6] * u.m qt = QTable([[1, 2], q, sc], names=['i', 'q', 'sc']) buf = StringIO() qt.write(buf, format='pandas.csv', sep=' ') exp = ['i q sc.ra sc.dec', '1 5.0 1.0 3.0', '2 6.0 2.0 4.0'] assert buf.getvalue().splitlines() == exp # Read it back buf.seek(0) qt2 = Table.read(buf, format='pandas.csv', sep=' ') exp_t = ascii.read(exp) assert qt2.colnames == exp_t.colnames assert np.all(qt2 == exp_t)
<commit_before><commit_msg>Add tests of pandas backend<commit_after>
# Licensed under a 3-clause BSD style license - see LICENSE.rst from io import StringIO import pytest import numpy as np from astropy.io import ascii from astropy.table import Table, QTable from astropy import units as u from astropy.coordinates import SkyCoord from astropy.io.misc.pandas.connect import PANDAS_FMTS pandas = pytest.importorskip("pandas") WRITE_FMTS = [fmt for fmt in PANDAS_FMTS if 'write' in PANDAS_FMTS[fmt]] @pytest.mark.parametrize('fmt', WRITE_FMTS) def test_read_write_format(fmt): """ Test round-trip through pandas write/read for supported formats. :param fmt: format name, e.g. csv, html, json :return: """ pandas_fmt = 'pandas.' + fmt t = Table([[1, 2, 3], [1.0, 2.5, 5.0], ['a', 'b', 'c']]) buf = StringIO() t.write(buf, format=pandas_fmt) buf.seek(0) t2 = Table.read(buf, format=pandas_fmt) assert t.colnames == t2.colnames assert np.all(t == t2) def test_read_fixed_width_format(): """Test reading with pandas read_fwf() """ tbl = """\ a b c 1 2.0 a 2 3.0 b""" buf = StringIO() buf.write(tbl) t = Table.read(tbl, format='ascii', guess=False) buf.seek(0) t2 = Table.read(buf, format='pandas.fwf') assert t.colnames == t2.colnames assert np.all(t == t2) def test_write_with_mixins(): """Writing a table with mixins just drops them via to_pandas() This also tests passing a kwarg to pandas read and write. """ sc = SkyCoord([1, 2], [3, 4], unit='deg') q = [5, 6] * u.m qt = QTable([[1, 2], q, sc], names=['i', 'q', 'sc']) buf = StringIO() qt.write(buf, format='pandas.csv', sep=' ') exp = ['i q sc.ra sc.dec', '1 5.0 1.0 3.0', '2 6.0 2.0 4.0'] assert buf.getvalue().splitlines() == exp # Read it back buf.seek(0) qt2 = Table.read(buf, format='pandas.csv', sep=' ') exp_t = ascii.read(exp) assert qt2.colnames == exp_t.colnames assert np.all(qt2 == exp_t)
Add tests of pandas backend# Licensed under a 3-clause BSD style license - see LICENSE.rst from io import StringIO import pytest import numpy as np from astropy.io import ascii from astropy.table import Table, QTable from astropy import units as u from astropy.coordinates import SkyCoord from astropy.io.misc.pandas.connect import PANDAS_FMTS pandas = pytest.importorskip("pandas") WRITE_FMTS = [fmt for fmt in PANDAS_FMTS if 'write' in PANDAS_FMTS[fmt]] @pytest.mark.parametrize('fmt', WRITE_FMTS) def test_read_write_format(fmt): """ Test round-trip through pandas write/read for supported formats. :param fmt: format name, e.g. csv, html, json :return: """ pandas_fmt = 'pandas.' + fmt t = Table([[1, 2, 3], [1.0, 2.5, 5.0], ['a', 'b', 'c']]) buf = StringIO() t.write(buf, format=pandas_fmt) buf.seek(0) t2 = Table.read(buf, format=pandas_fmt) assert t.colnames == t2.colnames assert np.all(t == t2) def test_read_fixed_width_format(): """Test reading with pandas read_fwf() """ tbl = """\ a b c 1 2.0 a 2 3.0 b""" buf = StringIO() buf.write(tbl) t = Table.read(tbl, format='ascii', guess=False) buf.seek(0) t2 = Table.read(buf, format='pandas.fwf') assert t.colnames == t2.colnames assert np.all(t == t2) def test_write_with_mixins(): """Writing a table with mixins just drops them via to_pandas() This also tests passing a kwarg to pandas read and write. """ sc = SkyCoord([1, 2], [3, 4], unit='deg') q = [5, 6] * u.m qt = QTable([[1, 2], q, sc], names=['i', 'q', 'sc']) buf = StringIO() qt.write(buf, format='pandas.csv', sep=' ') exp = ['i q sc.ra sc.dec', '1 5.0 1.0 3.0', '2 6.0 2.0 4.0'] assert buf.getvalue().splitlines() == exp # Read it back buf.seek(0) qt2 = Table.read(buf, format='pandas.csv', sep=' ') exp_t = ascii.read(exp) assert qt2.colnames == exp_t.colnames assert np.all(qt2 == exp_t)
<commit_before><commit_msg>Add tests of pandas backend<commit_after># Licensed under a 3-clause BSD style license - see LICENSE.rst from io import StringIO import pytest import numpy as np from astropy.io import ascii from astropy.table import Table, QTable from astropy import units as u from astropy.coordinates import SkyCoord from astropy.io.misc.pandas.connect import PANDAS_FMTS pandas = pytest.importorskip("pandas") WRITE_FMTS = [fmt for fmt in PANDAS_FMTS if 'write' in PANDAS_FMTS[fmt]] @pytest.mark.parametrize('fmt', WRITE_FMTS) def test_read_write_format(fmt): """ Test round-trip through pandas write/read for supported formats. :param fmt: format name, e.g. csv, html, json :return: """ pandas_fmt = 'pandas.' + fmt t = Table([[1, 2, 3], [1.0, 2.5, 5.0], ['a', 'b', 'c']]) buf = StringIO() t.write(buf, format=pandas_fmt) buf.seek(0) t2 = Table.read(buf, format=pandas_fmt) assert t.colnames == t2.colnames assert np.all(t == t2) def test_read_fixed_width_format(): """Test reading with pandas read_fwf() """ tbl = """\ a b c 1 2.0 a 2 3.0 b""" buf = StringIO() buf.write(tbl) t = Table.read(tbl, format='ascii', guess=False) buf.seek(0) t2 = Table.read(buf, format='pandas.fwf') assert t.colnames == t2.colnames assert np.all(t == t2) def test_write_with_mixins(): """Writing a table with mixins just drops them via to_pandas() This also tests passing a kwarg to pandas read and write. """ sc = SkyCoord([1, 2], [3, 4], unit='deg') q = [5, 6] * u.m qt = QTable([[1, 2], q, sc], names=['i', 'q', 'sc']) buf = StringIO() qt.write(buf, format='pandas.csv', sep=' ') exp = ['i q sc.ra sc.dec', '1 5.0 1.0 3.0', '2 6.0 2.0 4.0'] assert buf.getvalue().splitlines() == exp # Read it back buf.seek(0) qt2 = Table.read(buf, format='pandas.csv', sep=' ') exp_t = ascii.read(exp) assert qt2.colnames == exp_t.colnames assert np.all(qt2 == exp_t)
a5ec7be50e2ce2424883b859ff99fd77ff09f997
fabfile.py
fabfile.py
# Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master')
# Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master') # Remote Commands from fabric.api import cd, env, run env.hosts = [ 'vagrant@192.168.66.77:22', ] env.passwords = { 'vagrant@192.168.66.77:22': 'vagrant' } def create_empty_file(name='test'): env.forward_agent = True run('touch ' + name) run('ls -al') # ssh-add ~/.ssh/thaipy-demo.pem since accessing EC2 requires a key pair def my_ec2(): env.hosts = [ 'ubuntu@54.251.184.112:22', ]
Add remote commands for vagrant and ec2
Add remote commands for vagrant and ec2
Python
mit
zkan/fabric-workshop,zkan/fabric-workshop
# Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master') Add remote commands for vagrant and ec2
# Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master') # Remote Commands from fabric.api import cd, env, run env.hosts = [ 'vagrant@192.168.66.77:22', ] env.passwords = { 'vagrant@192.168.66.77:22': 'vagrant' } def create_empty_file(name='test'): env.forward_agent = True run('touch ' + name) run('ls -al') # ssh-add ~/.ssh/thaipy-demo.pem since accessing EC2 requires a key pair def my_ec2(): env.hosts = [ 'ubuntu@54.251.184.112:22', ]
<commit_before># Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master') <commit_msg>Add remote commands for vagrant and ec2<commit_after>
# Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master') # Remote Commands from fabric.api import cd, env, run env.hosts = [ 'vagrant@192.168.66.77:22', ] env.passwords = { 'vagrant@192.168.66.77:22': 'vagrant' } def create_empty_file(name='test'): env.forward_agent = True run('touch ' + name) run('ls -al') # ssh-add ~/.ssh/thaipy-demo.pem since accessing EC2 requires a key pair def my_ec2(): env.hosts = [ 'ubuntu@54.251.184.112:22', ]
# Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master') Add remote commands for vagrant and ec2# Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master') # Remote Commands from fabric.api import cd, env, run env.hosts = [ 'vagrant@192.168.66.77:22', ] env.passwords = { 'vagrant@192.168.66.77:22': 'vagrant' } def create_empty_file(name='test'): env.forward_agent = True run('touch ' + name) run('ls -al') # ssh-add ~/.ssh/thaipy-demo.pem since accessing EC2 requires a key pair def my_ec2(): env.hosts = [ 'ubuntu@54.251.184.112:22', ]
<commit_before># Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master') <commit_msg>Add remote commands for vagrant and ec2<commit_after># Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master') # Remote Commands from fabric.api import cd, env, run env.hosts = [ 'vagrant@192.168.66.77:22', ] env.passwords = { 'vagrant@192.168.66.77:22': 'vagrant' } def create_empty_file(name='test'): env.forward_agent = True run('touch ' + name) run('ls -al') # ssh-add ~/.ssh/thaipy-demo.pem since accessing EC2 requires a key pair def my_ec2(): env.hosts = [ 'ubuntu@54.251.184.112:22', ]
36c6b7e70c21b261dcb39568a17fd1cd353a25db
htmlify.py
htmlify.py
def getHTML(tag, contents=None, newLine=True, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): construct += " " + paramName + "=" + paramContent if contents is not None: construct += ">" + contents + "</" + tag + ">" else: construct += ">" + "</" + tag + ">" if newLine: return construct + "\n" else: return construct def dispHTML(tag, contents=None, **parameters): construct = getHTML(tag, contents=contents, **parameters) print(construct) def startTag(tag, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): construct += " " + paramName + "=" + paramContent construct += ">" print(construct + "\n") def endTag(tag): print("</" + tag + ">")
def getHTML(tag, contents=None, newLine=True, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): if type(paramContent) == str: construct += " " + paramName + "=\"" + paramContent + "\"" if contents is not None: construct += ">" + contents + "</" + tag + ">" else: construct += ">" + "</" + tag + ">" if newLine: return construct + "\n" else: return construct def dispHTML(tag, contents=None, **parameters): construct = getHTML(tag, contents=contents, **parameters) print(construct) def startTag(tag, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): if type(paramContent) == str: construct += " " + paramName + "=\"" + paramContent + "\"" construct += ">" print(construct + "\n") def endTag(tag): print("</" + tag + ">")
Add quotes to values htmlified
Add quotes to values htmlified
Python
apache-2.0
ISD-Sound-and-Lights/InventoryControl
def getHTML(tag, contents=None, newLine=True, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): construct += " " + paramName + "=" + paramContent if contents is not None: construct += ">" + contents + "</" + tag + ">" else: construct += ">" + "</" + tag + ">" if newLine: return construct + "\n" else: return construct def dispHTML(tag, contents=None, **parameters): construct = getHTML(tag, contents=contents, **parameters) print(construct) def startTag(tag, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): construct += " " + paramName + "=" + paramContent construct += ">" print(construct + "\n") def endTag(tag): print("</" + tag + ">") Add quotes to values htmlified
def getHTML(tag, contents=None, newLine=True, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): if type(paramContent) == str: construct += " " + paramName + "=\"" + paramContent + "\"" if contents is not None: construct += ">" + contents + "</" + tag + ">" else: construct += ">" + "</" + tag + ">" if newLine: return construct + "\n" else: return construct def dispHTML(tag, contents=None, **parameters): construct = getHTML(tag, contents=contents, **parameters) print(construct) def startTag(tag, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): if type(paramContent) == str: construct += " " + paramName + "=\"" + paramContent + "\"" construct += ">" print(construct + "\n") def endTag(tag): print("</" + tag + ">")
<commit_before>def getHTML(tag, contents=None, newLine=True, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): construct += " " + paramName + "=" + paramContent if contents is not None: construct += ">" + contents + "</" + tag + ">" else: construct += ">" + "</" + tag + ">" if newLine: return construct + "\n" else: return construct def dispHTML(tag, contents=None, **parameters): construct = getHTML(tag, contents=contents, **parameters) print(construct) def startTag(tag, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): construct += " " + paramName + "=" + paramContent construct += ">" print(construct + "\n") def endTag(tag): print("</" + tag + ">") <commit_msg>Add quotes to values htmlified<commit_after>
def getHTML(tag, contents=None, newLine=True, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): if type(paramContent) == str: construct += " " + paramName + "=\"" + paramContent + "\"" if contents is not None: construct += ">" + contents + "</" + tag + ">" else: construct += ">" + "</" + tag + ">" if newLine: return construct + "\n" else: return construct def dispHTML(tag, contents=None, **parameters): construct = getHTML(tag, contents=contents, **parameters) print(construct) def startTag(tag, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): if type(paramContent) == str: construct += " " + paramName + "=\"" + paramContent + "\"" construct += ">" print(construct + "\n") def endTag(tag): print("</" + tag + ">")
def getHTML(tag, contents=None, newLine=True, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): construct += " " + paramName + "=" + paramContent if contents is not None: construct += ">" + contents + "</" + tag + ">" else: construct += ">" + "</" + tag + ">" if newLine: return construct + "\n" else: return construct def dispHTML(tag, contents=None, **parameters): construct = getHTML(tag, contents=contents, **parameters) print(construct) def startTag(tag, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): construct += " " + paramName + "=" + paramContent construct += ">" print(construct + "\n") def endTag(tag): print("</" + tag + ">") Add quotes to values htmlifieddef getHTML(tag, contents=None, newLine=True, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): if type(paramContent) == str: construct += " " + paramName + "=\"" + paramContent + "\"" if contents is not None: construct += ">" + contents + "</" + tag + ">" else: construct += ">" + "</" + tag + ">" if newLine: return construct + "\n" else: return construct def dispHTML(tag, contents=None, **parameters): construct = getHTML(tag, contents=contents, **parameters) print(construct) def startTag(tag, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): if type(paramContent) == str: construct += " " + paramName + "=\"" + paramContent + "\"" construct += ">" print(construct + "\n") def endTag(tag): print("</" + tag + ">")
<commit_before>def getHTML(tag, contents=None, newLine=True, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): construct += " " + paramName + "=" + paramContent if contents is not None: construct += ">" + contents + "</" + tag + ">" else: construct += ">" + "</" + tag + ">" if newLine: return construct + "\n" else: return construct def dispHTML(tag, contents=None, **parameters): construct = getHTML(tag, contents=contents, **parameters) print(construct) def startTag(tag, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): construct += " " + paramName + "=" + paramContent construct += ">" print(construct + "\n") def endTag(tag): print("</" + tag + ">") <commit_msg>Add quotes to values htmlified<commit_after>def getHTML(tag, contents=None, newLine=True, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): if type(paramContent) == str: construct += " " + paramName + "=\"" + paramContent + "\"" if contents is not None: construct += ">" + contents + "</" + tag + ">" else: construct += ">" + "</" + tag + ">" if newLine: return construct + "\n" else: return construct def dispHTML(tag, contents=None, **parameters): construct = getHTML(tag, contents=contents, **parameters) print(construct) def startTag(tag, **parameters): construct = "<" + tag for paramName, paramContent in parameters.items(): if type(paramContent) == str: construct += " " + paramName + "=\"" + paramContent + "\"" construct += ">" print(construct + "\n") def endTag(tag): print("</" + tag + ">")
a2854d7bb90fa8e31afb86111f2f003d2b25fb90
scripts/data_download/higher_education/create_all_files.py
scripts/data_download/higher_education/create_all_files.py
import os import commands import time import logging import sys if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']): print "ERROR! Use:\n python scripts/data_download/higher_education/create_files.py en/pt output_path\n" exit() for year in range(2009, 2015): print "python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year) # commands.getoutput("python scripts/data_download/higher_education/create_files.py "+sys.argv[1]+" "+sys.argv[2]+" "+sys.argv[3])
import os import commands import time import logging import sys if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']): print "ERROR! Use:\n python scripts/data_download/higher_education/create_files.py en/pt output_path\n" exit() logging.basicConfig(filename=os.path.abspath(os.path.join(sys.argv[2],str(sys.argv[0].split('/')[2]) + '-all-data-download.log' )),level=logging.DEBUG) for year in range(2009, 2015): logging.info("python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year) + "\n") ret = commands.getoutput("python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year)) logging.info(str(ret) + "\nYear: " + str(year) + " ok =D\n\n")
Add file to create all files to higher education.
Add file to create all files to higher education.
Python
mit
DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site
import os import commands import time import logging import sys if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']): print "ERROR! Use:\n python scripts/data_download/higher_education/create_files.py en/pt output_path\n" exit() for year in range(2009, 2015): print "python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year) # commands.getoutput("python scripts/data_download/higher_education/create_files.py "+sys.argv[1]+" "+sys.argv[2]+" "+sys.argv[3]) Add file to create all files to higher education.
import os import commands import time import logging import sys if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']): print "ERROR! Use:\n python scripts/data_download/higher_education/create_files.py en/pt output_path\n" exit() logging.basicConfig(filename=os.path.abspath(os.path.join(sys.argv[2],str(sys.argv[0].split('/')[2]) + '-all-data-download.log' )),level=logging.DEBUG) for year in range(2009, 2015): logging.info("python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year) + "\n") ret = commands.getoutput("python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year)) logging.info(str(ret) + "\nYear: " + str(year) + " ok =D\n\n")
<commit_before>import os import commands import time import logging import sys if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']): print "ERROR! Use:\n python scripts/data_download/higher_education/create_files.py en/pt output_path\n" exit() for year in range(2009, 2015): print "python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year) # commands.getoutput("python scripts/data_download/higher_education/create_files.py "+sys.argv[1]+" "+sys.argv[2]+" "+sys.argv[3]) <commit_msg>Add file to create all files to higher education.<commit_after>
import os import commands import time import logging import sys if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']): print "ERROR! Use:\n python scripts/data_download/higher_education/create_files.py en/pt output_path\n" exit() logging.basicConfig(filename=os.path.abspath(os.path.join(sys.argv[2],str(sys.argv[0].split('/')[2]) + '-all-data-download.log' )),level=logging.DEBUG) for year in range(2009, 2015): logging.info("python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year) + "\n") ret = commands.getoutput("python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year)) logging.info(str(ret) + "\nYear: " + str(year) + " ok =D\n\n")
import os import commands import time import logging import sys if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']): print "ERROR! Use:\n python scripts/data_download/higher_education/create_files.py en/pt output_path\n" exit() for year in range(2009, 2015): print "python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year) # commands.getoutput("python scripts/data_download/higher_education/create_files.py "+sys.argv[1]+" "+sys.argv[2]+" "+sys.argv[3]) Add file to create all files to higher education.import os import commands import time import logging import sys if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']): print "ERROR! Use:\n python scripts/data_download/higher_education/create_files.py en/pt output_path\n" exit() logging.basicConfig(filename=os.path.abspath(os.path.join(sys.argv[2],str(sys.argv[0].split('/')[2]) + '-all-data-download.log' )),level=logging.DEBUG) for year in range(2009, 2015): logging.info("python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year) + "\n") ret = commands.getoutput("python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year)) logging.info(str(ret) + "\nYear: " + str(year) + " ok =D\n\n")
<commit_before>import os import commands import time import logging import sys if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']): print "ERROR! Use:\n python scripts/data_download/higher_education/create_files.py en/pt output_path\n" exit() for year in range(2009, 2015): print "python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year) # commands.getoutput("python scripts/data_download/higher_education/create_files.py "+sys.argv[1]+" "+sys.argv[2]+" "+sys.argv[3]) <commit_msg>Add file to create all files to higher education.<commit_after>import os import commands import time import logging import sys if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']): print "ERROR! Use:\n python scripts/data_download/higher_education/create_files.py en/pt output_path\n" exit() logging.basicConfig(filename=os.path.abspath(os.path.join(sys.argv[2],str(sys.argv[0].split('/')[2]) + '-all-data-download.log' )),level=logging.DEBUG) for year in range(2009, 2015): logging.info("python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year) + "\n") ret = commands.getoutput("python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year)) logging.info(str(ret) + "\nYear: " + str(year) + " ok =D\n\n")