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
1ba0f715a0730dbc575bd1998f2edc69fab60fc5
project_task_add_very_high/__openerp__.py
project_task_add_very_high/__openerp__.py
# -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein", "license": "AGPL-3", "category": "Project Management", "website": "http://www.onestein.eu", "depends": ["project"], "installable": True, "uninstall_hook": "uninstall_hook" }
# -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein, Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Project Management", "website": "http://www.onestein.eu", "depends": ["project"], "installable": True, "uninstall_hook": "uninstall_hook" }
Add OCA in authors list
Add OCA in authors list
Python
agpl-3.0
ddico/project,OCA/project-service,dreispt/project-service,NeovaHealth/project-service,dreispt/project,acsone/project,acsone/project-service
# -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein", "license": "AGPL-3", "category": "Project Management", "website": "http://www.onestein.eu", "depends": ["project"], "installable": True, "uninstall_hook": "uninstall_hook" } Add OCA in authors list
# -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein, Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Project Management", "website": "http://www.onestein.eu", "depends": ["project"], "installable": True, "uninstall_hook": "uninstall_hook" }
<commit_before># -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein", "license": "AGPL-3", "category": "Project Management", "website": "http://www.onestein.eu", "depends": ["project"], "installable": True, "uninstall_hook": "uninstall_hook" } <commit_msg>Add OCA in authors list<commit_after>
# -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein, Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Project Management", "website": "http://www.onestein.eu", "depends": ["project"], "installable": True, "uninstall_hook": "uninstall_hook" }
# -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein", "license": "AGPL-3", "category": "Project Management", "website": "http://www.onestein.eu", "depends": ["project"], "installable": True, "uninstall_hook": "uninstall_hook" } Add OCA in authors list# -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein, Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Project Management", "website": "http://www.onestein.eu", "depends": ["project"], "installable": True, "uninstall_hook": "uninstall_hook" }
<commit_before># -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein", "license": "AGPL-3", "category": "Project Management", "website": "http://www.onestein.eu", "depends": ["project"], "installable": True, "uninstall_hook": "uninstall_hook" } <commit_msg>Add OCA in authors list<commit_after># -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein, Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Project Management", "website": "http://www.onestein.eu", "depends": ["project"], "installable": True, "uninstall_hook": "uninstall_hook" }
729a814f976ceffba0092ba56efca8ccea06e6e6
apps/profiles/views.py
apps/profiles/views.py
from django.views.generic import DetailView, UpdateView from django.core.urlresolvers import reverse_lazy from braces.views import LoginRequiredMixin from .models import User from .forms import ProfileUpdateForm class ProfileDetailView(DetailView): ''' Displays the user profile information ''' model = User slug_field = 'username' slug_url_kwarg = 'username' class ProfileUpdateView(LoginRequiredMixin, UpdateView): model = User slug_field = 'username' slug_url_kwarg = 'username' form_class = ProfileUpdateForm def get_queryset(self): queryset = super(ProfileUpdateView, self).get_queryset() return queryset.filter(pk=self.request.user.pk) def get_success_url(self): return reverse_lazy('profile_update', args=[self.object.username])
from django.views.generic import DetailView, UpdateView from django.core.urlresolvers import reverse_lazy from django.contrib import messages from django.utils.translation import ugettext_lazy as _ from braces.views import LoginRequiredMixin from .models import User from .forms import ProfileUpdateForm class ProfileDetailView(DetailView): ''' Displays the user profile information ''' model = User slug_field = 'username' slug_url_kwarg = 'username' class ProfileUpdateView(LoginRequiredMixin, UpdateView): model = User slug_field = 'username' slug_url_kwarg = 'username' form_class = ProfileUpdateForm def get_queryset(self): queryset = super(ProfileUpdateView, self).get_queryset() return queryset.filter(pk=self.request.user.pk) def get_success_url(self): return reverse_lazy('profile_update', args=[self.object.username]) def form_valid(self, *args, **kwargs): messages.success(self.request, _('Perfil guardado con exito')) return super(ProfileUpdateView, self).form_valid(*args, **kwargs)
Add message on profile form save
Add message on profile form save
Python
mit
SoPR/horas,SoPR/horas,SoPR/horas,SoPR/horas
from django.views.generic import DetailView, UpdateView from django.core.urlresolvers import reverse_lazy from braces.views import LoginRequiredMixin from .models import User from .forms import ProfileUpdateForm class ProfileDetailView(DetailView): ''' Displays the user profile information ''' model = User slug_field = 'username' slug_url_kwarg = 'username' class ProfileUpdateView(LoginRequiredMixin, UpdateView): model = User slug_field = 'username' slug_url_kwarg = 'username' form_class = ProfileUpdateForm def get_queryset(self): queryset = super(ProfileUpdateView, self).get_queryset() return queryset.filter(pk=self.request.user.pk) def get_success_url(self): return reverse_lazy('profile_update', args=[self.object.username]) Add message on profile form save
from django.views.generic import DetailView, UpdateView from django.core.urlresolvers import reverse_lazy from django.contrib import messages from django.utils.translation import ugettext_lazy as _ from braces.views import LoginRequiredMixin from .models import User from .forms import ProfileUpdateForm class ProfileDetailView(DetailView): ''' Displays the user profile information ''' model = User slug_field = 'username' slug_url_kwarg = 'username' class ProfileUpdateView(LoginRequiredMixin, UpdateView): model = User slug_field = 'username' slug_url_kwarg = 'username' form_class = ProfileUpdateForm def get_queryset(self): queryset = super(ProfileUpdateView, self).get_queryset() return queryset.filter(pk=self.request.user.pk) def get_success_url(self): return reverse_lazy('profile_update', args=[self.object.username]) def form_valid(self, *args, **kwargs): messages.success(self.request, _('Perfil guardado con exito')) return super(ProfileUpdateView, self).form_valid(*args, **kwargs)
<commit_before>from django.views.generic import DetailView, UpdateView from django.core.urlresolvers import reverse_lazy from braces.views import LoginRequiredMixin from .models import User from .forms import ProfileUpdateForm class ProfileDetailView(DetailView): ''' Displays the user profile information ''' model = User slug_field = 'username' slug_url_kwarg = 'username' class ProfileUpdateView(LoginRequiredMixin, UpdateView): model = User slug_field = 'username' slug_url_kwarg = 'username' form_class = ProfileUpdateForm def get_queryset(self): queryset = super(ProfileUpdateView, self).get_queryset() return queryset.filter(pk=self.request.user.pk) def get_success_url(self): return reverse_lazy('profile_update', args=[self.object.username]) <commit_msg>Add message on profile form save<commit_after>
from django.views.generic import DetailView, UpdateView from django.core.urlresolvers import reverse_lazy from django.contrib import messages from django.utils.translation import ugettext_lazy as _ from braces.views import LoginRequiredMixin from .models import User from .forms import ProfileUpdateForm class ProfileDetailView(DetailView): ''' Displays the user profile information ''' model = User slug_field = 'username' slug_url_kwarg = 'username' class ProfileUpdateView(LoginRequiredMixin, UpdateView): model = User slug_field = 'username' slug_url_kwarg = 'username' form_class = ProfileUpdateForm def get_queryset(self): queryset = super(ProfileUpdateView, self).get_queryset() return queryset.filter(pk=self.request.user.pk) def get_success_url(self): return reverse_lazy('profile_update', args=[self.object.username]) def form_valid(self, *args, **kwargs): messages.success(self.request, _('Perfil guardado con exito')) return super(ProfileUpdateView, self).form_valid(*args, **kwargs)
from django.views.generic import DetailView, UpdateView from django.core.urlresolvers import reverse_lazy from braces.views import LoginRequiredMixin from .models import User from .forms import ProfileUpdateForm class ProfileDetailView(DetailView): ''' Displays the user profile information ''' model = User slug_field = 'username' slug_url_kwarg = 'username' class ProfileUpdateView(LoginRequiredMixin, UpdateView): model = User slug_field = 'username' slug_url_kwarg = 'username' form_class = ProfileUpdateForm def get_queryset(self): queryset = super(ProfileUpdateView, self).get_queryset() return queryset.filter(pk=self.request.user.pk) def get_success_url(self): return reverse_lazy('profile_update', args=[self.object.username]) Add message on profile form savefrom django.views.generic import DetailView, UpdateView from django.core.urlresolvers import reverse_lazy from django.contrib import messages from django.utils.translation import ugettext_lazy as _ from braces.views import LoginRequiredMixin from .models import User from .forms import ProfileUpdateForm class ProfileDetailView(DetailView): ''' Displays the user profile information ''' model = User slug_field = 'username' slug_url_kwarg = 'username' class ProfileUpdateView(LoginRequiredMixin, UpdateView): model = User slug_field = 'username' slug_url_kwarg = 'username' form_class = ProfileUpdateForm def get_queryset(self): queryset = super(ProfileUpdateView, self).get_queryset() return queryset.filter(pk=self.request.user.pk) def get_success_url(self): return reverse_lazy('profile_update', args=[self.object.username]) def form_valid(self, *args, **kwargs): messages.success(self.request, _('Perfil guardado con exito')) return super(ProfileUpdateView, self).form_valid(*args, **kwargs)
<commit_before>from django.views.generic import DetailView, UpdateView from django.core.urlresolvers import reverse_lazy from braces.views import LoginRequiredMixin from .models import User from .forms import ProfileUpdateForm class ProfileDetailView(DetailView): ''' Displays the user profile information ''' model = User slug_field = 'username' slug_url_kwarg = 'username' class ProfileUpdateView(LoginRequiredMixin, UpdateView): model = User slug_field = 'username' slug_url_kwarg = 'username' form_class = ProfileUpdateForm def get_queryset(self): queryset = super(ProfileUpdateView, self).get_queryset() return queryset.filter(pk=self.request.user.pk) def get_success_url(self): return reverse_lazy('profile_update', args=[self.object.username]) <commit_msg>Add message on profile form save<commit_after>from django.views.generic import DetailView, UpdateView from django.core.urlresolvers import reverse_lazy from django.contrib import messages from django.utils.translation import ugettext_lazy as _ from braces.views import LoginRequiredMixin from .models import User from .forms import ProfileUpdateForm class ProfileDetailView(DetailView): ''' Displays the user profile information ''' model = User slug_field = 'username' slug_url_kwarg = 'username' class ProfileUpdateView(LoginRequiredMixin, UpdateView): model = User slug_field = 'username' slug_url_kwarg = 'username' form_class = ProfileUpdateForm def get_queryset(self): queryset = super(ProfileUpdateView, self).get_queryset() return queryset.filter(pk=self.request.user.pk) def get_success_url(self): return reverse_lazy('profile_update', args=[self.object.username]) def form_valid(self, *args, **kwargs): messages.success(self.request, _('Perfil guardado con exito')) return super(ProfileUpdateView, self).form_valid(*args, **kwargs)
a662475e148b8ccd3186303cebdc0615ae2dab1b
asyncmongo/__init__.py
asyncmongo/__init__.py
#!/bin/env python # # Copyright 2010 bit.ly # # 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. """ AsyncMongo is an asynchronous library for accessing mongo http://github.com/bitly/asyncmongo """ try: import bson except ImportError: raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver") # also update in setup.py version = "1.3" version_info = (1, 3) ASCENDING = 1 """Ascending sort order.""" DESCENDING = -1 """Descending sort order.""" GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" TEXT = '{ $meta: "textScore" }' """TEXT Index sort order.""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, DataError, IntegrityError, ProgrammingError, NotSupportedError) from client import Client
#!/bin/env python # # Copyright 2010 bit.ly # # 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. """ AsyncMongo is an asynchronous library for accessing mongo http://github.com/bitly/asyncmongo """ try: import bson except ImportError: raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver") # also update in setup.py version = "1.3" version_info = (1, 3) ASCENDING = 1 """Ascending sort order.""" DESCENDING = -1 """Descending sort order.""" GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" TEXT = { $meta: "textScore" } """TEXT Index sort order.""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, DataError, IntegrityError, ProgrammingError, NotSupportedError) from client import Client
Support Sort Order For TEXT Index
Support Sort Order For TEXT Index
Python
apache-2.0
RealGeeks/asyncmongo
#!/bin/env python # # Copyright 2010 bit.ly # # 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. """ AsyncMongo is an asynchronous library for accessing mongo http://github.com/bitly/asyncmongo """ try: import bson except ImportError: raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver") # also update in setup.py version = "1.3" version_info = (1, 3) ASCENDING = 1 """Ascending sort order.""" DESCENDING = -1 """Descending sort order.""" GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" TEXT = '{ $meta: "textScore" }' """TEXT Index sort order.""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, DataError, IntegrityError, ProgrammingError, NotSupportedError) from client import Client Support Sort Order For TEXT Index
#!/bin/env python # # Copyright 2010 bit.ly # # 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. """ AsyncMongo is an asynchronous library for accessing mongo http://github.com/bitly/asyncmongo """ try: import bson except ImportError: raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver") # also update in setup.py version = "1.3" version_info = (1, 3) ASCENDING = 1 """Ascending sort order.""" DESCENDING = -1 """Descending sort order.""" GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" TEXT = { $meta: "textScore" } """TEXT Index sort order.""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, DataError, IntegrityError, ProgrammingError, NotSupportedError) from client import Client
<commit_before>#!/bin/env python # # Copyright 2010 bit.ly # # 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. """ AsyncMongo is an asynchronous library for accessing mongo http://github.com/bitly/asyncmongo """ try: import bson except ImportError: raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver") # also update in setup.py version = "1.3" version_info = (1, 3) ASCENDING = 1 """Ascending sort order.""" DESCENDING = -1 """Descending sort order.""" GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" TEXT = '{ $meta: "textScore" }' """TEXT Index sort order.""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, DataError, IntegrityError, ProgrammingError, NotSupportedError) from client import Client <commit_msg>Support Sort Order For TEXT Index<commit_after>
#!/bin/env python # # Copyright 2010 bit.ly # # 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. """ AsyncMongo is an asynchronous library for accessing mongo http://github.com/bitly/asyncmongo """ try: import bson except ImportError: raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver") # also update in setup.py version = "1.3" version_info = (1, 3) ASCENDING = 1 """Ascending sort order.""" DESCENDING = -1 """Descending sort order.""" GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" TEXT = { $meta: "textScore" } """TEXT Index sort order.""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, DataError, IntegrityError, ProgrammingError, NotSupportedError) from client import Client
#!/bin/env python # # Copyright 2010 bit.ly # # 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. """ AsyncMongo is an asynchronous library for accessing mongo http://github.com/bitly/asyncmongo """ try: import bson except ImportError: raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver") # also update in setup.py version = "1.3" version_info = (1, 3) ASCENDING = 1 """Ascending sort order.""" DESCENDING = -1 """Descending sort order.""" GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" TEXT = '{ $meta: "textScore" }' """TEXT Index sort order.""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, DataError, IntegrityError, ProgrammingError, NotSupportedError) from client import Client Support Sort Order For TEXT Index#!/bin/env python # # Copyright 2010 bit.ly # # 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. """ AsyncMongo is an asynchronous library for accessing mongo http://github.com/bitly/asyncmongo """ try: import bson except ImportError: raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver") # also update in setup.py version = "1.3" version_info = (1, 3) ASCENDING = 1 """Ascending sort order.""" DESCENDING = -1 """Descending sort order.""" GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" TEXT = { $meta: "textScore" } """TEXT Index sort order.""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, DataError, IntegrityError, ProgrammingError, NotSupportedError) from client import Client
<commit_before>#!/bin/env python # # Copyright 2010 bit.ly # # 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. """ AsyncMongo is an asynchronous library for accessing mongo http://github.com/bitly/asyncmongo """ try: import bson except ImportError: raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver") # also update in setup.py version = "1.3" version_info = (1, 3) ASCENDING = 1 """Ascending sort order.""" DESCENDING = -1 """Descending sort order.""" GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" TEXT = '{ $meta: "textScore" }' """TEXT Index sort order.""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, DataError, IntegrityError, ProgrammingError, NotSupportedError) from client import Client <commit_msg>Support Sort Order For TEXT Index<commit_after>#!/bin/env python # # Copyright 2010 bit.ly # # 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. """ AsyncMongo is an asynchronous library for accessing mongo http://github.com/bitly/asyncmongo """ try: import bson except ImportError: raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver") # also update in setup.py version = "1.3" version_info = (1, 3) ASCENDING = 1 """Ascending sort order.""" DESCENDING = -1 """Descending sort order.""" GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" TEXT = { $meta: "textScore" } """TEXT Index sort order.""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, DataError, IntegrityError, ProgrammingError, NotSupportedError) from client import Client
8c69e0e75454a5665ed2d428aba3c052b97b68b5
cmd2/constants.py
cmd2/constants.py
# # coding=utf-8 """Constants and definitions""" import re # Used for command parsing, tab completion and word breaks. Do not change. QUOTES = ['"', "'"] REDIRECTION_CHARS = ['|', '<', '>'] # Regular expression to match ANSI escape codes ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m')
# # coding=utf-8 """Constants and definitions""" import re # Used for command parsing, tab completion and word breaks. Do not change. QUOTES = ['"', "'"] REDIRECTION_CHARS = ['|', '>'] # Regular expression to match ANSI escape codes ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m')
Remove ‘<‘ from REDIRECTION_CHARS, it’s no longer used.
Remove ‘<‘ from REDIRECTION_CHARS, it’s no longer used.
Python
mit
python-cmd2/cmd2,python-cmd2/cmd2
# # coding=utf-8 """Constants and definitions""" import re # Used for command parsing, tab completion and word breaks. Do not change. QUOTES = ['"', "'"] REDIRECTION_CHARS = ['|', '<', '>'] # Regular expression to match ANSI escape codes ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m') Remove ‘<‘ from REDIRECTION_CHARS, it’s no longer used.
# # coding=utf-8 """Constants and definitions""" import re # Used for command parsing, tab completion and word breaks. Do not change. QUOTES = ['"', "'"] REDIRECTION_CHARS = ['|', '>'] # Regular expression to match ANSI escape codes ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m')
<commit_before># # coding=utf-8 """Constants and definitions""" import re # Used for command parsing, tab completion and word breaks. Do not change. QUOTES = ['"', "'"] REDIRECTION_CHARS = ['|', '<', '>'] # Regular expression to match ANSI escape codes ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m') <commit_msg>Remove ‘<‘ from REDIRECTION_CHARS, it’s no longer used.<commit_after>
# # coding=utf-8 """Constants and definitions""" import re # Used for command parsing, tab completion and word breaks. Do not change. QUOTES = ['"', "'"] REDIRECTION_CHARS = ['|', '>'] # Regular expression to match ANSI escape codes ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m')
# # coding=utf-8 """Constants and definitions""" import re # Used for command parsing, tab completion and word breaks. Do not change. QUOTES = ['"', "'"] REDIRECTION_CHARS = ['|', '<', '>'] # Regular expression to match ANSI escape codes ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m') Remove ‘<‘ from REDIRECTION_CHARS, it’s no longer used.# # coding=utf-8 """Constants and definitions""" import re # Used for command parsing, tab completion and word breaks. Do not change. QUOTES = ['"', "'"] REDIRECTION_CHARS = ['|', '>'] # Regular expression to match ANSI escape codes ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m')
<commit_before># # coding=utf-8 """Constants and definitions""" import re # Used for command parsing, tab completion and word breaks. Do not change. QUOTES = ['"', "'"] REDIRECTION_CHARS = ['|', '<', '>'] # Regular expression to match ANSI escape codes ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m') <commit_msg>Remove ‘<‘ from REDIRECTION_CHARS, it’s no longer used.<commit_after># # coding=utf-8 """Constants and definitions""" import re # Used for command parsing, tab completion and word breaks. Do not change. QUOTES = ['"', "'"] REDIRECTION_CHARS = ['|', '>'] # Regular expression to match ANSI escape codes ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m')
1892fc910e2a23971248121b44ff120ddc118270
src/sentry/api/authentication.py
src/sentry/api/authentication.py
from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.models import ApiKey, ProjectKey class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class ApiKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): if password: return try: key = ApiKey.objects.get_from_cache(key=userid) except ApiKey.DoesNotExist: return None if not key.is_active: raise AuthenticationFailed('Key is disabled') return (AnonymousUser(), key) class ProjectKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: return None if not constant_time_compare(pk.secret_key, password): return None if not pk.is_active: raise AuthenticationFailed('Key is disabled') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk)
from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.app import raven from sentry.models import ApiKey, ProjectKey class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class ApiKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): if password: return try: key = ApiKey.objects.get_from_cache(key=userid) except ApiKey.DoesNotExist: return None if not key.is_active: raise AuthenticationFailed('Key is disabled') raven.tags_context({ 'api_key': userid, }) return (AnonymousUser(), key) class ProjectKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: return None if not constant_time_compare(pk.secret_key, password): return None if not pk.is_active: raise AuthenticationFailed('Key is disabled') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk)
Add API key to context
Add API key to context
Python
bsd-3-clause
fotinakis/sentry,daevaorn/sentry,hongliang5623/sentry,ngonzalvez/sentry,looker/sentry,fuziontech/sentry,mitsuhiko/sentry,felixbuenemann/sentry,kevinlondon/sentry,BuildingLink/sentry,kevinlondon/sentry,Natim/sentry,wujuguang/sentry,ewdurbin/sentry,kevinastone/sentry,alexm92/sentry,ifduyue/sentry,zenefits/sentry,drcapulet/sentry,JamesMura/sentry,songyi199111/sentry,JamesMura/sentry,ngonzalvez/sentry,drcapulet/sentry,jean/sentry,nicholasserra/sentry,BayanGroup/sentry,beeftornado/sentry,JackDanger/sentry,gg7/sentry,TedaLIEz/sentry,ewdurbin/sentry,fotinakis/sentry,JTCunning/sentry,1tush/sentry,Kryz/sentry,JamesMura/sentry,wong2/sentry,zenefits/sentry,alexm92/sentry,hongliang5623/sentry,imankulov/sentry,gencer/sentry,fuziontech/sentry,zenefits/sentry,felixbuenemann/sentry,jean/sentry,beeftornado/sentry,nicholasserra/sentry,korealerts1/sentry,boneyao/sentry,ifduyue/sentry,TedaLIEz/sentry,BuildingLink/sentry,pauloschilling/sentry,mvaled/sentry,Natim/sentry,daevaorn/sentry,JackDanger/sentry,mvaled/sentry,zenefits/sentry,mvaled/sentry,BuildingLink/sentry,looker/sentry,jean/sentry,JTCunning/sentry,Natim/sentry,jean/sentry,songyi199111/sentry,mvaled/sentry,ngonzalvez/sentry,pauloschilling/sentry,mvaled/sentry,daevaorn/sentry,ifduyue/sentry,1tush/sentry,imankulov/sentry,vperron/sentry,wujuguang/sentry,JackDanger/sentry,boneyao/sentry,beeftornado/sentry,looker/sentry,vperron/sentry,mvaled/sentry,korealerts1/sentry,daevaorn/sentry,gg7/sentry,Kryz/sentry,songyi199111/sentry,kevinastone/sentry,JTCunning/sentry,gencer/sentry,jean/sentry,korealerts1/sentry,wong2/sentry,fotinakis/sentry,BayanGroup/sentry,pauloschilling/sentry,imankulov/sentry,wong2/sentry,fotinakis/sentry,TedaLIEz/sentry,nicholasserra/sentry,boneyao/sentry,gencer/sentry,looker/sentry,mitsuhiko/sentry,ifduyue/sentry,kevinlondon/sentry,kevinastone/sentry,alexm92/sentry,fuziontech/sentry,ifduyue/sentry,gencer/sentry,JamesMura/sentry,hongliang5623/sentry,vperron/sentry,zenefits/sentry,BayanGroup/sentry,gencer/sentry,ewdurbin/sentry,drcapulet/sentry,JamesMura/sentry,BuildingLink/sentry,1tush/sentry,Kryz/sentry,gg7/sentry,felixbuenemann/sentry,wujuguang/sentry,looker/sentry,BuildingLink/sentry
from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.models import ApiKey, ProjectKey class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class ApiKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): if password: return try: key = ApiKey.objects.get_from_cache(key=userid) except ApiKey.DoesNotExist: return None if not key.is_active: raise AuthenticationFailed('Key is disabled') return (AnonymousUser(), key) class ProjectKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: return None if not constant_time_compare(pk.secret_key, password): return None if not pk.is_active: raise AuthenticationFailed('Key is disabled') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk) Add API key to context
from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.app import raven from sentry.models import ApiKey, ProjectKey class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class ApiKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): if password: return try: key = ApiKey.objects.get_from_cache(key=userid) except ApiKey.DoesNotExist: return None if not key.is_active: raise AuthenticationFailed('Key is disabled') raven.tags_context({ 'api_key': userid, }) return (AnonymousUser(), key) class ProjectKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: return None if not constant_time_compare(pk.secret_key, password): return None if not pk.is_active: raise AuthenticationFailed('Key is disabled') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk)
<commit_before>from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.models import ApiKey, ProjectKey class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class ApiKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): if password: return try: key = ApiKey.objects.get_from_cache(key=userid) except ApiKey.DoesNotExist: return None if not key.is_active: raise AuthenticationFailed('Key is disabled') return (AnonymousUser(), key) class ProjectKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: return None if not constant_time_compare(pk.secret_key, password): return None if not pk.is_active: raise AuthenticationFailed('Key is disabled') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk) <commit_msg>Add API key to context<commit_after>
from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.app import raven from sentry.models import ApiKey, ProjectKey class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class ApiKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): if password: return try: key = ApiKey.objects.get_from_cache(key=userid) except ApiKey.DoesNotExist: return None if not key.is_active: raise AuthenticationFailed('Key is disabled') raven.tags_context({ 'api_key': userid, }) return (AnonymousUser(), key) class ProjectKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: return None if not constant_time_compare(pk.secret_key, password): return None if not pk.is_active: raise AuthenticationFailed('Key is disabled') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk)
from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.models import ApiKey, ProjectKey class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class ApiKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): if password: return try: key = ApiKey.objects.get_from_cache(key=userid) except ApiKey.DoesNotExist: return None if not key.is_active: raise AuthenticationFailed('Key is disabled') return (AnonymousUser(), key) class ProjectKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: return None if not constant_time_compare(pk.secret_key, password): return None if not pk.is_active: raise AuthenticationFailed('Key is disabled') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk) Add API key to contextfrom __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.app import raven from sentry.models import ApiKey, ProjectKey class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class ApiKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): if password: return try: key = ApiKey.objects.get_from_cache(key=userid) except ApiKey.DoesNotExist: return None if not key.is_active: raise AuthenticationFailed('Key is disabled') raven.tags_context({ 'api_key': userid, }) return (AnonymousUser(), key) class ProjectKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: return None if not constant_time_compare(pk.secret_key, password): return None if not pk.is_active: raise AuthenticationFailed('Key is disabled') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk)
<commit_before>from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.models import ApiKey, ProjectKey class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class ApiKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): if password: return try: key = ApiKey.objects.get_from_cache(key=userid) except ApiKey.DoesNotExist: return None if not key.is_active: raise AuthenticationFailed('Key is disabled') return (AnonymousUser(), key) class ProjectKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: return None if not constant_time_compare(pk.secret_key, password): return None if not pk.is_active: raise AuthenticationFailed('Key is disabled') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk) <commit_msg>Add API key to context<commit_after>from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.app import raven from sentry.models import ApiKey, ProjectKey class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class ApiKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): if password: return try: key = ApiKey.objects.get_from_cache(key=userid) except ApiKey.DoesNotExist: return None if not key.is_active: raise AuthenticationFailed('Key is disabled') raven.tags_context({ 'api_key': userid, }) return (AnonymousUser(), key) class ProjectKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: return None if not constant_time_compare(pk.secret_key, password): return None if not pk.is_active: raise AuthenticationFailed('Key is disabled') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk)
b8850bd7d457ebb14220213d18a6aa779d64b547
nirum/validate.py
nirum/validate.py
""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, type(boxed))) return True def validate_record_type(record): for attr, type_ in record.__nirum_field_types__.items(): data = getattr(record, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(record, attr, type_, type(data)) ) else: return True def validate_union_type(union): for attr, type_ in union.__nirum_tag_types__.items(): data = getattr(union, attr) print(attr, type_) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(union, attr, type_, type(data)) ) else: return True
""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, type(boxed))) return boxed def validate_record_type(record): for attr, type_ in record.__nirum_field_types__.items(): data = getattr(record, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(record, attr, type_, type(data)) ) else: return record def validate_union_type(union): for attr, type_ in union.__nirum_tag_types__.items(): data = getattr(union, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(union, attr, type_, type(data)) ) else: return union
Return its argument in validators
Return its argument in validators
Python
mit
spoqa/nirum-python,spoqa/nirum-python
""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, type(boxed))) return True def validate_record_type(record): for attr, type_ in record.__nirum_field_types__.items(): data = getattr(record, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(record, attr, type_, type(data)) ) else: return True def validate_union_type(union): for attr, type_ in union.__nirum_tag_types__.items(): data = getattr(union, attr) print(attr, type_) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(union, attr, type_, type(data)) ) else: return True Return its argument in validators
""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, type(boxed))) return boxed def validate_record_type(record): for attr, type_ in record.__nirum_field_types__.items(): data = getattr(record, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(record, attr, type_, type(data)) ) else: return record def validate_union_type(union): for attr, type_ in union.__nirum_tag_types__.items(): data = getattr(union, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(union, attr, type_, type(data)) ) else: return union
<commit_before>""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, type(boxed))) return True def validate_record_type(record): for attr, type_ in record.__nirum_field_types__.items(): data = getattr(record, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(record, attr, type_, type(data)) ) else: return True def validate_union_type(union): for attr, type_ in union.__nirum_tag_types__.items(): data = getattr(union, attr) print(attr, type_) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(union, attr, type_, type(data)) ) else: return True <commit_msg>Return its argument in validators<commit_after>
""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, type(boxed))) return boxed def validate_record_type(record): for attr, type_ in record.__nirum_field_types__.items(): data = getattr(record, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(record, attr, type_, type(data)) ) else: return record def validate_union_type(union): for attr, type_ in union.__nirum_tag_types__.items(): data = getattr(union, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(union, attr, type_, type(data)) ) else: return union
""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, type(boxed))) return True def validate_record_type(record): for attr, type_ in record.__nirum_field_types__.items(): data = getattr(record, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(record, attr, type_, type(data)) ) else: return True def validate_union_type(union): for attr, type_ in union.__nirum_tag_types__.items(): data = getattr(union, attr) print(attr, type_) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(union, attr, type_, type(data)) ) else: return True Return its argument in validators""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, type(boxed))) return boxed def validate_record_type(record): for attr, type_ in record.__nirum_field_types__.items(): data = getattr(record, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(record, attr, type_, type(data)) ) else: return record def validate_union_type(union): for attr, type_ in union.__nirum_tag_types__.items(): data = getattr(union, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(union, attr, type_, type(data)) ) else: return union
<commit_before>""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, type(boxed))) return True def validate_record_type(record): for attr, type_ in record.__nirum_field_types__.items(): data = getattr(record, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(record, attr, type_, type(data)) ) else: return True def validate_union_type(union): for attr, type_ in union.__nirum_tag_types__.items(): data = getattr(union, attr) print(attr, type_) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(union, attr, type_, type(data)) ) else: return True <commit_msg>Return its argument in validators<commit_after>""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, type(boxed))) return boxed def validate_record_type(record): for attr, type_ in record.__nirum_field_types__.items(): data = getattr(record, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(record, attr, type_, type(data)) ) else: return record def validate_union_type(union): for attr, type_ in union.__nirum_tag_types__.items(): data = getattr(union, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(union, attr, type_, type(data)) ) else: return union
cad5087328bd462d6db8758929d212c4b34fae6c
server_ui/glue.py
server_ui/glue.py
""" Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('This election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied)
""" Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s\n') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s\n') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('\nThis election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied)
Add blank space in email message
Add blank space in email message
Python
apache-2.0
shirlei/helios-server,shirlei/helios-server,shirlei/helios-server,shirlei/helios-server,shirlei/helios-server
""" Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('This election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied) Add blank space in email message
""" Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s\n') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s\n') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('\nThis election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied)
<commit_before>""" Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('This election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied) <commit_msg>Add blank space in email message<commit_after>
""" Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s\n') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s\n') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('\nThis election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied)
""" Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('This election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied) Add blank space in email message""" Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s\n') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s\n') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('\nThis election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied)
<commit_before>""" Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('This election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied) <commit_msg>Add blank space in email message<commit_after>""" Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s\n') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s\n') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('\nThis election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied)
4bcfb45ef0934dcbcfc711bac1a01c7204e83231
pw_docgen/py/setup.py
pw_docgen/py/setup.py
# Copyright 2020 The Pigweed Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # https://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. """pw_docgen""" import setuptools # type: ignore setuptools.setup( name='pw_docgen', version='0.0.1', author='Pigweed Authors', author_email='pigweed-developers@googlegroups.com', description='Generate Sphinx documentation', packages=setuptools.find_packages(), package_data={'pw_docgen': ['py.typed']}, zip_safe=False, install_requires=[ 'sphinx >3', 'sphinx-rtd-theme', # Diagram generation modules. 'sphinxcontrib-actdiag', 'sphinxcontrib-blockdiag', 'sphinxcontrib-nwdiag', 'sphinxcontrib-seqdiag', 'sphinxcontrib-mermaid', ], )
# Copyright 2020 The Pigweed Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # https://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. """pw_docgen""" import setuptools # type: ignore setuptools.setup( name='pw_docgen', version='0.0.1', author='Pigweed Authors', author_email='pigweed-developers@googlegroups.com', description='Generate Sphinx documentation', packages=setuptools.find_packages(), package_data={'pw_docgen': ['py.typed']}, zip_safe=False, install_requires=[ 'sphinx >3', 'sphinx-rtd-theme', # Pillow 8.3.0 is broken on Windows. 'Pillow >=6.2.2, <=8.2.0', # Diagram generation modules. 'sphinxcontrib-actdiag', 'sphinxcontrib-blockdiag', 'sphinxcontrib-nwdiag', 'sphinxcontrib-seqdiag', 'sphinxcontrib-mermaid', ], )
Set Pillow version to 8.2.0
pw_docgen: Set Pillow version to 8.2.0 Version 8.3.0 has yet to be resolved DLL problems on windows. No-Docs-Update-Reason: Pip dep fix. Change-Id: I50deecd7c5d3a7f5eb01898e13e5ccb5bedfabf2 Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/52041 Reviewed-by: Wyatt Hepler <cca3bedb37979eacd157a9bceb473582df8aea1e@google.com> Commit-Queue: Anthony DiGirolamo <4cc40125edc24ec5bc72df7917ea0b403ee8cebe@google.com> Pigweed-Auto-Submit: Anthony DiGirolamo <4cc40125edc24ec5bc72df7917ea0b403ee8cebe@google.com>
Python
apache-2.0
google/pigweed,google/pigweed,google/pigweed,google/pigweed,google/pigweed,google/pigweed,google/pigweed,google/pigweed,google/pigweed,google/pigweed
# Copyright 2020 The Pigweed Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # https://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. """pw_docgen""" import setuptools # type: ignore setuptools.setup( name='pw_docgen', version='0.0.1', author='Pigweed Authors', author_email='pigweed-developers@googlegroups.com', description='Generate Sphinx documentation', packages=setuptools.find_packages(), package_data={'pw_docgen': ['py.typed']}, zip_safe=False, install_requires=[ 'sphinx >3', 'sphinx-rtd-theme', # Diagram generation modules. 'sphinxcontrib-actdiag', 'sphinxcontrib-blockdiag', 'sphinxcontrib-nwdiag', 'sphinxcontrib-seqdiag', 'sphinxcontrib-mermaid', ], ) pw_docgen: Set Pillow version to 8.2.0 Version 8.3.0 has yet to be resolved DLL problems on windows. No-Docs-Update-Reason: Pip dep fix. Change-Id: I50deecd7c5d3a7f5eb01898e13e5ccb5bedfabf2 Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/52041 Reviewed-by: Wyatt Hepler <cca3bedb37979eacd157a9bceb473582df8aea1e@google.com> Commit-Queue: Anthony DiGirolamo <4cc40125edc24ec5bc72df7917ea0b403ee8cebe@google.com> Pigweed-Auto-Submit: Anthony DiGirolamo <4cc40125edc24ec5bc72df7917ea0b403ee8cebe@google.com>
# Copyright 2020 The Pigweed Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # https://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. """pw_docgen""" import setuptools # type: ignore setuptools.setup( name='pw_docgen', version='0.0.1', author='Pigweed Authors', author_email='pigweed-developers@googlegroups.com', description='Generate Sphinx documentation', packages=setuptools.find_packages(), package_data={'pw_docgen': ['py.typed']}, zip_safe=False, install_requires=[ 'sphinx >3', 'sphinx-rtd-theme', # Pillow 8.3.0 is broken on Windows. 'Pillow >=6.2.2, <=8.2.0', # Diagram generation modules. 'sphinxcontrib-actdiag', 'sphinxcontrib-blockdiag', 'sphinxcontrib-nwdiag', 'sphinxcontrib-seqdiag', 'sphinxcontrib-mermaid', ], )
<commit_before># Copyright 2020 The Pigweed Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # https://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. """pw_docgen""" import setuptools # type: ignore setuptools.setup( name='pw_docgen', version='0.0.1', author='Pigweed Authors', author_email='pigweed-developers@googlegroups.com', description='Generate Sphinx documentation', packages=setuptools.find_packages(), package_data={'pw_docgen': ['py.typed']}, zip_safe=False, install_requires=[ 'sphinx >3', 'sphinx-rtd-theme', # Diagram generation modules. 'sphinxcontrib-actdiag', 'sphinxcontrib-blockdiag', 'sphinxcontrib-nwdiag', 'sphinxcontrib-seqdiag', 'sphinxcontrib-mermaid', ], ) <commit_msg>pw_docgen: Set Pillow version to 8.2.0 Version 8.3.0 has yet to be resolved DLL problems on windows. No-Docs-Update-Reason: Pip dep fix. Change-Id: I50deecd7c5d3a7f5eb01898e13e5ccb5bedfabf2 Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/52041 Reviewed-by: Wyatt Hepler <cca3bedb37979eacd157a9bceb473582df8aea1e@google.com> Commit-Queue: Anthony DiGirolamo <4cc40125edc24ec5bc72df7917ea0b403ee8cebe@google.com> Pigweed-Auto-Submit: Anthony DiGirolamo <4cc40125edc24ec5bc72df7917ea0b403ee8cebe@google.com><commit_after>
# Copyright 2020 The Pigweed Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # https://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. """pw_docgen""" import setuptools # type: ignore setuptools.setup( name='pw_docgen', version='0.0.1', author='Pigweed Authors', author_email='pigweed-developers@googlegroups.com', description='Generate Sphinx documentation', packages=setuptools.find_packages(), package_data={'pw_docgen': ['py.typed']}, zip_safe=False, install_requires=[ 'sphinx >3', 'sphinx-rtd-theme', # Pillow 8.3.0 is broken on Windows. 'Pillow >=6.2.2, <=8.2.0', # Diagram generation modules. 'sphinxcontrib-actdiag', 'sphinxcontrib-blockdiag', 'sphinxcontrib-nwdiag', 'sphinxcontrib-seqdiag', 'sphinxcontrib-mermaid', ], )
# Copyright 2020 The Pigweed Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # https://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. """pw_docgen""" import setuptools # type: ignore setuptools.setup( name='pw_docgen', version='0.0.1', author='Pigweed Authors', author_email='pigweed-developers@googlegroups.com', description='Generate Sphinx documentation', packages=setuptools.find_packages(), package_data={'pw_docgen': ['py.typed']}, zip_safe=False, install_requires=[ 'sphinx >3', 'sphinx-rtd-theme', # Diagram generation modules. 'sphinxcontrib-actdiag', 'sphinxcontrib-blockdiag', 'sphinxcontrib-nwdiag', 'sphinxcontrib-seqdiag', 'sphinxcontrib-mermaid', ], ) pw_docgen: Set Pillow version to 8.2.0 Version 8.3.0 has yet to be resolved DLL problems on windows. No-Docs-Update-Reason: Pip dep fix. Change-Id: I50deecd7c5d3a7f5eb01898e13e5ccb5bedfabf2 Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/52041 Reviewed-by: Wyatt Hepler <cca3bedb37979eacd157a9bceb473582df8aea1e@google.com> Commit-Queue: Anthony DiGirolamo <4cc40125edc24ec5bc72df7917ea0b403ee8cebe@google.com> Pigweed-Auto-Submit: Anthony DiGirolamo <4cc40125edc24ec5bc72df7917ea0b403ee8cebe@google.com># Copyright 2020 The Pigweed Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # https://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. """pw_docgen""" import setuptools # type: ignore setuptools.setup( name='pw_docgen', version='0.0.1', author='Pigweed Authors', author_email='pigweed-developers@googlegroups.com', description='Generate Sphinx documentation', packages=setuptools.find_packages(), package_data={'pw_docgen': ['py.typed']}, zip_safe=False, install_requires=[ 'sphinx >3', 'sphinx-rtd-theme', # Pillow 8.3.0 is broken on Windows. 'Pillow >=6.2.2, <=8.2.0', # Diagram generation modules. 'sphinxcontrib-actdiag', 'sphinxcontrib-blockdiag', 'sphinxcontrib-nwdiag', 'sphinxcontrib-seqdiag', 'sphinxcontrib-mermaid', ], )
<commit_before># Copyright 2020 The Pigweed Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # https://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. """pw_docgen""" import setuptools # type: ignore setuptools.setup( name='pw_docgen', version='0.0.1', author='Pigweed Authors', author_email='pigweed-developers@googlegroups.com', description='Generate Sphinx documentation', packages=setuptools.find_packages(), package_data={'pw_docgen': ['py.typed']}, zip_safe=False, install_requires=[ 'sphinx >3', 'sphinx-rtd-theme', # Diagram generation modules. 'sphinxcontrib-actdiag', 'sphinxcontrib-blockdiag', 'sphinxcontrib-nwdiag', 'sphinxcontrib-seqdiag', 'sphinxcontrib-mermaid', ], ) <commit_msg>pw_docgen: Set Pillow version to 8.2.0 Version 8.3.0 has yet to be resolved DLL problems on windows. No-Docs-Update-Reason: Pip dep fix. Change-Id: I50deecd7c5d3a7f5eb01898e13e5ccb5bedfabf2 Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/52041 Reviewed-by: Wyatt Hepler <cca3bedb37979eacd157a9bceb473582df8aea1e@google.com> Commit-Queue: Anthony DiGirolamo <4cc40125edc24ec5bc72df7917ea0b403ee8cebe@google.com> Pigweed-Auto-Submit: Anthony DiGirolamo <4cc40125edc24ec5bc72df7917ea0b403ee8cebe@google.com><commit_after># Copyright 2020 The Pigweed Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # https://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. """pw_docgen""" import setuptools # type: ignore setuptools.setup( name='pw_docgen', version='0.0.1', author='Pigweed Authors', author_email='pigweed-developers@googlegroups.com', description='Generate Sphinx documentation', packages=setuptools.find_packages(), package_data={'pw_docgen': ['py.typed']}, zip_safe=False, install_requires=[ 'sphinx >3', 'sphinx-rtd-theme', # Pillow 8.3.0 is broken on Windows. 'Pillow >=6.2.2, <=8.2.0', # Diagram generation modules. 'sphinxcontrib-actdiag', 'sphinxcontrib-blockdiag', 'sphinxcontrib-nwdiag', 'sphinxcontrib-seqdiag', 'sphinxcontrib-mermaid', ], )
1f884083b612637b64f26532c221b7341c3dda8c
services/voicedetection/voicedetection.py
services/voicedetection/voicedetection.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import angus.cloud conn = angus.connect() service = conn.services.get_service('voice_detection', version=1) job = service.process({'sound': open("./sound.wav", 'rb'), 'sensitivity':0.7}) print job.result
import angus.cloud conn = angus.connect() service = conn.services.get_service('voice_detection', version=1) job = service.process({'sound': open("./sound.wav", 'rb'), 'sensitivity':0.7}) print job.result
Clean script header in voice detection.
Clean script header in voice detection.
Python
apache-2.0
angus-ai/angus-doc,angus-ai/angus-doc,angus-ai/angus-doc
#!/usr/bin/env python # -*- coding: utf-8 -*- import angus.cloud conn = angus.connect() service = conn.services.get_service('voice_detection', version=1) job = service.process({'sound': open("./sound.wav", 'rb'), 'sensitivity':0.7}) print job.result Clean script header in voice detection.
import angus.cloud conn = angus.connect() service = conn.services.get_service('voice_detection', version=1) job = service.process({'sound': open("./sound.wav", 'rb'), 'sensitivity':0.7}) print job.result
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import angus.cloud conn = angus.connect() service = conn.services.get_service('voice_detection', version=1) job = service.process({'sound': open("./sound.wav", 'rb'), 'sensitivity':0.7}) print job.result <commit_msg>Clean script header in voice detection.<commit_after>
import angus.cloud conn = angus.connect() service = conn.services.get_service('voice_detection', version=1) job = service.process({'sound': open("./sound.wav", 'rb'), 'sensitivity':0.7}) print job.result
#!/usr/bin/env python # -*- coding: utf-8 -*- import angus.cloud conn = angus.connect() service = conn.services.get_service('voice_detection', version=1) job = service.process({'sound': open("./sound.wav", 'rb'), 'sensitivity':0.7}) print job.result Clean script header in voice detection.import angus.cloud conn = angus.connect() service = conn.services.get_service('voice_detection', version=1) job = service.process({'sound': open("./sound.wav", 'rb'), 'sensitivity':0.7}) print job.result
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import angus.cloud conn = angus.connect() service = conn.services.get_service('voice_detection', version=1) job = service.process({'sound': open("./sound.wav", 'rb'), 'sensitivity':0.7}) print job.result <commit_msg>Clean script header in voice detection.<commit_after>import angus.cloud conn = angus.connect() service = conn.services.get_service('voice_detection', version=1) job = service.process({'sound': open("./sound.wav", 'rb'), 'sensitivity':0.7}) print job.result
93956645792f92cffc11f4e2c72a8df1b0b82a02
tests/runalldoctests.py
tests/runalldoctests.py
import doctest import glob import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass testfiles = glob.glob('*.txt') for file in testfiles: doctest.testfile(file)
import doctest import getopt import glob import sys import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass def run(pattern): if pattern is None: testfiles = glob.glob('*.txt') else: testfiles = glob.glob(pattern) for file in testfiles: doctest.testfile(file) if __name__ == "__main__": try: opts, args = getopt.getopt(sys.argv[1:], "t:v") except getopt.GetoptError: print "Usage: python runalldoctests.py [-t GLOB_PATTERN]" sys.exit(2) pattern = None for o, a in opts: if o == '-t': pattern = a run(pattern)
Add option to pick single test file from the runner
Add option to pick single test file from the runner
Python
bsd-3-clause
menegon/OWSLib,QuLogic/OWSLib,jachym/OWSLib,kwilcox/OWSLib,robmcmullen/OWSLib,KeyproOy/OWSLib,geopython/OWSLib,jaygoldfinch/OWSLib,JuergenWeichand/OWSLib,geographika/OWSLib,daf/OWSLib,ocefpaf/OWSLib,daf/OWSLib,bird-house/OWSLib,tomkralidis/OWSLib,datagovuk/OWSLib,dblodgett-usgs/OWSLib,b-cube/OWSLib,gfusca/OWSLib,mbertrand/OWSLib,daf/OWSLib,kalxas/OWSLib,Jenselme/OWSLib,jaygoldfinch/OWSLib,datagovuk/OWSLib,datagovuk/OWSLib
import doctest import glob import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass testfiles = glob.glob('*.txt') for file in testfiles: doctest.testfile(file) Add option to pick single test file from the runner
import doctest import getopt import glob import sys import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass def run(pattern): if pattern is None: testfiles = glob.glob('*.txt') else: testfiles = glob.glob(pattern) for file in testfiles: doctest.testfile(file) if __name__ == "__main__": try: opts, args = getopt.getopt(sys.argv[1:], "t:v") except getopt.GetoptError: print "Usage: python runalldoctests.py [-t GLOB_PATTERN]" sys.exit(2) pattern = None for o, a in opts: if o == '-t': pattern = a run(pattern)
<commit_before>import doctest import glob import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass testfiles = glob.glob('*.txt') for file in testfiles: doctest.testfile(file) <commit_msg>Add option to pick single test file from the runner<commit_after>
import doctest import getopt import glob import sys import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass def run(pattern): if pattern is None: testfiles = glob.glob('*.txt') else: testfiles = glob.glob(pattern) for file in testfiles: doctest.testfile(file) if __name__ == "__main__": try: opts, args = getopt.getopt(sys.argv[1:], "t:v") except getopt.GetoptError: print "Usage: python runalldoctests.py [-t GLOB_PATTERN]" sys.exit(2) pattern = None for o, a in opts: if o == '-t': pattern = a run(pattern)
import doctest import glob import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass testfiles = glob.glob('*.txt') for file in testfiles: doctest.testfile(file) Add option to pick single test file from the runnerimport doctest import getopt import glob import sys import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass def run(pattern): if pattern is None: testfiles = glob.glob('*.txt') else: testfiles = glob.glob(pattern) for file in testfiles: doctest.testfile(file) if __name__ == "__main__": try: opts, args = getopt.getopt(sys.argv[1:], "t:v") except getopt.GetoptError: print "Usage: python runalldoctests.py [-t GLOB_PATTERN]" sys.exit(2) pattern = None for o, a in opts: if o == '-t': pattern = a run(pattern)
<commit_before>import doctest import glob import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass testfiles = glob.glob('*.txt') for file in testfiles: doctest.testfile(file) <commit_msg>Add option to pick single test file from the runner<commit_after>import doctest import getopt import glob import sys import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass def run(pattern): if pattern is None: testfiles = glob.glob('*.txt') else: testfiles = glob.glob(pattern) for file in testfiles: doctest.testfile(file) if __name__ == "__main__": try: opts, args = getopt.getopt(sys.argv[1:], "t:v") except getopt.GetoptError: print "Usage: python runalldoctests.py [-t GLOB_PATTERN]" sys.exit(2) pattern = None for o, a in opts: if o == '-t': pattern = a run(pattern)
5d190f8d3b228820d1a537f0ed2b584b8c09fbae
tests/test_container.py
tests/test_container.py
# coding: utf8 from common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')
# coding: utf8 from .common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')
Fix relative import in tests.
Fix relative import in tests.
Python
bsd-3-clause
mikeboers/PyAV,PyAV-Org/PyAV,PyAV-Org/PyAV,mikeboers/PyAV
# coding: utf8 from common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w') Fix relative import in tests.
# coding: utf8 from .common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')
<commit_before># coding: utf8 from common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w') <commit_msg>Fix relative import in tests.<commit_after>
# coding: utf8 from .common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')
# coding: utf8 from common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w') Fix relative import in tests.# coding: utf8 from .common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')
<commit_before># coding: utf8 from common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w') <commit_msg>Fix relative import in tests.<commit_after># coding: utf8 from .common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')
5b8a39dc0fc5e383c30451a819c8e1542fd6f7ed
OpenSearchInNewTab.py
OpenSearchInNewTab.py
import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) view.set_scratch(True) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) )
import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) )
Remove unnecessary scratch file flag
Remove unnecessary scratch file flag
Python
mit
everyonesdesign/OpenSearchInNewTab
import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) view.set_scratch(True) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) ) Remove unnecessary scratch file flag
import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) )
<commit_before>import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) view.set_scratch(True) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) ) <commit_msg>Remove unnecessary scratch file flag<commit_after>
import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) )
import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) view.set_scratch(True) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) ) Remove unnecessary scratch file flagimport re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) )
<commit_before>import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) view.set_scratch(True) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) ) <commit_msg>Remove unnecessary scratch file flag<commit_after>import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) )
403a949a4b248076420d79ceb9d87983b1d26812
django_errordite/handlers.py
django_errordite/handlers.py
""" Django-aware exception handler for integration with Errordite. Adds django user and request information to the exception as appropriate. """ from errordite import ErrorditeHandler class DjangoErrorditeHandler(ErrorditeHandler): """ Django-aware Errordite handler than enriches logs with request info. """ def enrich_errordite_payload(self, payload, record): """ Overrides base class implementation to add Django-specific error data - specifically user and HTTP request information. """ payload = super(DjangoErrorditeHandler, self).enrich_errordite_payload( payload, record ) if not hasattr(record, 'request'): return rq = record.request payload['Url'] = rq.get_full_path() if 'HTTP_USER_AGENT' in rq.META: payload['UserAgent'] = rq.META['HTTP_USER_AGENT'] data = payload['ExceptionInfo'].get('Data', {}) if 'HTTP_X_FORWARDED_FOR' in rq.META: data['X-Forwarded-For'] = rq.META['HTTP_X_FORWARDED_FOR'] if 'REMOTE_ADDR' in rq.META: data['client_ip'] = rq.META['REMOTE_ADDR'] if hasattr(rq, 'user'): if rq.user is not None: if rq.user.is_anonymous(): data['user'] = "anonymous" else: data['user'] = rq.user.username payload['ExceptionInfo']['Data'] = data return payload
""" Django-aware exception handler for integration with Errordite. Adds django user and request information to the exception as appropriate. """ from errordite import ErrorditeHandler class DjangoErrorditeHandler(ErrorditeHandler): """ Django-aware Errordite handler than enriches logs with request info. """ def enrich_errordite_payload(self, payload, record): """ Overrides base class implementation to add Django-specific error data - specifically user and HTTP request information. """ payload = super(DjangoErrorditeHandler, self).enrich_errordite_payload( payload, record ) if not hasattr(record, 'request'): return payload rq = record.request payload['Url'] = rq.get_full_path() if 'HTTP_USER_AGENT' in rq.META: payload['UserAgent'] = rq.META['HTTP_USER_AGENT'] data = payload['ExceptionInfo'].get('Data', {}) if 'HTTP_X_FORWARDED_FOR' in rq.META: data['X-Forwarded-For'] = rq.META['HTTP_X_FORWARDED_FOR'] if 'REMOTE_ADDR' in rq.META: data['client_ip'] = rq.META['REMOTE_ADDR'] if hasattr(rq, 'user'): if rq.user is not None: if rq.user.is_anonymous(): data['user'] = "anonymous" else: data['user'] = rq.user.username payload['ExceptionInfo']['Data'] = data return payload
Return payload even if request arg is not passed in.
Return payload even if request arg is not passed in.
Python
bsd-2-clause
yunojuno/django-errordite
""" Django-aware exception handler for integration with Errordite. Adds django user and request information to the exception as appropriate. """ from errordite import ErrorditeHandler class DjangoErrorditeHandler(ErrorditeHandler): """ Django-aware Errordite handler than enriches logs with request info. """ def enrich_errordite_payload(self, payload, record): """ Overrides base class implementation to add Django-specific error data - specifically user and HTTP request information. """ payload = super(DjangoErrorditeHandler, self).enrich_errordite_payload( payload, record ) if not hasattr(record, 'request'): return rq = record.request payload['Url'] = rq.get_full_path() if 'HTTP_USER_AGENT' in rq.META: payload['UserAgent'] = rq.META['HTTP_USER_AGENT'] data = payload['ExceptionInfo'].get('Data', {}) if 'HTTP_X_FORWARDED_FOR' in rq.META: data['X-Forwarded-For'] = rq.META['HTTP_X_FORWARDED_FOR'] if 'REMOTE_ADDR' in rq.META: data['client_ip'] = rq.META['REMOTE_ADDR'] if hasattr(rq, 'user'): if rq.user is not None: if rq.user.is_anonymous(): data['user'] = "anonymous" else: data['user'] = rq.user.username payload['ExceptionInfo']['Data'] = data return payload Return payload even if request arg is not passed in.
""" Django-aware exception handler for integration with Errordite. Adds django user and request information to the exception as appropriate. """ from errordite import ErrorditeHandler class DjangoErrorditeHandler(ErrorditeHandler): """ Django-aware Errordite handler than enriches logs with request info. """ def enrich_errordite_payload(self, payload, record): """ Overrides base class implementation to add Django-specific error data - specifically user and HTTP request information. """ payload = super(DjangoErrorditeHandler, self).enrich_errordite_payload( payload, record ) if not hasattr(record, 'request'): return payload rq = record.request payload['Url'] = rq.get_full_path() if 'HTTP_USER_AGENT' in rq.META: payload['UserAgent'] = rq.META['HTTP_USER_AGENT'] data = payload['ExceptionInfo'].get('Data', {}) if 'HTTP_X_FORWARDED_FOR' in rq.META: data['X-Forwarded-For'] = rq.META['HTTP_X_FORWARDED_FOR'] if 'REMOTE_ADDR' in rq.META: data['client_ip'] = rq.META['REMOTE_ADDR'] if hasattr(rq, 'user'): if rq.user is not None: if rq.user.is_anonymous(): data['user'] = "anonymous" else: data['user'] = rq.user.username payload['ExceptionInfo']['Data'] = data return payload
<commit_before>""" Django-aware exception handler for integration with Errordite. Adds django user and request information to the exception as appropriate. """ from errordite import ErrorditeHandler class DjangoErrorditeHandler(ErrorditeHandler): """ Django-aware Errordite handler than enriches logs with request info. """ def enrich_errordite_payload(self, payload, record): """ Overrides base class implementation to add Django-specific error data - specifically user and HTTP request information. """ payload = super(DjangoErrorditeHandler, self).enrich_errordite_payload( payload, record ) if not hasattr(record, 'request'): return rq = record.request payload['Url'] = rq.get_full_path() if 'HTTP_USER_AGENT' in rq.META: payload['UserAgent'] = rq.META['HTTP_USER_AGENT'] data = payload['ExceptionInfo'].get('Data', {}) if 'HTTP_X_FORWARDED_FOR' in rq.META: data['X-Forwarded-For'] = rq.META['HTTP_X_FORWARDED_FOR'] if 'REMOTE_ADDR' in rq.META: data['client_ip'] = rq.META['REMOTE_ADDR'] if hasattr(rq, 'user'): if rq.user is not None: if rq.user.is_anonymous(): data['user'] = "anonymous" else: data['user'] = rq.user.username payload['ExceptionInfo']['Data'] = data return payload <commit_msg>Return payload even if request arg is not passed in.<commit_after>
""" Django-aware exception handler for integration with Errordite. Adds django user and request information to the exception as appropriate. """ from errordite import ErrorditeHandler class DjangoErrorditeHandler(ErrorditeHandler): """ Django-aware Errordite handler than enriches logs with request info. """ def enrich_errordite_payload(self, payload, record): """ Overrides base class implementation to add Django-specific error data - specifically user and HTTP request information. """ payload = super(DjangoErrorditeHandler, self).enrich_errordite_payload( payload, record ) if not hasattr(record, 'request'): return payload rq = record.request payload['Url'] = rq.get_full_path() if 'HTTP_USER_AGENT' in rq.META: payload['UserAgent'] = rq.META['HTTP_USER_AGENT'] data = payload['ExceptionInfo'].get('Data', {}) if 'HTTP_X_FORWARDED_FOR' in rq.META: data['X-Forwarded-For'] = rq.META['HTTP_X_FORWARDED_FOR'] if 'REMOTE_ADDR' in rq.META: data['client_ip'] = rq.META['REMOTE_ADDR'] if hasattr(rq, 'user'): if rq.user is not None: if rq.user.is_anonymous(): data['user'] = "anonymous" else: data['user'] = rq.user.username payload['ExceptionInfo']['Data'] = data return payload
""" Django-aware exception handler for integration with Errordite. Adds django user and request information to the exception as appropriate. """ from errordite import ErrorditeHandler class DjangoErrorditeHandler(ErrorditeHandler): """ Django-aware Errordite handler than enriches logs with request info. """ def enrich_errordite_payload(self, payload, record): """ Overrides base class implementation to add Django-specific error data - specifically user and HTTP request information. """ payload = super(DjangoErrorditeHandler, self).enrich_errordite_payload( payload, record ) if not hasattr(record, 'request'): return rq = record.request payload['Url'] = rq.get_full_path() if 'HTTP_USER_AGENT' in rq.META: payload['UserAgent'] = rq.META['HTTP_USER_AGENT'] data = payload['ExceptionInfo'].get('Data', {}) if 'HTTP_X_FORWARDED_FOR' in rq.META: data['X-Forwarded-For'] = rq.META['HTTP_X_FORWARDED_FOR'] if 'REMOTE_ADDR' in rq.META: data['client_ip'] = rq.META['REMOTE_ADDR'] if hasattr(rq, 'user'): if rq.user is not None: if rq.user.is_anonymous(): data['user'] = "anonymous" else: data['user'] = rq.user.username payload['ExceptionInfo']['Data'] = data return payload Return payload even if request arg is not passed in.""" Django-aware exception handler for integration with Errordite. Adds django user and request information to the exception as appropriate. """ from errordite import ErrorditeHandler class DjangoErrorditeHandler(ErrorditeHandler): """ Django-aware Errordite handler than enriches logs with request info. """ def enrich_errordite_payload(self, payload, record): """ Overrides base class implementation to add Django-specific error data - specifically user and HTTP request information. """ payload = super(DjangoErrorditeHandler, self).enrich_errordite_payload( payload, record ) if not hasattr(record, 'request'): return payload rq = record.request payload['Url'] = rq.get_full_path() if 'HTTP_USER_AGENT' in rq.META: payload['UserAgent'] = rq.META['HTTP_USER_AGENT'] data = payload['ExceptionInfo'].get('Data', {}) if 'HTTP_X_FORWARDED_FOR' in rq.META: data['X-Forwarded-For'] = rq.META['HTTP_X_FORWARDED_FOR'] if 'REMOTE_ADDR' in rq.META: data['client_ip'] = rq.META['REMOTE_ADDR'] if hasattr(rq, 'user'): if rq.user is not None: if rq.user.is_anonymous(): data['user'] = "anonymous" else: data['user'] = rq.user.username payload['ExceptionInfo']['Data'] = data return payload
<commit_before>""" Django-aware exception handler for integration with Errordite. Adds django user and request information to the exception as appropriate. """ from errordite import ErrorditeHandler class DjangoErrorditeHandler(ErrorditeHandler): """ Django-aware Errordite handler than enriches logs with request info. """ def enrich_errordite_payload(self, payload, record): """ Overrides base class implementation to add Django-specific error data - specifically user and HTTP request information. """ payload = super(DjangoErrorditeHandler, self).enrich_errordite_payload( payload, record ) if not hasattr(record, 'request'): return rq = record.request payload['Url'] = rq.get_full_path() if 'HTTP_USER_AGENT' in rq.META: payload['UserAgent'] = rq.META['HTTP_USER_AGENT'] data = payload['ExceptionInfo'].get('Data', {}) if 'HTTP_X_FORWARDED_FOR' in rq.META: data['X-Forwarded-For'] = rq.META['HTTP_X_FORWARDED_FOR'] if 'REMOTE_ADDR' in rq.META: data['client_ip'] = rq.META['REMOTE_ADDR'] if hasattr(rq, 'user'): if rq.user is not None: if rq.user.is_anonymous(): data['user'] = "anonymous" else: data['user'] = rq.user.username payload['ExceptionInfo']['Data'] = data return payload <commit_msg>Return payload even if request arg is not passed in.<commit_after>""" Django-aware exception handler for integration with Errordite. Adds django user and request information to the exception as appropriate. """ from errordite import ErrorditeHandler class DjangoErrorditeHandler(ErrorditeHandler): """ Django-aware Errordite handler than enriches logs with request info. """ def enrich_errordite_payload(self, payload, record): """ Overrides base class implementation to add Django-specific error data - specifically user and HTTP request information. """ payload = super(DjangoErrorditeHandler, self).enrich_errordite_payload( payload, record ) if not hasattr(record, 'request'): return payload rq = record.request payload['Url'] = rq.get_full_path() if 'HTTP_USER_AGENT' in rq.META: payload['UserAgent'] = rq.META['HTTP_USER_AGENT'] data = payload['ExceptionInfo'].get('Data', {}) if 'HTTP_X_FORWARDED_FOR' in rq.META: data['X-Forwarded-For'] = rq.META['HTTP_X_FORWARDED_FOR'] if 'REMOTE_ADDR' in rq.META: data['client_ip'] = rq.META['REMOTE_ADDR'] if hasattr(rq, 'user'): if rq.user is not None: if rq.user.is_anonymous(): data['user'] = "anonymous" else: data['user'] = rq.user.username payload['ExceptionInfo']['Data'] = data return payload
0a96055a08b27d195920ad88141676b02937e029
django_pytest/test_runner.py
django_pytest/test_runner.py
class TestRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def run_tests(self, test_labels): import pytest import sys if test_labels is None: print ('Not yet implemented: py.test is still not able to ' 'discover the tests in all the INSTALLED_APPS as Django ' 'requires.') exit(1) pytest_args = [] if self.failfast: pytest_args.append('--exitfirst') if self.verbosity == 0: pytest_args.append('--quiet') elif self.verbosity > 1: pytest_args.append('--verbose') # Remove arguments before (--). This separates Django command options # from py.test ones. try: pytest_args_index = sys.argv.index('--') + 1 pytest_args.extend(sys.argv[pytest_args_index:]) except ValueError: pass sys.exit(pytest.main(pytest_args)) # Keep the old name to be backwards-compatible def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]): runner = TestRunner(verbosity, interactive, failfast=False) runner.run_tests(test_labels)
class TestRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def run_tests(self, test_labels, extra_tests=None): import pytest import sys if test_labels is None: print ('Not yet implemented: py.test is still not able to ' 'discover the tests in all the INSTALLED_APPS as Django ' 'requires.') exit(1) if extra_tests: print ('Not yet implemented: py.test is still not able to ' 'run extra_tests as Django requires.') exit(1) pytest_args = [] if self.failfast: pytest_args.append('--exitfirst') if self.verbosity == 0: pytest_args.append('--quiet') elif self.verbosity > 1: pytest_args.append('--verbose') # Remove arguments before (--). This separates Django command options # from py.test ones. try: pytest_args_index = sys.argv.index('--') + 1 pytest_args.extend(sys.argv[pytest_args_index:]) except ValueError: pass sys.exit(pytest.main(pytest_args)) # Keep the old name to be backwards-compatible def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=None): runner = TestRunner(verbosity, interactive, failfast=False) runner.run_tests(test_labels, extra_tests)
Make run_tests a function to make it fully backwards compatible
Make run_tests a function to make it fully backwards compatible
Python
bsd-3-clause
0101/django-pytest,buchuki/django-pytest
class TestRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def run_tests(self, test_labels): import pytest import sys if test_labels is None: print ('Not yet implemented: py.test is still not able to ' 'discover the tests in all the INSTALLED_APPS as Django ' 'requires.') exit(1) pytest_args = [] if self.failfast: pytest_args.append('--exitfirst') if self.verbosity == 0: pytest_args.append('--quiet') elif self.verbosity > 1: pytest_args.append('--verbose') # Remove arguments before (--). This separates Django command options # from py.test ones. try: pytest_args_index = sys.argv.index('--') + 1 pytest_args.extend(sys.argv[pytest_args_index:]) except ValueError: pass sys.exit(pytest.main(pytest_args)) # Keep the old name to be backwards-compatible def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]): runner = TestRunner(verbosity, interactive, failfast=False) runner.run_tests(test_labels) Make run_tests a function to make it fully backwards compatible
class TestRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def run_tests(self, test_labels, extra_tests=None): import pytest import sys if test_labels is None: print ('Not yet implemented: py.test is still not able to ' 'discover the tests in all the INSTALLED_APPS as Django ' 'requires.') exit(1) if extra_tests: print ('Not yet implemented: py.test is still not able to ' 'run extra_tests as Django requires.') exit(1) pytest_args = [] if self.failfast: pytest_args.append('--exitfirst') if self.verbosity == 0: pytest_args.append('--quiet') elif self.verbosity > 1: pytest_args.append('--verbose') # Remove arguments before (--). This separates Django command options # from py.test ones. try: pytest_args_index = sys.argv.index('--') + 1 pytest_args.extend(sys.argv[pytest_args_index:]) except ValueError: pass sys.exit(pytest.main(pytest_args)) # Keep the old name to be backwards-compatible def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=None): runner = TestRunner(verbosity, interactive, failfast=False) runner.run_tests(test_labels, extra_tests)
<commit_before>class TestRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def run_tests(self, test_labels): import pytest import sys if test_labels is None: print ('Not yet implemented: py.test is still not able to ' 'discover the tests in all the INSTALLED_APPS as Django ' 'requires.') exit(1) pytest_args = [] if self.failfast: pytest_args.append('--exitfirst') if self.verbosity == 0: pytest_args.append('--quiet') elif self.verbosity > 1: pytest_args.append('--verbose') # Remove arguments before (--). This separates Django command options # from py.test ones. try: pytest_args_index = sys.argv.index('--') + 1 pytest_args.extend(sys.argv[pytest_args_index:]) except ValueError: pass sys.exit(pytest.main(pytest_args)) # Keep the old name to be backwards-compatible def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]): runner = TestRunner(verbosity, interactive, failfast=False) runner.run_tests(test_labels) <commit_msg>Make run_tests a function to make it fully backwards compatible<commit_after>
class TestRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def run_tests(self, test_labels, extra_tests=None): import pytest import sys if test_labels is None: print ('Not yet implemented: py.test is still not able to ' 'discover the tests in all the INSTALLED_APPS as Django ' 'requires.') exit(1) if extra_tests: print ('Not yet implemented: py.test is still not able to ' 'run extra_tests as Django requires.') exit(1) pytest_args = [] if self.failfast: pytest_args.append('--exitfirst') if self.verbosity == 0: pytest_args.append('--quiet') elif self.verbosity > 1: pytest_args.append('--verbose') # Remove arguments before (--). This separates Django command options # from py.test ones. try: pytest_args_index = sys.argv.index('--') + 1 pytest_args.extend(sys.argv[pytest_args_index:]) except ValueError: pass sys.exit(pytest.main(pytest_args)) # Keep the old name to be backwards-compatible def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=None): runner = TestRunner(verbosity, interactive, failfast=False) runner.run_tests(test_labels, extra_tests)
class TestRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def run_tests(self, test_labels): import pytest import sys if test_labels is None: print ('Not yet implemented: py.test is still not able to ' 'discover the tests in all the INSTALLED_APPS as Django ' 'requires.') exit(1) pytest_args = [] if self.failfast: pytest_args.append('--exitfirst') if self.verbosity == 0: pytest_args.append('--quiet') elif self.verbosity > 1: pytest_args.append('--verbose') # Remove arguments before (--). This separates Django command options # from py.test ones. try: pytest_args_index = sys.argv.index('--') + 1 pytest_args.extend(sys.argv[pytest_args_index:]) except ValueError: pass sys.exit(pytest.main(pytest_args)) # Keep the old name to be backwards-compatible def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]): runner = TestRunner(verbosity, interactive, failfast=False) runner.run_tests(test_labels) Make run_tests a function to make it fully backwards compatibleclass TestRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def run_tests(self, test_labels, extra_tests=None): import pytest import sys if test_labels is None: print ('Not yet implemented: py.test is still not able to ' 'discover the tests in all the INSTALLED_APPS as Django ' 'requires.') exit(1) if extra_tests: print ('Not yet implemented: py.test is still not able to ' 'run extra_tests as Django requires.') exit(1) pytest_args = [] if self.failfast: pytest_args.append('--exitfirst') if self.verbosity == 0: pytest_args.append('--quiet') elif self.verbosity > 1: pytest_args.append('--verbose') # Remove arguments before (--). This separates Django command options # from py.test ones. try: pytest_args_index = sys.argv.index('--') + 1 pytest_args.extend(sys.argv[pytest_args_index:]) except ValueError: pass sys.exit(pytest.main(pytest_args)) # Keep the old name to be backwards-compatible def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=None): runner = TestRunner(verbosity, interactive, failfast=False) runner.run_tests(test_labels, extra_tests)
<commit_before>class TestRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def run_tests(self, test_labels): import pytest import sys if test_labels is None: print ('Not yet implemented: py.test is still not able to ' 'discover the tests in all the INSTALLED_APPS as Django ' 'requires.') exit(1) pytest_args = [] if self.failfast: pytest_args.append('--exitfirst') if self.verbosity == 0: pytest_args.append('--quiet') elif self.verbosity > 1: pytest_args.append('--verbose') # Remove arguments before (--). This separates Django command options # from py.test ones. try: pytest_args_index = sys.argv.index('--') + 1 pytest_args.extend(sys.argv[pytest_args_index:]) except ValueError: pass sys.exit(pytest.main(pytest_args)) # Keep the old name to be backwards-compatible def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]): runner = TestRunner(verbosity, interactive, failfast=False) runner.run_tests(test_labels) <commit_msg>Make run_tests a function to make it fully backwards compatible<commit_after>class TestRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def run_tests(self, test_labels, extra_tests=None): import pytest import sys if test_labels is None: print ('Not yet implemented: py.test is still not able to ' 'discover the tests in all the INSTALLED_APPS as Django ' 'requires.') exit(1) if extra_tests: print ('Not yet implemented: py.test is still not able to ' 'run extra_tests as Django requires.') exit(1) pytest_args = [] if self.failfast: pytest_args.append('--exitfirst') if self.verbosity == 0: pytest_args.append('--quiet') elif self.verbosity > 1: pytest_args.append('--verbose') # Remove arguments before (--). This separates Django command options # from py.test ones. try: pytest_args_index = sys.argv.index('--') + 1 pytest_args.extend(sys.argv[pytest_args_index:]) except ValueError: pass sys.exit(pytest.main(pytest_args)) # Keep the old name to be backwards-compatible def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=None): runner = TestRunner(verbosity, interactive, failfast=False) runner.run_tests(test_labels, extra_tests)
61677883825eefcbdc2b1c943b1ce33b26def264
PrinterApplication.py
PrinterApplication.py
from Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): window = MainWindow("Cura Printer") window.Show() super(PrinterApplication, self).run()
from Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): self._plugin_registry.loadPlugins({ "type": "StorageDevice" }) window = MainWindow("Cura Printer") window.Show() super(PrinterApplication, self).run()
Load all storage plugins in the printer application
Load all storage plugins in the printer application
Python
agpl-3.0
totalretribution/Cura,Curahelper/Cura,senttech/Cura,lo0ol/Ultimaker-Cura,markwal/Cura,fieldOfView/Cura,ynotstartups/Wanhao,ynotstartups/Wanhao,quillford/Cura,bq/Ultimaker-Cura,ad1217/Cura,derekhe/Cura,senttech/Cura,hmflash/Cura,Curahelper/Cura,lo0ol/Ultimaker-Cura,DeskboxBrazil/Cura,derekhe/Cura,DeskboxBrazil/Cura,totalretribution/Cura,quillford/Cura,markwal/Cura,fieldOfView/Cura,bq/Ultimaker-Cura,fxtentacle/Cura,hmflash/Cura,fxtentacle/Cura,ad1217/Cura
from Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): window = MainWindow("Cura Printer") window.Show() super(PrinterApplication, self).run() Load all storage plugins in the printer application
from Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): self._plugin_registry.loadPlugins({ "type": "StorageDevice" }) window = MainWindow("Cura Printer") window.Show() super(PrinterApplication, self).run()
<commit_before>from Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): window = MainWindow("Cura Printer") window.Show() super(PrinterApplication, self).run() <commit_msg>Load all storage plugins in the printer application<commit_after>
from Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): self._plugin_registry.loadPlugins({ "type": "StorageDevice" }) window = MainWindow("Cura Printer") window.Show() super(PrinterApplication, self).run()
from Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): window = MainWindow("Cura Printer") window.Show() super(PrinterApplication, self).run() Load all storage plugins in the printer applicationfrom Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): self._plugin_registry.loadPlugins({ "type": "StorageDevice" }) window = MainWindow("Cura Printer") window.Show() super(PrinterApplication, self).run()
<commit_before>from Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): window = MainWindow("Cura Printer") window.Show() super(PrinterApplication, self).run() <commit_msg>Load all storage plugins in the printer application<commit_after>from Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): self._plugin_registry.loadPlugins({ "type": "StorageDevice" }) window = MainWindow("Cura Printer") window.Show() super(PrinterApplication, self).run()
e6ef3a1c609de227bff34a811910f08b3e5e69c9
Lib/sandbox/pyem/__init__.py
Lib/sandbox/pyem/__init__.py
#! /usr/bin/env python # Last Change: Sat Jun 09 10:00 PM 2007 J from info import __doc__ from gauss_mix import GmParamError, GM from gmm_em import GmmParamError, GMM, EM #from online_em import OnGMM as _OnGMM #import examples as _examples __all__ = filter(lambda s:not s.startswith('_'), dir()) from numpy.testing import NumpyTest test = NumpyTest().test
#! /usr/bin/env python # Last Change: Sun Jul 22 11:00 AM 2007 J raise ImportError( """pyem has been moved to scikits and renamed to em. Please install scikits.learn instead, and change your import to the following: from scickits.learn.machine import em.""") from info import __doc__ from gauss_mix import GmParamError, GM from gmm_em import GmmParamError, GMM, EM #from online_em import OnGMM as _OnGMM #import examples as _examples __all__ = filter(lambda s:not s.startswith('_'), dir()) from numpy.testing import NumpyTest test = NumpyTest().test
Raise an import error when importing pyem as it has been moved to scikits.
Raise an import error when importing pyem as it has been moved to scikits. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@3179 d6536bca-fef9-0310-8506-e4c0a848fbcf
Python
bsd-3-clause
scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt
#! /usr/bin/env python # Last Change: Sat Jun 09 10:00 PM 2007 J from info import __doc__ from gauss_mix import GmParamError, GM from gmm_em import GmmParamError, GMM, EM #from online_em import OnGMM as _OnGMM #import examples as _examples __all__ = filter(lambda s:not s.startswith('_'), dir()) from numpy.testing import NumpyTest test = NumpyTest().test Raise an import error when importing pyem as it has been moved to scikits. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@3179 d6536bca-fef9-0310-8506-e4c0a848fbcf
#! /usr/bin/env python # Last Change: Sun Jul 22 11:00 AM 2007 J raise ImportError( """pyem has been moved to scikits and renamed to em. Please install scikits.learn instead, and change your import to the following: from scickits.learn.machine import em.""") from info import __doc__ from gauss_mix import GmParamError, GM from gmm_em import GmmParamError, GMM, EM #from online_em import OnGMM as _OnGMM #import examples as _examples __all__ = filter(lambda s:not s.startswith('_'), dir()) from numpy.testing import NumpyTest test = NumpyTest().test
<commit_before>#! /usr/bin/env python # Last Change: Sat Jun 09 10:00 PM 2007 J from info import __doc__ from gauss_mix import GmParamError, GM from gmm_em import GmmParamError, GMM, EM #from online_em import OnGMM as _OnGMM #import examples as _examples __all__ = filter(lambda s:not s.startswith('_'), dir()) from numpy.testing import NumpyTest test = NumpyTest().test <commit_msg>Raise an import error when importing pyem as it has been moved to scikits. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@3179 d6536bca-fef9-0310-8506-e4c0a848fbcf<commit_after>
#! /usr/bin/env python # Last Change: Sun Jul 22 11:00 AM 2007 J raise ImportError( """pyem has been moved to scikits and renamed to em. Please install scikits.learn instead, and change your import to the following: from scickits.learn.machine import em.""") from info import __doc__ from gauss_mix import GmParamError, GM from gmm_em import GmmParamError, GMM, EM #from online_em import OnGMM as _OnGMM #import examples as _examples __all__ = filter(lambda s:not s.startswith('_'), dir()) from numpy.testing import NumpyTest test = NumpyTest().test
#! /usr/bin/env python # Last Change: Sat Jun 09 10:00 PM 2007 J from info import __doc__ from gauss_mix import GmParamError, GM from gmm_em import GmmParamError, GMM, EM #from online_em import OnGMM as _OnGMM #import examples as _examples __all__ = filter(lambda s:not s.startswith('_'), dir()) from numpy.testing import NumpyTest test = NumpyTest().test Raise an import error when importing pyem as it has been moved to scikits. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@3179 d6536bca-fef9-0310-8506-e4c0a848fbcf#! /usr/bin/env python # Last Change: Sun Jul 22 11:00 AM 2007 J raise ImportError( """pyem has been moved to scikits and renamed to em. Please install scikits.learn instead, and change your import to the following: from scickits.learn.machine import em.""") from info import __doc__ from gauss_mix import GmParamError, GM from gmm_em import GmmParamError, GMM, EM #from online_em import OnGMM as _OnGMM #import examples as _examples __all__ = filter(lambda s:not s.startswith('_'), dir()) from numpy.testing import NumpyTest test = NumpyTest().test
<commit_before>#! /usr/bin/env python # Last Change: Sat Jun 09 10:00 PM 2007 J from info import __doc__ from gauss_mix import GmParamError, GM from gmm_em import GmmParamError, GMM, EM #from online_em import OnGMM as _OnGMM #import examples as _examples __all__ = filter(lambda s:not s.startswith('_'), dir()) from numpy.testing import NumpyTest test = NumpyTest().test <commit_msg>Raise an import error when importing pyem as it has been moved to scikits. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@3179 d6536bca-fef9-0310-8506-e4c0a848fbcf<commit_after>#! /usr/bin/env python # Last Change: Sun Jul 22 11:00 AM 2007 J raise ImportError( """pyem has been moved to scikits and renamed to em. Please install scikits.learn instead, and change your import to the following: from scickits.learn.machine import em.""") from info import __doc__ from gauss_mix import GmParamError, GM from gmm_em import GmmParamError, GMM, EM #from online_em import OnGMM as _OnGMM #import examples as _examples __all__ = filter(lambda s:not s.startswith('_'), dir()) from numpy.testing import NumpyTest test = NumpyTest().test
e7ee29f03dd83a795828de92aba654e9a7db3dd4
deflect/views.py
deflect/views.py
from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import RedirectURL from .utils import add_query_params logger = logging.getLogger(__name__) def redirect(request, url_path): """ """ try: id = base32_crockford.decode(url_path) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(RedirectURL, pk=id) RedirectURL.objects.filter(pk=id).update(hits=F('hits') + 1, last_used=now()) # Inject Google campaign parameters; if any of these # are not set, they will be ignored utm_params = {'utm_source': redirect.short_url, 'utm_campaign': redirect.campaign, 'utm_content': redirect.content, 'utm_medium': redirect.medium} url = add_query_params(redirect.url, utm_params) return HttpResponsePermanentRedirect(url)
from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import RedirectURL from .utils import add_query_params logger = logging.getLogger(__name__) def redirect(request, url_path): """ Given the path component of a short URL, update the URL's statistics and redirect the user to the full destination URL, including available Google Analytics parameters. """ try: id = base32_crockford.decode(url_path) except ValueError as e: logger.warning("Error decoding redirect '%s': %s" % (url_path, e)) raise Http404 redirect = get_object_or_404(RedirectURL, pk=id) RedirectURL.objects.filter(pk=id).update(hits=F('hits') + 1, last_used=now()) # Inject Google campaign parameters; if any of these # are not set, they will be ignored utm_params = {'utm_source': redirect.short_url, 'utm_campaign': redirect.campaign, 'utm_content': redirect.content, 'utm_medium': redirect.medium} url = add_query_params(redirect.url, utm_params) return HttpResponsePermanentRedirect(url)
Improve comment and logging text
Improve comment and logging text
Python
bsd-3-clause
jbittel/django-deflect
from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import RedirectURL from .utils import add_query_params logger = logging.getLogger(__name__) def redirect(request, url_path): """ """ try: id = base32_crockford.decode(url_path) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(RedirectURL, pk=id) RedirectURL.objects.filter(pk=id).update(hits=F('hits') + 1, last_used=now()) # Inject Google campaign parameters; if any of these # are not set, they will be ignored utm_params = {'utm_source': redirect.short_url, 'utm_campaign': redirect.campaign, 'utm_content': redirect.content, 'utm_medium': redirect.medium} url = add_query_params(redirect.url, utm_params) return HttpResponsePermanentRedirect(url) Improve comment and logging text
from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import RedirectURL from .utils import add_query_params logger = logging.getLogger(__name__) def redirect(request, url_path): """ Given the path component of a short URL, update the URL's statistics and redirect the user to the full destination URL, including available Google Analytics parameters. """ try: id = base32_crockford.decode(url_path) except ValueError as e: logger.warning("Error decoding redirect '%s': %s" % (url_path, e)) raise Http404 redirect = get_object_or_404(RedirectURL, pk=id) RedirectURL.objects.filter(pk=id).update(hits=F('hits') + 1, last_used=now()) # Inject Google campaign parameters; if any of these # are not set, they will be ignored utm_params = {'utm_source': redirect.short_url, 'utm_campaign': redirect.campaign, 'utm_content': redirect.content, 'utm_medium': redirect.medium} url = add_query_params(redirect.url, utm_params) return HttpResponsePermanentRedirect(url)
<commit_before>from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import RedirectURL from .utils import add_query_params logger = logging.getLogger(__name__) def redirect(request, url_path): """ """ try: id = base32_crockford.decode(url_path) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(RedirectURL, pk=id) RedirectURL.objects.filter(pk=id).update(hits=F('hits') + 1, last_used=now()) # Inject Google campaign parameters; if any of these # are not set, they will be ignored utm_params = {'utm_source': redirect.short_url, 'utm_campaign': redirect.campaign, 'utm_content': redirect.content, 'utm_medium': redirect.medium} url = add_query_params(redirect.url, utm_params) return HttpResponsePermanentRedirect(url) <commit_msg>Improve comment and logging text<commit_after>
from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import RedirectURL from .utils import add_query_params logger = logging.getLogger(__name__) def redirect(request, url_path): """ Given the path component of a short URL, update the URL's statistics and redirect the user to the full destination URL, including available Google Analytics parameters. """ try: id = base32_crockford.decode(url_path) except ValueError as e: logger.warning("Error decoding redirect '%s': %s" % (url_path, e)) raise Http404 redirect = get_object_or_404(RedirectURL, pk=id) RedirectURL.objects.filter(pk=id).update(hits=F('hits') + 1, last_used=now()) # Inject Google campaign parameters; if any of these # are not set, they will be ignored utm_params = {'utm_source': redirect.short_url, 'utm_campaign': redirect.campaign, 'utm_content': redirect.content, 'utm_medium': redirect.medium} url = add_query_params(redirect.url, utm_params) return HttpResponsePermanentRedirect(url)
from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import RedirectURL from .utils import add_query_params logger = logging.getLogger(__name__) def redirect(request, url_path): """ """ try: id = base32_crockford.decode(url_path) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(RedirectURL, pk=id) RedirectURL.objects.filter(pk=id).update(hits=F('hits') + 1, last_used=now()) # Inject Google campaign parameters; if any of these # are not set, they will be ignored utm_params = {'utm_source': redirect.short_url, 'utm_campaign': redirect.campaign, 'utm_content': redirect.content, 'utm_medium': redirect.medium} url = add_query_params(redirect.url, utm_params) return HttpResponsePermanentRedirect(url) Improve comment and logging textfrom __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import RedirectURL from .utils import add_query_params logger = logging.getLogger(__name__) def redirect(request, url_path): """ Given the path component of a short URL, update the URL's statistics and redirect the user to the full destination URL, including available Google Analytics parameters. """ try: id = base32_crockford.decode(url_path) except ValueError as e: logger.warning("Error decoding redirect '%s': %s" % (url_path, e)) raise Http404 redirect = get_object_or_404(RedirectURL, pk=id) RedirectURL.objects.filter(pk=id).update(hits=F('hits') + 1, last_used=now()) # Inject Google campaign parameters; if any of these # are not set, they will be ignored utm_params = {'utm_source': redirect.short_url, 'utm_campaign': redirect.campaign, 'utm_content': redirect.content, 'utm_medium': redirect.medium} url = add_query_params(redirect.url, utm_params) return HttpResponsePermanentRedirect(url)
<commit_before>from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import RedirectURL from .utils import add_query_params logger = logging.getLogger(__name__) def redirect(request, url_path): """ """ try: id = base32_crockford.decode(url_path) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(RedirectURL, pk=id) RedirectURL.objects.filter(pk=id).update(hits=F('hits') + 1, last_used=now()) # Inject Google campaign parameters; if any of these # are not set, they will be ignored utm_params = {'utm_source': redirect.short_url, 'utm_campaign': redirect.campaign, 'utm_content': redirect.content, 'utm_medium': redirect.medium} url = add_query_params(redirect.url, utm_params) return HttpResponsePermanentRedirect(url) <commit_msg>Improve comment and logging text<commit_after>from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import RedirectURL from .utils import add_query_params logger = logging.getLogger(__name__) def redirect(request, url_path): """ Given the path component of a short URL, update the URL's statistics and redirect the user to the full destination URL, including available Google Analytics parameters. """ try: id = base32_crockford.decode(url_path) except ValueError as e: logger.warning("Error decoding redirect '%s': %s" % (url_path, e)) raise Http404 redirect = get_object_or_404(RedirectURL, pk=id) RedirectURL.objects.filter(pk=id).update(hits=F('hits') + 1, last_used=now()) # Inject Google campaign parameters; if any of these # are not set, they will be ignored utm_params = {'utm_source': redirect.short_url, 'utm_campaign': redirect.campaign, 'utm_content': redirect.content, 'utm_medium': redirect.medium} url = add_query_params(redirect.url, utm_params) return HttpResponsePermanentRedirect(url)
dd1c220606a1d7a40b9d3def1acbbfd03a865004
docs/conf.py
docs/conf.py
import sys import os import sphinx_rtd_theme # Provide path to the python modules we want to run autodoc on sys.path.insert(0, os.path.abspath('../qp')) # Avoid imports that may be unsatisfied when running sphinx, see: # http://stackoverflow.com/questions/15889621/sphinx-how-to-exclude-imports-in-automodule#15912502 autodoc_mock_imports = ["scipy","scipy.interpolate"] extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon' ] html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] master_doc = 'index' autosummary_generate = True autoclass_content = "class" autodoc_default_flags = ["members", "no-special-members"] html_sidebars = { '**': ['globaltoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'], } project = u'qp' author = u'Alex Malz and Phil Marshall' copyright = u'2016, ' + author version = "0.1" release = "0.1.0"
import sys import os import sphinx_rtd_theme # Provide path to the python modules we want to run autodoc on sys.path.insert(0, os.path.abspath('../qp')) # Avoid imports that may be unsatisfied when running sphinx, see: # http://stackoverflow.com/questions/15889621/sphinx-how-to-exclude-imports-in-automodule#15912502 autodoc_mock_imports = ["scipy","scipy.interpolate"] extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon', 'sphinx.ext.viewcode'] html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] master_doc = 'index' autosummary_generate = True autoclass_content = "class" autodoc_default_flags = ["members", "no-special-members"] html_sidebars = { '**': ['globaltoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'], } project = u'qp' author = u'Alex Malz and Phil Marshall' copyright = u'2016, ' + author version = "0.1" release = "0.1.0"
Include links to source code with viewcode extension
Include links to source code with viewcode extension
Python
mit
aimalz/qp
import sys import os import sphinx_rtd_theme # Provide path to the python modules we want to run autodoc on sys.path.insert(0, os.path.abspath('../qp')) # Avoid imports that may be unsatisfied when running sphinx, see: # http://stackoverflow.com/questions/15889621/sphinx-how-to-exclude-imports-in-automodule#15912502 autodoc_mock_imports = ["scipy","scipy.interpolate"] extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon' ] html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] master_doc = 'index' autosummary_generate = True autoclass_content = "class" autodoc_default_flags = ["members", "no-special-members"] html_sidebars = { '**': ['globaltoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'], } project = u'qp' author = u'Alex Malz and Phil Marshall' copyright = u'2016, ' + author version = "0.1" release = "0.1.0" Include links to source code with viewcode extension
import sys import os import sphinx_rtd_theme # Provide path to the python modules we want to run autodoc on sys.path.insert(0, os.path.abspath('../qp')) # Avoid imports that may be unsatisfied when running sphinx, see: # http://stackoverflow.com/questions/15889621/sphinx-how-to-exclude-imports-in-automodule#15912502 autodoc_mock_imports = ["scipy","scipy.interpolate"] extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon', 'sphinx.ext.viewcode'] html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] master_doc = 'index' autosummary_generate = True autoclass_content = "class" autodoc_default_flags = ["members", "no-special-members"] html_sidebars = { '**': ['globaltoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'], } project = u'qp' author = u'Alex Malz and Phil Marshall' copyright = u'2016, ' + author version = "0.1" release = "0.1.0"
<commit_before>import sys import os import sphinx_rtd_theme # Provide path to the python modules we want to run autodoc on sys.path.insert(0, os.path.abspath('../qp')) # Avoid imports that may be unsatisfied when running sphinx, see: # http://stackoverflow.com/questions/15889621/sphinx-how-to-exclude-imports-in-automodule#15912502 autodoc_mock_imports = ["scipy","scipy.interpolate"] extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon' ] html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] master_doc = 'index' autosummary_generate = True autoclass_content = "class" autodoc_default_flags = ["members", "no-special-members"] html_sidebars = { '**': ['globaltoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'], } project = u'qp' author = u'Alex Malz and Phil Marshall' copyright = u'2016, ' + author version = "0.1" release = "0.1.0" <commit_msg>Include links to source code with viewcode extension<commit_after>
import sys import os import sphinx_rtd_theme # Provide path to the python modules we want to run autodoc on sys.path.insert(0, os.path.abspath('../qp')) # Avoid imports that may be unsatisfied when running sphinx, see: # http://stackoverflow.com/questions/15889621/sphinx-how-to-exclude-imports-in-automodule#15912502 autodoc_mock_imports = ["scipy","scipy.interpolate"] extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon', 'sphinx.ext.viewcode'] html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] master_doc = 'index' autosummary_generate = True autoclass_content = "class" autodoc_default_flags = ["members", "no-special-members"] html_sidebars = { '**': ['globaltoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'], } project = u'qp' author = u'Alex Malz and Phil Marshall' copyright = u'2016, ' + author version = "0.1" release = "0.1.0"
import sys import os import sphinx_rtd_theme # Provide path to the python modules we want to run autodoc on sys.path.insert(0, os.path.abspath('../qp')) # Avoid imports that may be unsatisfied when running sphinx, see: # http://stackoverflow.com/questions/15889621/sphinx-how-to-exclude-imports-in-automodule#15912502 autodoc_mock_imports = ["scipy","scipy.interpolate"] extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon' ] html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] master_doc = 'index' autosummary_generate = True autoclass_content = "class" autodoc_default_flags = ["members", "no-special-members"] html_sidebars = { '**': ['globaltoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'], } project = u'qp' author = u'Alex Malz and Phil Marshall' copyright = u'2016, ' + author version = "0.1" release = "0.1.0" Include links to source code with viewcode extensionimport sys import os import sphinx_rtd_theme # Provide path to the python modules we want to run autodoc on sys.path.insert(0, os.path.abspath('../qp')) # Avoid imports that may be unsatisfied when running sphinx, see: # http://stackoverflow.com/questions/15889621/sphinx-how-to-exclude-imports-in-automodule#15912502 autodoc_mock_imports = ["scipy","scipy.interpolate"] extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon', 'sphinx.ext.viewcode'] html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] master_doc = 'index' autosummary_generate = True autoclass_content = "class" autodoc_default_flags = ["members", "no-special-members"] html_sidebars = { '**': ['globaltoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'], } project = u'qp' author = u'Alex Malz and Phil Marshall' copyright = u'2016, ' + author version = "0.1" release = "0.1.0"
<commit_before>import sys import os import sphinx_rtd_theme # Provide path to the python modules we want to run autodoc on sys.path.insert(0, os.path.abspath('../qp')) # Avoid imports that may be unsatisfied when running sphinx, see: # http://stackoverflow.com/questions/15889621/sphinx-how-to-exclude-imports-in-automodule#15912502 autodoc_mock_imports = ["scipy","scipy.interpolate"] extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon' ] html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] master_doc = 'index' autosummary_generate = True autoclass_content = "class" autodoc_default_flags = ["members", "no-special-members"] html_sidebars = { '**': ['globaltoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'], } project = u'qp' author = u'Alex Malz and Phil Marshall' copyright = u'2016, ' + author version = "0.1" release = "0.1.0" <commit_msg>Include links to source code with viewcode extension<commit_after>import sys import os import sphinx_rtd_theme # Provide path to the python modules we want to run autodoc on sys.path.insert(0, os.path.abspath('../qp')) # Avoid imports that may be unsatisfied when running sphinx, see: # http://stackoverflow.com/questions/15889621/sphinx-how-to-exclude-imports-in-automodule#15912502 autodoc_mock_imports = ["scipy","scipy.interpolate"] extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon', 'sphinx.ext.viewcode'] html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] master_doc = 'index' autosummary_generate = True autoclass_content = "class" autodoc_default_flags = ["members", "no-special-members"] html_sidebars = { '**': ['globaltoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'], } project = u'qp' author = u'Alex Malz and Phil Marshall' copyright = u'2016, ' + author version = "0.1" release = "0.1.0"
43ab1f2015b71ba5b63152dee524d0ccc1864302
test/helpers/xnat_test_helper.py
test/helpers/xnat_test_helper.py
import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name that is unique to the given test name. :param name: the test name :return: the test subject name """ return encode(name).strip('=')
import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name that is unique to the given test name. :param name: the test name :return: the test subject name """ return encode(name).strip('=') def delete_subjects(project, *subject_names): """ Deletes the given XNAT subjects, if they exist. :param project: the XNAT project id :param subject_names: the XNAT subject names """ with xnat_helper.connection() as xnat: for sbj_lbl in subject_names: sbj = xnat.get_subject(project, sbj_lbl) if sbj.exists(): sbj.delete() logger.debug("Deleted the XNAT test subject %s." % sbj_lbl)
Move delete_subjects to a test helper.
Move delete_subjects to a test helper.
Python
bsd-2-clause
ohsu-qin/qipipe
import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name that is unique to the given test name. :param name: the test name :return: the test subject name """ return encode(name).strip('=') Move delete_subjects to a test helper.
import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name that is unique to the given test name. :param name: the test name :return: the test subject name """ return encode(name).strip('=') def delete_subjects(project, *subject_names): """ Deletes the given XNAT subjects, if they exist. :param project: the XNAT project id :param subject_names: the XNAT subject names """ with xnat_helper.connection() as xnat: for sbj_lbl in subject_names: sbj = xnat.get_subject(project, sbj_lbl) if sbj.exists(): sbj.delete() logger.debug("Deleted the XNAT test subject %s." % sbj_lbl)
<commit_before>import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name that is unique to the given test name. :param name: the test name :return: the test subject name """ return encode(name).strip('=') <commit_msg>Move delete_subjects to a test helper.<commit_after>
import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name that is unique to the given test name. :param name: the test name :return: the test subject name """ return encode(name).strip('=') def delete_subjects(project, *subject_names): """ Deletes the given XNAT subjects, if they exist. :param project: the XNAT project id :param subject_names: the XNAT subject names """ with xnat_helper.connection() as xnat: for sbj_lbl in subject_names: sbj = xnat.get_subject(project, sbj_lbl) if sbj.exists(): sbj.delete() logger.debug("Deleted the XNAT test subject %s." % sbj_lbl)
import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name that is unique to the given test name. :param name: the test name :return: the test subject name """ return encode(name).strip('=') Move delete_subjects to a test helper.import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name that is unique to the given test name. :param name: the test name :return: the test subject name """ return encode(name).strip('=') def delete_subjects(project, *subject_names): """ Deletes the given XNAT subjects, if they exist. :param project: the XNAT project id :param subject_names: the XNAT subject names """ with xnat_helper.connection() as xnat: for sbj_lbl in subject_names: sbj = xnat.get_subject(project, sbj_lbl) if sbj.exists(): sbj.delete() logger.debug("Deleted the XNAT test subject %s." % sbj_lbl)
<commit_before>import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name that is unique to the given test name. :param name: the test name :return: the test subject name """ return encode(name).strip('=') <commit_msg>Move delete_subjects to a test helper.<commit_after>import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name that is unique to the given test name. :param name: the test name :return: the test subject name """ return encode(name).strip('=') def delete_subjects(project, *subject_names): """ Deletes the given XNAT subjects, if they exist. :param project: the XNAT project id :param subject_names: the XNAT subject names """ with xnat_helper.connection() as xnat: for sbj_lbl in subject_names: sbj = xnat.get_subject(project, sbj_lbl) if sbj.exists(): sbj.delete() logger.debug("Deleted the XNAT test subject %s." % sbj_lbl)
78a40488ee1adabb77400708e7d091e94807c1b5
PynamoDB/membership_stage.py
PynamoDB/membership_stage.py
from consistent_hash_ring import ConsistentHashRing from error_code import ErrorCode import util def get_hash(value): return hashlib.sha256(value).hexdigest() class MembershipStage(object): """ Stage for managing membership.""" @classmethod def from_node_list(cls, file_name, **kwargs): node_addresses = [] with open(file_name) as f: for line in f: node_addresses.append(line.strip()) return cls(**kwargs, node_addresses=node_addresses) def __init__(self, server = None, node_addresses=[]): self._server = server self._internal_request_stage = internal_request_stage self._node_lookup = {get_hash(node_address) : node_hash for node_address in node_addresses} self._consistent_hash_ring = ConsistentHashRing() def get_node_address(self, node_hash=None): """ Returns the IP address of a node identified by its hash value in the node ring.""" if node_hash: return self._node_lookup[node_hash] def partition_keyspace(self): """ Returns: a dict() where: keys: node_hashes values: keys for which the given node_hash is responsible """ pass
from consistent_hash_ring import ConsistentHashRing import logging import util import collections class MembershipStage(object): """ Stage for managing ring membeship and failure detection.""" def __init__(self, server = None, node_addresses=[]): self.logger = logging.getLogger('{}'.format(self.__class__.__name__)) self.logger.debug('__init__') self._server = server self._node_lookup = {util.get_hash(str(node_address)) : node_address for node_address in node_addresses} self._consistent_hash_ring = ConsistentHashRing(node_hashes = self._node_lookup.keys()) self.logger.debug('__init__. node_lookup: {}'.format(self._node_lookup)) def node_address(self, node_hash=None): """ Returns the address of a node identified by its hash value in the node ring.""" if node_hash: return self._node_lookup[node_hash] def get_responsible_node_hashes(self, *args, **kwargs): self.logger.debug('get_responsible_node_hashes') return self._consistent_hash_ring.get_responsible_node_hashes(*args, **kwargs) def _handle_announced_failure(self): """ Called when instructed to shut down. """ def _handle_unannounced_failure(self): """ Called when unannounced failure of another node is detected.""" def process(self): pass
Add skeleton methods for failures.
Add skeleton methods for failures. Decided that MembershipStage should handle the announced/unannounced failures since it’s in charge of detecting failures as well as the consistent hash ring.
Python
mit
samuelwu90/PynamoDB
from consistent_hash_ring import ConsistentHashRing from error_code import ErrorCode import util def get_hash(value): return hashlib.sha256(value).hexdigest() class MembershipStage(object): """ Stage for managing membership.""" @classmethod def from_node_list(cls, file_name, **kwargs): node_addresses = [] with open(file_name) as f: for line in f: node_addresses.append(line.strip()) return cls(**kwargs, node_addresses=node_addresses) def __init__(self, server = None, node_addresses=[]): self._server = server self._internal_request_stage = internal_request_stage self._node_lookup = {get_hash(node_address) : node_hash for node_address in node_addresses} self._consistent_hash_ring = ConsistentHashRing() def get_node_address(self, node_hash=None): """ Returns the IP address of a node identified by its hash value in the node ring.""" if node_hash: return self._node_lookup[node_hash] def partition_keyspace(self): """ Returns: a dict() where: keys: node_hashes values: keys for which the given node_hash is responsible """ pass Add skeleton methods for failures. Decided that MembershipStage should handle the announced/unannounced failures since it’s in charge of detecting failures as well as the consistent hash ring.
from consistent_hash_ring import ConsistentHashRing import logging import util import collections class MembershipStage(object): """ Stage for managing ring membeship and failure detection.""" def __init__(self, server = None, node_addresses=[]): self.logger = logging.getLogger('{}'.format(self.__class__.__name__)) self.logger.debug('__init__') self._server = server self._node_lookup = {util.get_hash(str(node_address)) : node_address for node_address in node_addresses} self._consistent_hash_ring = ConsistentHashRing(node_hashes = self._node_lookup.keys()) self.logger.debug('__init__. node_lookup: {}'.format(self._node_lookup)) def node_address(self, node_hash=None): """ Returns the address of a node identified by its hash value in the node ring.""" if node_hash: return self._node_lookup[node_hash] def get_responsible_node_hashes(self, *args, **kwargs): self.logger.debug('get_responsible_node_hashes') return self._consistent_hash_ring.get_responsible_node_hashes(*args, **kwargs) def _handle_announced_failure(self): """ Called when instructed to shut down. """ def _handle_unannounced_failure(self): """ Called when unannounced failure of another node is detected.""" def process(self): pass
<commit_before>from consistent_hash_ring import ConsistentHashRing from error_code import ErrorCode import util def get_hash(value): return hashlib.sha256(value).hexdigest() class MembershipStage(object): """ Stage for managing membership.""" @classmethod def from_node_list(cls, file_name, **kwargs): node_addresses = [] with open(file_name) as f: for line in f: node_addresses.append(line.strip()) return cls(**kwargs, node_addresses=node_addresses) def __init__(self, server = None, node_addresses=[]): self._server = server self._internal_request_stage = internal_request_stage self._node_lookup = {get_hash(node_address) : node_hash for node_address in node_addresses} self._consistent_hash_ring = ConsistentHashRing() def get_node_address(self, node_hash=None): """ Returns the IP address of a node identified by its hash value in the node ring.""" if node_hash: return self._node_lookup[node_hash] def partition_keyspace(self): """ Returns: a dict() where: keys: node_hashes values: keys for which the given node_hash is responsible """ pass <commit_msg>Add skeleton methods for failures. Decided that MembershipStage should handle the announced/unannounced failures since it’s in charge of detecting failures as well as the consistent hash ring.<commit_after>
from consistent_hash_ring import ConsistentHashRing import logging import util import collections class MembershipStage(object): """ Stage for managing ring membeship and failure detection.""" def __init__(self, server = None, node_addresses=[]): self.logger = logging.getLogger('{}'.format(self.__class__.__name__)) self.logger.debug('__init__') self._server = server self._node_lookup = {util.get_hash(str(node_address)) : node_address for node_address in node_addresses} self._consistent_hash_ring = ConsistentHashRing(node_hashes = self._node_lookup.keys()) self.logger.debug('__init__. node_lookup: {}'.format(self._node_lookup)) def node_address(self, node_hash=None): """ Returns the address of a node identified by its hash value in the node ring.""" if node_hash: return self._node_lookup[node_hash] def get_responsible_node_hashes(self, *args, **kwargs): self.logger.debug('get_responsible_node_hashes') return self._consistent_hash_ring.get_responsible_node_hashes(*args, **kwargs) def _handle_announced_failure(self): """ Called when instructed to shut down. """ def _handle_unannounced_failure(self): """ Called when unannounced failure of another node is detected.""" def process(self): pass
from consistent_hash_ring import ConsistentHashRing from error_code import ErrorCode import util def get_hash(value): return hashlib.sha256(value).hexdigest() class MembershipStage(object): """ Stage for managing membership.""" @classmethod def from_node_list(cls, file_name, **kwargs): node_addresses = [] with open(file_name) as f: for line in f: node_addresses.append(line.strip()) return cls(**kwargs, node_addresses=node_addresses) def __init__(self, server = None, node_addresses=[]): self._server = server self._internal_request_stage = internal_request_stage self._node_lookup = {get_hash(node_address) : node_hash for node_address in node_addresses} self._consistent_hash_ring = ConsistentHashRing() def get_node_address(self, node_hash=None): """ Returns the IP address of a node identified by its hash value in the node ring.""" if node_hash: return self._node_lookup[node_hash] def partition_keyspace(self): """ Returns: a dict() where: keys: node_hashes values: keys for which the given node_hash is responsible """ pass Add skeleton methods for failures. Decided that MembershipStage should handle the announced/unannounced failures since it’s in charge of detecting failures as well as the consistent hash ring.from consistent_hash_ring import ConsistentHashRing import logging import util import collections class MembershipStage(object): """ Stage for managing ring membeship and failure detection.""" def __init__(self, server = None, node_addresses=[]): self.logger = logging.getLogger('{}'.format(self.__class__.__name__)) self.logger.debug('__init__') self._server = server self._node_lookup = {util.get_hash(str(node_address)) : node_address for node_address in node_addresses} self._consistent_hash_ring = ConsistentHashRing(node_hashes = self._node_lookup.keys()) self.logger.debug('__init__. node_lookup: {}'.format(self._node_lookup)) def node_address(self, node_hash=None): """ Returns the address of a node identified by its hash value in the node ring.""" if node_hash: return self._node_lookup[node_hash] def get_responsible_node_hashes(self, *args, **kwargs): self.logger.debug('get_responsible_node_hashes') return self._consistent_hash_ring.get_responsible_node_hashes(*args, **kwargs) def _handle_announced_failure(self): """ Called when instructed to shut down. """ def _handle_unannounced_failure(self): """ Called when unannounced failure of another node is detected.""" def process(self): pass
<commit_before>from consistent_hash_ring import ConsistentHashRing from error_code import ErrorCode import util def get_hash(value): return hashlib.sha256(value).hexdigest() class MembershipStage(object): """ Stage for managing membership.""" @classmethod def from_node_list(cls, file_name, **kwargs): node_addresses = [] with open(file_name) as f: for line in f: node_addresses.append(line.strip()) return cls(**kwargs, node_addresses=node_addresses) def __init__(self, server = None, node_addresses=[]): self._server = server self._internal_request_stage = internal_request_stage self._node_lookup = {get_hash(node_address) : node_hash for node_address in node_addresses} self._consistent_hash_ring = ConsistentHashRing() def get_node_address(self, node_hash=None): """ Returns the IP address of a node identified by its hash value in the node ring.""" if node_hash: return self._node_lookup[node_hash] def partition_keyspace(self): """ Returns: a dict() where: keys: node_hashes values: keys for which the given node_hash is responsible """ pass <commit_msg>Add skeleton methods for failures. Decided that MembershipStage should handle the announced/unannounced failures since it’s in charge of detecting failures as well as the consistent hash ring.<commit_after>from consistent_hash_ring import ConsistentHashRing import logging import util import collections class MembershipStage(object): """ Stage for managing ring membeship and failure detection.""" def __init__(self, server = None, node_addresses=[]): self.logger = logging.getLogger('{}'.format(self.__class__.__name__)) self.logger.debug('__init__') self._server = server self._node_lookup = {util.get_hash(str(node_address)) : node_address for node_address in node_addresses} self._consistent_hash_ring = ConsistentHashRing(node_hashes = self._node_lookup.keys()) self.logger.debug('__init__. node_lookup: {}'.format(self._node_lookup)) def node_address(self, node_hash=None): """ Returns the address of a node identified by its hash value in the node ring.""" if node_hash: return self._node_lookup[node_hash] def get_responsible_node_hashes(self, *args, **kwargs): self.logger.debug('get_responsible_node_hashes') return self._consistent_hash_ring.get_responsible_node_hashes(*args, **kwargs) def _handle_announced_failure(self): """ Called when instructed to shut down. """ def _handle_unannounced_failure(self): """ Called when unannounced failure of another node is detected.""" def process(self): pass
bfce7465713edbc4e596138c9ce24c67454d533c
pomito/plugins/__init__.py
pomito/plugins/__init__.py
# -*- coding: utf-8 -*- # Pomito - Pomodoro timer on steroids # Base package for plugins __all__ = ['initialize', 'get_plugin'] # TODO Enable plugin discovery, support for drop-in plugins # TODO Validate plugins # TODO Some plugins may fail to import due to dependencies, gracefully handle them PLUGINS = {} def initialize(pomodoro_service): """Discover plugins. Every plugin has access to the pomodoro_service layer only. Args: pomodoro_service pomodoro.Pomodoro - The pomodoro service object """ import os from .ui import console from .task import asana from .task import rtm from .task import text global PLUGINS PLUGINS = {'console': console.Console(pomodoro_service), 'asana': asana.AsanaTask(pomodoro_service), 'text': text.TextTask(pomodoro_service), 'rtm': rtm.RTMTask(pomodoro_service)} if os.environ.get("POMITO_TEST") is None: from .ui import qtapp PLUGINS['qtapp'] = qtapp.QtUI(pomodoro_service) def get_plugin(plugin_name): return PLUGINS[plugin_name]
# -*- coding: utf-8 -*- # Pomito - Pomodoro timer on steroids # Base package for plugins __all__ = ['initialize', 'get_plugin'] # TODO Enable plugin discovery, support for drop-in plugins # TODO Validate plugins # TODO Some plugins may fail to import due to dependencies, gracefully handle them PLUGINS = {} def initialize(pomodoro_service): """Discover plugins. Every plugin has access to the pomodoro_service layer only. Args: pomodoro_service pomodoro.Pomodoro - The pomodoro service object """ import os from .ui import console from .task import asana from .task import rtm from .task import text global PLUGINS PLUGINS = {'console': console.Console(pomodoro_service), 'asana': asana.AsanaTask(pomodoro_service), 'text': text.TextTask(pomodoro_service), 'rtm': rtm.RTMTask(pomodoro_service)} if os.environ.get("POMITO_TEST") is None: from .ui import qtapp PLUGINS['qtapp'] = qtapp.QtUI(pomodoro_service) else: # CI machines may not have Qt installed, ensure the lookup # doesn't fail PLUGINS['qtapp'] = None def get_plugin(plugin_name): return PLUGINS[plugin_name]
Fix qtapp UI plugin key for CI machines where POMITO_TEST is set.
Fix qtapp UI plugin key for CI machines where POMITO_TEST is set.
Python
mit
codito/pomito
# -*- coding: utf-8 -*- # Pomito - Pomodoro timer on steroids # Base package for plugins __all__ = ['initialize', 'get_plugin'] # TODO Enable plugin discovery, support for drop-in plugins # TODO Validate plugins # TODO Some plugins may fail to import due to dependencies, gracefully handle them PLUGINS = {} def initialize(pomodoro_service): """Discover plugins. Every plugin has access to the pomodoro_service layer only. Args: pomodoro_service pomodoro.Pomodoro - The pomodoro service object """ import os from .ui import console from .task import asana from .task import rtm from .task import text global PLUGINS PLUGINS = {'console': console.Console(pomodoro_service), 'asana': asana.AsanaTask(pomodoro_service), 'text': text.TextTask(pomodoro_service), 'rtm': rtm.RTMTask(pomodoro_service)} if os.environ.get("POMITO_TEST") is None: from .ui import qtapp PLUGINS['qtapp'] = qtapp.QtUI(pomodoro_service) def get_plugin(plugin_name): return PLUGINS[plugin_name] Fix qtapp UI plugin key for CI machines where POMITO_TEST is set.
# -*- coding: utf-8 -*- # Pomito - Pomodoro timer on steroids # Base package for plugins __all__ = ['initialize', 'get_plugin'] # TODO Enable plugin discovery, support for drop-in plugins # TODO Validate plugins # TODO Some plugins may fail to import due to dependencies, gracefully handle them PLUGINS = {} def initialize(pomodoro_service): """Discover plugins. Every plugin has access to the pomodoro_service layer only. Args: pomodoro_service pomodoro.Pomodoro - The pomodoro service object """ import os from .ui import console from .task import asana from .task import rtm from .task import text global PLUGINS PLUGINS = {'console': console.Console(pomodoro_service), 'asana': asana.AsanaTask(pomodoro_service), 'text': text.TextTask(pomodoro_service), 'rtm': rtm.RTMTask(pomodoro_service)} if os.environ.get("POMITO_TEST") is None: from .ui import qtapp PLUGINS['qtapp'] = qtapp.QtUI(pomodoro_service) else: # CI machines may not have Qt installed, ensure the lookup # doesn't fail PLUGINS['qtapp'] = None def get_plugin(plugin_name): return PLUGINS[plugin_name]
<commit_before># -*- coding: utf-8 -*- # Pomito - Pomodoro timer on steroids # Base package for plugins __all__ = ['initialize', 'get_plugin'] # TODO Enable plugin discovery, support for drop-in plugins # TODO Validate plugins # TODO Some plugins may fail to import due to dependencies, gracefully handle them PLUGINS = {} def initialize(pomodoro_service): """Discover plugins. Every plugin has access to the pomodoro_service layer only. Args: pomodoro_service pomodoro.Pomodoro - The pomodoro service object """ import os from .ui import console from .task import asana from .task import rtm from .task import text global PLUGINS PLUGINS = {'console': console.Console(pomodoro_service), 'asana': asana.AsanaTask(pomodoro_service), 'text': text.TextTask(pomodoro_service), 'rtm': rtm.RTMTask(pomodoro_service)} if os.environ.get("POMITO_TEST") is None: from .ui import qtapp PLUGINS['qtapp'] = qtapp.QtUI(pomodoro_service) def get_plugin(plugin_name): return PLUGINS[plugin_name] <commit_msg>Fix qtapp UI plugin key for CI machines where POMITO_TEST is set.<commit_after>
# -*- coding: utf-8 -*- # Pomito - Pomodoro timer on steroids # Base package for plugins __all__ = ['initialize', 'get_plugin'] # TODO Enable plugin discovery, support for drop-in plugins # TODO Validate plugins # TODO Some plugins may fail to import due to dependencies, gracefully handle them PLUGINS = {} def initialize(pomodoro_service): """Discover plugins. Every plugin has access to the pomodoro_service layer only. Args: pomodoro_service pomodoro.Pomodoro - The pomodoro service object """ import os from .ui import console from .task import asana from .task import rtm from .task import text global PLUGINS PLUGINS = {'console': console.Console(pomodoro_service), 'asana': asana.AsanaTask(pomodoro_service), 'text': text.TextTask(pomodoro_service), 'rtm': rtm.RTMTask(pomodoro_service)} if os.environ.get("POMITO_TEST") is None: from .ui import qtapp PLUGINS['qtapp'] = qtapp.QtUI(pomodoro_service) else: # CI machines may not have Qt installed, ensure the lookup # doesn't fail PLUGINS['qtapp'] = None def get_plugin(plugin_name): return PLUGINS[plugin_name]
# -*- coding: utf-8 -*- # Pomito - Pomodoro timer on steroids # Base package for plugins __all__ = ['initialize', 'get_plugin'] # TODO Enable plugin discovery, support for drop-in plugins # TODO Validate plugins # TODO Some plugins may fail to import due to dependencies, gracefully handle them PLUGINS = {} def initialize(pomodoro_service): """Discover plugins. Every plugin has access to the pomodoro_service layer only. Args: pomodoro_service pomodoro.Pomodoro - The pomodoro service object """ import os from .ui import console from .task import asana from .task import rtm from .task import text global PLUGINS PLUGINS = {'console': console.Console(pomodoro_service), 'asana': asana.AsanaTask(pomodoro_service), 'text': text.TextTask(pomodoro_service), 'rtm': rtm.RTMTask(pomodoro_service)} if os.environ.get("POMITO_TEST") is None: from .ui import qtapp PLUGINS['qtapp'] = qtapp.QtUI(pomodoro_service) def get_plugin(plugin_name): return PLUGINS[plugin_name] Fix qtapp UI plugin key for CI machines where POMITO_TEST is set.# -*- coding: utf-8 -*- # Pomito - Pomodoro timer on steroids # Base package for plugins __all__ = ['initialize', 'get_plugin'] # TODO Enable plugin discovery, support for drop-in plugins # TODO Validate plugins # TODO Some plugins may fail to import due to dependencies, gracefully handle them PLUGINS = {} def initialize(pomodoro_service): """Discover plugins. Every plugin has access to the pomodoro_service layer only. Args: pomodoro_service pomodoro.Pomodoro - The pomodoro service object """ import os from .ui import console from .task import asana from .task import rtm from .task import text global PLUGINS PLUGINS = {'console': console.Console(pomodoro_service), 'asana': asana.AsanaTask(pomodoro_service), 'text': text.TextTask(pomodoro_service), 'rtm': rtm.RTMTask(pomodoro_service)} if os.environ.get("POMITO_TEST") is None: from .ui import qtapp PLUGINS['qtapp'] = qtapp.QtUI(pomodoro_service) else: # CI machines may not have Qt installed, ensure the lookup # doesn't fail PLUGINS['qtapp'] = None def get_plugin(plugin_name): return PLUGINS[plugin_name]
<commit_before># -*- coding: utf-8 -*- # Pomito - Pomodoro timer on steroids # Base package for plugins __all__ = ['initialize', 'get_plugin'] # TODO Enable plugin discovery, support for drop-in plugins # TODO Validate plugins # TODO Some plugins may fail to import due to dependencies, gracefully handle them PLUGINS = {} def initialize(pomodoro_service): """Discover plugins. Every plugin has access to the pomodoro_service layer only. Args: pomodoro_service pomodoro.Pomodoro - The pomodoro service object """ import os from .ui import console from .task import asana from .task import rtm from .task import text global PLUGINS PLUGINS = {'console': console.Console(pomodoro_service), 'asana': asana.AsanaTask(pomodoro_service), 'text': text.TextTask(pomodoro_service), 'rtm': rtm.RTMTask(pomodoro_service)} if os.environ.get("POMITO_TEST") is None: from .ui import qtapp PLUGINS['qtapp'] = qtapp.QtUI(pomodoro_service) def get_plugin(plugin_name): return PLUGINS[plugin_name] <commit_msg>Fix qtapp UI plugin key for CI machines where POMITO_TEST is set.<commit_after># -*- coding: utf-8 -*- # Pomito - Pomodoro timer on steroids # Base package for plugins __all__ = ['initialize', 'get_plugin'] # TODO Enable plugin discovery, support for drop-in plugins # TODO Validate plugins # TODO Some plugins may fail to import due to dependencies, gracefully handle them PLUGINS = {} def initialize(pomodoro_service): """Discover plugins. Every plugin has access to the pomodoro_service layer only. Args: pomodoro_service pomodoro.Pomodoro - The pomodoro service object """ import os from .ui import console from .task import asana from .task import rtm from .task import text global PLUGINS PLUGINS = {'console': console.Console(pomodoro_service), 'asana': asana.AsanaTask(pomodoro_service), 'text': text.TextTask(pomodoro_service), 'rtm': rtm.RTMTask(pomodoro_service)} if os.environ.get("POMITO_TEST") is None: from .ui import qtapp PLUGINS['qtapp'] = qtapp.QtUI(pomodoro_service) else: # CI machines may not have Qt installed, ensure the lookup # doesn't fail PLUGINS['qtapp'] = None def get_plugin(plugin_name): return PLUGINS[plugin_name]
5b0dde337bbad6361e32fc99f12d51af534e6278
ceilometer/api/config.py
ceilometer/api/config.py
# Server Specific Configurations server = { 'port': '8080', 'host': '0.0.0.0' } # Pecan Application Configurations app = { 'root': 'ceilometer.api.controllers.root.RootController', 'modules': ['ceilometer.api'], 'static_root': '%(confdir)s/public', 'template_path': '%(confdir)s/ceilometer/api/templates', 'debug': False, } logging = { 'loggers': { 'root': {'level': 'INFO', 'handlers': ['console']}, 'ceilometer': {'level': 'DEBUG', 'handlers': ['console']} }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'formatters': { 'simple': { 'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]' '[%(threadName)s] %(message)s') } }, } # Custom Configurations must be in Python dictionary format:: # # foo = {'bar':'baz'} # # All configurations are accessible at:: # pecan.conf
# Server Specific Configurations server = { 'port': '8777', 'host': '0.0.0.0' } # Pecan Application Configurations app = { 'root': 'ceilometer.api.controllers.root.RootController', 'modules': ['ceilometer.api'], 'static_root': '%(confdir)s/public', 'template_path': '%(confdir)s/ceilometer/api/templates', 'debug': False, } logging = { 'loggers': { 'root': {'level': 'INFO', 'handlers': ['console']}, 'ceilometer': {'level': 'DEBUG', 'handlers': ['console']}, 'wsme': {'level': 'DEBUG', 'handlers': ['console']} }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'formatters': { 'simple': { 'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]' '[%(threadName)s] %(message)s') } }, } # Custom Configurations must be in Python dictionary format:: # # foo = {'bar':'baz'} # # All configurations are accessible at:: # pecan.conf
Make debugging the wsme app a bit easier.
Make debugging the wsme app a bit easier. - add a logger so we get exceptions - setup the port to 8777 so 'pecan serve config.py' works normally Change-Id: I7374a34ae5534d7d4127e4b405daa11cab5f5547
Python
apache-2.0
ityaptin/ceilometer,citrix-openstack-build/ceilometer,luogangyi/Ceilometer-oVirt,dreamhost/ceilometer,JioCloud/ceilometer,openstack/ceilometer,tanglei528/ceilometer,pkilambi/ceilometer,JioCloud/ceilometer,dreamhost/ceilometer,isyippee/ceilometer,openstack/aodh,maestro-hybrid-cloud/ceilometer,citrix-openstack-build/ceilometer,shootstar/ctest,rickerc/ceilometer_audit,m1093782566/openstack_org_ceilometer,cernops/ceilometer,MisterPup/Ceilometer-Juno-Extension,NeCTAR-RC/ceilometer,Juniper/ceilometer,mathslinux/ceilometer,fabian4/ceilometer,mathslinux/ceilometer,eayunstack/ceilometer,openstack/ceilometer,chungg/aodh,r-mibu/ceilometer,ityaptin/ceilometer,redhat-openstack/ceilometer,rickerc/ceilometer_audit,pkilambi/ceilometer,NeCTAR-RC/ceilometer,Juniper/ceilometer,maestro-hybrid-cloud/ceilometer,tanglei528/ceilometer,idegtiarov/ceilometer,rackerlabs/instrumented-ceilometer,chungg/aodh,idegtiarov/ceilometer,JioCloud/ceilometer,rackerlabs/instrumented-ceilometer,pczerkas/aodh,openstack/aodh,isyippee/ceilometer,tanglei528/ceilometer,MisterPup/Ceilometer-Juno-Extension,NeCTAR-RC/ceilometer,rackerlabs/instrumented-ceilometer,r-mibu/ceilometer,cernops/ceilometer,shootstar/ctest,rickerc/ceilometer_audit,fabian4/ceilometer,pczerkas/aodh,citrix-openstack-build/ceilometer,eayunstack/ceilometer,froyobin/ceilometer,m1093782566/openstack_org_ceilometer,sileht/aodh,sileht/aodh,redhat-openstack/ceilometer,froyobin/ceilometer,luogangyi/Ceilometer-oVirt
# Server Specific Configurations server = { 'port': '8080', 'host': '0.0.0.0' } # Pecan Application Configurations app = { 'root': 'ceilometer.api.controllers.root.RootController', 'modules': ['ceilometer.api'], 'static_root': '%(confdir)s/public', 'template_path': '%(confdir)s/ceilometer/api/templates', 'debug': False, } logging = { 'loggers': { 'root': {'level': 'INFO', 'handlers': ['console']}, 'ceilometer': {'level': 'DEBUG', 'handlers': ['console']} }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'formatters': { 'simple': { 'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]' '[%(threadName)s] %(message)s') } }, } # Custom Configurations must be in Python dictionary format:: # # foo = {'bar':'baz'} # # All configurations are accessible at:: # pecan.conf Make debugging the wsme app a bit easier. - add a logger so we get exceptions - setup the port to 8777 so 'pecan serve config.py' works normally Change-Id: I7374a34ae5534d7d4127e4b405daa11cab5f5547
# Server Specific Configurations server = { 'port': '8777', 'host': '0.0.0.0' } # Pecan Application Configurations app = { 'root': 'ceilometer.api.controllers.root.RootController', 'modules': ['ceilometer.api'], 'static_root': '%(confdir)s/public', 'template_path': '%(confdir)s/ceilometer/api/templates', 'debug': False, } logging = { 'loggers': { 'root': {'level': 'INFO', 'handlers': ['console']}, 'ceilometer': {'level': 'DEBUG', 'handlers': ['console']}, 'wsme': {'level': 'DEBUG', 'handlers': ['console']} }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'formatters': { 'simple': { 'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]' '[%(threadName)s] %(message)s') } }, } # Custom Configurations must be in Python dictionary format:: # # foo = {'bar':'baz'} # # All configurations are accessible at:: # pecan.conf
<commit_before># Server Specific Configurations server = { 'port': '8080', 'host': '0.0.0.0' } # Pecan Application Configurations app = { 'root': 'ceilometer.api.controllers.root.RootController', 'modules': ['ceilometer.api'], 'static_root': '%(confdir)s/public', 'template_path': '%(confdir)s/ceilometer/api/templates', 'debug': False, } logging = { 'loggers': { 'root': {'level': 'INFO', 'handlers': ['console']}, 'ceilometer': {'level': 'DEBUG', 'handlers': ['console']} }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'formatters': { 'simple': { 'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]' '[%(threadName)s] %(message)s') } }, } # Custom Configurations must be in Python dictionary format:: # # foo = {'bar':'baz'} # # All configurations are accessible at:: # pecan.conf <commit_msg>Make debugging the wsme app a bit easier. - add a logger so we get exceptions - setup the port to 8777 so 'pecan serve config.py' works normally Change-Id: I7374a34ae5534d7d4127e4b405daa11cab5f5547<commit_after>
# Server Specific Configurations server = { 'port': '8777', 'host': '0.0.0.0' } # Pecan Application Configurations app = { 'root': 'ceilometer.api.controllers.root.RootController', 'modules': ['ceilometer.api'], 'static_root': '%(confdir)s/public', 'template_path': '%(confdir)s/ceilometer/api/templates', 'debug': False, } logging = { 'loggers': { 'root': {'level': 'INFO', 'handlers': ['console']}, 'ceilometer': {'level': 'DEBUG', 'handlers': ['console']}, 'wsme': {'level': 'DEBUG', 'handlers': ['console']} }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'formatters': { 'simple': { 'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]' '[%(threadName)s] %(message)s') } }, } # Custom Configurations must be in Python dictionary format:: # # foo = {'bar':'baz'} # # All configurations are accessible at:: # pecan.conf
# Server Specific Configurations server = { 'port': '8080', 'host': '0.0.0.0' } # Pecan Application Configurations app = { 'root': 'ceilometer.api.controllers.root.RootController', 'modules': ['ceilometer.api'], 'static_root': '%(confdir)s/public', 'template_path': '%(confdir)s/ceilometer/api/templates', 'debug': False, } logging = { 'loggers': { 'root': {'level': 'INFO', 'handlers': ['console']}, 'ceilometer': {'level': 'DEBUG', 'handlers': ['console']} }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'formatters': { 'simple': { 'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]' '[%(threadName)s] %(message)s') } }, } # Custom Configurations must be in Python dictionary format:: # # foo = {'bar':'baz'} # # All configurations are accessible at:: # pecan.conf Make debugging the wsme app a bit easier. - add a logger so we get exceptions - setup the port to 8777 so 'pecan serve config.py' works normally Change-Id: I7374a34ae5534d7d4127e4b405daa11cab5f5547# Server Specific Configurations server = { 'port': '8777', 'host': '0.0.0.0' } # Pecan Application Configurations app = { 'root': 'ceilometer.api.controllers.root.RootController', 'modules': ['ceilometer.api'], 'static_root': '%(confdir)s/public', 'template_path': '%(confdir)s/ceilometer/api/templates', 'debug': False, } logging = { 'loggers': { 'root': {'level': 'INFO', 'handlers': ['console']}, 'ceilometer': {'level': 'DEBUG', 'handlers': ['console']}, 'wsme': {'level': 'DEBUG', 'handlers': ['console']} }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'formatters': { 'simple': { 'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]' '[%(threadName)s] %(message)s') } }, } # Custom Configurations must be in Python dictionary format:: # # foo = {'bar':'baz'} # # All configurations are accessible at:: # pecan.conf
<commit_before># Server Specific Configurations server = { 'port': '8080', 'host': '0.0.0.0' } # Pecan Application Configurations app = { 'root': 'ceilometer.api.controllers.root.RootController', 'modules': ['ceilometer.api'], 'static_root': '%(confdir)s/public', 'template_path': '%(confdir)s/ceilometer/api/templates', 'debug': False, } logging = { 'loggers': { 'root': {'level': 'INFO', 'handlers': ['console']}, 'ceilometer': {'level': 'DEBUG', 'handlers': ['console']} }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'formatters': { 'simple': { 'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]' '[%(threadName)s] %(message)s') } }, } # Custom Configurations must be in Python dictionary format:: # # foo = {'bar':'baz'} # # All configurations are accessible at:: # pecan.conf <commit_msg>Make debugging the wsme app a bit easier. - add a logger so we get exceptions - setup the port to 8777 so 'pecan serve config.py' works normally Change-Id: I7374a34ae5534d7d4127e4b405daa11cab5f5547<commit_after># Server Specific Configurations server = { 'port': '8777', 'host': '0.0.0.0' } # Pecan Application Configurations app = { 'root': 'ceilometer.api.controllers.root.RootController', 'modules': ['ceilometer.api'], 'static_root': '%(confdir)s/public', 'template_path': '%(confdir)s/ceilometer/api/templates', 'debug': False, } logging = { 'loggers': { 'root': {'level': 'INFO', 'handlers': ['console']}, 'ceilometer': {'level': 'DEBUG', 'handlers': ['console']}, 'wsme': {'level': 'DEBUG', 'handlers': ['console']} }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'formatters': { 'simple': { 'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]' '[%(threadName)s] %(message)s') } }, } # Custom Configurations must be in Python dictionary format:: # # foo = {'bar':'baz'} # # All configurations are accessible at:: # pecan.conf
7ad5619318fdac555a4350219f298adc702f6d6f
erpnext/domains/education.py
erpnext/domains/education.py
from __future__ import unicode_literals data = { 'desktop_icons': [ 'Student', 'Program', 'Course', 'Student Group', 'Instructor', 'Fees', 'Task', 'ToDo', 'Education', 'Student Attendance Tool', 'Student Applicant' ], 'default_portal_role': 'Guardian', 'restricted_roles': [ 'Student', 'Instructor', 'Academics User', 'Education Manager' ], 'modules': [ 'Education' ], 'on_setup': 'erpnext.education.setup.setup_education' }
from __future__ import unicode_literals data = { 'desktop_icons': [ 'Student', 'Program', 'Course', 'Student Group', 'Instructor', 'Fees', 'Task', 'ToDo', 'Education', 'Student Attendance Tool', 'Student Applicant' ], 'default_portal_role': 'LMS User', 'restricted_roles': [ 'Student', 'Instructor', 'Academics User', 'Education Manager' ], 'modules': [ 'Education' ], 'on_setup': 'erpnext.education.setup.setup_education' }
Set default role to LMS User for signup in Education
feat: Set default role to LMS User for signup in Education
Python
agpl-3.0
gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext
from __future__ import unicode_literals data = { 'desktop_icons': [ 'Student', 'Program', 'Course', 'Student Group', 'Instructor', 'Fees', 'Task', 'ToDo', 'Education', 'Student Attendance Tool', 'Student Applicant' ], 'default_portal_role': 'Guardian', 'restricted_roles': [ 'Student', 'Instructor', 'Academics User', 'Education Manager' ], 'modules': [ 'Education' ], 'on_setup': 'erpnext.education.setup.setup_education' }feat: Set default role to LMS User for signup in Education
from __future__ import unicode_literals data = { 'desktop_icons': [ 'Student', 'Program', 'Course', 'Student Group', 'Instructor', 'Fees', 'Task', 'ToDo', 'Education', 'Student Attendance Tool', 'Student Applicant' ], 'default_portal_role': 'LMS User', 'restricted_roles': [ 'Student', 'Instructor', 'Academics User', 'Education Manager' ], 'modules': [ 'Education' ], 'on_setup': 'erpnext.education.setup.setup_education' }
<commit_before>from __future__ import unicode_literals data = { 'desktop_icons': [ 'Student', 'Program', 'Course', 'Student Group', 'Instructor', 'Fees', 'Task', 'ToDo', 'Education', 'Student Attendance Tool', 'Student Applicant' ], 'default_portal_role': 'Guardian', 'restricted_roles': [ 'Student', 'Instructor', 'Academics User', 'Education Manager' ], 'modules': [ 'Education' ], 'on_setup': 'erpnext.education.setup.setup_education' }<commit_msg>feat: Set default role to LMS User for signup in Education<commit_after>
from __future__ import unicode_literals data = { 'desktop_icons': [ 'Student', 'Program', 'Course', 'Student Group', 'Instructor', 'Fees', 'Task', 'ToDo', 'Education', 'Student Attendance Tool', 'Student Applicant' ], 'default_portal_role': 'LMS User', 'restricted_roles': [ 'Student', 'Instructor', 'Academics User', 'Education Manager' ], 'modules': [ 'Education' ], 'on_setup': 'erpnext.education.setup.setup_education' }
from __future__ import unicode_literals data = { 'desktop_icons': [ 'Student', 'Program', 'Course', 'Student Group', 'Instructor', 'Fees', 'Task', 'ToDo', 'Education', 'Student Attendance Tool', 'Student Applicant' ], 'default_portal_role': 'Guardian', 'restricted_roles': [ 'Student', 'Instructor', 'Academics User', 'Education Manager' ], 'modules': [ 'Education' ], 'on_setup': 'erpnext.education.setup.setup_education' }feat: Set default role to LMS User for signup in Educationfrom __future__ import unicode_literals data = { 'desktop_icons': [ 'Student', 'Program', 'Course', 'Student Group', 'Instructor', 'Fees', 'Task', 'ToDo', 'Education', 'Student Attendance Tool', 'Student Applicant' ], 'default_portal_role': 'LMS User', 'restricted_roles': [ 'Student', 'Instructor', 'Academics User', 'Education Manager' ], 'modules': [ 'Education' ], 'on_setup': 'erpnext.education.setup.setup_education' }
<commit_before>from __future__ import unicode_literals data = { 'desktop_icons': [ 'Student', 'Program', 'Course', 'Student Group', 'Instructor', 'Fees', 'Task', 'ToDo', 'Education', 'Student Attendance Tool', 'Student Applicant' ], 'default_portal_role': 'Guardian', 'restricted_roles': [ 'Student', 'Instructor', 'Academics User', 'Education Manager' ], 'modules': [ 'Education' ], 'on_setup': 'erpnext.education.setup.setup_education' }<commit_msg>feat: Set default role to LMS User for signup in Education<commit_after>from __future__ import unicode_literals data = { 'desktop_icons': [ 'Student', 'Program', 'Course', 'Student Group', 'Instructor', 'Fees', 'Task', 'ToDo', 'Education', 'Student Attendance Tool', 'Student Applicant' ], 'default_portal_role': 'LMS User', 'restricted_roles': [ 'Student', 'Instructor', 'Academics User', 'Education Manager' ], 'modules': [ 'Education' ], 'on_setup': 'erpnext.education.setup.setup_education' }
3ba8af66d0c6ebbdd4a3799b819a72292da2c6c5
netmiko/citrix/netscaler_ssh.py
netmiko/citrix/netscaler_ssh.py
import time from netmiko.base_connection import BaseConnection class NetscalerSSH(BaseConnection): """ Netscaler SSH class. """ def session_preparation(self): """Prepare the session after the connection has been established.""" # 0 will defer to the global delay factor delay_factor = self.select_delay_factor(delay_factor=0) self._test_channel_read() self.set_base_prompt() self.disable_paging(command="\nset cli mode -page OFF\n") time.sleep(1 * delay_factor) self.set_base_prompt() time.sleep(.3 * self.global_delay_factor) self.clear_buffer() def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs): """ Nothing to exit""" return super(NetscalerSSH, self).send_config_set(config_commands=config_commands, exit_config_mode=False, **kwargs) def strip_prompt(self, a_string): """ Strip 'Done' from command output """ output = super(NetscalerSSH, self).strip_prompt(a_string) lines = output.split('\n') if "Done" in lines[-1]: return '\n'.join(lines[:-1]) else: return output
import time from netmiko.base_connection import BaseConnection class NetscalerSSH(BaseConnection): """ Netscaler SSH class. """ def session_preparation(self): """Prepare the session after the connection has been established.""" # 0 will defer to the global delay factor delay_factor = self.select_delay_factor(delay_factor=0) self._test_channel_read() self.set_base_prompt() cmd = "{}set cli mode -page OFF{}".format(self.RETURN, self.RETURN) self.disable_paging(command=cmd) time.sleep(1 * delay_factor) self.set_base_prompt() time.sleep(.3 * delay_factor) self.clear_buffer() def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs): """Nothing to exit""" return super(NetscalerSSH, self).send_config_set(config_commands=config_commands, exit_config_mode=False, **kwargs) def strip_prompt(self, a_string): """ Strip 'Done' from command output """ output = super(NetscalerSSH, self).strip_prompt(a_string) lines = output.split(self.RESPONSE_RETURN) if "Done" in lines[-1]: return 'self.RESPONSE_RETURN'.join(lines[:-1]) else: return output
Make return character an attribute
Make return character an attribute
Python
mit
ktbyers/netmiko,ktbyers/netmiko
import time from netmiko.base_connection import BaseConnection class NetscalerSSH(BaseConnection): """ Netscaler SSH class. """ def session_preparation(self): """Prepare the session after the connection has been established.""" # 0 will defer to the global delay factor delay_factor = self.select_delay_factor(delay_factor=0) self._test_channel_read() self.set_base_prompt() self.disable_paging(command="\nset cli mode -page OFF\n") time.sleep(1 * delay_factor) self.set_base_prompt() time.sleep(.3 * self.global_delay_factor) self.clear_buffer() def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs): """ Nothing to exit""" return super(NetscalerSSH, self).send_config_set(config_commands=config_commands, exit_config_mode=False, **kwargs) def strip_prompt(self, a_string): """ Strip 'Done' from command output """ output = super(NetscalerSSH, self).strip_prompt(a_string) lines = output.split('\n') if "Done" in lines[-1]: return '\n'.join(lines[:-1]) else: return output Make return character an attribute
import time from netmiko.base_connection import BaseConnection class NetscalerSSH(BaseConnection): """ Netscaler SSH class. """ def session_preparation(self): """Prepare the session after the connection has been established.""" # 0 will defer to the global delay factor delay_factor = self.select_delay_factor(delay_factor=0) self._test_channel_read() self.set_base_prompt() cmd = "{}set cli mode -page OFF{}".format(self.RETURN, self.RETURN) self.disable_paging(command=cmd) time.sleep(1 * delay_factor) self.set_base_prompt() time.sleep(.3 * delay_factor) self.clear_buffer() def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs): """Nothing to exit""" return super(NetscalerSSH, self).send_config_set(config_commands=config_commands, exit_config_mode=False, **kwargs) def strip_prompt(self, a_string): """ Strip 'Done' from command output """ output = super(NetscalerSSH, self).strip_prompt(a_string) lines = output.split(self.RESPONSE_RETURN) if "Done" in lines[-1]: return 'self.RESPONSE_RETURN'.join(lines[:-1]) else: return output
<commit_before>import time from netmiko.base_connection import BaseConnection class NetscalerSSH(BaseConnection): """ Netscaler SSH class. """ def session_preparation(self): """Prepare the session after the connection has been established.""" # 0 will defer to the global delay factor delay_factor = self.select_delay_factor(delay_factor=0) self._test_channel_read() self.set_base_prompt() self.disable_paging(command="\nset cli mode -page OFF\n") time.sleep(1 * delay_factor) self.set_base_prompt() time.sleep(.3 * self.global_delay_factor) self.clear_buffer() def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs): """ Nothing to exit""" return super(NetscalerSSH, self).send_config_set(config_commands=config_commands, exit_config_mode=False, **kwargs) def strip_prompt(self, a_string): """ Strip 'Done' from command output """ output = super(NetscalerSSH, self).strip_prompt(a_string) lines = output.split('\n') if "Done" in lines[-1]: return '\n'.join(lines[:-1]) else: return output <commit_msg>Make return character an attribute<commit_after>
import time from netmiko.base_connection import BaseConnection class NetscalerSSH(BaseConnection): """ Netscaler SSH class. """ def session_preparation(self): """Prepare the session after the connection has been established.""" # 0 will defer to the global delay factor delay_factor = self.select_delay_factor(delay_factor=0) self._test_channel_read() self.set_base_prompt() cmd = "{}set cli mode -page OFF{}".format(self.RETURN, self.RETURN) self.disable_paging(command=cmd) time.sleep(1 * delay_factor) self.set_base_prompt() time.sleep(.3 * delay_factor) self.clear_buffer() def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs): """Nothing to exit""" return super(NetscalerSSH, self).send_config_set(config_commands=config_commands, exit_config_mode=False, **kwargs) def strip_prompt(self, a_string): """ Strip 'Done' from command output """ output = super(NetscalerSSH, self).strip_prompt(a_string) lines = output.split(self.RESPONSE_RETURN) if "Done" in lines[-1]: return 'self.RESPONSE_RETURN'.join(lines[:-1]) else: return output
import time from netmiko.base_connection import BaseConnection class NetscalerSSH(BaseConnection): """ Netscaler SSH class. """ def session_preparation(self): """Prepare the session after the connection has been established.""" # 0 will defer to the global delay factor delay_factor = self.select_delay_factor(delay_factor=0) self._test_channel_read() self.set_base_prompt() self.disable_paging(command="\nset cli mode -page OFF\n") time.sleep(1 * delay_factor) self.set_base_prompt() time.sleep(.3 * self.global_delay_factor) self.clear_buffer() def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs): """ Nothing to exit""" return super(NetscalerSSH, self).send_config_set(config_commands=config_commands, exit_config_mode=False, **kwargs) def strip_prompt(self, a_string): """ Strip 'Done' from command output """ output = super(NetscalerSSH, self).strip_prompt(a_string) lines = output.split('\n') if "Done" in lines[-1]: return '\n'.join(lines[:-1]) else: return output Make return character an attributeimport time from netmiko.base_connection import BaseConnection class NetscalerSSH(BaseConnection): """ Netscaler SSH class. """ def session_preparation(self): """Prepare the session after the connection has been established.""" # 0 will defer to the global delay factor delay_factor = self.select_delay_factor(delay_factor=0) self._test_channel_read() self.set_base_prompt() cmd = "{}set cli mode -page OFF{}".format(self.RETURN, self.RETURN) self.disable_paging(command=cmd) time.sleep(1 * delay_factor) self.set_base_prompt() time.sleep(.3 * delay_factor) self.clear_buffer() def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs): """Nothing to exit""" return super(NetscalerSSH, self).send_config_set(config_commands=config_commands, exit_config_mode=False, **kwargs) def strip_prompt(self, a_string): """ Strip 'Done' from command output """ output = super(NetscalerSSH, self).strip_prompt(a_string) lines = output.split(self.RESPONSE_RETURN) if "Done" in lines[-1]: return 'self.RESPONSE_RETURN'.join(lines[:-1]) else: return output
<commit_before>import time from netmiko.base_connection import BaseConnection class NetscalerSSH(BaseConnection): """ Netscaler SSH class. """ def session_preparation(self): """Prepare the session after the connection has been established.""" # 0 will defer to the global delay factor delay_factor = self.select_delay_factor(delay_factor=0) self._test_channel_read() self.set_base_prompt() self.disable_paging(command="\nset cli mode -page OFF\n") time.sleep(1 * delay_factor) self.set_base_prompt() time.sleep(.3 * self.global_delay_factor) self.clear_buffer() def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs): """ Nothing to exit""" return super(NetscalerSSH, self).send_config_set(config_commands=config_commands, exit_config_mode=False, **kwargs) def strip_prompt(self, a_string): """ Strip 'Done' from command output """ output = super(NetscalerSSH, self).strip_prompt(a_string) lines = output.split('\n') if "Done" in lines[-1]: return '\n'.join(lines[:-1]) else: return output <commit_msg>Make return character an attribute<commit_after>import time from netmiko.base_connection import BaseConnection class NetscalerSSH(BaseConnection): """ Netscaler SSH class. """ def session_preparation(self): """Prepare the session after the connection has been established.""" # 0 will defer to the global delay factor delay_factor = self.select_delay_factor(delay_factor=0) self._test_channel_read() self.set_base_prompt() cmd = "{}set cli mode -page OFF{}".format(self.RETURN, self.RETURN) self.disable_paging(command=cmd) time.sleep(1 * delay_factor) self.set_base_prompt() time.sleep(.3 * delay_factor) self.clear_buffer() def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs): """Nothing to exit""" return super(NetscalerSSH, self).send_config_set(config_commands=config_commands, exit_config_mode=False, **kwargs) def strip_prompt(self, a_string): """ Strip 'Done' from command output """ output = super(NetscalerSSH, self).strip_prompt(a_string) lines = output.split(self.RESPONSE_RETURN) if "Done" in lines[-1]: return 'self.RESPONSE_RETURN'.join(lines[:-1]) else: return output
efe3c6acb6b5336461adc18d993ad74a31205c06
pre_push.py
pre_push.py
#!/usr/bin/env python """Run static analysis on the project.""" from shutil import rmtree from subprocess import CalledProcessError, check_call from tempfile import mkdtemp import sys def do_process(*args): """Run program provided by args. Return True on success. Output failed message on non-zero exit and return False. Exit if command is not found. """ print('Running: {}'.format(' '.join(args))) try: check_call(args) except CalledProcessError: print('\nFailed: {}'.format(' '.join(args))) return False except Exception as exc: sys.stderr.write(str(exc) + '\n') sys.exit(1) return True def main(): """Entry point to pre_push.py.""" success = True success &= do_process('flake8', '--exclude=.eggs,docs') success &= do_process('pydocstyle', 'praw') success &= do_process('pylint', '--rcfile=.pylintrc', 'praw') tmp_dir = mkdtemp() try: success &= do_process('sphinx-build', '-W', 'docs', tmp_dir) finally: rmtree(tmp_dir) return 0 if success else 1 if __name__ == '__main__': sys.exit(main())
#!/usr/bin/env python """Run static analysis on the project.""" from shutil import rmtree from subprocess import CalledProcessError, check_call from tempfile import mkdtemp import sys def do_process(*args): """Run program provided by args. Return True on success. Output failed message on non-zero exit and return False. Exit if command is not found. """ print('Running: {}'.format(' '.join(args))) try: check_call(args) except CalledProcessError: print('\nFailed: {}'.format(' '.join(args))) return False except Exception as exc: sys.stderr.write(str(exc) + '\n') sys.exit(1) return True def main(): """Entry point to pre_push.py.""" success = True success &= do_process('flake8', '--exclude=.eggs,docs,.tox') success &= do_process('pydocstyle', 'praw') success &= do_process('pylint', '--rcfile=.pylintrc', 'praw') tmp_dir = mkdtemp() try: success &= do_process('sphinx-build', '-W', 'docs', tmp_dir) finally: rmtree(tmp_dir) return 0 if success else 1 if __name__ == '__main__': sys.exit(main())
Exclude .tox/ from flake8 target
Exclude .tox/ from flake8 target
Python
bsd-2-clause
13steinj/praw,leviroth/praw,gschizas/praw,praw-dev/praw,gschizas/praw,13steinj/praw,praw-dev/praw,leviroth/praw
#!/usr/bin/env python """Run static analysis on the project.""" from shutil import rmtree from subprocess import CalledProcessError, check_call from tempfile import mkdtemp import sys def do_process(*args): """Run program provided by args. Return True on success. Output failed message on non-zero exit and return False. Exit if command is not found. """ print('Running: {}'.format(' '.join(args))) try: check_call(args) except CalledProcessError: print('\nFailed: {}'.format(' '.join(args))) return False except Exception as exc: sys.stderr.write(str(exc) + '\n') sys.exit(1) return True def main(): """Entry point to pre_push.py.""" success = True success &= do_process('flake8', '--exclude=.eggs,docs') success &= do_process('pydocstyle', 'praw') success &= do_process('pylint', '--rcfile=.pylintrc', 'praw') tmp_dir = mkdtemp() try: success &= do_process('sphinx-build', '-W', 'docs', tmp_dir) finally: rmtree(tmp_dir) return 0 if success else 1 if __name__ == '__main__': sys.exit(main()) Exclude .tox/ from flake8 target
#!/usr/bin/env python """Run static analysis on the project.""" from shutil import rmtree from subprocess import CalledProcessError, check_call from tempfile import mkdtemp import sys def do_process(*args): """Run program provided by args. Return True on success. Output failed message on non-zero exit and return False. Exit if command is not found. """ print('Running: {}'.format(' '.join(args))) try: check_call(args) except CalledProcessError: print('\nFailed: {}'.format(' '.join(args))) return False except Exception as exc: sys.stderr.write(str(exc) + '\n') sys.exit(1) return True def main(): """Entry point to pre_push.py.""" success = True success &= do_process('flake8', '--exclude=.eggs,docs,.tox') success &= do_process('pydocstyle', 'praw') success &= do_process('pylint', '--rcfile=.pylintrc', 'praw') tmp_dir = mkdtemp() try: success &= do_process('sphinx-build', '-W', 'docs', tmp_dir) finally: rmtree(tmp_dir) return 0 if success else 1 if __name__ == '__main__': sys.exit(main())
<commit_before>#!/usr/bin/env python """Run static analysis on the project.""" from shutil import rmtree from subprocess import CalledProcessError, check_call from tempfile import mkdtemp import sys def do_process(*args): """Run program provided by args. Return True on success. Output failed message on non-zero exit and return False. Exit if command is not found. """ print('Running: {}'.format(' '.join(args))) try: check_call(args) except CalledProcessError: print('\nFailed: {}'.format(' '.join(args))) return False except Exception as exc: sys.stderr.write(str(exc) + '\n') sys.exit(1) return True def main(): """Entry point to pre_push.py.""" success = True success &= do_process('flake8', '--exclude=.eggs,docs') success &= do_process('pydocstyle', 'praw') success &= do_process('pylint', '--rcfile=.pylintrc', 'praw') tmp_dir = mkdtemp() try: success &= do_process('sphinx-build', '-W', 'docs', tmp_dir) finally: rmtree(tmp_dir) return 0 if success else 1 if __name__ == '__main__': sys.exit(main()) <commit_msg>Exclude .tox/ from flake8 target<commit_after>
#!/usr/bin/env python """Run static analysis on the project.""" from shutil import rmtree from subprocess import CalledProcessError, check_call from tempfile import mkdtemp import sys def do_process(*args): """Run program provided by args. Return True on success. Output failed message on non-zero exit and return False. Exit if command is not found. """ print('Running: {}'.format(' '.join(args))) try: check_call(args) except CalledProcessError: print('\nFailed: {}'.format(' '.join(args))) return False except Exception as exc: sys.stderr.write(str(exc) + '\n') sys.exit(1) return True def main(): """Entry point to pre_push.py.""" success = True success &= do_process('flake8', '--exclude=.eggs,docs,.tox') success &= do_process('pydocstyle', 'praw') success &= do_process('pylint', '--rcfile=.pylintrc', 'praw') tmp_dir = mkdtemp() try: success &= do_process('sphinx-build', '-W', 'docs', tmp_dir) finally: rmtree(tmp_dir) return 0 if success else 1 if __name__ == '__main__': sys.exit(main())
#!/usr/bin/env python """Run static analysis on the project.""" from shutil import rmtree from subprocess import CalledProcessError, check_call from tempfile import mkdtemp import sys def do_process(*args): """Run program provided by args. Return True on success. Output failed message on non-zero exit and return False. Exit if command is not found. """ print('Running: {}'.format(' '.join(args))) try: check_call(args) except CalledProcessError: print('\nFailed: {}'.format(' '.join(args))) return False except Exception as exc: sys.stderr.write(str(exc) + '\n') sys.exit(1) return True def main(): """Entry point to pre_push.py.""" success = True success &= do_process('flake8', '--exclude=.eggs,docs') success &= do_process('pydocstyle', 'praw') success &= do_process('pylint', '--rcfile=.pylintrc', 'praw') tmp_dir = mkdtemp() try: success &= do_process('sphinx-build', '-W', 'docs', tmp_dir) finally: rmtree(tmp_dir) return 0 if success else 1 if __name__ == '__main__': sys.exit(main()) Exclude .tox/ from flake8 target#!/usr/bin/env python """Run static analysis on the project.""" from shutil import rmtree from subprocess import CalledProcessError, check_call from tempfile import mkdtemp import sys def do_process(*args): """Run program provided by args. Return True on success. Output failed message on non-zero exit and return False. Exit if command is not found. """ print('Running: {}'.format(' '.join(args))) try: check_call(args) except CalledProcessError: print('\nFailed: {}'.format(' '.join(args))) return False except Exception as exc: sys.stderr.write(str(exc) + '\n') sys.exit(1) return True def main(): """Entry point to pre_push.py.""" success = True success &= do_process('flake8', '--exclude=.eggs,docs,.tox') success &= do_process('pydocstyle', 'praw') success &= do_process('pylint', '--rcfile=.pylintrc', 'praw') tmp_dir = mkdtemp() try: success &= do_process('sphinx-build', '-W', 'docs', tmp_dir) finally: rmtree(tmp_dir) return 0 if success else 1 if __name__ == '__main__': sys.exit(main())
<commit_before>#!/usr/bin/env python """Run static analysis on the project.""" from shutil import rmtree from subprocess import CalledProcessError, check_call from tempfile import mkdtemp import sys def do_process(*args): """Run program provided by args. Return True on success. Output failed message on non-zero exit and return False. Exit if command is not found. """ print('Running: {}'.format(' '.join(args))) try: check_call(args) except CalledProcessError: print('\nFailed: {}'.format(' '.join(args))) return False except Exception as exc: sys.stderr.write(str(exc) + '\n') sys.exit(1) return True def main(): """Entry point to pre_push.py.""" success = True success &= do_process('flake8', '--exclude=.eggs,docs') success &= do_process('pydocstyle', 'praw') success &= do_process('pylint', '--rcfile=.pylintrc', 'praw') tmp_dir = mkdtemp() try: success &= do_process('sphinx-build', '-W', 'docs', tmp_dir) finally: rmtree(tmp_dir) return 0 if success else 1 if __name__ == '__main__': sys.exit(main()) <commit_msg>Exclude .tox/ from flake8 target<commit_after>#!/usr/bin/env python """Run static analysis on the project.""" from shutil import rmtree from subprocess import CalledProcessError, check_call from tempfile import mkdtemp import sys def do_process(*args): """Run program provided by args. Return True on success. Output failed message on non-zero exit and return False. Exit if command is not found. """ print('Running: {}'.format(' '.join(args))) try: check_call(args) except CalledProcessError: print('\nFailed: {}'.format(' '.join(args))) return False except Exception as exc: sys.stderr.write(str(exc) + '\n') sys.exit(1) return True def main(): """Entry point to pre_push.py.""" success = True success &= do_process('flake8', '--exclude=.eggs,docs,.tox') success &= do_process('pydocstyle', 'praw') success &= do_process('pylint', '--rcfile=.pylintrc', 'praw') tmp_dir = mkdtemp() try: success &= do_process('sphinx-build', '-W', 'docs', tmp_dir) finally: rmtree(tmp_dir) return 0 if success else 1 if __name__ == '__main__': sys.exit(main())
477a6334482b7cfad0a4b1edb1cf1528824e82e4
tests/test_setuptools_command.py
tests/test_setuptools_command.py
import os from unittest.mock import MagicMock import pytest from isort import setuptools_commands def test_isort_command_smoke(src_dir): """A basic smoke test for the setuptools_commands command""" from distutils.dist import Distribution command = setuptools_commands.ISortCommand(Distribution()) command.distribution.packages = ["isort"] command.distribution.package_dir = {"isort": src_dir} command.initialize_options() command.finalize_options() try: command.run() except Exception: pass command.distribution.package_dir = {"": "isort"} command.distribution.py_modules = ["one", "two"] command.initialize_options() command.finalize_options() command.run() command.distribution.packages = ["not_a_file"] command.distribution.package_dir = {"not_a_file": src_dir} command.initialize_options() command.finalize_options() try: command.run() except Exception: pass
import os from unittest.mock import MagicMock import pytest from isort import setuptools_commands def test_isort_command_smoke(src_dir): """A basic smoke test for the setuptools_commands command""" from distutils.dist import Distribution command = setuptools_commands.ISortCommand(Distribution()) command.distribution.packages = ["isort"] command.distribution.package_dir = {"isort": src_dir} command.initialize_options() command.finalize_options() try: command.run() except BaseException: pass command.distribution.package_dir = {"": "isort"} command.distribution.py_modules = ["one", "two"] command.initialize_options() command.finalize_options() command.run() command.distribution.packages = ["not_a_file"] command.distribution.package_dir = {"not_a_file": src_dir} command.initialize_options() command.finalize_options() try: command.run() except BaseException: pass
Fix exception test to handle system exceptions
Fix exception test to handle system exceptions
Python
mit
PyCQA/isort,PyCQA/isort
import os from unittest.mock import MagicMock import pytest from isort import setuptools_commands def test_isort_command_smoke(src_dir): """A basic smoke test for the setuptools_commands command""" from distutils.dist import Distribution command = setuptools_commands.ISortCommand(Distribution()) command.distribution.packages = ["isort"] command.distribution.package_dir = {"isort": src_dir} command.initialize_options() command.finalize_options() try: command.run() except Exception: pass command.distribution.package_dir = {"": "isort"} command.distribution.py_modules = ["one", "two"] command.initialize_options() command.finalize_options() command.run() command.distribution.packages = ["not_a_file"] command.distribution.package_dir = {"not_a_file": src_dir} command.initialize_options() command.finalize_options() try: command.run() except Exception: pass Fix exception test to handle system exceptions
import os from unittest.mock import MagicMock import pytest from isort import setuptools_commands def test_isort_command_smoke(src_dir): """A basic smoke test for the setuptools_commands command""" from distutils.dist import Distribution command = setuptools_commands.ISortCommand(Distribution()) command.distribution.packages = ["isort"] command.distribution.package_dir = {"isort": src_dir} command.initialize_options() command.finalize_options() try: command.run() except BaseException: pass command.distribution.package_dir = {"": "isort"} command.distribution.py_modules = ["one", "two"] command.initialize_options() command.finalize_options() command.run() command.distribution.packages = ["not_a_file"] command.distribution.package_dir = {"not_a_file": src_dir} command.initialize_options() command.finalize_options() try: command.run() except BaseException: pass
<commit_before>import os from unittest.mock import MagicMock import pytest from isort import setuptools_commands def test_isort_command_smoke(src_dir): """A basic smoke test for the setuptools_commands command""" from distutils.dist import Distribution command = setuptools_commands.ISortCommand(Distribution()) command.distribution.packages = ["isort"] command.distribution.package_dir = {"isort": src_dir} command.initialize_options() command.finalize_options() try: command.run() except Exception: pass command.distribution.package_dir = {"": "isort"} command.distribution.py_modules = ["one", "two"] command.initialize_options() command.finalize_options() command.run() command.distribution.packages = ["not_a_file"] command.distribution.package_dir = {"not_a_file": src_dir} command.initialize_options() command.finalize_options() try: command.run() except Exception: pass <commit_msg>Fix exception test to handle system exceptions<commit_after>
import os from unittest.mock import MagicMock import pytest from isort import setuptools_commands def test_isort_command_smoke(src_dir): """A basic smoke test for the setuptools_commands command""" from distutils.dist import Distribution command = setuptools_commands.ISortCommand(Distribution()) command.distribution.packages = ["isort"] command.distribution.package_dir = {"isort": src_dir} command.initialize_options() command.finalize_options() try: command.run() except BaseException: pass command.distribution.package_dir = {"": "isort"} command.distribution.py_modules = ["one", "two"] command.initialize_options() command.finalize_options() command.run() command.distribution.packages = ["not_a_file"] command.distribution.package_dir = {"not_a_file": src_dir} command.initialize_options() command.finalize_options() try: command.run() except BaseException: pass
import os from unittest.mock import MagicMock import pytest from isort import setuptools_commands def test_isort_command_smoke(src_dir): """A basic smoke test for the setuptools_commands command""" from distutils.dist import Distribution command = setuptools_commands.ISortCommand(Distribution()) command.distribution.packages = ["isort"] command.distribution.package_dir = {"isort": src_dir} command.initialize_options() command.finalize_options() try: command.run() except Exception: pass command.distribution.package_dir = {"": "isort"} command.distribution.py_modules = ["one", "two"] command.initialize_options() command.finalize_options() command.run() command.distribution.packages = ["not_a_file"] command.distribution.package_dir = {"not_a_file": src_dir} command.initialize_options() command.finalize_options() try: command.run() except Exception: pass Fix exception test to handle system exceptionsimport os from unittest.mock import MagicMock import pytest from isort import setuptools_commands def test_isort_command_smoke(src_dir): """A basic smoke test for the setuptools_commands command""" from distutils.dist import Distribution command = setuptools_commands.ISortCommand(Distribution()) command.distribution.packages = ["isort"] command.distribution.package_dir = {"isort": src_dir} command.initialize_options() command.finalize_options() try: command.run() except BaseException: pass command.distribution.package_dir = {"": "isort"} command.distribution.py_modules = ["one", "two"] command.initialize_options() command.finalize_options() command.run() command.distribution.packages = ["not_a_file"] command.distribution.package_dir = {"not_a_file": src_dir} command.initialize_options() command.finalize_options() try: command.run() except BaseException: pass
<commit_before>import os from unittest.mock import MagicMock import pytest from isort import setuptools_commands def test_isort_command_smoke(src_dir): """A basic smoke test for the setuptools_commands command""" from distutils.dist import Distribution command = setuptools_commands.ISortCommand(Distribution()) command.distribution.packages = ["isort"] command.distribution.package_dir = {"isort": src_dir} command.initialize_options() command.finalize_options() try: command.run() except Exception: pass command.distribution.package_dir = {"": "isort"} command.distribution.py_modules = ["one", "two"] command.initialize_options() command.finalize_options() command.run() command.distribution.packages = ["not_a_file"] command.distribution.package_dir = {"not_a_file": src_dir} command.initialize_options() command.finalize_options() try: command.run() except Exception: pass <commit_msg>Fix exception test to handle system exceptions<commit_after>import os from unittest.mock import MagicMock import pytest from isort import setuptools_commands def test_isort_command_smoke(src_dir): """A basic smoke test for the setuptools_commands command""" from distutils.dist import Distribution command = setuptools_commands.ISortCommand(Distribution()) command.distribution.packages = ["isort"] command.distribution.package_dir = {"isort": src_dir} command.initialize_options() command.finalize_options() try: command.run() except BaseException: pass command.distribution.package_dir = {"": "isort"} command.distribution.py_modules = ["one", "two"] command.initialize_options() command.finalize_options() command.run() command.distribution.packages = ["not_a_file"] command.distribution.package_dir = {"not_a_file": src_dir} command.initialize_options() command.finalize_options() try: command.run() except BaseException: pass
62017dc7dc210d09e8f6753ad86365ac679f4a0a
oscar/apps/catalogue/categories.py
oscar/apps/catalogue/categories.py
from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node try: root = Category.objects.get(depth=1, name=bits[0]) except Category.DoesNotExist: root = Category.add_root(name=bits[0]) return [root] else: parents = create_from_sequence(bits[:-1]) try: child = parents[-1].get_children().get(name=bits[-1]) except Category.DoesNotExist: child = parents[-1].add_child(name=bits[-1]) parents.append(child) return parents def create_from_breadcrumbs(breadcrumb_str, separator='>'): """ Create categories from a breadcrumb string """ category_names = [x.strip() for x in breadcrumb_str.split(separator)] categories = create_from_sequence(category_names) return categories[-1]
from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node name = bits[0] try: # Category names should be unique at the depth=1 root = Category.objects.get(depth=1, name=name) except Category.DoesNotExist: root = Category.add_root(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s at depth=1") % name) return [root] else: parents = create_from_sequence(bits[:-1]) parent, name = parents[-1], bits[-1] try: child = parent.get_children().get(name=name) except Category.DoesNotExist: child = parent.add_child(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s which are children of %s") % (name, parent)) parents.append(child) return parents def create_from_breadcrumbs(breadcrumb_str, separator='>'): """ Create categories from a breadcrumb string """ category_names = [x.strip() for x in breadcrumb_str.split(separator)] categories = create_from_sequence(category_names) return categories[-1]
Rework category creation from breadcrumbs
Rework category creation from breadcrumbs We now handle MultipleObjectsReturned exceptions, which are possible as we are looking up based on non-unique filters.
Python
bsd-3-clause
vovanbo/django-oscar,adamend/django-oscar,MatthewWilkes/django-oscar,manevant/django-oscar,django-oscar/django-oscar,WadeYuChen/django-oscar,elliotthill/django-oscar,sasha0/django-oscar,WillisXChen/django-oscar,jinnykoo/wuyisj,Jannes123/django-oscar,makielab/django-oscar,WadeYuChen/django-oscar,lijoantony/django-oscar,jinnykoo/christmas,elliotthill/django-oscar,vovanbo/django-oscar,dongguangming/django-oscar,adamend/django-oscar,WillisXChen/django-oscar,ka7eh/django-oscar,dongguangming/django-oscar,bschuon/django-oscar,jinnykoo/wuyisj,monikasulik/django-oscar,solarissmoke/django-oscar,WadeYuChen/django-oscar,pdonadeo/django-oscar,DrOctogon/unwash_ecom,josesanch/django-oscar,nfletton/django-oscar,jinnykoo/wuyisj.com,WillisXChen/django-oscar,john-parton/django-oscar,spartonia/django-oscar,saadatqadri/django-oscar,eddiep1101/django-oscar,QLGu/django-oscar,ademuk/django-oscar,MatthewWilkes/django-oscar,eddiep1101/django-oscar,jmt4/django-oscar,Jannes123/django-oscar,bnprk/django-oscar,rocopartners/django-oscar,anentropic/django-oscar,ka7eh/django-oscar,taedori81/django-oscar,ka7eh/django-oscar,kapari/django-oscar,lijoantony/django-oscar,ademuk/django-oscar,bnprk/django-oscar,eddiep1101/django-oscar,adamend/django-oscar,marcoantoniooliveira/labweb,kapari/django-oscar,Bogh/django-oscar,machtfit/django-oscar,spartonia/django-oscar,manevant/django-oscar,jmt4/django-oscar,makielab/django-oscar,nfletton/django-oscar,jmt4/django-oscar,rocopartners/django-oscar,thechampanurag/django-oscar,Jannes123/django-oscar,monikasulik/django-oscar,manevant/django-oscar,jinnykoo/wuyisj.com,mexeniz/django-oscar,sonofatailor/django-oscar,ahmetdaglarbas/e-commerce,vovanbo/django-oscar,marcoantoniooliveira/labweb,taedori81/django-oscar,kapari/django-oscar,okfish/django-oscar,nickpack/django-oscar,dongguangming/django-oscar,kapt/django-oscar,manevant/django-oscar,marcoantoniooliveira/labweb,kapt/django-oscar,itbabu/django-oscar,okfish/django-oscar,QLGu/django-oscar,okfish/django-oscar,nickpack/django-oscar,solarissmoke/django-oscar,marcoantoniooliveira/labweb,kapari/django-oscar,itbabu/django-oscar,sonofatailor/django-oscar,vovanbo/django-oscar,Bogh/django-oscar,faratro/django-oscar,binarydud/django-oscar,jinnykoo/wuyisj.com,pasqualguerrero/django-oscar,saadatqadri/django-oscar,nfletton/django-oscar,jlmadurga/django-oscar,michaelkuty/django-oscar,WillisXChen/django-oscar,elliotthill/django-oscar,spartonia/django-oscar,Idematica/django-oscar,anentropic/django-oscar,dongguangming/django-oscar,okfish/django-oscar,faratro/django-oscar,QLGu/django-oscar,Bogh/django-oscar,josesanch/django-oscar,kapt/django-oscar,adamend/django-oscar,jinnykoo/wuyisj,mexeniz/django-oscar,solarissmoke/django-oscar,john-parton/django-oscar,michaelkuty/django-oscar,sasha0/django-oscar,WillisXChen/django-oscar,Jannes123/django-oscar,Bogh/django-oscar,faratro/django-oscar,amirrpp/django-oscar,ademuk/django-oscar,anentropic/django-oscar,DrOctogon/unwash_ecom,john-parton/django-oscar,itbabu/django-oscar,jinnykoo/christmas,jinnykoo/wuyisj.com,WadeYuChen/django-oscar,itbabu/django-oscar,pdonadeo/django-oscar,monikasulik/django-oscar,ahmetdaglarbas/e-commerce,eddiep1101/django-oscar,django-oscar/django-oscar,thechampanurag/django-oscar,makielab/django-oscar,binarydud/django-oscar,josesanch/django-oscar,monikasulik/django-oscar,machtfit/django-oscar,lijoantony/django-oscar,taedori81/django-oscar,sonofatailor/django-oscar,lijoantony/django-oscar,faratro/django-oscar,bschuon/django-oscar,amirrpp/django-oscar,taedori81/django-oscar,DrOctogon/unwash_ecom,michaelkuty/django-oscar,nfletton/django-oscar,WillisXChen/django-oscar,solarissmoke/django-oscar,bnprk/django-oscar,john-parton/django-oscar,saadatqadri/django-oscar,Idematica/django-oscar,mexeniz/django-oscar,jlmadurga/django-oscar,MatthewWilkes/django-oscar,MatthewWilkes/django-oscar,ahmetdaglarbas/e-commerce,bnprk/django-oscar,django-oscar/django-oscar,ademuk/django-oscar,bschuon/django-oscar,Idematica/django-oscar,ahmetdaglarbas/e-commerce,jlmadurga/django-oscar,amirrpp/django-oscar,binarydud/django-oscar,amirrpp/django-oscar,mexeniz/django-oscar,pdonadeo/django-oscar,spartonia/django-oscar,bschuon/django-oscar,rocopartners/django-oscar,makielab/django-oscar,jmt4/django-oscar,sonofatailor/django-oscar,thechampanurag/django-oscar,nickpack/django-oscar,ka7eh/django-oscar,sasha0/django-oscar,anentropic/django-oscar,jinnykoo/christmas,michaelkuty/django-oscar,pasqualguerrero/django-oscar,binarydud/django-oscar,machtfit/django-oscar,pasqualguerrero/django-oscar,saadatqadri/django-oscar,django-oscar/django-oscar,jinnykoo/wuyisj,jlmadurga/django-oscar,rocopartners/django-oscar,pasqualguerrero/django-oscar,QLGu/django-oscar,pdonadeo/django-oscar,thechampanurag/django-oscar,sasha0/django-oscar,nickpack/django-oscar
from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node try: root = Category.objects.get(depth=1, name=bits[0]) except Category.DoesNotExist: root = Category.add_root(name=bits[0]) return [root] else: parents = create_from_sequence(bits[:-1]) try: child = parents[-1].get_children().get(name=bits[-1]) except Category.DoesNotExist: child = parents[-1].add_child(name=bits[-1]) parents.append(child) return parents def create_from_breadcrumbs(breadcrumb_str, separator='>'): """ Create categories from a breadcrumb string """ category_names = [x.strip() for x in breadcrumb_str.split(separator)] categories = create_from_sequence(category_names) return categories[-1] Rework category creation from breadcrumbs We now handle MultipleObjectsReturned exceptions, which are possible as we are looking up based on non-unique filters.
from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node name = bits[0] try: # Category names should be unique at the depth=1 root = Category.objects.get(depth=1, name=name) except Category.DoesNotExist: root = Category.add_root(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s at depth=1") % name) return [root] else: parents = create_from_sequence(bits[:-1]) parent, name = parents[-1], bits[-1] try: child = parent.get_children().get(name=name) except Category.DoesNotExist: child = parent.add_child(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s which are children of %s") % (name, parent)) parents.append(child) return parents def create_from_breadcrumbs(breadcrumb_str, separator='>'): """ Create categories from a breadcrumb string """ category_names = [x.strip() for x in breadcrumb_str.split(separator)] categories = create_from_sequence(category_names) return categories[-1]
<commit_before>from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node try: root = Category.objects.get(depth=1, name=bits[0]) except Category.DoesNotExist: root = Category.add_root(name=bits[0]) return [root] else: parents = create_from_sequence(bits[:-1]) try: child = parents[-1].get_children().get(name=bits[-1]) except Category.DoesNotExist: child = parents[-1].add_child(name=bits[-1]) parents.append(child) return parents def create_from_breadcrumbs(breadcrumb_str, separator='>'): """ Create categories from a breadcrumb string """ category_names = [x.strip() for x in breadcrumb_str.split(separator)] categories = create_from_sequence(category_names) return categories[-1] <commit_msg>Rework category creation from breadcrumbs We now handle MultipleObjectsReturned exceptions, which are possible as we are looking up based on non-unique filters.<commit_after>
from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node name = bits[0] try: # Category names should be unique at the depth=1 root = Category.objects.get(depth=1, name=name) except Category.DoesNotExist: root = Category.add_root(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s at depth=1") % name) return [root] else: parents = create_from_sequence(bits[:-1]) parent, name = parents[-1], bits[-1] try: child = parent.get_children().get(name=name) except Category.DoesNotExist: child = parent.add_child(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s which are children of %s") % (name, parent)) parents.append(child) return parents def create_from_breadcrumbs(breadcrumb_str, separator='>'): """ Create categories from a breadcrumb string """ category_names = [x.strip() for x in breadcrumb_str.split(separator)] categories = create_from_sequence(category_names) return categories[-1]
from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node try: root = Category.objects.get(depth=1, name=bits[0]) except Category.DoesNotExist: root = Category.add_root(name=bits[0]) return [root] else: parents = create_from_sequence(bits[:-1]) try: child = parents[-1].get_children().get(name=bits[-1]) except Category.DoesNotExist: child = parents[-1].add_child(name=bits[-1]) parents.append(child) return parents def create_from_breadcrumbs(breadcrumb_str, separator='>'): """ Create categories from a breadcrumb string """ category_names = [x.strip() for x in breadcrumb_str.split(separator)] categories = create_from_sequence(category_names) return categories[-1] Rework category creation from breadcrumbs We now handle MultipleObjectsReturned exceptions, which are possible as we are looking up based on non-unique filters.from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node name = bits[0] try: # Category names should be unique at the depth=1 root = Category.objects.get(depth=1, name=name) except Category.DoesNotExist: root = Category.add_root(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s at depth=1") % name) return [root] else: parents = create_from_sequence(bits[:-1]) parent, name = parents[-1], bits[-1] try: child = parent.get_children().get(name=name) except Category.DoesNotExist: child = parent.add_child(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s which are children of %s") % (name, parent)) parents.append(child) return parents def create_from_breadcrumbs(breadcrumb_str, separator='>'): """ Create categories from a breadcrumb string """ category_names = [x.strip() for x in breadcrumb_str.split(separator)] categories = create_from_sequence(category_names) return categories[-1]
<commit_before>from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node try: root = Category.objects.get(depth=1, name=bits[0]) except Category.DoesNotExist: root = Category.add_root(name=bits[0]) return [root] else: parents = create_from_sequence(bits[:-1]) try: child = parents[-1].get_children().get(name=bits[-1]) except Category.DoesNotExist: child = parents[-1].add_child(name=bits[-1]) parents.append(child) return parents def create_from_breadcrumbs(breadcrumb_str, separator='>'): """ Create categories from a breadcrumb string """ category_names = [x.strip() for x in breadcrumb_str.split(separator)] categories = create_from_sequence(category_names) return categories[-1] <commit_msg>Rework category creation from breadcrumbs We now handle MultipleObjectsReturned exceptions, which are possible as we are looking up based on non-unique filters.<commit_after>from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node name = bits[0] try: # Category names should be unique at the depth=1 root = Category.objects.get(depth=1, name=name) except Category.DoesNotExist: root = Category.add_root(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s at depth=1") % name) return [root] else: parents = create_from_sequence(bits[:-1]) parent, name = parents[-1], bits[-1] try: child = parent.get_children().get(name=name) except Category.DoesNotExist: child = parent.add_child(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s which are children of %s") % (name, parent)) parents.append(child) return parents def create_from_breadcrumbs(breadcrumb_str, separator='>'): """ Create categories from a breadcrumb string """ category_names = [x.strip() for x in breadcrumb_str.split(separator)] categories = create_from_sequence(category_names) return categories[-1]
00a7f018b80d7ddf9cad775ee39d90813879253b
migrations/194-questions-product-migration.py
migrations/194-questions-product-migration.py
from django.utils.encoding import smart_str from kitsune.products.models import Product from kitsune.taggit.models import Tag from kitsune.questions.models import Question tags_to_migrate = { # source tag -> product 'desktop': ['firefox'], 'mobile': ['mobile'] } def assert_equals(a, b): assert a == b, '%s != %s' % (a, b) def run(): # Get all the tags to migrate. tags = list(Tag.objects.filter(slug__in=tags_to_migrate.keys())) total_affected = 0 # For each tag, get the question and add a product for it. for tag in tags: for product_slug in tags_to_migrate[tag.slug]: product = Product.objects.get(slug=product_slug) # Assign the product to all the questions tagged with tag. # Pull in 5000 at a time from the db. n = 5000 qs = Question.objects.filter(tags__slug=tag.slug) count = qs.count() print '%s %s questions to work on...' % (count, product_slug) for i in range(0, count, n): for question in qs[i:i + n]: question.products.add(product) print 'Added product "%s" to question "%s"' % ( smart_str(product.slug), smart_str(question.title)) total_affected += 1 print 'Done! (%d)' % total_affected
from django.utils.encoding import smart_str from kitsune.products.models import Product from taggit.models import Tag from kitsune.questions.models import Question tags_to_migrate = { # source tag -> product 'desktop': ['firefox'], 'mobile': ['mobile'] } def assert_equals(a, b): assert a == b, '%s != %s' % (a, b) def run(): # Get all the tags to migrate. tags = list(Tag.objects.filter(slug__in=tags_to_migrate.keys())) total_affected = 0 # For each tag, get the question and add a product for it. for tag in tags: for product_slug in tags_to_migrate[tag.slug]: product = Product.objects.get(slug=product_slug) # Assign the product to all the questions tagged with tag. # Pull in 5000 at a time from the db. n = 5000 qs = Question.objects.filter(tags__slug=tag.slug) count = qs.count() print '%s %s questions to work on...' % (count, product_slug) for i in range(0, count, n): for question in qs[i:i + n]: question.products.add(product) print 'Added product "%s" to question "%s"' % ( smart_str(product.slug), smart_str(question.title)) total_affected += 1 print 'Done! (%d)' % total_affected
Fix wrong module name in migrations
Fix wrong module name in migrations
Python
bsd-3-clause
MikkCZ/kitsune,dbbhattacharya/kitsune,MziRintu/kitsune,dbbhattacharya/kitsune,YOTOV-LIMITED/kitsune,rlr/kitsune,turtleloveshoes/kitsune,feer56/Kitsune1,Osmose/kitsune,mythmon/kitsune,Osmose/kitsune,safwanrahman/kitsune,Osmose/kitsune,YOTOV-LIMITED/kitsune,rlr/kitsune,Osmose/kitsune,NewPresident1/kitsune,feer56/Kitsune2,safwanrahman/kitsune,silentbob73/kitsune,asdofindia/kitsune,safwanrahman/kitsune,dbbhattacharya/kitsune,chirilo/kitsune,anushbmx/kitsune,MikkCZ/kitsune,orvi2014/kitsune,mozilla/kitsune,H1ghT0p/kitsune,turtleloveshoes/kitsune,mythmon/kitsune,MziRintu/kitsune,H1ghT0p/kitsune,safwanrahman/linuxdesh,safwanrahman/linuxdesh,brittanystoroz/kitsune,feer56/Kitsune1,philipp-sumo/kitsune,iDTLabssl/kitsune,anushbmx/kitsune,MikkCZ/kitsune,feer56/Kitsune1,iDTLabssl/kitsune,turtleloveshoes/kitsune,chirilo/kitsune,dbbhattacharya/kitsune,NewPresident1/kitsune,orvi2014/kitsune,anushbmx/kitsune,iDTLabssl/kitsune,turtleloveshoes/kitsune,orvi2014/kitsune,H1ghT0p/kitsune,safwanrahman/kitsune,mozilla/kitsune,NewPresident1/kitsune,iDTLabssl/kitsune,silentbob73/kitsune,rlr/kitsune,brittanystoroz/kitsune,brittanystoroz/kitsune,chirilo/kitsune,asdofindia/kitsune,philipp-sumo/kitsune,feer56/Kitsune2,mythmon/kitsune,mozilla/kitsune,silentbob73/kitsune,rlr/kitsune,asdofindia/kitsune,mythmon/kitsune,brittanystoroz/kitsune,mozilla/kitsune,orvi2014/kitsune,YOTOV-LIMITED/kitsune,chirilo/kitsune,MziRintu/kitsune,asdofindia/kitsune,safwanrahman/linuxdesh,silentbob73/kitsune,H1ghT0p/kitsune,philipp-sumo/kitsune,anushbmx/kitsune,feer56/Kitsune2,MziRintu/kitsune,MikkCZ/kitsune,YOTOV-LIMITED/kitsune,feer56/Kitsune2,NewPresident1/kitsune
from django.utils.encoding import smart_str from kitsune.products.models import Product from kitsune.taggit.models import Tag from kitsune.questions.models import Question tags_to_migrate = { # source tag -> product 'desktop': ['firefox'], 'mobile': ['mobile'] } def assert_equals(a, b): assert a == b, '%s != %s' % (a, b) def run(): # Get all the tags to migrate. tags = list(Tag.objects.filter(slug__in=tags_to_migrate.keys())) total_affected = 0 # For each tag, get the question and add a product for it. for tag in tags: for product_slug in tags_to_migrate[tag.slug]: product = Product.objects.get(slug=product_slug) # Assign the product to all the questions tagged with tag. # Pull in 5000 at a time from the db. n = 5000 qs = Question.objects.filter(tags__slug=tag.slug) count = qs.count() print '%s %s questions to work on...' % (count, product_slug) for i in range(0, count, n): for question in qs[i:i + n]: question.products.add(product) print 'Added product "%s" to question "%s"' % ( smart_str(product.slug), smart_str(question.title)) total_affected += 1 print 'Done! (%d)' % total_affected Fix wrong module name in migrations
from django.utils.encoding import smart_str from kitsune.products.models import Product from taggit.models import Tag from kitsune.questions.models import Question tags_to_migrate = { # source tag -> product 'desktop': ['firefox'], 'mobile': ['mobile'] } def assert_equals(a, b): assert a == b, '%s != %s' % (a, b) def run(): # Get all the tags to migrate. tags = list(Tag.objects.filter(slug__in=tags_to_migrate.keys())) total_affected = 0 # For each tag, get the question and add a product for it. for tag in tags: for product_slug in tags_to_migrate[tag.slug]: product = Product.objects.get(slug=product_slug) # Assign the product to all the questions tagged with tag. # Pull in 5000 at a time from the db. n = 5000 qs = Question.objects.filter(tags__slug=tag.slug) count = qs.count() print '%s %s questions to work on...' % (count, product_slug) for i in range(0, count, n): for question in qs[i:i + n]: question.products.add(product) print 'Added product "%s" to question "%s"' % ( smart_str(product.slug), smart_str(question.title)) total_affected += 1 print 'Done! (%d)' % total_affected
<commit_before>from django.utils.encoding import smart_str from kitsune.products.models import Product from kitsune.taggit.models import Tag from kitsune.questions.models import Question tags_to_migrate = { # source tag -> product 'desktop': ['firefox'], 'mobile': ['mobile'] } def assert_equals(a, b): assert a == b, '%s != %s' % (a, b) def run(): # Get all the tags to migrate. tags = list(Tag.objects.filter(slug__in=tags_to_migrate.keys())) total_affected = 0 # For each tag, get the question and add a product for it. for tag in tags: for product_slug in tags_to_migrate[tag.slug]: product = Product.objects.get(slug=product_slug) # Assign the product to all the questions tagged with tag. # Pull in 5000 at a time from the db. n = 5000 qs = Question.objects.filter(tags__slug=tag.slug) count = qs.count() print '%s %s questions to work on...' % (count, product_slug) for i in range(0, count, n): for question in qs[i:i + n]: question.products.add(product) print 'Added product "%s" to question "%s"' % ( smart_str(product.slug), smart_str(question.title)) total_affected += 1 print 'Done! (%d)' % total_affected <commit_msg>Fix wrong module name in migrations<commit_after>
from django.utils.encoding import smart_str from kitsune.products.models import Product from taggit.models import Tag from kitsune.questions.models import Question tags_to_migrate = { # source tag -> product 'desktop': ['firefox'], 'mobile': ['mobile'] } def assert_equals(a, b): assert a == b, '%s != %s' % (a, b) def run(): # Get all the tags to migrate. tags = list(Tag.objects.filter(slug__in=tags_to_migrate.keys())) total_affected = 0 # For each tag, get the question and add a product for it. for tag in tags: for product_slug in tags_to_migrate[tag.slug]: product = Product.objects.get(slug=product_slug) # Assign the product to all the questions tagged with tag. # Pull in 5000 at a time from the db. n = 5000 qs = Question.objects.filter(tags__slug=tag.slug) count = qs.count() print '%s %s questions to work on...' % (count, product_slug) for i in range(0, count, n): for question in qs[i:i + n]: question.products.add(product) print 'Added product "%s" to question "%s"' % ( smart_str(product.slug), smart_str(question.title)) total_affected += 1 print 'Done! (%d)' % total_affected
from django.utils.encoding import smart_str from kitsune.products.models import Product from kitsune.taggit.models import Tag from kitsune.questions.models import Question tags_to_migrate = { # source tag -> product 'desktop': ['firefox'], 'mobile': ['mobile'] } def assert_equals(a, b): assert a == b, '%s != %s' % (a, b) def run(): # Get all the tags to migrate. tags = list(Tag.objects.filter(slug__in=tags_to_migrate.keys())) total_affected = 0 # For each tag, get the question and add a product for it. for tag in tags: for product_slug in tags_to_migrate[tag.slug]: product = Product.objects.get(slug=product_slug) # Assign the product to all the questions tagged with tag. # Pull in 5000 at a time from the db. n = 5000 qs = Question.objects.filter(tags__slug=tag.slug) count = qs.count() print '%s %s questions to work on...' % (count, product_slug) for i in range(0, count, n): for question in qs[i:i + n]: question.products.add(product) print 'Added product "%s" to question "%s"' % ( smart_str(product.slug), smart_str(question.title)) total_affected += 1 print 'Done! (%d)' % total_affected Fix wrong module name in migrationsfrom django.utils.encoding import smart_str from kitsune.products.models import Product from taggit.models import Tag from kitsune.questions.models import Question tags_to_migrate = { # source tag -> product 'desktop': ['firefox'], 'mobile': ['mobile'] } def assert_equals(a, b): assert a == b, '%s != %s' % (a, b) def run(): # Get all the tags to migrate. tags = list(Tag.objects.filter(slug__in=tags_to_migrate.keys())) total_affected = 0 # For each tag, get the question and add a product for it. for tag in tags: for product_slug in tags_to_migrate[tag.slug]: product = Product.objects.get(slug=product_slug) # Assign the product to all the questions tagged with tag. # Pull in 5000 at a time from the db. n = 5000 qs = Question.objects.filter(tags__slug=tag.slug) count = qs.count() print '%s %s questions to work on...' % (count, product_slug) for i in range(0, count, n): for question in qs[i:i + n]: question.products.add(product) print 'Added product "%s" to question "%s"' % ( smart_str(product.slug), smart_str(question.title)) total_affected += 1 print 'Done! (%d)' % total_affected
<commit_before>from django.utils.encoding import smart_str from kitsune.products.models import Product from kitsune.taggit.models import Tag from kitsune.questions.models import Question tags_to_migrate = { # source tag -> product 'desktop': ['firefox'], 'mobile': ['mobile'] } def assert_equals(a, b): assert a == b, '%s != %s' % (a, b) def run(): # Get all the tags to migrate. tags = list(Tag.objects.filter(slug__in=tags_to_migrate.keys())) total_affected = 0 # For each tag, get the question and add a product for it. for tag in tags: for product_slug in tags_to_migrate[tag.slug]: product = Product.objects.get(slug=product_slug) # Assign the product to all the questions tagged with tag. # Pull in 5000 at a time from the db. n = 5000 qs = Question.objects.filter(tags__slug=tag.slug) count = qs.count() print '%s %s questions to work on...' % (count, product_slug) for i in range(0, count, n): for question in qs[i:i + n]: question.products.add(product) print 'Added product "%s" to question "%s"' % ( smart_str(product.slug), smart_str(question.title)) total_affected += 1 print 'Done! (%d)' % total_affected <commit_msg>Fix wrong module name in migrations<commit_after>from django.utils.encoding import smart_str from kitsune.products.models import Product from taggit.models import Tag from kitsune.questions.models import Question tags_to_migrate = { # source tag -> product 'desktop': ['firefox'], 'mobile': ['mobile'] } def assert_equals(a, b): assert a == b, '%s != %s' % (a, b) def run(): # Get all the tags to migrate. tags = list(Tag.objects.filter(slug__in=tags_to_migrate.keys())) total_affected = 0 # For each tag, get the question and add a product for it. for tag in tags: for product_slug in tags_to_migrate[tag.slug]: product = Product.objects.get(slug=product_slug) # Assign the product to all the questions tagged with tag. # Pull in 5000 at a time from the db. n = 5000 qs = Question.objects.filter(tags__slug=tag.slug) count = qs.count() print '%s %s questions to work on...' % (count, product_slug) for i in range(0, count, n): for question in qs[i:i + n]: question.products.add(product) print 'Added product "%s" to question "%s"' % ( smart_str(product.slug), smart_str(question.title)) total_affected += 1 print 'Done! (%d)' % total_affected
09102cb87c41330d1ae670f0e1cea00037c74b5b
src/librement/profile/models.py
src/librement/profile/models.py
from django.db import models from django_enumfield import EnumField from librement.utils.user_data import PerUserData from .enums import AccountEnum, CountryEnum class Profile(PerUserData('profile')): account_type = EnumField(AccountEnum) organisation = models.CharField(max_length=100, blank=True) address_1 = models.CharField(max_length=150, blank=True) address_2 = models.CharField(max_length=150, blank=True) city = models.CharField(max_length=100, blank=True) region = models.CharField(max_length=100, blank=True) zipcode = models.CharField(max_length=100, blank=True) country = EnumField(CountryEnum)
from django.db import models from django_enumfield import EnumField from librement.utils.user_data import PerUserData from .enums import AccountEnum, CountryEnum class Profile(PerUserData('profile')): account_type = EnumField(AccountEnum) organisation = models.CharField(max_length=100, blank=True) address_1 = models.CharField(max_length=150, blank=True) address_2 = models.CharField(max_length=150, blank=True) city = models.CharField(max_length=100, blank=True) region = models.CharField(max_length=100, blank=True) zipcode = models.CharField(max_length=100, blank=True) country = EnumField(CountryEnum) class Email(models.Model): user = models.ForeignKey('auth.User', related_name='emails') email = models.EmailField(unique=True) def __unicode__(self): return u"%s" % self.email
Add model for storing multiple email addresses.
Add model for storing multiple email addresses. Signed-off-by: Chris Lamb <29e6d179a8d73471df7861382db6dd7e64138033@debian.org>
Python
agpl-3.0
rhertzog/librement,rhertzog/librement,rhertzog/librement
from django.db import models from django_enumfield import EnumField from librement.utils.user_data import PerUserData from .enums import AccountEnum, CountryEnum class Profile(PerUserData('profile')): account_type = EnumField(AccountEnum) organisation = models.CharField(max_length=100, blank=True) address_1 = models.CharField(max_length=150, blank=True) address_2 = models.CharField(max_length=150, blank=True) city = models.CharField(max_length=100, blank=True) region = models.CharField(max_length=100, blank=True) zipcode = models.CharField(max_length=100, blank=True) country = EnumField(CountryEnum) Add model for storing multiple email addresses. Signed-off-by: Chris Lamb <29e6d179a8d73471df7861382db6dd7e64138033@debian.org>
from django.db import models from django_enumfield import EnumField from librement.utils.user_data import PerUserData from .enums import AccountEnum, CountryEnum class Profile(PerUserData('profile')): account_type = EnumField(AccountEnum) organisation = models.CharField(max_length=100, blank=True) address_1 = models.CharField(max_length=150, blank=True) address_2 = models.CharField(max_length=150, blank=True) city = models.CharField(max_length=100, blank=True) region = models.CharField(max_length=100, blank=True) zipcode = models.CharField(max_length=100, blank=True) country = EnumField(CountryEnum) class Email(models.Model): user = models.ForeignKey('auth.User', related_name='emails') email = models.EmailField(unique=True) def __unicode__(self): return u"%s" % self.email
<commit_before>from django.db import models from django_enumfield import EnumField from librement.utils.user_data import PerUserData from .enums import AccountEnum, CountryEnum class Profile(PerUserData('profile')): account_type = EnumField(AccountEnum) organisation = models.CharField(max_length=100, blank=True) address_1 = models.CharField(max_length=150, blank=True) address_2 = models.CharField(max_length=150, blank=True) city = models.CharField(max_length=100, blank=True) region = models.CharField(max_length=100, blank=True) zipcode = models.CharField(max_length=100, blank=True) country = EnumField(CountryEnum) <commit_msg>Add model for storing multiple email addresses. Signed-off-by: Chris Lamb <29e6d179a8d73471df7861382db6dd7e64138033@debian.org><commit_after>
from django.db import models from django_enumfield import EnumField from librement.utils.user_data import PerUserData from .enums import AccountEnum, CountryEnum class Profile(PerUserData('profile')): account_type = EnumField(AccountEnum) organisation = models.CharField(max_length=100, blank=True) address_1 = models.CharField(max_length=150, blank=True) address_2 = models.CharField(max_length=150, blank=True) city = models.CharField(max_length=100, blank=True) region = models.CharField(max_length=100, blank=True) zipcode = models.CharField(max_length=100, blank=True) country = EnumField(CountryEnum) class Email(models.Model): user = models.ForeignKey('auth.User', related_name='emails') email = models.EmailField(unique=True) def __unicode__(self): return u"%s" % self.email
from django.db import models from django_enumfield import EnumField from librement.utils.user_data import PerUserData from .enums import AccountEnum, CountryEnum class Profile(PerUserData('profile')): account_type = EnumField(AccountEnum) organisation = models.CharField(max_length=100, blank=True) address_1 = models.CharField(max_length=150, blank=True) address_2 = models.CharField(max_length=150, blank=True) city = models.CharField(max_length=100, blank=True) region = models.CharField(max_length=100, blank=True) zipcode = models.CharField(max_length=100, blank=True) country = EnumField(CountryEnum) Add model for storing multiple email addresses. Signed-off-by: Chris Lamb <29e6d179a8d73471df7861382db6dd7e64138033@debian.org>from django.db import models from django_enumfield import EnumField from librement.utils.user_data import PerUserData from .enums import AccountEnum, CountryEnum class Profile(PerUserData('profile')): account_type = EnumField(AccountEnum) organisation = models.CharField(max_length=100, blank=True) address_1 = models.CharField(max_length=150, blank=True) address_2 = models.CharField(max_length=150, blank=True) city = models.CharField(max_length=100, blank=True) region = models.CharField(max_length=100, blank=True) zipcode = models.CharField(max_length=100, blank=True) country = EnumField(CountryEnum) class Email(models.Model): user = models.ForeignKey('auth.User', related_name='emails') email = models.EmailField(unique=True) def __unicode__(self): return u"%s" % self.email
<commit_before>from django.db import models from django_enumfield import EnumField from librement.utils.user_data import PerUserData from .enums import AccountEnum, CountryEnum class Profile(PerUserData('profile')): account_type = EnumField(AccountEnum) organisation = models.CharField(max_length=100, blank=True) address_1 = models.CharField(max_length=150, blank=True) address_2 = models.CharField(max_length=150, blank=True) city = models.CharField(max_length=100, blank=True) region = models.CharField(max_length=100, blank=True) zipcode = models.CharField(max_length=100, blank=True) country = EnumField(CountryEnum) <commit_msg>Add model for storing multiple email addresses. Signed-off-by: Chris Lamb <29e6d179a8d73471df7861382db6dd7e64138033@debian.org><commit_after>from django.db import models from django_enumfield import EnumField from librement.utils.user_data import PerUserData from .enums import AccountEnum, CountryEnum class Profile(PerUserData('profile')): account_type = EnumField(AccountEnum) organisation = models.CharField(max_length=100, blank=True) address_1 = models.CharField(max_length=150, blank=True) address_2 = models.CharField(max_length=150, blank=True) city = models.CharField(max_length=100, blank=True) region = models.CharField(max_length=100, blank=True) zipcode = models.CharField(max_length=100, blank=True) country = EnumField(CountryEnum) class Email(models.Model): user = models.ForeignKey('auth.User', related_name='emails') email = models.EmailField(unique=True) def __unicode__(self): return u"%s" % self.email
402d30d840e7e1d8885412cce7bee2897150a1cf
widelanguagedemo/public/views.py
widelanguagedemo/public/views.py
# -*- coding: utf-8 -*- # # views.py # wide-language-index-demo # """ Public facing frontpage. """ import json import random from flask import (Blueprint, request, render_template, redirect) from . import forms from ..index import util blueprint = Blueprint('public', __name__, static_folder="../static") @blueprint.route("/", methods=["GET", "POST"]) def home(): language = request.args.get('language') if language: return _render_language(language) form = forms.SearchForm() return render_template("public/home.html", form=form, has_query=False) def _render_language(language): index = util.get_index() if language == 'random': language = random.choice(list(index.keys())) return redirect('/?language={0}'.format(language)) records = index.get(language) inverted_name = util.get_languages().get(language) if records: record = random.choice(records) record_json = json.dumps(record, indent=2, sort_keys=True) form = forms.SearchForm(request.args) return render_template("public/home.html", form=form, record=record, record_json=record_json, inverted_name=inverted_name, has_query=bool(request.args))
# -*- coding: utf-8 -*- # # views.py # wide-language-index-demo # """ Public facing frontpage. """ import json import random from flask import (Blueprint, request, render_template, redirect) from . import forms from ..index import util blueprint = Blueprint('public', __name__, static_folder="../static") @blueprint.route("/", methods=["GET", "POST"]) def home(): language = request.args.get('language') if language: return _render_language(language) form = forms.SearchForm() return render_template("public/home.html", form=form, has_query=False) def _render_language(language): index = util.get_index() if language == 'random': language = random.choice(list(index.keys())) return redirect('/?language={0}'.format(language)) records = index.get(language) inverted_name = util.get_languages().get(language) record = None record_json = None if records: record = random.choice(records) record_json = json.dumps(record, indent=2, sort_keys=True) form = forms.SearchForm(request.args) return render_template("public/home.html", form=form, record=record, record_json=record_json, inverted_name=inverted_name, has_query=bool(request.args))
Fix an error when no samples were found.
Fix an error when no samples were found.
Python
bsd-3-clause
larsyencken/wide-language-demo,larsyencken/wide-language-demo,larsyencken/wide-language-demo,larsyencken/wide-language-demo,larsyencken/wide-language-demo
# -*- coding: utf-8 -*- # # views.py # wide-language-index-demo # """ Public facing frontpage. """ import json import random from flask import (Blueprint, request, render_template, redirect) from . import forms from ..index import util blueprint = Blueprint('public', __name__, static_folder="../static") @blueprint.route("/", methods=["GET", "POST"]) def home(): language = request.args.get('language') if language: return _render_language(language) form = forms.SearchForm() return render_template("public/home.html", form=form, has_query=False) def _render_language(language): index = util.get_index() if language == 'random': language = random.choice(list(index.keys())) return redirect('/?language={0}'.format(language)) records = index.get(language) inverted_name = util.get_languages().get(language) if records: record = random.choice(records) record_json = json.dumps(record, indent=2, sort_keys=True) form = forms.SearchForm(request.args) return render_template("public/home.html", form=form, record=record, record_json=record_json, inverted_name=inverted_name, has_query=bool(request.args)) Fix an error when no samples were found.
# -*- coding: utf-8 -*- # # views.py # wide-language-index-demo # """ Public facing frontpage. """ import json import random from flask import (Blueprint, request, render_template, redirect) from . import forms from ..index import util blueprint = Blueprint('public', __name__, static_folder="../static") @blueprint.route("/", methods=["GET", "POST"]) def home(): language = request.args.get('language') if language: return _render_language(language) form = forms.SearchForm() return render_template("public/home.html", form=form, has_query=False) def _render_language(language): index = util.get_index() if language == 'random': language = random.choice(list(index.keys())) return redirect('/?language={0}'.format(language)) records = index.get(language) inverted_name = util.get_languages().get(language) record = None record_json = None if records: record = random.choice(records) record_json = json.dumps(record, indent=2, sort_keys=True) form = forms.SearchForm(request.args) return render_template("public/home.html", form=form, record=record, record_json=record_json, inverted_name=inverted_name, has_query=bool(request.args))
<commit_before># -*- coding: utf-8 -*- # # views.py # wide-language-index-demo # """ Public facing frontpage. """ import json import random from flask import (Blueprint, request, render_template, redirect) from . import forms from ..index import util blueprint = Blueprint('public', __name__, static_folder="../static") @blueprint.route("/", methods=["GET", "POST"]) def home(): language = request.args.get('language') if language: return _render_language(language) form = forms.SearchForm() return render_template("public/home.html", form=form, has_query=False) def _render_language(language): index = util.get_index() if language == 'random': language = random.choice(list(index.keys())) return redirect('/?language={0}'.format(language)) records = index.get(language) inverted_name = util.get_languages().get(language) if records: record = random.choice(records) record_json = json.dumps(record, indent=2, sort_keys=True) form = forms.SearchForm(request.args) return render_template("public/home.html", form=form, record=record, record_json=record_json, inverted_name=inverted_name, has_query=bool(request.args)) <commit_msg>Fix an error when no samples were found.<commit_after>
# -*- coding: utf-8 -*- # # views.py # wide-language-index-demo # """ Public facing frontpage. """ import json import random from flask import (Blueprint, request, render_template, redirect) from . import forms from ..index import util blueprint = Blueprint('public', __name__, static_folder="../static") @blueprint.route("/", methods=["GET", "POST"]) def home(): language = request.args.get('language') if language: return _render_language(language) form = forms.SearchForm() return render_template("public/home.html", form=form, has_query=False) def _render_language(language): index = util.get_index() if language == 'random': language = random.choice(list(index.keys())) return redirect('/?language={0}'.format(language)) records = index.get(language) inverted_name = util.get_languages().get(language) record = None record_json = None if records: record = random.choice(records) record_json = json.dumps(record, indent=2, sort_keys=True) form = forms.SearchForm(request.args) return render_template("public/home.html", form=form, record=record, record_json=record_json, inverted_name=inverted_name, has_query=bool(request.args))
# -*- coding: utf-8 -*- # # views.py # wide-language-index-demo # """ Public facing frontpage. """ import json import random from flask import (Blueprint, request, render_template, redirect) from . import forms from ..index import util blueprint = Blueprint('public', __name__, static_folder="../static") @blueprint.route("/", methods=["GET", "POST"]) def home(): language = request.args.get('language') if language: return _render_language(language) form = forms.SearchForm() return render_template("public/home.html", form=form, has_query=False) def _render_language(language): index = util.get_index() if language == 'random': language = random.choice(list(index.keys())) return redirect('/?language={0}'.format(language)) records = index.get(language) inverted_name = util.get_languages().get(language) if records: record = random.choice(records) record_json = json.dumps(record, indent=2, sort_keys=True) form = forms.SearchForm(request.args) return render_template("public/home.html", form=form, record=record, record_json=record_json, inverted_name=inverted_name, has_query=bool(request.args)) Fix an error when no samples were found.# -*- coding: utf-8 -*- # # views.py # wide-language-index-demo # """ Public facing frontpage. """ import json import random from flask import (Blueprint, request, render_template, redirect) from . import forms from ..index import util blueprint = Blueprint('public', __name__, static_folder="../static") @blueprint.route("/", methods=["GET", "POST"]) def home(): language = request.args.get('language') if language: return _render_language(language) form = forms.SearchForm() return render_template("public/home.html", form=form, has_query=False) def _render_language(language): index = util.get_index() if language == 'random': language = random.choice(list(index.keys())) return redirect('/?language={0}'.format(language)) records = index.get(language) inverted_name = util.get_languages().get(language) record = None record_json = None if records: record = random.choice(records) record_json = json.dumps(record, indent=2, sort_keys=True) form = forms.SearchForm(request.args) return render_template("public/home.html", form=form, record=record, record_json=record_json, inverted_name=inverted_name, has_query=bool(request.args))
<commit_before># -*- coding: utf-8 -*- # # views.py # wide-language-index-demo # """ Public facing frontpage. """ import json import random from flask import (Blueprint, request, render_template, redirect) from . import forms from ..index import util blueprint = Blueprint('public', __name__, static_folder="../static") @blueprint.route("/", methods=["GET", "POST"]) def home(): language = request.args.get('language') if language: return _render_language(language) form = forms.SearchForm() return render_template("public/home.html", form=form, has_query=False) def _render_language(language): index = util.get_index() if language == 'random': language = random.choice(list(index.keys())) return redirect('/?language={0}'.format(language)) records = index.get(language) inverted_name = util.get_languages().get(language) if records: record = random.choice(records) record_json = json.dumps(record, indent=2, sort_keys=True) form = forms.SearchForm(request.args) return render_template("public/home.html", form=form, record=record, record_json=record_json, inverted_name=inverted_name, has_query=bool(request.args)) <commit_msg>Fix an error when no samples were found.<commit_after># -*- coding: utf-8 -*- # # views.py # wide-language-index-demo # """ Public facing frontpage. """ import json import random from flask import (Blueprint, request, render_template, redirect) from . import forms from ..index import util blueprint = Blueprint('public', __name__, static_folder="../static") @blueprint.route("/", methods=["GET", "POST"]) def home(): language = request.args.get('language') if language: return _render_language(language) form = forms.SearchForm() return render_template("public/home.html", form=form, has_query=False) def _render_language(language): index = util.get_index() if language == 'random': language = random.choice(list(index.keys())) return redirect('/?language={0}'.format(language)) records = index.get(language) inverted_name = util.get_languages().get(language) record = None record_json = None if records: record = random.choice(records) record_json = json.dumps(record, indent=2, sort_keys=True) form = forms.SearchForm(request.args) return render_template("public/home.html", form=form, record=record, record_json=record_json, inverted_name=inverted_name, has_query=bool(request.args))
cbd6097cc070967963587441e6fdcf40f7c5293b
st2common/st2common/jinja/filters/data.py
st2common/st2common/jinja/filters/data.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import yaml __all__ = [ 'to_json_string', 'to_yaml_string', ] def to_json_string(value, indent=4, sort_keys=False, separators=(',', ':')): return json.dumps(value, indent=indent, separators=separators, sort_keys=sort_keys) def to_yaml_string(value, indent=4, allow_unicode=True): return yaml.safe_dump(value, indent=indent, allow_unicode=allow_unicode)
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import yaml __all__ = [ 'to_json_string', 'to_yaml_string', ] def to_json_string(value, indent=4, sort_keys=False, separators=(',', ':')): return json.dumps(value, indent=indent, separators=separators, sort_keys=sort_keys) def to_yaml_string(value, indent=4, allow_unicode=True): return yaml.safe_dump(value, indent=indent, allow_unicode=allow_unicode, default_flow_style=False)
Set default_flow_style for yaml jinja filter
Set default_flow_style for yaml jinja filter
Python
apache-2.0
Plexxi/st2,nzlosh/st2,lakshmi-kannan/st2,StackStorm/st2,lakshmi-kannan/st2,tonybaloney/st2,StackStorm/st2,Plexxi/st2,nzlosh/st2,tonybaloney/st2,peak6/st2,tonybaloney/st2,StackStorm/st2,peak6/st2,nzlosh/st2,StackStorm/st2,peak6/st2,nzlosh/st2,lakshmi-kannan/st2,Plexxi/st2,Plexxi/st2
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import yaml __all__ = [ 'to_json_string', 'to_yaml_string', ] def to_json_string(value, indent=4, sort_keys=False, separators=(',', ':')): return json.dumps(value, indent=indent, separators=separators, sort_keys=sort_keys) def to_yaml_string(value, indent=4, allow_unicode=True): return yaml.safe_dump(value, indent=indent, allow_unicode=allow_unicode) Set default_flow_style for yaml jinja filter
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import yaml __all__ = [ 'to_json_string', 'to_yaml_string', ] def to_json_string(value, indent=4, sort_keys=False, separators=(',', ':')): return json.dumps(value, indent=indent, separators=separators, sort_keys=sort_keys) def to_yaml_string(value, indent=4, allow_unicode=True): return yaml.safe_dump(value, indent=indent, allow_unicode=allow_unicode, default_flow_style=False)
<commit_before># Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import yaml __all__ = [ 'to_json_string', 'to_yaml_string', ] def to_json_string(value, indent=4, sort_keys=False, separators=(',', ':')): return json.dumps(value, indent=indent, separators=separators, sort_keys=sort_keys) def to_yaml_string(value, indent=4, allow_unicode=True): return yaml.safe_dump(value, indent=indent, allow_unicode=allow_unicode) <commit_msg>Set default_flow_style for yaml jinja filter<commit_after>
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import yaml __all__ = [ 'to_json_string', 'to_yaml_string', ] def to_json_string(value, indent=4, sort_keys=False, separators=(',', ':')): return json.dumps(value, indent=indent, separators=separators, sort_keys=sort_keys) def to_yaml_string(value, indent=4, allow_unicode=True): return yaml.safe_dump(value, indent=indent, allow_unicode=allow_unicode, default_flow_style=False)
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import yaml __all__ = [ 'to_json_string', 'to_yaml_string', ] def to_json_string(value, indent=4, sort_keys=False, separators=(',', ':')): return json.dumps(value, indent=indent, separators=separators, sort_keys=sort_keys) def to_yaml_string(value, indent=4, allow_unicode=True): return yaml.safe_dump(value, indent=indent, allow_unicode=allow_unicode) Set default_flow_style for yaml jinja filter# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import yaml __all__ = [ 'to_json_string', 'to_yaml_string', ] def to_json_string(value, indent=4, sort_keys=False, separators=(',', ':')): return json.dumps(value, indent=indent, separators=separators, sort_keys=sort_keys) def to_yaml_string(value, indent=4, allow_unicode=True): return yaml.safe_dump(value, indent=indent, allow_unicode=allow_unicode, default_flow_style=False)
<commit_before># Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import yaml __all__ = [ 'to_json_string', 'to_yaml_string', ] def to_json_string(value, indent=4, sort_keys=False, separators=(',', ':')): return json.dumps(value, indent=indent, separators=separators, sort_keys=sort_keys) def to_yaml_string(value, indent=4, allow_unicode=True): return yaml.safe_dump(value, indent=indent, allow_unicode=allow_unicode) <commit_msg>Set default_flow_style for yaml jinja filter<commit_after># Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import yaml __all__ = [ 'to_json_string', 'to_yaml_string', ] def to_json_string(value, indent=4, sort_keys=False, separators=(',', ':')): return json.dumps(value, indent=indent, separators=separators, sort_keys=sort_keys) def to_yaml_string(value, indent=4, allow_unicode=True): return yaml.safe_dump(value, indent=indent, allow_unicode=allow_unicode, default_flow_style=False)
042720760a71b5e372489af2335c2fccc5b4905b
ynr/apps/uk_results/views/api.py
ynr/apps/uk_results/views/api.py
from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset = CandidateResult.objects.select_related( "membership__party", "membership__post", "membership__person" ).order_by("id") serializer_class = CandidateResultSerializer pagination_class = ResultsSetPagination class ProductFilter(filterset.FilterSet): election_id = filters.CharFilter(name="post_election__election__slug") election_date = filters.DateFilter( name="post_election__election__election_date" ) class Meta: model = ResultSet fields = ["election_date", "election_id"] class ResultSetViewSet(viewsets.ModelViewSet): queryset = ResultSet.objects.select_related( "post_election__post", "user" ).order_by("id") serializer_class = ResultSetSerializer pagination_class = ResultsSetPagination filter_class = ProductFilter
from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset = CandidateResult.objects.select_related( "membership__party", "membership__post", "membership__person" ).order_by("id") serializer_class = CandidateResultSerializer pagination_class = ResultsSetPagination class ResultSetFilter(filterset.FilterSet): election_id = filters.CharFilter(field_name="post_election__election__slug") election_date = filters.DateFilter( field_name="post_election__election__election_date" ) class Meta: model = ResultSet fields = ["election_date", "election_id"] class ResultSetViewSet(viewsets.ModelViewSet): queryset = ResultSet.objects.select_related( "post_election__post", "user" ).order_by("id") serializer_class = ResultSetSerializer pagination_class = ResultsSetPagination filter_class = ResultSetFilter
Update filter args and fix name
Update filter args and fix name The newer version of django-filter uses `field_name` rather than `name`
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset = CandidateResult.objects.select_related( "membership__party", "membership__post", "membership__person" ).order_by("id") serializer_class = CandidateResultSerializer pagination_class = ResultsSetPagination class ProductFilter(filterset.FilterSet): election_id = filters.CharFilter(name="post_election__election__slug") election_date = filters.DateFilter( name="post_election__election__election_date" ) class Meta: model = ResultSet fields = ["election_date", "election_id"] class ResultSetViewSet(viewsets.ModelViewSet): queryset = ResultSet.objects.select_related( "post_election__post", "user" ).order_by("id") serializer_class = ResultSetSerializer pagination_class = ResultsSetPagination filter_class = ProductFilter Update filter args and fix name The newer version of django-filter uses `field_name` rather than `name`
from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset = CandidateResult.objects.select_related( "membership__party", "membership__post", "membership__person" ).order_by("id") serializer_class = CandidateResultSerializer pagination_class = ResultsSetPagination class ResultSetFilter(filterset.FilterSet): election_id = filters.CharFilter(field_name="post_election__election__slug") election_date = filters.DateFilter( field_name="post_election__election__election_date" ) class Meta: model = ResultSet fields = ["election_date", "election_id"] class ResultSetViewSet(viewsets.ModelViewSet): queryset = ResultSet.objects.select_related( "post_election__post", "user" ).order_by("id") serializer_class = ResultSetSerializer pagination_class = ResultsSetPagination filter_class = ResultSetFilter
<commit_before>from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset = CandidateResult.objects.select_related( "membership__party", "membership__post", "membership__person" ).order_by("id") serializer_class = CandidateResultSerializer pagination_class = ResultsSetPagination class ProductFilter(filterset.FilterSet): election_id = filters.CharFilter(name="post_election__election__slug") election_date = filters.DateFilter( name="post_election__election__election_date" ) class Meta: model = ResultSet fields = ["election_date", "election_id"] class ResultSetViewSet(viewsets.ModelViewSet): queryset = ResultSet.objects.select_related( "post_election__post", "user" ).order_by("id") serializer_class = ResultSetSerializer pagination_class = ResultsSetPagination filter_class = ProductFilter <commit_msg>Update filter args and fix name The newer version of django-filter uses `field_name` rather than `name`<commit_after>
from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset = CandidateResult.objects.select_related( "membership__party", "membership__post", "membership__person" ).order_by("id") serializer_class = CandidateResultSerializer pagination_class = ResultsSetPagination class ResultSetFilter(filterset.FilterSet): election_id = filters.CharFilter(field_name="post_election__election__slug") election_date = filters.DateFilter( field_name="post_election__election__election_date" ) class Meta: model = ResultSet fields = ["election_date", "election_id"] class ResultSetViewSet(viewsets.ModelViewSet): queryset = ResultSet.objects.select_related( "post_election__post", "user" ).order_by("id") serializer_class = ResultSetSerializer pagination_class = ResultsSetPagination filter_class = ResultSetFilter
from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset = CandidateResult.objects.select_related( "membership__party", "membership__post", "membership__person" ).order_by("id") serializer_class = CandidateResultSerializer pagination_class = ResultsSetPagination class ProductFilter(filterset.FilterSet): election_id = filters.CharFilter(name="post_election__election__slug") election_date = filters.DateFilter( name="post_election__election__election_date" ) class Meta: model = ResultSet fields = ["election_date", "election_id"] class ResultSetViewSet(viewsets.ModelViewSet): queryset = ResultSet.objects.select_related( "post_election__post", "user" ).order_by("id") serializer_class = ResultSetSerializer pagination_class = ResultsSetPagination filter_class = ProductFilter Update filter args and fix name The newer version of django-filter uses `field_name` rather than `name`from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset = CandidateResult.objects.select_related( "membership__party", "membership__post", "membership__person" ).order_by("id") serializer_class = CandidateResultSerializer pagination_class = ResultsSetPagination class ResultSetFilter(filterset.FilterSet): election_id = filters.CharFilter(field_name="post_election__election__slug") election_date = filters.DateFilter( field_name="post_election__election__election_date" ) class Meta: model = ResultSet fields = ["election_date", "election_id"] class ResultSetViewSet(viewsets.ModelViewSet): queryset = ResultSet.objects.select_related( "post_election__post", "user" ).order_by("id") serializer_class = ResultSetSerializer pagination_class = ResultsSetPagination filter_class = ResultSetFilter
<commit_before>from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset = CandidateResult.objects.select_related( "membership__party", "membership__post", "membership__person" ).order_by("id") serializer_class = CandidateResultSerializer pagination_class = ResultsSetPagination class ProductFilter(filterset.FilterSet): election_id = filters.CharFilter(name="post_election__election__slug") election_date = filters.DateFilter( name="post_election__election__election_date" ) class Meta: model = ResultSet fields = ["election_date", "election_id"] class ResultSetViewSet(viewsets.ModelViewSet): queryset = ResultSet.objects.select_related( "post_election__post", "user" ).order_by("id") serializer_class = ResultSetSerializer pagination_class = ResultsSetPagination filter_class = ProductFilter <commit_msg>Update filter args and fix name The newer version of django-filter uses `field_name` rather than `name`<commit_after>from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset = CandidateResult.objects.select_related( "membership__party", "membership__post", "membership__person" ).order_by("id") serializer_class = CandidateResultSerializer pagination_class = ResultsSetPagination class ResultSetFilter(filterset.FilterSet): election_id = filters.CharFilter(field_name="post_election__election__slug") election_date = filters.DateFilter( field_name="post_election__election__election_date" ) class Meta: model = ResultSet fields = ["election_date", "election_id"] class ResultSetViewSet(viewsets.ModelViewSet): queryset = ResultSet.objects.select_related( "post_election__post", "user" ).order_by("id") serializer_class = ResultSetSerializer pagination_class = ResultsSetPagination filter_class = ResultSetFilter
853108e1c5cd9fca27d0f1dc8324b4b2a4d4b871
pyqode/python/plugins/pyqode_python_plugin.py
pyqode/python/plugins/pyqode_python_plugin.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyQode - Python/Qt Code Editor widget # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ This file contains all the PCEF QtDesigner plugins. Installation: ================== run designer.pyw (Qt Designer must be installed on your system and must be in your path on Windows) """ # This only works with PyQt, PySide does not support the QtDesigner module import os if not 'QT_API' in os.environ: os.environ.setdefault("QT_API", "PyQt") import pcef.python PLUGINS_TYPES = {'QPythonCodeEdit': pcef.python.QPythonCodeEdit} try: from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin class QPythonCodeEditPlugin(QCodeEditPlugin): _module = 'pcef.python' # path to the widget's module _class = 'QPythonCodeEdit' # name of the widget class _name = "QPythonCodeEdit" _icon = None _type = pcef.python.QPythonCodeEdit def createWidget(self, parent): return pcef.python.QPythonCodeEdit(parent) except ImportError: print("Cannot use pcef plugins without PyQt4")
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyQode - Python/Qt Code Editor widget # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ This file contains all the PCEF QtDesigner plugins. Installation: ================== run designer.pyw (Qt Designer must be installed on your system and must be in your path on Windows) """ # This only works with PyQt, PySide does not support the QtDesigner module import os if not 'QT_API' in os.environ: os.environ.setdefault("QT_API", "PyQt") import pyqode.python PLUGINS_TYPES = {'QPythonCodeEdit': pyqode.python.QPythonCodeEdit} try: from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin class QPythonCodeEditPlugin(QCodeEditPlugin): _module = 'pcef.python' # path to the widget's module _class = 'QPythonCodeEdit' # name of the widget class _name = "QPythonCodeEdit" _icon = None _type = pyqode.python.QPythonCodeEdit def createWidget(self, parent): return pyqode.python.QPythonCodeEdit(parent) except ImportError: print("Cannot use pcef plugins without PyQt4")
Fix bug with python plugin and pyside
Fix bug with python plugin and pyside
Python
mit
pyQode/pyqode.python,mmolero/pyqode.python,pyQode/pyqode.python,zwadar/pyqode.python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyQode - Python/Qt Code Editor widget # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ This file contains all the PCEF QtDesigner plugins. Installation: ================== run designer.pyw (Qt Designer must be installed on your system and must be in your path on Windows) """ # This only works with PyQt, PySide does not support the QtDesigner module import os if not 'QT_API' in os.environ: os.environ.setdefault("QT_API", "PyQt") import pcef.python PLUGINS_TYPES = {'QPythonCodeEdit': pcef.python.QPythonCodeEdit} try: from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin class QPythonCodeEditPlugin(QCodeEditPlugin): _module = 'pcef.python' # path to the widget's module _class = 'QPythonCodeEdit' # name of the widget class _name = "QPythonCodeEdit" _icon = None _type = pcef.python.QPythonCodeEdit def createWidget(self, parent): return pcef.python.QPythonCodeEdit(parent) except ImportError: print("Cannot use pcef plugins without PyQt4") Fix bug with python plugin and pyside
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyQode - Python/Qt Code Editor widget # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ This file contains all the PCEF QtDesigner plugins. Installation: ================== run designer.pyw (Qt Designer must be installed on your system and must be in your path on Windows) """ # This only works with PyQt, PySide does not support the QtDesigner module import os if not 'QT_API' in os.environ: os.environ.setdefault("QT_API", "PyQt") import pyqode.python PLUGINS_TYPES = {'QPythonCodeEdit': pyqode.python.QPythonCodeEdit} try: from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin class QPythonCodeEditPlugin(QCodeEditPlugin): _module = 'pcef.python' # path to the widget's module _class = 'QPythonCodeEdit' # name of the widget class _name = "QPythonCodeEdit" _icon = None _type = pyqode.python.QPythonCodeEdit def createWidget(self, parent): return pyqode.python.QPythonCodeEdit(parent) except ImportError: print("Cannot use pcef plugins without PyQt4")
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyQode - Python/Qt Code Editor widget # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ This file contains all the PCEF QtDesigner plugins. Installation: ================== run designer.pyw (Qt Designer must be installed on your system and must be in your path on Windows) """ # This only works with PyQt, PySide does not support the QtDesigner module import os if not 'QT_API' in os.environ: os.environ.setdefault("QT_API", "PyQt") import pcef.python PLUGINS_TYPES = {'QPythonCodeEdit': pcef.python.QPythonCodeEdit} try: from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin class QPythonCodeEditPlugin(QCodeEditPlugin): _module = 'pcef.python' # path to the widget's module _class = 'QPythonCodeEdit' # name of the widget class _name = "QPythonCodeEdit" _icon = None _type = pcef.python.QPythonCodeEdit def createWidget(self, parent): return pcef.python.QPythonCodeEdit(parent) except ImportError: print("Cannot use pcef plugins without PyQt4") <commit_msg>Fix bug with python plugin and pyside<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyQode - Python/Qt Code Editor widget # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ This file contains all the PCEF QtDesigner plugins. Installation: ================== run designer.pyw (Qt Designer must be installed on your system and must be in your path on Windows) """ # This only works with PyQt, PySide does not support the QtDesigner module import os if not 'QT_API' in os.environ: os.environ.setdefault("QT_API", "PyQt") import pyqode.python PLUGINS_TYPES = {'QPythonCodeEdit': pyqode.python.QPythonCodeEdit} try: from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin class QPythonCodeEditPlugin(QCodeEditPlugin): _module = 'pcef.python' # path to the widget's module _class = 'QPythonCodeEdit' # name of the widget class _name = "QPythonCodeEdit" _icon = None _type = pyqode.python.QPythonCodeEdit def createWidget(self, parent): return pyqode.python.QPythonCodeEdit(parent) except ImportError: print("Cannot use pcef plugins without PyQt4")
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyQode - Python/Qt Code Editor widget # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ This file contains all the PCEF QtDesigner plugins. Installation: ================== run designer.pyw (Qt Designer must be installed on your system and must be in your path on Windows) """ # This only works with PyQt, PySide does not support the QtDesigner module import os if not 'QT_API' in os.environ: os.environ.setdefault("QT_API", "PyQt") import pcef.python PLUGINS_TYPES = {'QPythonCodeEdit': pcef.python.QPythonCodeEdit} try: from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin class QPythonCodeEditPlugin(QCodeEditPlugin): _module = 'pcef.python' # path to the widget's module _class = 'QPythonCodeEdit' # name of the widget class _name = "QPythonCodeEdit" _icon = None _type = pcef.python.QPythonCodeEdit def createWidget(self, parent): return pcef.python.QPythonCodeEdit(parent) except ImportError: print("Cannot use pcef plugins without PyQt4") Fix bug with python plugin and pyside#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyQode - Python/Qt Code Editor widget # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ This file contains all the PCEF QtDesigner plugins. Installation: ================== run designer.pyw (Qt Designer must be installed on your system and must be in your path on Windows) """ # This only works with PyQt, PySide does not support the QtDesigner module import os if not 'QT_API' in os.environ: os.environ.setdefault("QT_API", "PyQt") import pyqode.python PLUGINS_TYPES = {'QPythonCodeEdit': pyqode.python.QPythonCodeEdit} try: from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin class QPythonCodeEditPlugin(QCodeEditPlugin): _module = 'pcef.python' # path to the widget's module _class = 'QPythonCodeEdit' # name of the widget class _name = "QPythonCodeEdit" _icon = None _type = pyqode.python.QPythonCodeEdit def createWidget(self, parent): return pyqode.python.QPythonCodeEdit(parent) except ImportError: print("Cannot use pcef plugins without PyQt4")
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyQode - Python/Qt Code Editor widget # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ This file contains all the PCEF QtDesigner plugins. Installation: ================== run designer.pyw (Qt Designer must be installed on your system and must be in your path on Windows) """ # This only works with PyQt, PySide does not support the QtDesigner module import os if not 'QT_API' in os.environ: os.environ.setdefault("QT_API", "PyQt") import pcef.python PLUGINS_TYPES = {'QPythonCodeEdit': pcef.python.QPythonCodeEdit} try: from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin class QPythonCodeEditPlugin(QCodeEditPlugin): _module = 'pcef.python' # path to the widget's module _class = 'QPythonCodeEdit' # name of the widget class _name = "QPythonCodeEdit" _icon = None _type = pcef.python.QPythonCodeEdit def createWidget(self, parent): return pcef.python.QPythonCodeEdit(parent) except ImportError: print("Cannot use pcef plugins without PyQt4") <commit_msg>Fix bug with python plugin and pyside<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyQode - Python/Qt Code Editor widget # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ This file contains all the PCEF QtDesigner plugins. Installation: ================== run designer.pyw (Qt Designer must be installed on your system and must be in your path on Windows) """ # This only works with PyQt, PySide does not support the QtDesigner module import os if not 'QT_API' in os.environ: os.environ.setdefault("QT_API", "PyQt") import pyqode.python PLUGINS_TYPES = {'QPythonCodeEdit': pyqode.python.QPythonCodeEdit} try: from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin class QPythonCodeEditPlugin(QCodeEditPlugin): _module = 'pcef.python' # path to the widget's module _class = 'QPythonCodeEdit' # name of the widget class _name = "QPythonCodeEdit" _icon = None _type = pyqode.python.QPythonCodeEdit def createWidget(self, parent): return pyqode.python.QPythonCodeEdit(parent) except ImportError: print("Cannot use pcef plugins without PyQt4")
e9605bd92e67c7f5daf7011f871c3a9d915abe76
core/urls/base.py
core/urls/base.py
from django.conf.urls import patterns, url, include from django.conf.urls.static import static from core.views import Home, register # Use this file to import all other url from game_website import settings urlpatterns = patterns( # Examples: # url(r'^blog/', include('blog.urls')), '', url(r'^$', Home.as_view(), name='home'), url(r'^games/', include('core.urls.games')), url(r'^register/$', register, name='register'), url(r'^login/$', 'django.contrib.auth.views.login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', name='logout'), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Used to serve static media in a dev environment. Should be disabled in production
from django.conf.urls import patterns, url, include from django.conf.urls.static import static from core.views import Home, register # Use this file to import all other url from game_website import settings urlpatterns = patterns( # Examples: # url(r'^blog/', include('blog.urls')), '', url(r'^$', Home.as_view(), name='home'), url(r'^games/', include('core.urls.games')), url(r'^register/$', register, name='register'), url(r'^login/$', 'django.contrib.auth.views.login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': 'core:home'}, name='logout'), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Used to serve static media in a dev environment. Should be disabled in production
Make logout redirect to home
Make logout redirect to home
Python
mit
joshsamara/game-website,joshsamara/game-website,joshsamara/game-website
from django.conf.urls import patterns, url, include from django.conf.urls.static import static from core.views import Home, register # Use this file to import all other url from game_website import settings urlpatterns = patterns( # Examples: # url(r'^blog/', include('blog.urls')), '', url(r'^$', Home.as_view(), name='home'), url(r'^games/', include('core.urls.games')), url(r'^register/$', register, name='register'), url(r'^login/$', 'django.contrib.auth.views.login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', name='logout'), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Used to serve static media in a dev environment. Should be disabled in production Make logout redirect to home
from django.conf.urls import patterns, url, include from django.conf.urls.static import static from core.views import Home, register # Use this file to import all other url from game_website import settings urlpatterns = patterns( # Examples: # url(r'^blog/', include('blog.urls')), '', url(r'^$', Home.as_view(), name='home'), url(r'^games/', include('core.urls.games')), url(r'^register/$', register, name='register'), url(r'^login/$', 'django.contrib.auth.views.login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': 'core:home'}, name='logout'), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Used to serve static media in a dev environment. Should be disabled in production
<commit_before>from django.conf.urls import patterns, url, include from django.conf.urls.static import static from core.views import Home, register # Use this file to import all other url from game_website import settings urlpatterns = patterns( # Examples: # url(r'^blog/', include('blog.urls')), '', url(r'^$', Home.as_view(), name='home'), url(r'^games/', include('core.urls.games')), url(r'^register/$', register, name='register'), url(r'^login/$', 'django.contrib.auth.views.login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', name='logout'), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Used to serve static media in a dev environment. Should be disabled in production <commit_msg>Make logout redirect to home<commit_after>
from django.conf.urls import patterns, url, include from django.conf.urls.static import static from core.views import Home, register # Use this file to import all other url from game_website import settings urlpatterns = patterns( # Examples: # url(r'^blog/', include('blog.urls')), '', url(r'^$', Home.as_view(), name='home'), url(r'^games/', include('core.urls.games')), url(r'^register/$', register, name='register'), url(r'^login/$', 'django.contrib.auth.views.login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': 'core:home'}, name='logout'), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Used to serve static media in a dev environment. Should be disabled in production
from django.conf.urls import patterns, url, include from django.conf.urls.static import static from core.views import Home, register # Use this file to import all other url from game_website import settings urlpatterns = patterns( # Examples: # url(r'^blog/', include('blog.urls')), '', url(r'^$', Home.as_view(), name='home'), url(r'^games/', include('core.urls.games')), url(r'^register/$', register, name='register'), url(r'^login/$', 'django.contrib.auth.views.login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', name='logout'), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Used to serve static media in a dev environment. Should be disabled in production Make logout redirect to homefrom django.conf.urls import patterns, url, include from django.conf.urls.static import static from core.views import Home, register # Use this file to import all other url from game_website import settings urlpatterns = patterns( # Examples: # url(r'^blog/', include('blog.urls')), '', url(r'^$', Home.as_view(), name='home'), url(r'^games/', include('core.urls.games')), url(r'^register/$', register, name='register'), url(r'^login/$', 'django.contrib.auth.views.login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': 'core:home'}, name='logout'), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Used to serve static media in a dev environment. Should be disabled in production
<commit_before>from django.conf.urls import patterns, url, include from django.conf.urls.static import static from core.views import Home, register # Use this file to import all other url from game_website import settings urlpatterns = patterns( # Examples: # url(r'^blog/', include('blog.urls')), '', url(r'^$', Home.as_view(), name='home'), url(r'^games/', include('core.urls.games')), url(r'^register/$', register, name='register'), url(r'^login/$', 'django.contrib.auth.views.login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', name='logout'), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Used to serve static media in a dev environment. Should be disabled in production <commit_msg>Make logout redirect to home<commit_after>from django.conf.urls import patterns, url, include from django.conf.urls.static import static from core.views import Home, register # Use this file to import all other url from game_website import settings urlpatterns = patterns( # Examples: # url(r'^blog/', include('blog.urls')), '', url(r'^$', Home.as_view(), name='home'), url(r'^games/', include('core.urls.games')), url(r'^register/$', register, name='register'), url(r'^login/$', 'django.contrib.auth.views.login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': 'core:home'}, name='logout'), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Used to serve static media in a dev environment. Should be disabled in production
198181baa0b095d120b456e7191c0c49c98b3c03
conans/client/generators/xcode.py
conans/client/generators/xcode.py
from conans.model import Generator from conans.paths import BUILD_INFO_XCODE class XCodeGenerator(Generator): template = ''' HEADER_SEARCH_PATHS = $(inherited) {include_dirs} LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs} OTHER_LDFLAGS = $(inherited) {linker_flags} {libs} GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags} OTHER_CFLAGS = $(inherited) OTHER_CPLUSPLUSFLAGS = $(inherited) ''' def __init__(self, deps_cpp_info, cpp_info): super(VisualStudioGenerator, self).__init__(deps_cpp_info, cpp_info) self.include_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.include_paths) self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.lib_paths) self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs]) self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines) self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags) self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags) @property def filename(self): return BUILD_INFO_XCODE @property def content(self): return self.template.format(**self.__dict__)
from conans.model import Generator from conans.paths import BUILD_INFO_XCODE class XCodeGenerator(Generator): template = ''' HEADER_SEARCH_PATHS = $(inherited) {include_dirs} LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs} OTHER_LDFLAGS = $(inherited) {linker_flags} {libs} GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags} OTHER_CFLAGS = $(inherited) OTHER_CPLUSPLUSFLAGS = $(inherited) ''' def __init__(self, deps_cpp_info, cpp_info): super(XCodeGenerator, self).__init__(deps_cpp_info, cpp_info) self.include_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.include_paths) self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.lib_paths) self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs]) self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines) self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags) self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags) @property def filename(self): return BUILD_INFO_XCODE @property def content(self): return self.template.format(**self.__dict__)
Fix copy and paste error
Fix copy and paste error
Python
mit
conan-io/conan,conan-io/conan,luckielordie/conan,dragly/conan,lasote/conan,dragly/conan,tivek/conan,luckielordie/conan,memsharded/conan,conan-io/conan,memsharded/conan,birsoyo/conan,lasote/conan,memsharded/conan,mropert/conan,Xaltotun/conan,memsharded/conan,Xaltotun/conan,mropert/conan,birsoyo/conan,tivek/conan
from conans.model import Generator from conans.paths import BUILD_INFO_XCODE class XCodeGenerator(Generator): template = ''' HEADER_SEARCH_PATHS = $(inherited) {include_dirs} LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs} OTHER_LDFLAGS = $(inherited) {linker_flags} {libs} GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags} OTHER_CFLAGS = $(inherited) OTHER_CPLUSPLUSFLAGS = $(inherited) ''' def __init__(self, deps_cpp_info, cpp_info): super(VisualStudioGenerator, self).__init__(deps_cpp_info, cpp_info) self.include_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.include_paths) self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.lib_paths) self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs]) self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines) self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags) self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags) @property def filename(self): return BUILD_INFO_XCODE @property def content(self): return self.template.format(**self.__dict__) Fix copy and paste error
from conans.model import Generator from conans.paths import BUILD_INFO_XCODE class XCodeGenerator(Generator): template = ''' HEADER_SEARCH_PATHS = $(inherited) {include_dirs} LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs} OTHER_LDFLAGS = $(inherited) {linker_flags} {libs} GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags} OTHER_CFLAGS = $(inherited) OTHER_CPLUSPLUSFLAGS = $(inherited) ''' def __init__(self, deps_cpp_info, cpp_info): super(XCodeGenerator, self).__init__(deps_cpp_info, cpp_info) self.include_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.include_paths) self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.lib_paths) self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs]) self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines) self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags) self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags) @property def filename(self): return BUILD_INFO_XCODE @property def content(self): return self.template.format(**self.__dict__)
<commit_before>from conans.model import Generator from conans.paths import BUILD_INFO_XCODE class XCodeGenerator(Generator): template = ''' HEADER_SEARCH_PATHS = $(inherited) {include_dirs} LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs} OTHER_LDFLAGS = $(inherited) {linker_flags} {libs} GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags} OTHER_CFLAGS = $(inherited) OTHER_CPLUSPLUSFLAGS = $(inherited) ''' def __init__(self, deps_cpp_info, cpp_info): super(VisualStudioGenerator, self).__init__(deps_cpp_info, cpp_info) self.include_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.include_paths) self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.lib_paths) self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs]) self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines) self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags) self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags) @property def filename(self): return BUILD_INFO_XCODE @property def content(self): return self.template.format(**self.__dict__) <commit_msg>Fix copy and paste error<commit_after>
from conans.model import Generator from conans.paths import BUILD_INFO_XCODE class XCodeGenerator(Generator): template = ''' HEADER_SEARCH_PATHS = $(inherited) {include_dirs} LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs} OTHER_LDFLAGS = $(inherited) {linker_flags} {libs} GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags} OTHER_CFLAGS = $(inherited) OTHER_CPLUSPLUSFLAGS = $(inherited) ''' def __init__(self, deps_cpp_info, cpp_info): super(XCodeGenerator, self).__init__(deps_cpp_info, cpp_info) self.include_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.include_paths) self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.lib_paths) self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs]) self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines) self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags) self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags) @property def filename(self): return BUILD_INFO_XCODE @property def content(self): return self.template.format(**self.__dict__)
from conans.model import Generator from conans.paths import BUILD_INFO_XCODE class XCodeGenerator(Generator): template = ''' HEADER_SEARCH_PATHS = $(inherited) {include_dirs} LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs} OTHER_LDFLAGS = $(inherited) {linker_flags} {libs} GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags} OTHER_CFLAGS = $(inherited) OTHER_CPLUSPLUSFLAGS = $(inherited) ''' def __init__(self, deps_cpp_info, cpp_info): super(VisualStudioGenerator, self).__init__(deps_cpp_info, cpp_info) self.include_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.include_paths) self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.lib_paths) self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs]) self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines) self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags) self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags) @property def filename(self): return BUILD_INFO_XCODE @property def content(self): return self.template.format(**self.__dict__) Fix copy and paste errorfrom conans.model import Generator from conans.paths import BUILD_INFO_XCODE class XCodeGenerator(Generator): template = ''' HEADER_SEARCH_PATHS = $(inherited) {include_dirs} LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs} OTHER_LDFLAGS = $(inherited) {linker_flags} {libs} GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags} OTHER_CFLAGS = $(inherited) OTHER_CPLUSPLUSFLAGS = $(inherited) ''' def __init__(self, deps_cpp_info, cpp_info): super(XCodeGenerator, self).__init__(deps_cpp_info, cpp_info) self.include_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.include_paths) self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.lib_paths) self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs]) self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines) self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags) self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags) @property def filename(self): return BUILD_INFO_XCODE @property def content(self): return self.template.format(**self.__dict__)
<commit_before>from conans.model import Generator from conans.paths import BUILD_INFO_XCODE class XCodeGenerator(Generator): template = ''' HEADER_SEARCH_PATHS = $(inherited) {include_dirs} LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs} OTHER_LDFLAGS = $(inherited) {linker_flags} {libs} GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags} OTHER_CFLAGS = $(inherited) OTHER_CPLUSPLUSFLAGS = $(inherited) ''' def __init__(self, deps_cpp_info, cpp_info): super(VisualStudioGenerator, self).__init__(deps_cpp_info, cpp_info) self.include_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.include_paths) self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.lib_paths) self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs]) self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines) self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags) self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags) @property def filename(self): return BUILD_INFO_XCODE @property def content(self): return self.template.format(**self.__dict__) <commit_msg>Fix copy and paste error<commit_after>from conans.model import Generator from conans.paths import BUILD_INFO_XCODE class XCodeGenerator(Generator): template = ''' HEADER_SEARCH_PATHS = $(inherited) {include_dirs} LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs} OTHER_LDFLAGS = $(inherited) {linker_flags} {libs} GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags} OTHER_CFLAGS = $(inherited) OTHER_CPLUSPLUSFLAGS = $(inherited) ''' def __init__(self, deps_cpp_info, cpp_info): super(XCodeGenerator, self).__init__(deps_cpp_info, cpp_info) self.include_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.include_paths) self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.lib_paths) self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs]) self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines) self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags) self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags) @property def filename(self): return BUILD_INFO_XCODE @property def content(self): return self.template.format(**self.__dict__)
80bb5557f78268545139cd37f593278e35979fd5
corehq/mobile_flags.py
corehq/mobile_flags.py
from collections import namedtuple MobileFlag = namedtuple('MobileFlag', 'slug label') MULTIPLE_APPS_UNLIMITED = MobileFlag( 'multiple_apps_unlimited', 'Enable unlimited multiple apps' )
from collections import namedtuple MobileFlag = namedtuple('MobileFlag', 'slug label') MULTIPLE_APPS_UNLIMITED = MobileFlag( 'multiple_apps_unlimited', 'Enable unlimited multiple apps' ) ADVANCED_SETTINGS_ACCESS = MobileFlag( 'advanced_settings_access', 'Enable access to advanced settings' )
Add Flag enum for settings access
Add Flag enum for settings access
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from collections import namedtuple MobileFlag = namedtuple('MobileFlag', 'slug label') MULTIPLE_APPS_UNLIMITED = MobileFlag( 'multiple_apps_unlimited', 'Enable unlimited multiple apps' ) Add Flag enum for settings access
from collections import namedtuple MobileFlag = namedtuple('MobileFlag', 'slug label') MULTIPLE_APPS_UNLIMITED = MobileFlag( 'multiple_apps_unlimited', 'Enable unlimited multiple apps' ) ADVANCED_SETTINGS_ACCESS = MobileFlag( 'advanced_settings_access', 'Enable access to advanced settings' )
<commit_before>from collections import namedtuple MobileFlag = namedtuple('MobileFlag', 'slug label') MULTIPLE_APPS_UNLIMITED = MobileFlag( 'multiple_apps_unlimited', 'Enable unlimited multiple apps' ) <commit_msg>Add Flag enum for settings access<commit_after>
from collections import namedtuple MobileFlag = namedtuple('MobileFlag', 'slug label') MULTIPLE_APPS_UNLIMITED = MobileFlag( 'multiple_apps_unlimited', 'Enable unlimited multiple apps' ) ADVANCED_SETTINGS_ACCESS = MobileFlag( 'advanced_settings_access', 'Enable access to advanced settings' )
from collections import namedtuple MobileFlag = namedtuple('MobileFlag', 'slug label') MULTIPLE_APPS_UNLIMITED = MobileFlag( 'multiple_apps_unlimited', 'Enable unlimited multiple apps' ) Add Flag enum for settings accessfrom collections import namedtuple MobileFlag = namedtuple('MobileFlag', 'slug label') MULTIPLE_APPS_UNLIMITED = MobileFlag( 'multiple_apps_unlimited', 'Enable unlimited multiple apps' ) ADVANCED_SETTINGS_ACCESS = MobileFlag( 'advanced_settings_access', 'Enable access to advanced settings' )
<commit_before>from collections import namedtuple MobileFlag = namedtuple('MobileFlag', 'slug label') MULTIPLE_APPS_UNLIMITED = MobileFlag( 'multiple_apps_unlimited', 'Enable unlimited multiple apps' ) <commit_msg>Add Flag enum for settings access<commit_after>from collections import namedtuple MobileFlag = namedtuple('MobileFlag', 'slug label') MULTIPLE_APPS_UNLIMITED = MobileFlag( 'multiple_apps_unlimited', 'Enable unlimited multiple apps' ) ADVANCED_SETTINGS_ACCESS = MobileFlag( 'advanced_settings_access', 'Enable access to advanced settings' )
26e2feb6f2dfe74ade46cf871167101599c0acba
app/timetables/models.py
app/timetables/models.py
from __future__ import unicode_literals from django.db import models from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) capitalized_field_names = ('name',) def __str__(self): return self.name class Meal(ForceCapitalizeMixin, models.Model): """ Model representing food occasions. This represents an occasion during the day that food is scheduled to be served. E.g breakfast, lunch, etc. """ name = models.CharField(max_length=60, unique=True) start_time = models.TimeField() end_time = models.TimeField() capitalized_field_names = ('name',) def __str__(self): return self.name
from __future__ import unicode_literals from django.db import models from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) capitalized_field_names = ('name',) def __str__(self): return self.name class Meal(ForceCapitalizeMixin, models.Model): """ Model representing food occasions. This represents an occasion during the day that food is scheduled to be served. E.g breakfast, lunch, etc. """ name = models.CharField(max_length=60, unique=True) start_time = models.TimeField() end_time = models.TimeField() capitalized_field_names = ('name',) def clean(self): if self.start_time >= self.end_time: raise ValidationError(_('start_time must be less than end_time.')) super().clean() def __str__(self): return self.name
Update clean method to ensure that meal end_time is not same as or less than meal start_time
Update clean method to ensure that meal end_time is not same as or less than meal start_time
Python
mit
teamtaverna/core
from __future__ import unicode_literals from django.db import models from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) capitalized_field_names = ('name',) def __str__(self): return self.name class Meal(ForceCapitalizeMixin, models.Model): """ Model representing food occasions. This represents an occasion during the day that food is scheduled to be served. E.g breakfast, lunch, etc. """ name = models.CharField(max_length=60, unique=True) start_time = models.TimeField() end_time = models.TimeField() capitalized_field_names = ('name',) def __str__(self): return self.name Update clean method to ensure that meal end_time is not same as or less than meal start_time
from __future__ import unicode_literals from django.db import models from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) capitalized_field_names = ('name',) def __str__(self): return self.name class Meal(ForceCapitalizeMixin, models.Model): """ Model representing food occasions. This represents an occasion during the day that food is scheduled to be served. E.g breakfast, lunch, etc. """ name = models.CharField(max_length=60, unique=True) start_time = models.TimeField() end_time = models.TimeField() capitalized_field_names = ('name',) def clean(self): if self.start_time >= self.end_time: raise ValidationError(_('start_time must be less than end_time.')) super().clean() def __str__(self): return self.name
<commit_before>from __future__ import unicode_literals from django.db import models from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) capitalized_field_names = ('name',) def __str__(self): return self.name class Meal(ForceCapitalizeMixin, models.Model): """ Model representing food occasions. This represents an occasion during the day that food is scheduled to be served. E.g breakfast, lunch, etc. """ name = models.CharField(max_length=60, unique=True) start_time = models.TimeField() end_time = models.TimeField() capitalized_field_names = ('name',) def __str__(self): return self.name <commit_msg>Update clean method to ensure that meal end_time is not same as or less than meal start_time<commit_after>
from __future__ import unicode_literals from django.db import models from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) capitalized_field_names = ('name',) def __str__(self): return self.name class Meal(ForceCapitalizeMixin, models.Model): """ Model representing food occasions. This represents an occasion during the day that food is scheduled to be served. E.g breakfast, lunch, etc. """ name = models.CharField(max_length=60, unique=True) start_time = models.TimeField() end_time = models.TimeField() capitalized_field_names = ('name',) def clean(self): if self.start_time >= self.end_time: raise ValidationError(_('start_time must be less than end_time.')) super().clean() def __str__(self): return self.name
from __future__ import unicode_literals from django.db import models from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) capitalized_field_names = ('name',) def __str__(self): return self.name class Meal(ForceCapitalizeMixin, models.Model): """ Model representing food occasions. This represents an occasion during the day that food is scheduled to be served. E.g breakfast, lunch, etc. """ name = models.CharField(max_length=60, unique=True) start_time = models.TimeField() end_time = models.TimeField() capitalized_field_names = ('name',) def __str__(self): return self.name Update clean method to ensure that meal end_time is not same as or less than meal start_timefrom __future__ import unicode_literals from django.db import models from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) capitalized_field_names = ('name',) def __str__(self): return self.name class Meal(ForceCapitalizeMixin, models.Model): """ Model representing food occasions. This represents an occasion during the day that food is scheduled to be served. E.g breakfast, lunch, etc. """ name = models.CharField(max_length=60, unique=True) start_time = models.TimeField() end_time = models.TimeField() capitalized_field_names = ('name',) def clean(self): if self.start_time >= self.end_time: raise ValidationError(_('start_time must be less than end_time.')) super().clean() def __str__(self): return self.name
<commit_before>from __future__ import unicode_literals from django.db import models from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) capitalized_field_names = ('name',) def __str__(self): return self.name class Meal(ForceCapitalizeMixin, models.Model): """ Model representing food occasions. This represents an occasion during the day that food is scheduled to be served. E.g breakfast, lunch, etc. """ name = models.CharField(max_length=60, unique=True) start_time = models.TimeField() end_time = models.TimeField() capitalized_field_names = ('name',) def __str__(self): return self.name <commit_msg>Update clean method to ensure that meal end_time is not same as or less than meal start_time<commit_after>from __future__ import unicode_literals from django.db import models from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) capitalized_field_names = ('name',) def __str__(self): return self.name class Meal(ForceCapitalizeMixin, models.Model): """ Model representing food occasions. This represents an occasion during the day that food is scheduled to be served. E.g breakfast, lunch, etc. """ name = models.CharField(max_length=60, unique=True) start_time = models.TimeField() end_time = models.TimeField() capitalized_field_names = ('name',) def clean(self): if self.start_time >= self.end_time: raise ValidationError(_('start_time must be less than end_time.')) super().clean() def __str__(self): return self.name
922c6350fda965068927611348bdd9127ee405d9
scaffolder/commands/vcs.py
scaffolder/commands/vcs.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.vcs import VCS class VcsCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-u", "--url", dest="url", help='Clone URL, it can be SSH or HTTPS. Git only for now.', metavar="REPO_URL" ), make_option( "-t", "--target", dest="target", default='.', help="Target directory where the repo will be cloned.", metavar="TARGET" ), ) def __init__(self, name, help='', aliases=(), stdout=None, stderr=None): help = 'Command to clone github repos' aliases = ('git','hg',) #TODO: Move to BaseCommand, create methods and have each subcommand override parser = OptionParser( version=self.get_version(), option_list=self.get_option_list(), usage='\n %prog {0} [OPTIONS] FILE...'.format(name), description='', epilog='' ) BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases) # self.update_parser() def update_parser(self): self.parser.set_usage('%prog [OPTIONS] FILE...') # self.parser.prog = '%s %s' % (self.parser.get_prog_name(), self.name) self.parser.version = self.get_version() self.parser.option_list = sorted(self.get_option_list()) def run(self, *args, **options): url = options.get('url') tgt = options.get('target') boot = VCS(url) boot.clone(target_dir=tgt)
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.vcs import VCS class VcsCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-u", "--url", dest="url", help='Clone URL, it can be SSH or HTTPS. Git only for now.', metavar="REPO_URL" ), make_option( "-t", "--target", dest="target", default='.', help="Target directory where the repo will be cloned.", metavar="TARGET" ), ) help = 'Command to clone github repos' def run(self, *args, **options): url = options.get('url') tgt = options.get('target') boot = VCS(url) boot.clone(target_dir=tgt)
Remove __init__ method, not needed.
VcsCommand: Remove __init__ method, not needed.
Python
mit
goliatone/minions
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.vcs import VCS class VcsCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-u", "--url", dest="url", help='Clone URL, it can be SSH or HTTPS. Git only for now.', metavar="REPO_URL" ), make_option( "-t", "--target", dest="target", default='.', help="Target directory where the repo will be cloned.", metavar="TARGET" ), ) def __init__(self, name, help='', aliases=(), stdout=None, stderr=None): help = 'Command to clone github repos' aliases = ('git','hg',) #TODO: Move to BaseCommand, create methods and have each subcommand override parser = OptionParser( version=self.get_version(), option_list=self.get_option_list(), usage='\n %prog {0} [OPTIONS] FILE...'.format(name), description='', epilog='' ) BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases) # self.update_parser() def update_parser(self): self.parser.set_usage('%prog [OPTIONS] FILE...') # self.parser.prog = '%s %s' % (self.parser.get_prog_name(), self.name) self.parser.version = self.get_version() self.parser.option_list = sorted(self.get_option_list()) def run(self, *args, **options): url = options.get('url') tgt = options.get('target') boot = VCS(url) boot.clone(target_dir=tgt) VcsCommand: Remove __init__ method, not needed.
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.vcs import VCS class VcsCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-u", "--url", dest="url", help='Clone URL, it can be SSH or HTTPS. Git only for now.', metavar="REPO_URL" ), make_option( "-t", "--target", dest="target", default='.', help="Target directory where the repo will be cloned.", metavar="TARGET" ), ) help = 'Command to clone github repos' def run(self, *args, **options): url = options.get('url') tgt = options.get('target') boot = VCS(url) boot.clone(target_dir=tgt)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.vcs import VCS class VcsCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-u", "--url", dest="url", help='Clone URL, it can be SSH or HTTPS. Git only for now.', metavar="REPO_URL" ), make_option( "-t", "--target", dest="target", default='.', help="Target directory where the repo will be cloned.", metavar="TARGET" ), ) def __init__(self, name, help='', aliases=(), stdout=None, stderr=None): help = 'Command to clone github repos' aliases = ('git','hg',) #TODO: Move to BaseCommand, create methods and have each subcommand override parser = OptionParser( version=self.get_version(), option_list=self.get_option_list(), usage='\n %prog {0} [OPTIONS] FILE...'.format(name), description='', epilog='' ) BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases) # self.update_parser() def update_parser(self): self.parser.set_usage('%prog [OPTIONS] FILE...') # self.parser.prog = '%s %s' % (self.parser.get_prog_name(), self.name) self.parser.version = self.get_version() self.parser.option_list = sorted(self.get_option_list()) def run(self, *args, **options): url = options.get('url') tgt = options.get('target') boot = VCS(url) boot.clone(target_dir=tgt) <commit_msg>VcsCommand: Remove __init__ method, not needed.<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.vcs import VCS class VcsCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-u", "--url", dest="url", help='Clone URL, it can be SSH or HTTPS. Git only for now.', metavar="REPO_URL" ), make_option( "-t", "--target", dest="target", default='.', help="Target directory where the repo will be cloned.", metavar="TARGET" ), ) help = 'Command to clone github repos' def run(self, *args, **options): url = options.get('url') tgt = options.get('target') boot = VCS(url) boot.clone(target_dir=tgt)
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.vcs import VCS class VcsCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-u", "--url", dest="url", help='Clone URL, it can be SSH or HTTPS. Git only for now.', metavar="REPO_URL" ), make_option( "-t", "--target", dest="target", default='.', help="Target directory where the repo will be cloned.", metavar="TARGET" ), ) def __init__(self, name, help='', aliases=(), stdout=None, stderr=None): help = 'Command to clone github repos' aliases = ('git','hg',) #TODO: Move to BaseCommand, create methods and have each subcommand override parser = OptionParser( version=self.get_version(), option_list=self.get_option_list(), usage='\n %prog {0} [OPTIONS] FILE...'.format(name), description='', epilog='' ) BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases) # self.update_parser() def update_parser(self): self.parser.set_usage('%prog [OPTIONS] FILE...') # self.parser.prog = '%s %s' % (self.parser.get_prog_name(), self.name) self.parser.version = self.get_version() self.parser.option_list = sorted(self.get_option_list()) def run(self, *args, **options): url = options.get('url') tgt = options.get('target') boot = VCS(url) boot.clone(target_dir=tgt) VcsCommand: Remove __init__ method, not needed.#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.vcs import VCS class VcsCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-u", "--url", dest="url", help='Clone URL, it can be SSH or HTTPS. Git only for now.', metavar="REPO_URL" ), make_option( "-t", "--target", dest="target", default='.', help="Target directory where the repo will be cloned.", metavar="TARGET" ), ) help = 'Command to clone github repos' def run(self, *args, **options): url = options.get('url') tgt = options.get('target') boot = VCS(url) boot.clone(target_dir=tgt)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.vcs import VCS class VcsCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-u", "--url", dest="url", help='Clone URL, it can be SSH or HTTPS. Git only for now.', metavar="REPO_URL" ), make_option( "-t", "--target", dest="target", default='.', help="Target directory where the repo will be cloned.", metavar="TARGET" ), ) def __init__(self, name, help='', aliases=(), stdout=None, stderr=None): help = 'Command to clone github repos' aliases = ('git','hg',) #TODO: Move to BaseCommand, create methods and have each subcommand override parser = OptionParser( version=self.get_version(), option_list=self.get_option_list(), usage='\n %prog {0} [OPTIONS] FILE...'.format(name), description='', epilog='' ) BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases) # self.update_parser() def update_parser(self): self.parser.set_usage('%prog [OPTIONS] FILE...') # self.parser.prog = '%s %s' % (self.parser.get_prog_name(), self.name) self.parser.version = self.get_version() self.parser.option_list = sorted(self.get_option_list()) def run(self, *args, **options): url = options.get('url') tgt = options.get('target') boot = VCS(url) boot.clone(target_dir=tgt) <commit_msg>VcsCommand: Remove __init__ method, not needed.<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.vcs import VCS class VcsCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-u", "--url", dest="url", help='Clone URL, it can be SSH or HTTPS. Git only for now.', metavar="REPO_URL" ), make_option( "-t", "--target", dest="target", default='.', help="Target directory where the repo will be cloned.", metavar="TARGET" ), ) help = 'Command to clone github repos' def run(self, *args, **options): url = options.get('url') tgt = options.get('target') boot = VCS(url) boot.clone(target_dir=tgt)
7d6ecfe52f60ac07c57bbd6e966cded11ce40e4c
scripts/hydrafw-version.py
scripts/hydrafw-version.py
import sys from optparse import OptionParser from datetime import * from git import * if __name__=="__main__": usage = """ %prog outfile.txt""" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args)==1: sys.stdout = open(args[0], 'w') git=Repo().git print '#define HYDRAFW_GIT_TAG "' + git.describe(tags=True,always=True) + '"' if Repo().is_dirty: print '#define HYDRAFW_GIT_HASH "' + git.rev_parse('HEAD',short=True) + '-dirty"' else: print '#define HYDRAFW_GIT_HASH "' + git.rev_parse('HEAD',short=True) + '"' print '#define HYDRAFW_BUILD_DATE "' + date.today().isoformat() + '"' else: parser.print_help() sys.exit(1)
import sys from optparse import OptionParser from datetime import * from git import * if __name__=="__main__": usage = """ %prog outfile.txt""" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args)==1: sys.stdout = open(args[0], 'w') git=Repo().git print '#define HYDRAFW_GIT_TAG "' + git.describe(tags=True,always=True,dirty=True) + '"' print '#define HYDRAFW_GIT_HASH "' + git.rev_parse('HEAD',short=True) + '"' print '#define HYDRAFW_BUILD_DATE "' + date.today().isoformat() + '"' else: parser.print_help() sys.exit(1)
Fix python script dirty flag for firmware version
Fix python script dirty flag for firmware version
Python
apache-2.0
Baldanos/hydrafw,hydrabus/hydrafw,hydrabus/hydrafw,hydrabus/hydrafw,Baldanos/hydrafw,Baldanos/hydrafw
import sys from optparse import OptionParser from datetime import * from git import * if __name__=="__main__": usage = """ %prog outfile.txt""" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args)==1: sys.stdout = open(args[0], 'w') git=Repo().git print '#define HYDRAFW_GIT_TAG "' + git.describe(tags=True,always=True) + '"' if Repo().is_dirty: print '#define HYDRAFW_GIT_HASH "' + git.rev_parse('HEAD',short=True) + '-dirty"' else: print '#define HYDRAFW_GIT_HASH "' + git.rev_parse('HEAD',short=True) + '"' print '#define HYDRAFW_BUILD_DATE "' + date.today().isoformat() + '"' else: parser.print_help() sys.exit(1) Fix python script dirty flag for firmware version
import sys from optparse import OptionParser from datetime import * from git import * if __name__=="__main__": usage = """ %prog outfile.txt""" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args)==1: sys.stdout = open(args[0], 'w') git=Repo().git print '#define HYDRAFW_GIT_TAG "' + git.describe(tags=True,always=True,dirty=True) + '"' print '#define HYDRAFW_GIT_HASH "' + git.rev_parse('HEAD',short=True) + '"' print '#define HYDRAFW_BUILD_DATE "' + date.today().isoformat() + '"' else: parser.print_help() sys.exit(1)
<commit_before>import sys from optparse import OptionParser from datetime import * from git import * if __name__=="__main__": usage = """ %prog outfile.txt""" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args)==1: sys.stdout = open(args[0], 'w') git=Repo().git print '#define HYDRAFW_GIT_TAG "' + git.describe(tags=True,always=True) + '"' if Repo().is_dirty: print '#define HYDRAFW_GIT_HASH "' + git.rev_parse('HEAD',short=True) + '-dirty"' else: print '#define HYDRAFW_GIT_HASH "' + git.rev_parse('HEAD',short=True) + '"' print '#define HYDRAFW_BUILD_DATE "' + date.today().isoformat() + '"' else: parser.print_help() sys.exit(1) <commit_msg>Fix python script dirty flag for firmware version<commit_after>
import sys from optparse import OptionParser from datetime import * from git import * if __name__=="__main__": usage = """ %prog outfile.txt""" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args)==1: sys.stdout = open(args[0], 'w') git=Repo().git print '#define HYDRAFW_GIT_TAG "' + git.describe(tags=True,always=True,dirty=True) + '"' print '#define HYDRAFW_GIT_HASH "' + git.rev_parse('HEAD',short=True) + '"' print '#define HYDRAFW_BUILD_DATE "' + date.today().isoformat() + '"' else: parser.print_help() sys.exit(1)
import sys from optparse import OptionParser from datetime import * from git import * if __name__=="__main__": usage = """ %prog outfile.txt""" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args)==1: sys.stdout = open(args[0], 'w') git=Repo().git print '#define HYDRAFW_GIT_TAG "' + git.describe(tags=True,always=True) + '"' if Repo().is_dirty: print '#define HYDRAFW_GIT_HASH "' + git.rev_parse('HEAD',short=True) + '-dirty"' else: print '#define HYDRAFW_GIT_HASH "' + git.rev_parse('HEAD',short=True) + '"' print '#define HYDRAFW_BUILD_DATE "' + date.today().isoformat() + '"' else: parser.print_help() sys.exit(1) Fix python script dirty flag for firmware versionimport sys from optparse import OptionParser from datetime import * from git import * if __name__=="__main__": usage = """ %prog outfile.txt""" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args)==1: sys.stdout = open(args[0], 'w') git=Repo().git print '#define HYDRAFW_GIT_TAG "' + git.describe(tags=True,always=True,dirty=True) + '"' print '#define HYDRAFW_GIT_HASH "' + git.rev_parse('HEAD',short=True) + '"' print '#define HYDRAFW_BUILD_DATE "' + date.today().isoformat() + '"' else: parser.print_help() sys.exit(1)
<commit_before>import sys from optparse import OptionParser from datetime import * from git import * if __name__=="__main__": usage = """ %prog outfile.txt""" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args)==1: sys.stdout = open(args[0], 'w') git=Repo().git print '#define HYDRAFW_GIT_TAG "' + git.describe(tags=True,always=True) + '"' if Repo().is_dirty: print '#define HYDRAFW_GIT_HASH "' + git.rev_parse('HEAD',short=True) + '-dirty"' else: print '#define HYDRAFW_GIT_HASH "' + git.rev_parse('HEAD',short=True) + '"' print '#define HYDRAFW_BUILD_DATE "' + date.today().isoformat() + '"' else: parser.print_help() sys.exit(1) <commit_msg>Fix python script dirty flag for firmware version<commit_after>import sys from optparse import OptionParser from datetime import * from git import * if __name__=="__main__": usage = """ %prog outfile.txt""" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args)==1: sys.stdout = open(args[0], 'w') git=Repo().git print '#define HYDRAFW_GIT_TAG "' + git.describe(tags=True,always=True,dirty=True) + '"' print '#define HYDRAFW_GIT_HASH "' + git.rev_parse('HEAD',short=True) + '"' print '#define HYDRAFW_BUILD_DATE "' + date.today().isoformat() + '"' else: parser.print_help() sys.exit(1)
7420d9208067f5144b301ff00d962b0b84e2a0f3
tinymce/settings.py
tinymce/settings.py
import os from django.conf import settings DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG', {'theme': "simple", 'relative_urls': False}) USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False) USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False) USE_FILEBROWSER = getattr(settings, 'TINYMCE_FILEBROWSER', 'filebrowser' in settings.INSTALLED_APPS) if 'staticfiles' in settings.INSTALLED_APPS: JS_URL = os.path.join(settings.STATIC_URL, 'tiny_mce/tiny_mce.js') JS_ROOT = os.path.join(settings.STATIC_ROOT, 'tiny_mce') else: JS_URL = getattr(settings, 'TINYMCE_JS_URL', '%sjs/tiny_mce/tiny_mce.js' % settings.MEDIA_URL) JS_ROOT = getattr(settings, 'TINYMCE_JS_ROOT', os.path.join(settings.MEDIA_ROOT, 'js/tiny_mce')) JS_BASE_URL = JS_URL[:JS_URL.rfind('/')]
import os from django.conf import settings DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG', {'theme': "simple", 'relative_urls': False}) USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False) USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False) USE_FILEBROWSER = getattr(settings, 'TINYMCE_FILEBROWSER', 'filebrowser' in settings.INSTALLED_APPS) if 'staticfiles' in settings.INSTALLED_APPS or \ 'django.contrib.staticfiles' in settings.INSTALLED_APPS: JS_URL = os.path.join(getattr(settings, 'STATIC_URL', ''), 'tiny_mce/tiny_mce.js') JS_ROOT = os.path.join(getattr(settings, 'STATIC_ROOT', ''), 'tiny_mce') else: JS_URL = getattr(settings, 'TINYMCE_JS_URL', '%sjs/tiny_mce/tiny_mce.js' % settings.MEDIA_URL) JS_ROOT = getattr(settings, 'TINYMCE_JS_ROOT', os.path.join(settings.MEDIA_ROOT, 'js/tiny_mce')) JS_BASE_URL = JS_URL[:JS_URL.rfind('/')]
Use STATIC_URL/STATIC_ROOT when using django.contrib.staticfiles (django 1.3)
Use STATIC_URL/STATIC_ROOT when using django.contrib.staticfiles (django 1.3)
Python
mit
pterk/django-tinymce,pterk/django-tinymce
import os from django.conf import settings DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG', {'theme': "simple", 'relative_urls': False}) USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False) USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False) USE_FILEBROWSER = getattr(settings, 'TINYMCE_FILEBROWSER', 'filebrowser' in settings.INSTALLED_APPS) if 'staticfiles' in settings.INSTALLED_APPS: JS_URL = os.path.join(settings.STATIC_URL, 'tiny_mce/tiny_mce.js') JS_ROOT = os.path.join(settings.STATIC_ROOT, 'tiny_mce') else: JS_URL = getattr(settings, 'TINYMCE_JS_URL', '%sjs/tiny_mce/tiny_mce.js' % settings.MEDIA_URL) JS_ROOT = getattr(settings, 'TINYMCE_JS_ROOT', os.path.join(settings.MEDIA_ROOT, 'js/tiny_mce')) JS_BASE_URL = JS_URL[:JS_URL.rfind('/')] Use STATIC_URL/STATIC_ROOT when using django.contrib.staticfiles (django 1.3)
import os from django.conf import settings DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG', {'theme': "simple", 'relative_urls': False}) USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False) USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False) USE_FILEBROWSER = getattr(settings, 'TINYMCE_FILEBROWSER', 'filebrowser' in settings.INSTALLED_APPS) if 'staticfiles' in settings.INSTALLED_APPS or \ 'django.contrib.staticfiles' in settings.INSTALLED_APPS: JS_URL = os.path.join(getattr(settings, 'STATIC_URL', ''), 'tiny_mce/tiny_mce.js') JS_ROOT = os.path.join(getattr(settings, 'STATIC_ROOT', ''), 'tiny_mce') else: JS_URL = getattr(settings, 'TINYMCE_JS_URL', '%sjs/tiny_mce/tiny_mce.js' % settings.MEDIA_URL) JS_ROOT = getattr(settings, 'TINYMCE_JS_ROOT', os.path.join(settings.MEDIA_ROOT, 'js/tiny_mce')) JS_BASE_URL = JS_URL[:JS_URL.rfind('/')]
<commit_before>import os from django.conf import settings DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG', {'theme': "simple", 'relative_urls': False}) USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False) USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False) USE_FILEBROWSER = getattr(settings, 'TINYMCE_FILEBROWSER', 'filebrowser' in settings.INSTALLED_APPS) if 'staticfiles' in settings.INSTALLED_APPS: JS_URL = os.path.join(settings.STATIC_URL, 'tiny_mce/tiny_mce.js') JS_ROOT = os.path.join(settings.STATIC_ROOT, 'tiny_mce') else: JS_URL = getattr(settings, 'TINYMCE_JS_URL', '%sjs/tiny_mce/tiny_mce.js' % settings.MEDIA_URL) JS_ROOT = getattr(settings, 'TINYMCE_JS_ROOT', os.path.join(settings.MEDIA_ROOT, 'js/tiny_mce')) JS_BASE_URL = JS_URL[:JS_URL.rfind('/')] <commit_msg>Use STATIC_URL/STATIC_ROOT when using django.contrib.staticfiles (django 1.3)<commit_after>
import os from django.conf import settings DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG', {'theme': "simple", 'relative_urls': False}) USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False) USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False) USE_FILEBROWSER = getattr(settings, 'TINYMCE_FILEBROWSER', 'filebrowser' in settings.INSTALLED_APPS) if 'staticfiles' in settings.INSTALLED_APPS or \ 'django.contrib.staticfiles' in settings.INSTALLED_APPS: JS_URL = os.path.join(getattr(settings, 'STATIC_URL', ''), 'tiny_mce/tiny_mce.js') JS_ROOT = os.path.join(getattr(settings, 'STATIC_ROOT', ''), 'tiny_mce') else: JS_URL = getattr(settings, 'TINYMCE_JS_URL', '%sjs/tiny_mce/tiny_mce.js' % settings.MEDIA_URL) JS_ROOT = getattr(settings, 'TINYMCE_JS_ROOT', os.path.join(settings.MEDIA_ROOT, 'js/tiny_mce')) JS_BASE_URL = JS_URL[:JS_URL.rfind('/')]
import os from django.conf import settings DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG', {'theme': "simple", 'relative_urls': False}) USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False) USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False) USE_FILEBROWSER = getattr(settings, 'TINYMCE_FILEBROWSER', 'filebrowser' in settings.INSTALLED_APPS) if 'staticfiles' in settings.INSTALLED_APPS: JS_URL = os.path.join(settings.STATIC_URL, 'tiny_mce/tiny_mce.js') JS_ROOT = os.path.join(settings.STATIC_ROOT, 'tiny_mce') else: JS_URL = getattr(settings, 'TINYMCE_JS_URL', '%sjs/tiny_mce/tiny_mce.js' % settings.MEDIA_URL) JS_ROOT = getattr(settings, 'TINYMCE_JS_ROOT', os.path.join(settings.MEDIA_ROOT, 'js/tiny_mce')) JS_BASE_URL = JS_URL[:JS_URL.rfind('/')] Use STATIC_URL/STATIC_ROOT when using django.contrib.staticfiles (django 1.3)import os from django.conf import settings DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG', {'theme': "simple", 'relative_urls': False}) USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False) USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False) USE_FILEBROWSER = getattr(settings, 'TINYMCE_FILEBROWSER', 'filebrowser' in settings.INSTALLED_APPS) if 'staticfiles' in settings.INSTALLED_APPS or \ 'django.contrib.staticfiles' in settings.INSTALLED_APPS: JS_URL = os.path.join(getattr(settings, 'STATIC_URL', ''), 'tiny_mce/tiny_mce.js') JS_ROOT = os.path.join(getattr(settings, 'STATIC_ROOT', ''), 'tiny_mce') else: JS_URL = getattr(settings, 'TINYMCE_JS_URL', '%sjs/tiny_mce/tiny_mce.js' % settings.MEDIA_URL) JS_ROOT = getattr(settings, 'TINYMCE_JS_ROOT', os.path.join(settings.MEDIA_ROOT, 'js/tiny_mce')) JS_BASE_URL = JS_URL[:JS_URL.rfind('/')]
<commit_before>import os from django.conf import settings DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG', {'theme': "simple", 'relative_urls': False}) USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False) USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False) USE_FILEBROWSER = getattr(settings, 'TINYMCE_FILEBROWSER', 'filebrowser' in settings.INSTALLED_APPS) if 'staticfiles' in settings.INSTALLED_APPS: JS_URL = os.path.join(settings.STATIC_URL, 'tiny_mce/tiny_mce.js') JS_ROOT = os.path.join(settings.STATIC_ROOT, 'tiny_mce') else: JS_URL = getattr(settings, 'TINYMCE_JS_URL', '%sjs/tiny_mce/tiny_mce.js' % settings.MEDIA_URL) JS_ROOT = getattr(settings, 'TINYMCE_JS_ROOT', os.path.join(settings.MEDIA_ROOT, 'js/tiny_mce')) JS_BASE_URL = JS_URL[:JS_URL.rfind('/')] <commit_msg>Use STATIC_URL/STATIC_ROOT when using django.contrib.staticfiles (django 1.3)<commit_after>import os from django.conf import settings DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG', {'theme': "simple", 'relative_urls': False}) USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False) USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False) USE_FILEBROWSER = getattr(settings, 'TINYMCE_FILEBROWSER', 'filebrowser' in settings.INSTALLED_APPS) if 'staticfiles' in settings.INSTALLED_APPS or \ 'django.contrib.staticfiles' in settings.INSTALLED_APPS: JS_URL = os.path.join(getattr(settings, 'STATIC_URL', ''), 'tiny_mce/tiny_mce.js') JS_ROOT = os.path.join(getattr(settings, 'STATIC_ROOT', ''), 'tiny_mce') else: JS_URL = getattr(settings, 'TINYMCE_JS_URL', '%sjs/tiny_mce/tiny_mce.js' % settings.MEDIA_URL) JS_ROOT = getattr(settings, 'TINYMCE_JS_ROOT', os.path.join(settings.MEDIA_ROOT, 'js/tiny_mce')) JS_BASE_URL = JS_URL[:JS_URL.rfind('/')]
287609cc21ae7024507a662b2afe13520fdf8eb7
tests/test_mysql.py
tests/test_mysql.py
import unittest import logging; logger = logging.getLogger() from checks.db.mysql import MySql class TestMySql(unittest.TestCase): def setUp(self): # This should run on pre-2.7 python so no skiptest try: import MySQLdb self.mysql = MySql(logger) except ImportError: self.skip = True def testChecks(self): if not self.skip: results = self.mysql.check({"mysql_server": "localhost", "mysql_user": "dog", "mysql_pass": "dog"}) assert results if __name__ == '__main__': unittest.main()
import unittest import logging; logger = logging.getLogger() from checks.db.mysql import MySql from tests.common import load_check import time class TestMySql(unittest.TestCase): def testChecks(self): agentConfig = { 'mysql_server': 'localhost', 'mysql_user': "datadog", 'mysql_pass': "phQOrbaXem0kP8JHri1qSMRS", 'version': '0.1', 'api_key': 'toto' } # Initialize the check from checks.d c = load_check('mysql', {'init_config': {}, 'instances':{}},agentConfig) conf = c.parse_agent_config(agentConfig) self.check = load_check('mysql', conf, agentConfig) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 8, metrics) time.sleep(1) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 16, metrics) if __name__ == '__main__': unittest.main()
Fix mysql check to use checks.d version
Fix mysql check to use checks.d version
Python
bsd-3-clause
eeroniemi/dd-agent,indeedops/dd-agent,relateiq/dd-agent,Shopify/dd-agent,remh/dd-agent,huhongbo/dd-agent,darron/dd-agent,jamesandariese/dd-agent,jraede/dd-agent,eeroniemi/dd-agent,urosgruber/dd-agent,jvassev/dd-agent,eeroniemi/dd-agent,polynomial/dd-agent,lookout/dd-agent,jvassev/dd-agent,Mashape/dd-agent,Shopify/dd-agent,AntoCard/powerdns-recursor_check,Wattpad/dd-agent,jamesandariese/dd-agent,jvassev/dd-agent,remh/dd-agent,Wattpad/dd-agent,brettlangdon/dd-agent,amalakar/dd-agent,Mashape/dd-agent,brettlangdon/dd-agent,manolama/dd-agent,mderomph-coolblue/dd-agent,amalakar/dd-agent,packetloop/dd-agent,polynomial/dd-agent,joelvanvelden/dd-agent,truthbk/dd-agent,tebriel/dd-agent,zendesk/dd-agent,brettlangdon/dd-agent,Mashape/dd-agent,jraede/dd-agent,jraede/dd-agent,takus/dd-agent,takus/dd-agent,AniruddhaSAtre/dd-agent,ess/dd-agent,truthbk/dd-agent,jvassev/dd-agent,tebriel/dd-agent,gphat/dd-agent,guruxu/dd-agent,cberry777/dd-agent,packetloop/dd-agent,zendesk/dd-agent,polynomial/dd-agent,jamesandariese/dd-agent,takus/dd-agent,mderomph-coolblue/dd-agent,pmav99/praktoras,JohnLZeller/dd-agent,GabrielNicolasAvellaneda/dd-agent,PagerDuty/dd-agent,jamesandariese/dd-agent,benmccann/dd-agent,pfmooney/dd-agent,benmccann/dd-agent,JohnLZeller/dd-agent,relateiq/dd-agent,JohnLZeller/dd-agent,AniruddhaSAtre/dd-agent,truthbk/dd-agent,AntoCard/powerdns-recursor_check,Mashape/dd-agent,Mashape/dd-agent,cberry777/dd-agent,gphat/dd-agent,oneandoneis2/dd-agent,GabrielNicolasAvellaneda/dd-agent,pmav99/praktoras,a20012251/dd-agent,jshum/dd-agent,darron/dd-agent,a20012251/dd-agent,pmav99/praktoras,GabrielNicolasAvellaneda/dd-agent,urosgruber/dd-agent,yuecong/dd-agent,takus/dd-agent,citrusleaf/dd-agent,c960657/dd-agent,Wattpad/dd-agent,cberry777/dd-agent,remh/dd-agent,packetloop/dd-agent,guruxu/dd-agent,darron/dd-agent,truthbk/dd-agent,ess/dd-agent,citrusleaf/dd-agent,manolama/dd-agent,darron/dd-agent,manolama/dd-agent,packetloop/dd-agent,takus/dd-agent,oneandoneis2/dd-agent,a20012251/dd-agent,GabrielNicolasAvellaneda/dd-agent,Shopify/dd-agent,joelvanvelden/dd-agent,jyogi/purvar-agent,packetloop/dd-agent,a20012251/dd-agent,PagerDuty/dd-agent,urosgruber/dd-agent,pfmooney/dd-agent,c960657/dd-agent,tebriel/dd-agent,jshum/dd-agent,mderomph-coolblue/dd-agent,remh/dd-agent,AntoCard/powerdns-recursor_check,indeedops/dd-agent,ess/dd-agent,truthbk/dd-agent,JohnLZeller/dd-agent,a20012251/dd-agent,indeedops/dd-agent,jyogi/purvar-agent,joelvanvelden/dd-agent,pfmooney/dd-agent,Shopify/dd-agent,polynomial/dd-agent,cberry777/dd-agent,lookout/dd-agent,lookout/dd-agent,jvassev/dd-agent,indeedops/dd-agent,mderomph-coolblue/dd-agent,zendesk/dd-agent,joelvanvelden/dd-agent,jamesandariese/dd-agent,oneandoneis2/dd-agent,tebriel/dd-agent,ess/dd-agent,lookout/dd-agent,remh/dd-agent,oneandoneis2/dd-agent,GabrielNicolasAvellaneda/dd-agent,c960657/dd-agent,cberry777/dd-agent,zendesk/dd-agent,oneandoneis2/dd-agent,pfmooney/dd-agent,manolama/dd-agent,PagerDuty/dd-agent,AniruddhaSAtre/dd-agent,jyogi/purvar-agent,citrusleaf/dd-agent,AntoCard/powerdns-recursor_check,benmccann/dd-agent,indeedops/dd-agent,pmav99/praktoras,c960657/dd-agent,brettlangdon/dd-agent,jraede/dd-agent,urosgruber/dd-agent,yuecong/dd-agent,huhongbo/dd-agent,tebriel/dd-agent,benmccann/dd-agent,guruxu/dd-agent,citrusleaf/dd-agent,urosgruber/dd-agent,JohnLZeller/dd-agent,jraede/dd-agent,AniruddhaSAtre/dd-agent,jshum/dd-agent,relateiq/dd-agent,eeroniemi/dd-agent,mderomph-coolblue/dd-agent,citrusleaf/dd-agent,gphat/dd-agent,zendesk/dd-agent,guruxu/dd-agent,jshum/dd-agent,huhongbo/dd-agent,joelvanvelden/dd-agent,Wattpad/dd-agent,pmav99/praktoras,PagerDuty/dd-agent,guruxu/dd-agent,amalakar/dd-agent,yuecong/dd-agent,jshum/dd-agent,jyogi/purvar-agent,manolama/dd-agent,PagerDuty/dd-agent,lookout/dd-agent,huhongbo/dd-agent,gphat/dd-agent,Wattpad/dd-agent,brettlangdon/dd-agent,ess/dd-agent,huhongbo/dd-agent,jyogi/purvar-agent,AniruddhaSAtre/dd-agent,yuecong/dd-agent,relateiq/dd-agent,amalakar/dd-agent,gphat/dd-agent,c960657/dd-agent,eeroniemi/dd-agent,amalakar/dd-agent,polynomial/dd-agent,benmccann/dd-agent,pfmooney/dd-agent,relateiq/dd-agent,yuecong/dd-agent,AntoCard/powerdns-recursor_check,Shopify/dd-agent,darron/dd-agent
import unittest import logging; logger = logging.getLogger() from checks.db.mysql import MySql class TestMySql(unittest.TestCase): def setUp(self): # This should run on pre-2.7 python so no skiptest try: import MySQLdb self.mysql = MySql(logger) except ImportError: self.skip = True def testChecks(self): if not self.skip: results = self.mysql.check({"mysql_server": "localhost", "mysql_user": "dog", "mysql_pass": "dog"}) assert results if __name__ == '__main__': unittest.main() Fix mysql check to use checks.d version
import unittest import logging; logger = logging.getLogger() from checks.db.mysql import MySql from tests.common import load_check import time class TestMySql(unittest.TestCase): def testChecks(self): agentConfig = { 'mysql_server': 'localhost', 'mysql_user': "datadog", 'mysql_pass': "phQOrbaXem0kP8JHri1qSMRS", 'version': '0.1', 'api_key': 'toto' } # Initialize the check from checks.d c = load_check('mysql', {'init_config': {}, 'instances':{}},agentConfig) conf = c.parse_agent_config(agentConfig) self.check = load_check('mysql', conf, agentConfig) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 8, metrics) time.sleep(1) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 16, metrics) if __name__ == '__main__': unittest.main()
<commit_before>import unittest import logging; logger = logging.getLogger() from checks.db.mysql import MySql class TestMySql(unittest.TestCase): def setUp(self): # This should run on pre-2.7 python so no skiptest try: import MySQLdb self.mysql = MySql(logger) except ImportError: self.skip = True def testChecks(self): if not self.skip: results = self.mysql.check({"mysql_server": "localhost", "mysql_user": "dog", "mysql_pass": "dog"}) assert results if __name__ == '__main__': unittest.main() <commit_msg>Fix mysql check to use checks.d version<commit_after>
import unittest import logging; logger = logging.getLogger() from checks.db.mysql import MySql from tests.common import load_check import time class TestMySql(unittest.TestCase): def testChecks(self): agentConfig = { 'mysql_server': 'localhost', 'mysql_user': "datadog", 'mysql_pass': "phQOrbaXem0kP8JHri1qSMRS", 'version': '0.1', 'api_key': 'toto' } # Initialize the check from checks.d c = load_check('mysql', {'init_config': {}, 'instances':{}},agentConfig) conf = c.parse_agent_config(agentConfig) self.check = load_check('mysql', conf, agentConfig) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 8, metrics) time.sleep(1) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 16, metrics) if __name__ == '__main__': unittest.main()
import unittest import logging; logger = logging.getLogger() from checks.db.mysql import MySql class TestMySql(unittest.TestCase): def setUp(self): # This should run on pre-2.7 python so no skiptest try: import MySQLdb self.mysql = MySql(logger) except ImportError: self.skip = True def testChecks(self): if not self.skip: results = self.mysql.check({"mysql_server": "localhost", "mysql_user": "dog", "mysql_pass": "dog"}) assert results if __name__ == '__main__': unittest.main() Fix mysql check to use checks.d versionimport unittest import logging; logger = logging.getLogger() from checks.db.mysql import MySql from tests.common import load_check import time class TestMySql(unittest.TestCase): def testChecks(self): agentConfig = { 'mysql_server': 'localhost', 'mysql_user': "datadog", 'mysql_pass': "phQOrbaXem0kP8JHri1qSMRS", 'version': '0.1', 'api_key': 'toto' } # Initialize the check from checks.d c = load_check('mysql', {'init_config': {}, 'instances':{}},agentConfig) conf = c.parse_agent_config(agentConfig) self.check = load_check('mysql', conf, agentConfig) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 8, metrics) time.sleep(1) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 16, metrics) if __name__ == '__main__': unittest.main()
<commit_before>import unittest import logging; logger = logging.getLogger() from checks.db.mysql import MySql class TestMySql(unittest.TestCase): def setUp(self): # This should run on pre-2.7 python so no skiptest try: import MySQLdb self.mysql = MySql(logger) except ImportError: self.skip = True def testChecks(self): if not self.skip: results = self.mysql.check({"mysql_server": "localhost", "mysql_user": "dog", "mysql_pass": "dog"}) assert results if __name__ == '__main__': unittest.main() <commit_msg>Fix mysql check to use checks.d version<commit_after>import unittest import logging; logger = logging.getLogger() from checks.db.mysql import MySql from tests.common import load_check import time class TestMySql(unittest.TestCase): def testChecks(self): agentConfig = { 'mysql_server': 'localhost', 'mysql_user': "datadog", 'mysql_pass': "phQOrbaXem0kP8JHri1qSMRS", 'version': '0.1', 'api_key': 'toto' } # Initialize the check from checks.d c = load_check('mysql', {'init_config': {}, 'instances':{}},agentConfig) conf = c.parse_agent_config(agentConfig) self.check = load_check('mysql', conf, agentConfig) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 8, metrics) time.sleep(1) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 16, metrics) if __name__ == '__main__': unittest.main()
5b99fa7adf8ce65309f47d6456ecba32b02995a4
tests/utils.py
tests/utils.py
import os import sphinx_tests_util from xml.etree import ElementTree from xml.dom import minidom # ============================================================================= # Utility functions def srcdir(name): test_root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(test_root, "data", name) def pretty_print_xml(node): minidom_xml = minidom.parseString(ElementTree.tostring(node)) output = minidom_xml.toprettyxml(indent=" ") lines = [line for line in output.splitlines() if line.strip()] print "\n".join(lines) def with_app(*args, **kwargs): kwargs = kwargs.copy() if "srcdir" in kwargs: kwargs["srcdir"] = srcdir(kwargs["srcdir"]) return sphinx_tests_util.with_app(*args, **kwargs)
import os import sphinx_tests_util from xml.etree import ElementTree from xml.dom import minidom # ============================================================================= # Utility functions def srcdir(name): test_root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(test_root, "data", name) def pretty_print_xml(node): minidom_xml = minidom.parseString(ElementTree.tostring(node)) output = minidom_xml.toprettyxml(indent=" ") lines = [line for line in output.splitlines() if line.strip()] print "\n".join(lines) def with_app(*args, **kwargs): kwargs = kwargs.copy() # Expand test data directory. if "srcdir" in kwargs: kwargs["srcdir"] = srcdir(kwargs["srcdir"]) # By default use a fresh build environment. if "freshenv" not in kwargs: kwargs["freshenv"] = True return sphinx_tests_util.with_app(*args, **kwargs)
Use fresh build environment by default in tests
Use fresh build environment by default in tests
Python
apache-2.0
t4ngo/sphinxcontrib-traceables
import os import sphinx_tests_util from xml.etree import ElementTree from xml.dom import minidom # ============================================================================= # Utility functions def srcdir(name): test_root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(test_root, "data", name) def pretty_print_xml(node): minidom_xml = minidom.parseString(ElementTree.tostring(node)) output = minidom_xml.toprettyxml(indent=" ") lines = [line for line in output.splitlines() if line.strip()] print "\n".join(lines) def with_app(*args, **kwargs): kwargs = kwargs.copy() if "srcdir" in kwargs: kwargs["srcdir"] = srcdir(kwargs["srcdir"]) return sphinx_tests_util.with_app(*args, **kwargs) Use fresh build environment by default in tests
import os import sphinx_tests_util from xml.etree import ElementTree from xml.dom import minidom # ============================================================================= # Utility functions def srcdir(name): test_root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(test_root, "data", name) def pretty_print_xml(node): minidom_xml = minidom.parseString(ElementTree.tostring(node)) output = minidom_xml.toprettyxml(indent=" ") lines = [line for line in output.splitlines() if line.strip()] print "\n".join(lines) def with_app(*args, **kwargs): kwargs = kwargs.copy() # Expand test data directory. if "srcdir" in kwargs: kwargs["srcdir"] = srcdir(kwargs["srcdir"]) # By default use a fresh build environment. if "freshenv" not in kwargs: kwargs["freshenv"] = True return sphinx_tests_util.with_app(*args, **kwargs)
<commit_before> import os import sphinx_tests_util from xml.etree import ElementTree from xml.dom import minidom # ============================================================================= # Utility functions def srcdir(name): test_root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(test_root, "data", name) def pretty_print_xml(node): minidom_xml = minidom.parseString(ElementTree.tostring(node)) output = minidom_xml.toprettyxml(indent=" ") lines = [line for line in output.splitlines() if line.strip()] print "\n".join(lines) def with_app(*args, **kwargs): kwargs = kwargs.copy() if "srcdir" in kwargs: kwargs["srcdir"] = srcdir(kwargs["srcdir"]) return sphinx_tests_util.with_app(*args, **kwargs) <commit_msg>Use fresh build environment by default in tests<commit_after>
import os import sphinx_tests_util from xml.etree import ElementTree from xml.dom import minidom # ============================================================================= # Utility functions def srcdir(name): test_root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(test_root, "data", name) def pretty_print_xml(node): minidom_xml = minidom.parseString(ElementTree.tostring(node)) output = minidom_xml.toprettyxml(indent=" ") lines = [line for line in output.splitlines() if line.strip()] print "\n".join(lines) def with_app(*args, **kwargs): kwargs = kwargs.copy() # Expand test data directory. if "srcdir" in kwargs: kwargs["srcdir"] = srcdir(kwargs["srcdir"]) # By default use a fresh build environment. if "freshenv" not in kwargs: kwargs["freshenv"] = True return sphinx_tests_util.with_app(*args, **kwargs)
import os import sphinx_tests_util from xml.etree import ElementTree from xml.dom import minidom # ============================================================================= # Utility functions def srcdir(name): test_root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(test_root, "data", name) def pretty_print_xml(node): minidom_xml = minidom.parseString(ElementTree.tostring(node)) output = minidom_xml.toprettyxml(indent=" ") lines = [line for line in output.splitlines() if line.strip()] print "\n".join(lines) def with_app(*args, **kwargs): kwargs = kwargs.copy() if "srcdir" in kwargs: kwargs["srcdir"] = srcdir(kwargs["srcdir"]) return sphinx_tests_util.with_app(*args, **kwargs) Use fresh build environment by default in tests import os import sphinx_tests_util from xml.etree import ElementTree from xml.dom import minidom # ============================================================================= # Utility functions def srcdir(name): test_root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(test_root, "data", name) def pretty_print_xml(node): minidom_xml = minidom.parseString(ElementTree.tostring(node)) output = minidom_xml.toprettyxml(indent=" ") lines = [line for line in output.splitlines() if line.strip()] print "\n".join(lines) def with_app(*args, **kwargs): kwargs = kwargs.copy() # Expand test data directory. if "srcdir" in kwargs: kwargs["srcdir"] = srcdir(kwargs["srcdir"]) # By default use a fresh build environment. if "freshenv" not in kwargs: kwargs["freshenv"] = True return sphinx_tests_util.with_app(*args, **kwargs)
<commit_before> import os import sphinx_tests_util from xml.etree import ElementTree from xml.dom import minidom # ============================================================================= # Utility functions def srcdir(name): test_root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(test_root, "data", name) def pretty_print_xml(node): minidom_xml = minidom.parseString(ElementTree.tostring(node)) output = minidom_xml.toprettyxml(indent=" ") lines = [line for line in output.splitlines() if line.strip()] print "\n".join(lines) def with_app(*args, **kwargs): kwargs = kwargs.copy() if "srcdir" in kwargs: kwargs["srcdir"] = srcdir(kwargs["srcdir"]) return sphinx_tests_util.with_app(*args, **kwargs) <commit_msg>Use fresh build environment by default in tests<commit_after> import os import sphinx_tests_util from xml.etree import ElementTree from xml.dom import minidom # ============================================================================= # Utility functions def srcdir(name): test_root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(test_root, "data", name) def pretty_print_xml(node): minidom_xml = minidom.parseString(ElementTree.tostring(node)) output = minidom_xml.toprettyxml(indent=" ") lines = [line for line in output.splitlines() if line.strip()] print "\n".join(lines) def with_app(*args, **kwargs): kwargs = kwargs.copy() # Expand test data directory. if "srcdir" in kwargs: kwargs["srcdir"] = srcdir(kwargs["srcdir"]) # By default use a fresh build environment. if "freshenv" not in kwargs: kwargs["freshenv"] = True return sphinx_tests_util.with_app(*args, **kwargs)
f54fd0bf65d731b4f25cfc2ddffb8d6f472e0d7c
examples/eiger_use_case.py
examples/eiger_use_case.py
'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files),) + sh, dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0)
'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0)
Fix layout for Eiger example
Fix layout for Eiger example
Python
bsd-3-clause
h5py/h5py,h5py/h5py,h5py/h5py
'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files),) + sh, dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0) Fix layout for Eiger example
'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0)
<commit_before>'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files),) + sh, dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0) <commit_msg>Fix layout for Eiger example<commit_after>
'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0)
'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files),) + sh, dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0) Fix layout for Eiger example'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0)
<commit_before>'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files),) + sh, dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0) <commit_msg>Fix layout for Eiger example<commit_after>'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0)
dd2c92bea635d7cfc93b437ce32266126bceb1e9
qipipe/helpers/bolus_arrival.py
qipipe/helpers/bolus_arrival.py
class BolusArrivalError(Exception): pass def bolus_arrival_index(time_series): """ Determines the DCE bolus arrival series index. The bolus arrival is the first series with a difference in average signal larger than double the difference from first two points. :param time_series: the 4D NiFTI scan image file path :return: the bolus arrival series index :raise BolusArrivalError: if the bolus arrival could not be determined """ import nibabel as nb import numpy as np nii = nb.load(time_series) data = nii.get_data() n_vols = data.shape[-1] signal_means = np.array([np.mean(data[:,:,:, idx]) for idx in xrange(n_vols)]) signal_diffs = np.diff(signal_means) # If we see a difference in average signal larger than double the # difference from first two points, take that as bolus arrival. base_diff = np.abs(signal_diffs[0]) for idx, diff_val in enumerate(signal_diffs[1:]): if diff_val > 2 * base_diff: return idx + 1 else: raise BolusArrivalError("Unable to determine bolus arrival")
class BolusArrivalError(Exception): pass def bolus_arrival_index(time_series): """ Determines the DCE bolus arrival time point index. The bolus arrival is the first occurence of a difference in average signal larger than double the difference from first two points. :param time_series: the 4D NiFTI scan image file path :return: the bolus arrival time point index :raise BolusArrivalError: if the bolus arrival could not be determined """ import nibabel as nb import numpy as np nii = nb.load(time_series) data = nii.get_data() n_vols = data.shape[-1] signal_means = np.array([np.mean(data[:,:,:, idx]) for idx in xrange(n_vols)]) signal_diffs = np.diff(signal_means) # If we see a difference in average signal larger than double the # difference from first two points, take that as bolus arrival. base_diff = np.abs(signal_diffs[0]) for idx, diff_val in enumerate(signal_diffs[1:]): if diff_val > 2 * base_diff: return idx + 1 else: raise BolusArrivalError("Unable to determine bolus arrival")
Change series to time point.
Change series to time point.
Python
bsd-2-clause
ohsu-qin/qipipe
class BolusArrivalError(Exception): pass def bolus_arrival_index(time_series): """ Determines the DCE bolus arrival series index. The bolus arrival is the first series with a difference in average signal larger than double the difference from first two points. :param time_series: the 4D NiFTI scan image file path :return: the bolus arrival series index :raise BolusArrivalError: if the bolus arrival could not be determined """ import nibabel as nb import numpy as np nii = nb.load(time_series) data = nii.get_data() n_vols = data.shape[-1] signal_means = np.array([np.mean(data[:,:,:, idx]) for idx in xrange(n_vols)]) signal_diffs = np.diff(signal_means) # If we see a difference in average signal larger than double the # difference from first two points, take that as bolus arrival. base_diff = np.abs(signal_diffs[0]) for idx, diff_val in enumerate(signal_diffs[1:]): if diff_val > 2 * base_diff: return idx + 1 else: raise BolusArrivalError("Unable to determine bolus arrival") Change series to time point.
class BolusArrivalError(Exception): pass def bolus_arrival_index(time_series): """ Determines the DCE bolus arrival time point index. The bolus arrival is the first occurence of a difference in average signal larger than double the difference from first two points. :param time_series: the 4D NiFTI scan image file path :return: the bolus arrival time point index :raise BolusArrivalError: if the bolus arrival could not be determined """ import nibabel as nb import numpy as np nii = nb.load(time_series) data = nii.get_data() n_vols = data.shape[-1] signal_means = np.array([np.mean(data[:,:,:, idx]) for idx in xrange(n_vols)]) signal_diffs = np.diff(signal_means) # If we see a difference in average signal larger than double the # difference from first two points, take that as bolus arrival. base_diff = np.abs(signal_diffs[0]) for idx, diff_val in enumerate(signal_diffs[1:]): if diff_val > 2 * base_diff: return idx + 1 else: raise BolusArrivalError("Unable to determine bolus arrival")
<commit_before>class BolusArrivalError(Exception): pass def bolus_arrival_index(time_series): """ Determines the DCE bolus arrival series index. The bolus arrival is the first series with a difference in average signal larger than double the difference from first two points. :param time_series: the 4D NiFTI scan image file path :return: the bolus arrival series index :raise BolusArrivalError: if the bolus arrival could not be determined """ import nibabel as nb import numpy as np nii = nb.load(time_series) data = nii.get_data() n_vols = data.shape[-1] signal_means = np.array([np.mean(data[:,:,:, idx]) for idx in xrange(n_vols)]) signal_diffs = np.diff(signal_means) # If we see a difference in average signal larger than double the # difference from first two points, take that as bolus arrival. base_diff = np.abs(signal_diffs[0]) for idx, diff_val in enumerate(signal_diffs[1:]): if diff_val > 2 * base_diff: return idx + 1 else: raise BolusArrivalError("Unable to determine bolus arrival") <commit_msg>Change series to time point.<commit_after>
class BolusArrivalError(Exception): pass def bolus_arrival_index(time_series): """ Determines the DCE bolus arrival time point index. The bolus arrival is the first occurence of a difference in average signal larger than double the difference from first two points. :param time_series: the 4D NiFTI scan image file path :return: the bolus arrival time point index :raise BolusArrivalError: if the bolus arrival could not be determined """ import nibabel as nb import numpy as np nii = nb.load(time_series) data = nii.get_data() n_vols = data.shape[-1] signal_means = np.array([np.mean(data[:,:,:, idx]) for idx in xrange(n_vols)]) signal_diffs = np.diff(signal_means) # If we see a difference in average signal larger than double the # difference from first two points, take that as bolus arrival. base_diff = np.abs(signal_diffs[0]) for idx, diff_val in enumerate(signal_diffs[1:]): if diff_val > 2 * base_diff: return idx + 1 else: raise BolusArrivalError("Unable to determine bolus arrival")
class BolusArrivalError(Exception): pass def bolus_arrival_index(time_series): """ Determines the DCE bolus arrival series index. The bolus arrival is the first series with a difference in average signal larger than double the difference from first two points. :param time_series: the 4D NiFTI scan image file path :return: the bolus arrival series index :raise BolusArrivalError: if the bolus arrival could not be determined """ import nibabel as nb import numpy as np nii = nb.load(time_series) data = nii.get_data() n_vols = data.shape[-1] signal_means = np.array([np.mean(data[:,:,:, idx]) for idx in xrange(n_vols)]) signal_diffs = np.diff(signal_means) # If we see a difference in average signal larger than double the # difference from first two points, take that as bolus arrival. base_diff = np.abs(signal_diffs[0]) for idx, diff_val in enumerate(signal_diffs[1:]): if diff_val > 2 * base_diff: return idx + 1 else: raise BolusArrivalError("Unable to determine bolus arrival") Change series to time point.class BolusArrivalError(Exception): pass def bolus_arrival_index(time_series): """ Determines the DCE bolus arrival time point index. The bolus arrival is the first occurence of a difference in average signal larger than double the difference from first two points. :param time_series: the 4D NiFTI scan image file path :return: the bolus arrival time point index :raise BolusArrivalError: if the bolus arrival could not be determined """ import nibabel as nb import numpy as np nii = nb.load(time_series) data = nii.get_data() n_vols = data.shape[-1] signal_means = np.array([np.mean(data[:,:,:, idx]) for idx in xrange(n_vols)]) signal_diffs = np.diff(signal_means) # If we see a difference in average signal larger than double the # difference from first two points, take that as bolus arrival. base_diff = np.abs(signal_diffs[0]) for idx, diff_val in enumerate(signal_diffs[1:]): if diff_val > 2 * base_diff: return idx + 1 else: raise BolusArrivalError("Unable to determine bolus arrival")
<commit_before>class BolusArrivalError(Exception): pass def bolus_arrival_index(time_series): """ Determines the DCE bolus arrival series index. The bolus arrival is the first series with a difference in average signal larger than double the difference from first two points. :param time_series: the 4D NiFTI scan image file path :return: the bolus arrival series index :raise BolusArrivalError: if the bolus arrival could not be determined """ import nibabel as nb import numpy as np nii = nb.load(time_series) data = nii.get_data() n_vols = data.shape[-1] signal_means = np.array([np.mean(data[:,:,:, idx]) for idx in xrange(n_vols)]) signal_diffs = np.diff(signal_means) # If we see a difference in average signal larger than double the # difference from first two points, take that as bolus arrival. base_diff = np.abs(signal_diffs[0]) for idx, diff_val in enumerate(signal_diffs[1:]): if diff_val > 2 * base_diff: return idx + 1 else: raise BolusArrivalError("Unable to determine bolus arrival") <commit_msg>Change series to time point.<commit_after>class BolusArrivalError(Exception): pass def bolus_arrival_index(time_series): """ Determines the DCE bolus arrival time point index. The bolus arrival is the first occurence of a difference in average signal larger than double the difference from first two points. :param time_series: the 4D NiFTI scan image file path :return: the bolus arrival time point index :raise BolusArrivalError: if the bolus arrival could not be determined """ import nibabel as nb import numpy as np nii = nb.load(time_series) data = nii.get_data() n_vols = data.shape[-1] signal_means = np.array([np.mean(data[:,:,:, idx]) for idx in xrange(n_vols)]) signal_diffs = np.diff(signal_means) # If we see a difference in average signal larger than double the # difference from first two points, take that as bolus arrival. base_diff = np.abs(signal_diffs[0]) for idx, diff_val in enumerate(signal_diffs[1:]): if diff_val > 2 * base_diff: return idx + 1 else: raise BolusArrivalError("Unable to determine bolus arrival")
ffd1ba9eee804fdd55e86908b158a4ad94f2f366
Tools/idle/ZoomHeight.py
Tools/idle/ZoomHeight.py
# Sample extension: zoom a window to maximum height import re import sys class ZoomHeight: menudefs = [ ('windows', [ ('_Zoom Height', '<<zoom-height>>'), ]) ] windows_keydefs = { '<<zoom-height>>': ['<Alt-F2>'], } unix_keydefs = { '<<zoom-height>>': ['<Control-x><Control-z>'], } def __init__(self, editwin): self.editwin = editwin def zoom_height_event(self, event): top = self.editwin.top geom = top.wm_geometry() m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom) if not m: top.bell() return width, height, x, y = map(int, m.groups()) height = top.winfo_screenheight() if sys.platform == 'win32': y = 0 height = height - 72 else: y = 24 height = height - 96 newgeom = "%dx%d+%d+%d" % (width, height, x, y) if geom == newgeom: newgeom = "" top.wm_geometry(newgeom)
# Sample extension: zoom a window to maximum height import re import sys class ZoomHeight: menudefs = [ ('windows', [ ('_Zoom Height', '<<zoom-height>>'), ]) ] windows_keydefs = { '<<zoom-height>>': ['<Alt-F2>'], } unix_keydefs = { '<<zoom-height>>': ['<Control-x><Control-z>'], } def __init__(self, editwin): self.editwin = editwin def zoom_height_event(self, event): top = self.editwin.top geom = top.wm_geometry() m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom) if not m: top.bell() return width, height, x, y = map(int, m.groups()) newheight = top.winfo_screenheight() if sys.platform == 'win32': newy = 0 newheight = newheight - 72 else: newy = 24 newheight = newheight - 96 if height >= newheight: newgeom = "" else: newgeom = "%dx%d+%d+%d" % (width, newheight, x, newy) top.wm_geometry(newgeom)
Use only the height to decide whether to zoom in or out.
Use only the height to decide whether to zoom in or out.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
# Sample extension: zoom a window to maximum height import re import sys class ZoomHeight: menudefs = [ ('windows', [ ('_Zoom Height', '<<zoom-height>>'), ]) ] windows_keydefs = { '<<zoom-height>>': ['<Alt-F2>'], } unix_keydefs = { '<<zoom-height>>': ['<Control-x><Control-z>'], } def __init__(self, editwin): self.editwin = editwin def zoom_height_event(self, event): top = self.editwin.top geom = top.wm_geometry() m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom) if not m: top.bell() return width, height, x, y = map(int, m.groups()) height = top.winfo_screenheight() if sys.platform == 'win32': y = 0 height = height - 72 else: y = 24 height = height - 96 newgeom = "%dx%d+%d+%d" % (width, height, x, y) if geom == newgeom: newgeom = "" top.wm_geometry(newgeom) Use only the height to decide whether to zoom in or out.
# Sample extension: zoom a window to maximum height import re import sys class ZoomHeight: menudefs = [ ('windows', [ ('_Zoom Height', '<<zoom-height>>'), ]) ] windows_keydefs = { '<<zoom-height>>': ['<Alt-F2>'], } unix_keydefs = { '<<zoom-height>>': ['<Control-x><Control-z>'], } def __init__(self, editwin): self.editwin = editwin def zoom_height_event(self, event): top = self.editwin.top geom = top.wm_geometry() m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom) if not m: top.bell() return width, height, x, y = map(int, m.groups()) newheight = top.winfo_screenheight() if sys.platform == 'win32': newy = 0 newheight = newheight - 72 else: newy = 24 newheight = newheight - 96 if height >= newheight: newgeom = "" else: newgeom = "%dx%d+%d+%d" % (width, newheight, x, newy) top.wm_geometry(newgeom)
<commit_before># Sample extension: zoom a window to maximum height import re import sys class ZoomHeight: menudefs = [ ('windows', [ ('_Zoom Height', '<<zoom-height>>'), ]) ] windows_keydefs = { '<<zoom-height>>': ['<Alt-F2>'], } unix_keydefs = { '<<zoom-height>>': ['<Control-x><Control-z>'], } def __init__(self, editwin): self.editwin = editwin def zoom_height_event(self, event): top = self.editwin.top geom = top.wm_geometry() m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom) if not m: top.bell() return width, height, x, y = map(int, m.groups()) height = top.winfo_screenheight() if sys.platform == 'win32': y = 0 height = height - 72 else: y = 24 height = height - 96 newgeom = "%dx%d+%d+%d" % (width, height, x, y) if geom == newgeom: newgeom = "" top.wm_geometry(newgeom) <commit_msg>Use only the height to decide whether to zoom in or out.<commit_after>
# Sample extension: zoom a window to maximum height import re import sys class ZoomHeight: menudefs = [ ('windows', [ ('_Zoom Height', '<<zoom-height>>'), ]) ] windows_keydefs = { '<<zoom-height>>': ['<Alt-F2>'], } unix_keydefs = { '<<zoom-height>>': ['<Control-x><Control-z>'], } def __init__(self, editwin): self.editwin = editwin def zoom_height_event(self, event): top = self.editwin.top geom = top.wm_geometry() m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom) if not m: top.bell() return width, height, x, y = map(int, m.groups()) newheight = top.winfo_screenheight() if sys.platform == 'win32': newy = 0 newheight = newheight - 72 else: newy = 24 newheight = newheight - 96 if height >= newheight: newgeom = "" else: newgeom = "%dx%d+%d+%d" % (width, newheight, x, newy) top.wm_geometry(newgeom)
# Sample extension: zoom a window to maximum height import re import sys class ZoomHeight: menudefs = [ ('windows', [ ('_Zoom Height', '<<zoom-height>>'), ]) ] windows_keydefs = { '<<zoom-height>>': ['<Alt-F2>'], } unix_keydefs = { '<<zoom-height>>': ['<Control-x><Control-z>'], } def __init__(self, editwin): self.editwin = editwin def zoom_height_event(self, event): top = self.editwin.top geom = top.wm_geometry() m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom) if not m: top.bell() return width, height, x, y = map(int, m.groups()) height = top.winfo_screenheight() if sys.platform == 'win32': y = 0 height = height - 72 else: y = 24 height = height - 96 newgeom = "%dx%d+%d+%d" % (width, height, x, y) if geom == newgeom: newgeom = "" top.wm_geometry(newgeom) Use only the height to decide whether to zoom in or out.# Sample extension: zoom a window to maximum height import re import sys class ZoomHeight: menudefs = [ ('windows', [ ('_Zoom Height', '<<zoom-height>>'), ]) ] windows_keydefs = { '<<zoom-height>>': ['<Alt-F2>'], } unix_keydefs = { '<<zoom-height>>': ['<Control-x><Control-z>'], } def __init__(self, editwin): self.editwin = editwin def zoom_height_event(self, event): top = self.editwin.top geom = top.wm_geometry() m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom) if not m: top.bell() return width, height, x, y = map(int, m.groups()) newheight = top.winfo_screenheight() if sys.platform == 'win32': newy = 0 newheight = newheight - 72 else: newy = 24 newheight = newheight - 96 if height >= newheight: newgeom = "" else: newgeom = "%dx%d+%d+%d" % (width, newheight, x, newy) top.wm_geometry(newgeom)
<commit_before># Sample extension: zoom a window to maximum height import re import sys class ZoomHeight: menudefs = [ ('windows', [ ('_Zoom Height', '<<zoom-height>>'), ]) ] windows_keydefs = { '<<zoom-height>>': ['<Alt-F2>'], } unix_keydefs = { '<<zoom-height>>': ['<Control-x><Control-z>'], } def __init__(self, editwin): self.editwin = editwin def zoom_height_event(self, event): top = self.editwin.top geom = top.wm_geometry() m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom) if not m: top.bell() return width, height, x, y = map(int, m.groups()) height = top.winfo_screenheight() if sys.platform == 'win32': y = 0 height = height - 72 else: y = 24 height = height - 96 newgeom = "%dx%d+%d+%d" % (width, height, x, y) if geom == newgeom: newgeom = "" top.wm_geometry(newgeom) <commit_msg>Use only the height to decide whether to zoom in or out.<commit_after># Sample extension: zoom a window to maximum height import re import sys class ZoomHeight: menudefs = [ ('windows', [ ('_Zoom Height', '<<zoom-height>>'), ]) ] windows_keydefs = { '<<zoom-height>>': ['<Alt-F2>'], } unix_keydefs = { '<<zoom-height>>': ['<Control-x><Control-z>'], } def __init__(self, editwin): self.editwin = editwin def zoom_height_event(self, event): top = self.editwin.top geom = top.wm_geometry() m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom) if not m: top.bell() return width, height, x, y = map(int, m.groups()) newheight = top.winfo_screenheight() if sys.platform == 'win32': newy = 0 newheight = newheight - 72 else: newy = 24 newheight = newheight - 96 if height >= newheight: newgeom = "" else: newgeom = "%dx%d+%d+%d" % (width, newheight, x, newy) top.wm_geometry(newgeom)
1d0570ca75419f441aa1324de78051534efba74b
search_engine.py
search_engine.py
import requests from bs4 import BeautifulSoup def download_url(url): r = requests.get(url) if r.status_code != 200: raise Exception('Non-OK status code: {}'.format(r.status_code)) return r.text def parse_text(html): bs = BeautifulSoup(html, 'html.parser') return bs.select('div.usertext-body')[1].text
import requests from bs4 import BeautifulSoup import os.path from base64 import b16encode import time def download_reddit_url(url): assert url.startswith('https://www.reddit.com/r/learnprogramming') headers = {'User-Agent':'JustSearch bot version 0.1'} r = requests.get(url, headers=headers) if r.status_code != 200: raise Exception('Non-OK status code: {}'.format(r.status_code)) return r.text def parse_reddit_post(html): bs = BeautifulSoup(html, 'html.parser') return bs.select('div.usertext-body')[1].text class Crawler(object): def __init__(self, start_url, storage_dir): self.start_url = start_url self.storage_dir = storage_dir @staticmethod def _make_absolute_url(url): return 'https://www.reddit.com' + url def crawl(self): current_page_url = self.start_url while True: current_page = download_reddit_url(current_page_url) bs = BeautifulSoup(current_page) all_posts_links = bs.findAll('a', attrs={'class': 'title'}) post_links = [Crawler._make_absolute_url(link['href']) for link in all_posts_links] for post_link in post_links: html = download_reddit_url(post_link) stored_text_file_name = os.path.join(self.storage_dir, b16encode(post_link)) stored_text_file = open(stored_text_file_name, 'w') stored_text_file.write(html.encode('utf8')) stored_text_file.close() next_page_url = bs.find('a', attrs={'rel':'next'})['href'] current_page_url = next_page_url time.sleep(2) print next_page_url
Create files with posts and can go to the next page.
Create files with posts and can go to the next page.
Python
mit
tori-smile/JustSearch
import requests from bs4 import BeautifulSoup def download_url(url): r = requests.get(url) if r.status_code != 200: raise Exception('Non-OK status code: {}'.format(r.status_code)) return r.text def parse_text(html): bs = BeautifulSoup(html, 'html.parser') return bs.select('div.usertext-body')[1].text Create files with posts and can go to the next page.
import requests from bs4 import BeautifulSoup import os.path from base64 import b16encode import time def download_reddit_url(url): assert url.startswith('https://www.reddit.com/r/learnprogramming') headers = {'User-Agent':'JustSearch bot version 0.1'} r = requests.get(url, headers=headers) if r.status_code != 200: raise Exception('Non-OK status code: {}'.format(r.status_code)) return r.text def parse_reddit_post(html): bs = BeautifulSoup(html, 'html.parser') return bs.select('div.usertext-body')[1].text class Crawler(object): def __init__(self, start_url, storage_dir): self.start_url = start_url self.storage_dir = storage_dir @staticmethod def _make_absolute_url(url): return 'https://www.reddit.com' + url def crawl(self): current_page_url = self.start_url while True: current_page = download_reddit_url(current_page_url) bs = BeautifulSoup(current_page) all_posts_links = bs.findAll('a', attrs={'class': 'title'}) post_links = [Crawler._make_absolute_url(link['href']) for link in all_posts_links] for post_link in post_links: html = download_reddit_url(post_link) stored_text_file_name = os.path.join(self.storage_dir, b16encode(post_link)) stored_text_file = open(stored_text_file_name, 'w') stored_text_file.write(html.encode('utf8')) stored_text_file.close() next_page_url = bs.find('a', attrs={'rel':'next'})['href'] current_page_url = next_page_url time.sleep(2) print next_page_url
<commit_before>import requests from bs4 import BeautifulSoup def download_url(url): r = requests.get(url) if r.status_code != 200: raise Exception('Non-OK status code: {}'.format(r.status_code)) return r.text def parse_text(html): bs = BeautifulSoup(html, 'html.parser') return bs.select('div.usertext-body')[1].text <commit_msg>Create files with posts and can go to the next page.<commit_after>
import requests from bs4 import BeautifulSoup import os.path from base64 import b16encode import time def download_reddit_url(url): assert url.startswith('https://www.reddit.com/r/learnprogramming') headers = {'User-Agent':'JustSearch bot version 0.1'} r = requests.get(url, headers=headers) if r.status_code != 200: raise Exception('Non-OK status code: {}'.format(r.status_code)) return r.text def parse_reddit_post(html): bs = BeautifulSoup(html, 'html.parser') return bs.select('div.usertext-body')[1].text class Crawler(object): def __init__(self, start_url, storage_dir): self.start_url = start_url self.storage_dir = storage_dir @staticmethod def _make_absolute_url(url): return 'https://www.reddit.com' + url def crawl(self): current_page_url = self.start_url while True: current_page = download_reddit_url(current_page_url) bs = BeautifulSoup(current_page) all_posts_links = bs.findAll('a', attrs={'class': 'title'}) post_links = [Crawler._make_absolute_url(link['href']) for link in all_posts_links] for post_link in post_links: html = download_reddit_url(post_link) stored_text_file_name = os.path.join(self.storage_dir, b16encode(post_link)) stored_text_file = open(stored_text_file_name, 'w') stored_text_file.write(html.encode('utf8')) stored_text_file.close() next_page_url = bs.find('a', attrs={'rel':'next'})['href'] current_page_url = next_page_url time.sleep(2) print next_page_url
import requests from bs4 import BeautifulSoup def download_url(url): r = requests.get(url) if r.status_code != 200: raise Exception('Non-OK status code: {}'.format(r.status_code)) return r.text def parse_text(html): bs = BeautifulSoup(html, 'html.parser') return bs.select('div.usertext-body')[1].text Create files with posts and can go to the next page.import requests from bs4 import BeautifulSoup import os.path from base64 import b16encode import time def download_reddit_url(url): assert url.startswith('https://www.reddit.com/r/learnprogramming') headers = {'User-Agent':'JustSearch bot version 0.1'} r = requests.get(url, headers=headers) if r.status_code != 200: raise Exception('Non-OK status code: {}'.format(r.status_code)) return r.text def parse_reddit_post(html): bs = BeautifulSoup(html, 'html.parser') return bs.select('div.usertext-body')[1].text class Crawler(object): def __init__(self, start_url, storage_dir): self.start_url = start_url self.storage_dir = storage_dir @staticmethod def _make_absolute_url(url): return 'https://www.reddit.com' + url def crawl(self): current_page_url = self.start_url while True: current_page = download_reddit_url(current_page_url) bs = BeautifulSoup(current_page) all_posts_links = bs.findAll('a', attrs={'class': 'title'}) post_links = [Crawler._make_absolute_url(link['href']) for link in all_posts_links] for post_link in post_links: html = download_reddit_url(post_link) stored_text_file_name = os.path.join(self.storage_dir, b16encode(post_link)) stored_text_file = open(stored_text_file_name, 'w') stored_text_file.write(html.encode('utf8')) stored_text_file.close() next_page_url = bs.find('a', attrs={'rel':'next'})['href'] current_page_url = next_page_url time.sleep(2) print next_page_url
<commit_before>import requests from bs4 import BeautifulSoup def download_url(url): r = requests.get(url) if r.status_code != 200: raise Exception('Non-OK status code: {}'.format(r.status_code)) return r.text def parse_text(html): bs = BeautifulSoup(html, 'html.parser') return bs.select('div.usertext-body')[1].text <commit_msg>Create files with posts and can go to the next page.<commit_after>import requests from bs4 import BeautifulSoup import os.path from base64 import b16encode import time def download_reddit_url(url): assert url.startswith('https://www.reddit.com/r/learnprogramming') headers = {'User-Agent':'JustSearch bot version 0.1'} r = requests.get(url, headers=headers) if r.status_code != 200: raise Exception('Non-OK status code: {}'.format(r.status_code)) return r.text def parse_reddit_post(html): bs = BeautifulSoup(html, 'html.parser') return bs.select('div.usertext-body')[1].text class Crawler(object): def __init__(self, start_url, storage_dir): self.start_url = start_url self.storage_dir = storage_dir @staticmethod def _make_absolute_url(url): return 'https://www.reddit.com' + url def crawl(self): current_page_url = self.start_url while True: current_page = download_reddit_url(current_page_url) bs = BeautifulSoup(current_page) all_posts_links = bs.findAll('a', attrs={'class': 'title'}) post_links = [Crawler._make_absolute_url(link['href']) for link in all_posts_links] for post_link in post_links: html = download_reddit_url(post_link) stored_text_file_name = os.path.join(self.storage_dir, b16encode(post_link)) stored_text_file = open(stored_text_file_name, 'w') stored_text_file.write(html.encode('utf8')) stored_text_file.close() next_page_url = bs.find('a', attrs={'rel':'next'})['href'] current_page_url = next_page_url time.sleep(2) print next_page_url
f4c1837eaadc9dfd2510e64d8dc7838ccc884379
python/servo/packages.py
python/servo/packages.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at https://mozilla.org/MPL/2.0/. WINDOWS_MSVC = { "cmake": "3.14.3", "llvm": "8.0.0", "moztools": "3.2", "ninja": "1.7.1", "nuget": "08-08-2019", "openssl": "111.3.0+1.1.1c-vs2017-2019-09-18", "gstreamer-uwp": "1.16.0.5", "openxr-loader-uwp": "1.0", "xargo": "v0.3.17", }
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at https://mozilla.org/MPL/2.0/. WINDOWS_MSVC = { "cmake": "3.14.3", "llvm": "8.0.1", "moztools": "3.2", "ninja": "1.7.1", "nuget": "08-08-2019", "openssl": "111.3.0+1.1.1c-vs2017-2019-09-18", "gstreamer-uwp": "1.16.0.5", "openxr-loader-uwp": "1.0", "xargo": "v0.3.17", }
Update windows llvm to 8.0.1.
Update windows llvm to 8.0.1.
Python
mpl-2.0
KiChjang/servo,KiChjang/servo,splav/servo,KiChjang/servo,KiChjang/servo,splav/servo,splav/servo,KiChjang/servo,splav/servo,KiChjang/servo,splav/servo,splav/servo,KiChjang/servo,splav/servo,splav/servo,KiChjang/servo,KiChjang/servo,KiChjang/servo,splav/servo,splav/servo
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at https://mozilla.org/MPL/2.0/. WINDOWS_MSVC = { "cmake": "3.14.3", "llvm": "8.0.0", "moztools": "3.2", "ninja": "1.7.1", "nuget": "08-08-2019", "openssl": "111.3.0+1.1.1c-vs2017-2019-09-18", "gstreamer-uwp": "1.16.0.5", "openxr-loader-uwp": "1.0", "xargo": "v0.3.17", } Update windows llvm to 8.0.1.
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at https://mozilla.org/MPL/2.0/. WINDOWS_MSVC = { "cmake": "3.14.3", "llvm": "8.0.1", "moztools": "3.2", "ninja": "1.7.1", "nuget": "08-08-2019", "openssl": "111.3.0+1.1.1c-vs2017-2019-09-18", "gstreamer-uwp": "1.16.0.5", "openxr-loader-uwp": "1.0", "xargo": "v0.3.17", }
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at https://mozilla.org/MPL/2.0/. WINDOWS_MSVC = { "cmake": "3.14.3", "llvm": "8.0.0", "moztools": "3.2", "ninja": "1.7.1", "nuget": "08-08-2019", "openssl": "111.3.0+1.1.1c-vs2017-2019-09-18", "gstreamer-uwp": "1.16.0.5", "openxr-loader-uwp": "1.0", "xargo": "v0.3.17", } <commit_msg>Update windows llvm to 8.0.1.<commit_after>
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at https://mozilla.org/MPL/2.0/. WINDOWS_MSVC = { "cmake": "3.14.3", "llvm": "8.0.1", "moztools": "3.2", "ninja": "1.7.1", "nuget": "08-08-2019", "openssl": "111.3.0+1.1.1c-vs2017-2019-09-18", "gstreamer-uwp": "1.16.0.5", "openxr-loader-uwp": "1.0", "xargo": "v0.3.17", }
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at https://mozilla.org/MPL/2.0/. WINDOWS_MSVC = { "cmake": "3.14.3", "llvm": "8.0.0", "moztools": "3.2", "ninja": "1.7.1", "nuget": "08-08-2019", "openssl": "111.3.0+1.1.1c-vs2017-2019-09-18", "gstreamer-uwp": "1.16.0.5", "openxr-loader-uwp": "1.0", "xargo": "v0.3.17", } Update windows llvm to 8.0.1.# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at https://mozilla.org/MPL/2.0/. WINDOWS_MSVC = { "cmake": "3.14.3", "llvm": "8.0.1", "moztools": "3.2", "ninja": "1.7.1", "nuget": "08-08-2019", "openssl": "111.3.0+1.1.1c-vs2017-2019-09-18", "gstreamer-uwp": "1.16.0.5", "openxr-loader-uwp": "1.0", "xargo": "v0.3.17", }
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at https://mozilla.org/MPL/2.0/. WINDOWS_MSVC = { "cmake": "3.14.3", "llvm": "8.0.0", "moztools": "3.2", "ninja": "1.7.1", "nuget": "08-08-2019", "openssl": "111.3.0+1.1.1c-vs2017-2019-09-18", "gstreamer-uwp": "1.16.0.5", "openxr-loader-uwp": "1.0", "xargo": "v0.3.17", } <commit_msg>Update windows llvm to 8.0.1.<commit_after># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at https://mozilla.org/MPL/2.0/. WINDOWS_MSVC = { "cmake": "3.14.3", "llvm": "8.0.1", "moztools": "3.2", "ninja": "1.7.1", "nuget": "08-08-2019", "openssl": "111.3.0+1.1.1c-vs2017-2019-09-18", "gstreamer-uwp": "1.16.0.5", "openxr-loader-uwp": "1.0", "xargo": "v0.3.17", }
73a96c3ddcf19df6534ae9dd57bcdca8d28ec615
registration/__init__.py
registration/__init__.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
Add reminder to myself to to importlib fallback.
Add reminder to myself to to importlib fallback.
Python
bsd-3-clause
lubosz/django-registration,lubosz/django-registration
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class() Add reminder to myself to to importlib fallback.
from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
<commit_before>from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class() <commit_msg>Add reminder to myself to to importlib fallback.<commit_after>
from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class() Add reminder to myself to to importlib fallback.from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
<commit_before>from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class() <commit_msg>Add reminder to myself to to importlib fallback.<commit_after>from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
f2294b289b6eaa9c103f667dd3252429aac360e1
tools/miranda/miranda_parser.py
tools/miranda/miranda_parser.py
import sys # get hits from miranda scans cap = "" with open (sys.argv[1]) as infile1: for line1 in infile1: line1 = line1.strip() if "%" in line1 and "Forward:" not in line1: #print(line1) cap = cap + line1 + "\n" allregnettf = open(sys.argv[2], "w") allregnettf.write(cap) allregnettf.close()
import sys # get hits from miranda scans with open(sys.argv[1]) as infile1: with open(sys.argv[2], "w") as outfile: for line1 in infile1: if "%" in line1 and "Forward:" not in line1: outfile.write(line1)
Write output on the file.
Write output on the file.
Python
mit
anilthanki/tgac-galaxytools,TGAC/earlham-galaxytools,anilthanki/tgac-galaxytools,TGAC/earlham-galaxytools,TGAC/earlham-galaxytools,TGAC/earlham-galaxytools,TGAC/tgac-galaxytools,PerlaTroncosoRey/tgac-galaxytools,wjurkowski/earlham-galaxytools,TGAC/tgac-galaxytools,anilthanki/tgac-galaxytools,anilthanki/tgac-galaxytools,anilthanki/tgac-galaxytools,TGAC/earlham-galaxytools
import sys # get hits from miranda scans cap = "" with open (sys.argv[1]) as infile1: for line1 in infile1: line1 = line1.strip() if "%" in line1 and "Forward:" not in line1: #print(line1) cap = cap + line1 + "\n" allregnettf = open(sys.argv[2], "w") allregnettf.write(cap) allregnettf.close() Write output on the file.
import sys # get hits from miranda scans with open(sys.argv[1]) as infile1: with open(sys.argv[2], "w") as outfile: for line1 in infile1: if "%" in line1 and "Forward:" not in line1: outfile.write(line1)
<commit_before>import sys # get hits from miranda scans cap = "" with open (sys.argv[1]) as infile1: for line1 in infile1: line1 = line1.strip() if "%" in line1 and "Forward:" not in line1: #print(line1) cap = cap + line1 + "\n" allregnettf = open(sys.argv[2], "w") allregnettf.write(cap) allregnettf.close() <commit_msg>Write output on the file.<commit_after>
import sys # get hits from miranda scans with open(sys.argv[1]) as infile1: with open(sys.argv[2], "w") as outfile: for line1 in infile1: if "%" in line1 and "Forward:" not in line1: outfile.write(line1)
import sys # get hits from miranda scans cap = "" with open (sys.argv[1]) as infile1: for line1 in infile1: line1 = line1.strip() if "%" in line1 and "Forward:" not in line1: #print(line1) cap = cap + line1 + "\n" allregnettf = open(sys.argv[2], "w") allregnettf.write(cap) allregnettf.close() Write output on the file.import sys # get hits from miranda scans with open(sys.argv[1]) as infile1: with open(sys.argv[2], "w") as outfile: for line1 in infile1: if "%" in line1 and "Forward:" not in line1: outfile.write(line1)
<commit_before>import sys # get hits from miranda scans cap = "" with open (sys.argv[1]) as infile1: for line1 in infile1: line1 = line1.strip() if "%" in line1 and "Forward:" not in line1: #print(line1) cap = cap + line1 + "\n" allregnettf = open(sys.argv[2], "w") allregnettf.write(cap) allregnettf.close() <commit_msg>Write output on the file.<commit_after>import sys # get hits from miranda scans with open(sys.argv[1]) as infile1: with open(sys.argv[2], "w") as outfile: for line1 in infile1: if "%" in line1 and "Forward:" not in line1: outfile.write(line1)
d70e563c3119e59de2ae23a77724e0fd803b768b
Python/tests.py
Python/tests.py
import unittest from BKKCrypt import BKKCrypt import urllib.request class TestEncodeStrings(unittest.TestCase): def test_simple_strings(self): self.assertEqual(BKKCrypt('adminadmin'), 'adminadmin') self.assertEqual(BKKCrypt('hunter2'), 'hunter2') self.assertEqual(BKKCrypt('password'), 'password') def test_PIN_numbers(self): self.assertEqual(BKKCrypt(1234), 1234) self.assertEqual(BKKCrypt('1234'), '1234') self.assertEqual(BKKCrypt(6969), 6969) self.assertEqual(BKKCrypt('6969'), '6969') def test_empty_passwords(self): self.assertEqual(BKKCrypt(''), '') class TestBLNS(unittest.TestCase): """Test strings from https://github.com/minimaxir/big-list-of-naughty-strings/""" blns_request = urllib.request.urlretrieve("https://raw.githubusercontent.com/minimaxir/big-list-of-naughty-strings/master/blns.txt") with open(blns_request[0]) as blns_file: blns = blns_file.readlines() def test_blns_lines(self): for line in self.blns: with self.subTest(line=line): self.assertEqual(BKKCrypt(line), line) if __name__ == '__main__': unittest.main()
import unittest from BKKCrypt import BKKCrypt import urllib.request class TestEncodeStrings(unittest.TestCase): def test_simple_strings(self): self.assertEqual(BKKCrypt('adminadmin'), 'adminadmin') self.assertEqual(BKKCrypt('hunter2'), 'hunter2') self.assertEqual(BKKCrypt('password'), 'password') def test_PIN_numbers(self): self.assertEqual(BKKCrypt(1234), 1234) self.assertEqual(BKKCrypt('1234'), '1234') self.assertEqual(BKKCrypt(6969), 6969) self.assertEqual(BKKCrypt('6969'), '6969') def test_empty_passwords(self): self.assertEqual(BKKCrypt(''), '') class TestBLNS(unittest.TestCase): """Test strings from https://github.com/minimaxir/big-list-of-naughty-strings/""" blns_request = urllib.request.urlretrieve("https://raw.githubusercontent.com/minimaxir/big-list-of-naughty-strings/master/blns.txt") with open(blns_request[0]) as blns_file: blns = blns_file.readlines() blns = list(map(lambda x: x.strip(), blns)) def test_blns_lines(self): for line in self.blns: with self.subTest(line=line): self.assertEqual(BKKCrypt(line), line) if __name__ == '__main__': unittest.main()
Remove trailing newlines from test cases
Remove trailing newlines from test cases
Python
mit
moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt
import unittest from BKKCrypt import BKKCrypt import urllib.request class TestEncodeStrings(unittest.TestCase): def test_simple_strings(self): self.assertEqual(BKKCrypt('adminadmin'), 'adminadmin') self.assertEqual(BKKCrypt('hunter2'), 'hunter2') self.assertEqual(BKKCrypt('password'), 'password') def test_PIN_numbers(self): self.assertEqual(BKKCrypt(1234), 1234) self.assertEqual(BKKCrypt('1234'), '1234') self.assertEqual(BKKCrypt(6969), 6969) self.assertEqual(BKKCrypt('6969'), '6969') def test_empty_passwords(self): self.assertEqual(BKKCrypt(''), '') class TestBLNS(unittest.TestCase): """Test strings from https://github.com/minimaxir/big-list-of-naughty-strings/""" blns_request = urllib.request.urlretrieve("https://raw.githubusercontent.com/minimaxir/big-list-of-naughty-strings/master/blns.txt") with open(blns_request[0]) as blns_file: blns = blns_file.readlines() def test_blns_lines(self): for line in self.blns: with self.subTest(line=line): self.assertEqual(BKKCrypt(line), line) if __name__ == '__main__': unittest.main() Remove trailing newlines from test cases
import unittest from BKKCrypt import BKKCrypt import urllib.request class TestEncodeStrings(unittest.TestCase): def test_simple_strings(self): self.assertEqual(BKKCrypt('adminadmin'), 'adminadmin') self.assertEqual(BKKCrypt('hunter2'), 'hunter2') self.assertEqual(BKKCrypt('password'), 'password') def test_PIN_numbers(self): self.assertEqual(BKKCrypt(1234), 1234) self.assertEqual(BKKCrypt('1234'), '1234') self.assertEqual(BKKCrypt(6969), 6969) self.assertEqual(BKKCrypt('6969'), '6969') def test_empty_passwords(self): self.assertEqual(BKKCrypt(''), '') class TestBLNS(unittest.TestCase): """Test strings from https://github.com/minimaxir/big-list-of-naughty-strings/""" blns_request = urllib.request.urlretrieve("https://raw.githubusercontent.com/minimaxir/big-list-of-naughty-strings/master/blns.txt") with open(blns_request[0]) as blns_file: blns = blns_file.readlines() blns = list(map(lambda x: x.strip(), blns)) def test_blns_lines(self): for line in self.blns: with self.subTest(line=line): self.assertEqual(BKKCrypt(line), line) if __name__ == '__main__': unittest.main()
<commit_before>import unittest from BKKCrypt import BKKCrypt import urllib.request class TestEncodeStrings(unittest.TestCase): def test_simple_strings(self): self.assertEqual(BKKCrypt('adminadmin'), 'adminadmin') self.assertEqual(BKKCrypt('hunter2'), 'hunter2') self.assertEqual(BKKCrypt('password'), 'password') def test_PIN_numbers(self): self.assertEqual(BKKCrypt(1234), 1234) self.assertEqual(BKKCrypt('1234'), '1234') self.assertEqual(BKKCrypt(6969), 6969) self.assertEqual(BKKCrypt('6969'), '6969') def test_empty_passwords(self): self.assertEqual(BKKCrypt(''), '') class TestBLNS(unittest.TestCase): """Test strings from https://github.com/minimaxir/big-list-of-naughty-strings/""" blns_request = urllib.request.urlretrieve("https://raw.githubusercontent.com/minimaxir/big-list-of-naughty-strings/master/blns.txt") with open(blns_request[0]) as blns_file: blns = blns_file.readlines() def test_blns_lines(self): for line in self.blns: with self.subTest(line=line): self.assertEqual(BKKCrypt(line), line) if __name__ == '__main__': unittest.main() <commit_msg>Remove trailing newlines from test cases<commit_after>
import unittest from BKKCrypt import BKKCrypt import urllib.request class TestEncodeStrings(unittest.TestCase): def test_simple_strings(self): self.assertEqual(BKKCrypt('adminadmin'), 'adminadmin') self.assertEqual(BKKCrypt('hunter2'), 'hunter2') self.assertEqual(BKKCrypt('password'), 'password') def test_PIN_numbers(self): self.assertEqual(BKKCrypt(1234), 1234) self.assertEqual(BKKCrypt('1234'), '1234') self.assertEqual(BKKCrypt(6969), 6969) self.assertEqual(BKKCrypt('6969'), '6969') def test_empty_passwords(self): self.assertEqual(BKKCrypt(''), '') class TestBLNS(unittest.TestCase): """Test strings from https://github.com/minimaxir/big-list-of-naughty-strings/""" blns_request = urllib.request.urlretrieve("https://raw.githubusercontent.com/minimaxir/big-list-of-naughty-strings/master/blns.txt") with open(blns_request[0]) as blns_file: blns = blns_file.readlines() blns = list(map(lambda x: x.strip(), blns)) def test_blns_lines(self): for line in self.blns: with self.subTest(line=line): self.assertEqual(BKKCrypt(line), line) if __name__ == '__main__': unittest.main()
import unittest from BKKCrypt import BKKCrypt import urllib.request class TestEncodeStrings(unittest.TestCase): def test_simple_strings(self): self.assertEqual(BKKCrypt('adminadmin'), 'adminadmin') self.assertEqual(BKKCrypt('hunter2'), 'hunter2') self.assertEqual(BKKCrypt('password'), 'password') def test_PIN_numbers(self): self.assertEqual(BKKCrypt(1234), 1234) self.assertEqual(BKKCrypt('1234'), '1234') self.assertEqual(BKKCrypt(6969), 6969) self.assertEqual(BKKCrypt('6969'), '6969') def test_empty_passwords(self): self.assertEqual(BKKCrypt(''), '') class TestBLNS(unittest.TestCase): """Test strings from https://github.com/minimaxir/big-list-of-naughty-strings/""" blns_request = urllib.request.urlretrieve("https://raw.githubusercontent.com/minimaxir/big-list-of-naughty-strings/master/blns.txt") with open(blns_request[0]) as blns_file: blns = blns_file.readlines() def test_blns_lines(self): for line in self.blns: with self.subTest(line=line): self.assertEqual(BKKCrypt(line), line) if __name__ == '__main__': unittest.main() Remove trailing newlines from test casesimport unittest from BKKCrypt import BKKCrypt import urllib.request class TestEncodeStrings(unittest.TestCase): def test_simple_strings(self): self.assertEqual(BKKCrypt('adminadmin'), 'adminadmin') self.assertEqual(BKKCrypt('hunter2'), 'hunter2') self.assertEqual(BKKCrypt('password'), 'password') def test_PIN_numbers(self): self.assertEqual(BKKCrypt(1234), 1234) self.assertEqual(BKKCrypt('1234'), '1234') self.assertEqual(BKKCrypt(6969), 6969) self.assertEqual(BKKCrypt('6969'), '6969') def test_empty_passwords(self): self.assertEqual(BKKCrypt(''), '') class TestBLNS(unittest.TestCase): """Test strings from https://github.com/minimaxir/big-list-of-naughty-strings/""" blns_request = urllib.request.urlretrieve("https://raw.githubusercontent.com/minimaxir/big-list-of-naughty-strings/master/blns.txt") with open(blns_request[0]) as blns_file: blns = blns_file.readlines() blns = list(map(lambda x: x.strip(), blns)) def test_blns_lines(self): for line in self.blns: with self.subTest(line=line): self.assertEqual(BKKCrypt(line), line) if __name__ == '__main__': unittest.main()
<commit_before>import unittest from BKKCrypt import BKKCrypt import urllib.request class TestEncodeStrings(unittest.TestCase): def test_simple_strings(self): self.assertEqual(BKKCrypt('adminadmin'), 'adminadmin') self.assertEqual(BKKCrypt('hunter2'), 'hunter2') self.assertEqual(BKKCrypt('password'), 'password') def test_PIN_numbers(self): self.assertEqual(BKKCrypt(1234), 1234) self.assertEqual(BKKCrypt('1234'), '1234') self.assertEqual(BKKCrypt(6969), 6969) self.assertEqual(BKKCrypt('6969'), '6969') def test_empty_passwords(self): self.assertEqual(BKKCrypt(''), '') class TestBLNS(unittest.TestCase): """Test strings from https://github.com/minimaxir/big-list-of-naughty-strings/""" blns_request = urllib.request.urlretrieve("https://raw.githubusercontent.com/minimaxir/big-list-of-naughty-strings/master/blns.txt") with open(blns_request[0]) as blns_file: blns = blns_file.readlines() def test_blns_lines(self): for line in self.blns: with self.subTest(line=line): self.assertEqual(BKKCrypt(line), line) if __name__ == '__main__': unittest.main() <commit_msg>Remove trailing newlines from test cases<commit_after>import unittest from BKKCrypt import BKKCrypt import urllib.request class TestEncodeStrings(unittest.TestCase): def test_simple_strings(self): self.assertEqual(BKKCrypt('adminadmin'), 'adminadmin') self.assertEqual(BKKCrypt('hunter2'), 'hunter2') self.assertEqual(BKKCrypt('password'), 'password') def test_PIN_numbers(self): self.assertEqual(BKKCrypt(1234), 1234) self.assertEqual(BKKCrypt('1234'), '1234') self.assertEqual(BKKCrypt(6969), 6969) self.assertEqual(BKKCrypt('6969'), '6969') def test_empty_passwords(self): self.assertEqual(BKKCrypt(''), '') class TestBLNS(unittest.TestCase): """Test strings from https://github.com/minimaxir/big-list-of-naughty-strings/""" blns_request = urllib.request.urlretrieve("https://raw.githubusercontent.com/minimaxir/big-list-of-naughty-strings/master/blns.txt") with open(blns_request[0]) as blns_file: blns = blns_file.readlines() blns = list(map(lambda x: x.strip(), blns)) def test_blns_lines(self): for line in self.blns: with self.subTest(line=line): self.assertEqual(BKKCrypt(line), line) if __name__ == '__main__': unittest.main()
819b968a3bb73c1e8fed1a9c5440c8122a6dec9e
plugin/core/logging.py
plugin/core/logging.py
import traceback from .settings import settings, PLUGIN_NAME def debug(*args): """Print args to the console if the "debug" setting is True.""" if settings.log_debug: printf(*args) def exception_log(message, ex): print(message) ex_traceback = ex.__traceback__ print(''.join(traceback.format_exception(ex.__class__, ex, ex_traceback))) def server_log(binary, *args): printf(*args, prefix=binary) def printf(*args, prefix=PLUGIN_NAME): """Print args to the console, prefixed by the plugin name.""" print(prefix + ":", *args)
import traceback from .settings import settings, PLUGIN_NAME def debug(*args): """Print args to the console if the "debug" setting is True.""" if settings.log_debug: printf(*args) def exception_log(message, ex): print(message) ex_traceback = ex.__traceback__ print(''.join(traceback.format_exception(ex.__class__, ex, ex_traceback))) def server_log(*args): printf(*args, prefix="server") def printf(*args, prefix=PLUGIN_NAME): """Print args to the console, prefixed by the plugin name.""" print(prefix + ":", *args)
Replace binary argument with hardcoded text "server"
Replace binary argument with hardcoded text "server"
Python
mit
tomv564/LSP
import traceback from .settings import settings, PLUGIN_NAME def debug(*args): """Print args to the console if the "debug" setting is True.""" if settings.log_debug: printf(*args) def exception_log(message, ex): print(message) ex_traceback = ex.__traceback__ print(''.join(traceback.format_exception(ex.__class__, ex, ex_traceback))) def server_log(binary, *args): printf(*args, prefix=binary) def printf(*args, prefix=PLUGIN_NAME): """Print args to the console, prefixed by the plugin name.""" print(prefix + ":", *args) Replace binary argument with hardcoded text "server"
import traceback from .settings import settings, PLUGIN_NAME def debug(*args): """Print args to the console if the "debug" setting is True.""" if settings.log_debug: printf(*args) def exception_log(message, ex): print(message) ex_traceback = ex.__traceback__ print(''.join(traceback.format_exception(ex.__class__, ex, ex_traceback))) def server_log(*args): printf(*args, prefix="server") def printf(*args, prefix=PLUGIN_NAME): """Print args to the console, prefixed by the plugin name.""" print(prefix + ":", *args)
<commit_before>import traceback from .settings import settings, PLUGIN_NAME def debug(*args): """Print args to the console if the "debug" setting is True.""" if settings.log_debug: printf(*args) def exception_log(message, ex): print(message) ex_traceback = ex.__traceback__ print(''.join(traceback.format_exception(ex.__class__, ex, ex_traceback))) def server_log(binary, *args): printf(*args, prefix=binary) def printf(*args, prefix=PLUGIN_NAME): """Print args to the console, prefixed by the plugin name.""" print(prefix + ":", *args) <commit_msg>Replace binary argument with hardcoded text "server"<commit_after>
import traceback from .settings import settings, PLUGIN_NAME def debug(*args): """Print args to the console if the "debug" setting is True.""" if settings.log_debug: printf(*args) def exception_log(message, ex): print(message) ex_traceback = ex.__traceback__ print(''.join(traceback.format_exception(ex.__class__, ex, ex_traceback))) def server_log(*args): printf(*args, prefix="server") def printf(*args, prefix=PLUGIN_NAME): """Print args to the console, prefixed by the plugin name.""" print(prefix + ":", *args)
import traceback from .settings import settings, PLUGIN_NAME def debug(*args): """Print args to the console if the "debug" setting is True.""" if settings.log_debug: printf(*args) def exception_log(message, ex): print(message) ex_traceback = ex.__traceback__ print(''.join(traceback.format_exception(ex.__class__, ex, ex_traceback))) def server_log(binary, *args): printf(*args, prefix=binary) def printf(*args, prefix=PLUGIN_NAME): """Print args to the console, prefixed by the plugin name.""" print(prefix + ":", *args) Replace binary argument with hardcoded text "server"import traceback from .settings import settings, PLUGIN_NAME def debug(*args): """Print args to the console if the "debug" setting is True.""" if settings.log_debug: printf(*args) def exception_log(message, ex): print(message) ex_traceback = ex.__traceback__ print(''.join(traceback.format_exception(ex.__class__, ex, ex_traceback))) def server_log(*args): printf(*args, prefix="server") def printf(*args, prefix=PLUGIN_NAME): """Print args to the console, prefixed by the plugin name.""" print(prefix + ":", *args)
<commit_before>import traceback from .settings import settings, PLUGIN_NAME def debug(*args): """Print args to the console if the "debug" setting is True.""" if settings.log_debug: printf(*args) def exception_log(message, ex): print(message) ex_traceback = ex.__traceback__ print(''.join(traceback.format_exception(ex.__class__, ex, ex_traceback))) def server_log(binary, *args): printf(*args, prefix=binary) def printf(*args, prefix=PLUGIN_NAME): """Print args to the console, prefixed by the plugin name.""" print(prefix + ":", *args) <commit_msg>Replace binary argument with hardcoded text "server"<commit_after>import traceback from .settings import settings, PLUGIN_NAME def debug(*args): """Print args to the console if the "debug" setting is True.""" if settings.log_debug: printf(*args) def exception_log(message, ex): print(message) ex_traceback = ex.__traceback__ print(''.join(traceback.format_exception(ex.__class__, ex, ex_traceback))) def server_log(*args): printf(*args, prefix="server") def printf(*args, prefix=PLUGIN_NAME): """Print args to the console, prefixed by the plugin name.""" print(prefix + ":", *args)
45542f012b3dc6d089bc991529523a4ea6401b35
br_rss/boilerroomtv/management/commands/scrape_all.py
br_rss/boilerroomtv/management/commands/scrape_all.py
from django.core.management.base import BaseCommand from boilerroomtv.tasks import scrape_genres, scrape_all_recordings, scrape_channels class Command(BaseCommand): def handle(self, *args, **options): scrape_genres() scrape_all_recordings() scrape_channels()
from django.core.management.base import BaseCommand from ...tasks import scrape_genres, scrape_all_recordings, scrape_channels class Command(BaseCommand): def handle(self, *args, **options): scrape_genres() scrape_all_recordings() scrape_channels()
Use relative import in command.
Use relative import in command.
Python
mpl-2.0
jeffbr13/br-rss,jeffbr13/br-rss
from django.core.management.base import BaseCommand from boilerroomtv.tasks import scrape_genres, scrape_all_recordings, scrape_channels class Command(BaseCommand): def handle(self, *args, **options): scrape_genres() scrape_all_recordings() scrape_channels() Use relative import in command.
from django.core.management.base import BaseCommand from ...tasks import scrape_genres, scrape_all_recordings, scrape_channels class Command(BaseCommand): def handle(self, *args, **options): scrape_genres() scrape_all_recordings() scrape_channels()
<commit_before>from django.core.management.base import BaseCommand from boilerroomtv.tasks import scrape_genres, scrape_all_recordings, scrape_channels class Command(BaseCommand): def handle(self, *args, **options): scrape_genres() scrape_all_recordings() scrape_channels() <commit_msg>Use relative import in command.<commit_after>
from django.core.management.base import BaseCommand from ...tasks import scrape_genres, scrape_all_recordings, scrape_channels class Command(BaseCommand): def handle(self, *args, **options): scrape_genres() scrape_all_recordings() scrape_channels()
from django.core.management.base import BaseCommand from boilerroomtv.tasks import scrape_genres, scrape_all_recordings, scrape_channels class Command(BaseCommand): def handle(self, *args, **options): scrape_genres() scrape_all_recordings() scrape_channels() Use relative import in command.from django.core.management.base import BaseCommand from ...tasks import scrape_genres, scrape_all_recordings, scrape_channels class Command(BaseCommand): def handle(self, *args, **options): scrape_genres() scrape_all_recordings() scrape_channels()
<commit_before>from django.core.management.base import BaseCommand from boilerroomtv.tasks import scrape_genres, scrape_all_recordings, scrape_channels class Command(BaseCommand): def handle(self, *args, **options): scrape_genres() scrape_all_recordings() scrape_channels() <commit_msg>Use relative import in command.<commit_after>from django.core.management.base import BaseCommand from ...tasks import scrape_genres, scrape_all_recordings, scrape_channels class Command(BaseCommand): def handle(self, *args, **options): scrape_genres() scrape_all_recordings() scrape_channels()
d3f0d83b0c783d2f15a6f5eaf6fd4ace426307a6
tests/__init__.py
tests/__init__.py
import os import sys import unittest def suite(): MODULE_DIR = os.path.join(os.path.dirname(__file__), '..') MODULE_DIR = os.path.abspath(MODULE_DIR) sys.path.insert(0, MODULE_DIR) sys.path.insert(0, os.path.dirname(__file__)) SUB_UNITS = os.path.dirname(__file__) SUB_UNITS = os.listdir(SUB_UNITS) SUB_UNITS = [ filename[:-3] for filename in SUB_UNITS if filename.startswith('test_') ] os.chdir(os.path.dirname(__file__)) loader = unittest.TestLoader() return loader.loadTestsFromNames(SUB_UNITS)
from os import walk, chdir from os.path import join, dirname, splitext, abspath, relpath import sys import unittest MODULE_DIR = join(dirname(__file__), '..') MODULE_DIR = abspath(MODULE_DIR) def walker(opath='.'): for path, folders, files in walk(opath): for filename in files: if filename.startswith('test_') and filename.endswith('.py'): rpath = relpath(path, opath) yield (rpath + '.' + splitext(filename)[0]).strip('.') def suite(): sys.path.insert(0, MODULE_DIR) sys.path.insert(0, dirname(__file__)) SUB_UNITS = dirname(__file__) SUB_UNITS = walker(SUB_UNITS) chdir(dirname(__file__)) return unittest.TestLoader().loadTestsFromNames(SUB_UNITS)
Rework for tests in subdirectories
Rework for tests in subdirectories
Python
mit
Mause/pytransperth,Mause/pytransperth
import os import sys import unittest def suite(): MODULE_DIR = os.path.join(os.path.dirname(__file__), '..') MODULE_DIR = os.path.abspath(MODULE_DIR) sys.path.insert(0, MODULE_DIR) sys.path.insert(0, os.path.dirname(__file__)) SUB_UNITS = os.path.dirname(__file__) SUB_UNITS = os.listdir(SUB_UNITS) SUB_UNITS = [ filename[:-3] for filename in SUB_UNITS if filename.startswith('test_') ] os.chdir(os.path.dirname(__file__)) loader = unittest.TestLoader() return loader.loadTestsFromNames(SUB_UNITS) Rework for tests in subdirectories
from os import walk, chdir from os.path import join, dirname, splitext, abspath, relpath import sys import unittest MODULE_DIR = join(dirname(__file__), '..') MODULE_DIR = abspath(MODULE_DIR) def walker(opath='.'): for path, folders, files in walk(opath): for filename in files: if filename.startswith('test_') and filename.endswith('.py'): rpath = relpath(path, opath) yield (rpath + '.' + splitext(filename)[0]).strip('.') def suite(): sys.path.insert(0, MODULE_DIR) sys.path.insert(0, dirname(__file__)) SUB_UNITS = dirname(__file__) SUB_UNITS = walker(SUB_UNITS) chdir(dirname(__file__)) return unittest.TestLoader().loadTestsFromNames(SUB_UNITS)
<commit_before>import os import sys import unittest def suite(): MODULE_DIR = os.path.join(os.path.dirname(__file__), '..') MODULE_DIR = os.path.abspath(MODULE_DIR) sys.path.insert(0, MODULE_DIR) sys.path.insert(0, os.path.dirname(__file__)) SUB_UNITS = os.path.dirname(__file__) SUB_UNITS = os.listdir(SUB_UNITS) SUB_UNITS = [ filename[:-3] for filename in SUB_UNITS if filename.startswith('test_') ] os.chdir(os.path.dirname(__file__)) loader = unittest.TestLoader() return loader.loadTestsFromNames(SUB_UNITS) <commit_msg>Rework for tests in subdirectories<commit_after>
from os import walk, chdir from os.path import join, dirname, splitext, abspath, relpath import sys import unittest MODULE_DIR = join(dirname(__file__), '..') MODULE_DIR = abspath(MODULE_DIR) def walker(opath='.'): for path, folders, files in walk(opath): for filename in files: if filename.startswith('test_') and filename.endswith('.py'): rpath = relpath(path, opath) yield (rpath + '.' + splitext(filename)[0]).strip('.') def suite(): sys.path.insert(0, MODULE_DIR) sys.path.insert(0, dirname(__file__)) SUB_UNITS = dirname(__file__) SUB_UNITS = walker(SUB_UNITS) chdir(dirname(__file__)) return unittest.TestLoader().loadTestsFromNames(SUB_UNITS)
import os import sys import unittest def suite(): MODULE_DIR = os.path.join(os.path.dirname(__file__), '..') MODULE_DIR = os.path.abspath(MODULE_DIR) sys.path.insert(0, MODULE_DIR) sys.path.insert(0, os.path.dirname(__file__)) SUB_UNITS = os.path.dirname(__file__) SUB_UNITS = os.listdir(SUB_UNITS) SUB_UNITS = [ filename[:-3] for filename in SUB_UNITS if filename.startswith('test_') ] os.chdir(os.path.dirname(__file__)) loader = unittest.TestLoader() return loader.loadTestsFromNames(SUB_UNITS) Rework for tests in subdirectoriesfrom os import walk, chdir from os.path import join, dirname, splitext, abspath, relpath import sys import unittest MODULE_DIR = join(dirname(__file__), '..') MODULE_DIR = abspath(MODULE_DIR) def walker(opath='.'): for path, folders, files in walk(opath): for filename in files: if filename.startswith('test_') and filename.endswith('.py'): rpath = relpath(path, opath) yield (rpath + '.' + splitext(filename)[0]).strip('.') def suite(): sys.path.insert(0, MODULE_DIR) sys.path.insert(0, dirname(__file__)) SUB_UNITS = dirname(__file__) SUB_UNITS = walker(SUB_UNITS) chdir(dirname(__file__)) return unittest.TestLoader().loadTestsFromNames(SUB_UNITS)
<commit_before>import os import sys import unittest def suite(): MODULE_DIR = os.path.join(os.path.dirname(__file__), '..') MODULE_DIR = os.path.abspath(MODULE_DIR) sys.path.insert(0, MODULE_DIR) sys.path.insert(0, os.path.dirname(__file__)) SUB_UNITS = os.path.dirname(__file__) SUB_UNITS = os.listdir(SUB_UNITS) SUB_UNITS = [ filename[:-3] for filename in SUB_UNITS if filename.startswith('test_') ] os.chdir(os.path.dirname(__file__)) loader = unittest.TestLoader() return loader.loadTestsFromNames(SUB_UNITS) <commit_msg>Rework for tests in subdirectories<commit_after>from os import walk, chdir from os.path import join, dirname, splitext, abspath, relpath import sys import unittest MODULE_DIR = join(dirname(__file__), '..') MODULE_DIR = abspath(MODULE_DIR) def walker(opath='.'): for path, folders, files in walk(opath): for filename in files: if filename.startswith('test_') and filename.endswith('.py'): rpath = relpath(path, opath) yield (rpath + '.' + splitext(filename)[0]).strip('.') def suite(): sys.path.insert(0, MODULE_DIR) sys.path.insert(0, dirname(__file__)) SUB_UNITS = dirname(__file__) SUB_UNITS = walker(SUB_UNITS) chdir(dirname(__file__)) return unittest.TestLoader().loadTestsFromNames(SUB_UNITS)
db0ef5f31d82729f654d1d07fa39c1168aa5e5f7
tests/__init__.py
tests/__init__.py
# -*- coding: utf-8 -*- # # (C) Pywikipedia bot team, 2007 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' import os import pywikibot.data.api from pywikibot.data.api import Request as _original_Request from pywikibot.data.api import CachedRequest class TestRequest(CachedRequest): def __init__(self, *args, **kwargs): super(TestRequest, self).__init__(0, *args, **kwargs) def _get_cache_dir(self): path = os.path.join(os.path.split(__file__)[0], 'apicache') self._make_dir(path) return path def _expired(self, dt): return False def submit(self): cached_available = self._load_cache() if not cached_available: print str(self) return super(TestRequest, self).submit() def patch_request(): pywikibot.data.api.Request = TestRequest def unpatch_request(): pywikibot.data.api.Request = _original_Request
# -*- coding: utf-8 -*- # # (C) Pywikipedia bot team, 2007 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' import os import pywikibot.data.api from pywikibot.data.api import Request as _original_Request from pywikibot.data.api import CachedRequest class TestRequest(CachedRequest): def __init__(self, *args, **kwargs): super(TestRequest, self).__init__(0, *args, **kwargs) def _get_cache_dir(self): path = os.path.join(os.path.split(__file__)[0], 'apicache') self._make_dir(path) return path def _expired(self, dt): return False def patch_request(): pywikibot.data.api.Request = TestRequest def unpatch_request(): pywikibot.data.api.Request = _original_Request
Disable printing of API parameters which could leak private info and were generally not useful
Disable printing of API parameters which could leak private info and were generally not useful Change-Id: I8a8a8d10799df4f61e4465fe60b6c7efbefbd962
Python
mit
npdoty/pywikibot,PersianWikipedia/pywikibot-core,trishnaguha/pywikibot-core,jayvdb/pywikibot-core,emijrp/pywikibot-core,wikimedia/pywikibot-core,xZise/pywikibot-core,happy5214/pywikibot-core,hasteur/g13bot_tools_new,jayvdb/pywikibot-core,magul/pywikibot-core,h4ck3rm1k3/pywikibot-core,TridevGuha/pywikibot-core,hasteur/g13bot_tools_new,smalyshev/pywikibot-core,hasteur/g13bot_tools_new,npdoty/pywikibot,Darkdadaah/pywikibot-core,h4ck3rm1k3/pywikibot-core,magul/pywikibot-core,happy5214/pywikibot-core,wikimedia/pywikibot-core,Darkdadaah/pywikibot-core,valhallasw/pywikibot-core,VcamX/pywikibot-core,icyflame/batman,darthbhyrava/pywikibot-local
# -*- coding: utf-8 -*- # # (C) Pywikipedia bot team, 2007 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' import os import pywikibot.data.api from pywikibot.data.api import Request as _original_Request from pywikibot.data.api import CachedRequest class TestRequest(CachedRequest): def __init__(self, *args, **kwargs): super(TestRequest, self).__init__(0, *args, **kwargs) def _get_cache_dir(self): path = os.path.join(os.path.split(__file__)[0], 'apicache') self._make_dir(path) return path def _expired(self, dt): return False def submit(self): cached_available = self._load_cache() if not cached_available: print str(self) return super(TestRequest, self).submit() def patch_request(): pywikibot.data.api.Request = TestRequest def unpatch_request(): pywikibot.data.api.Request = _original_Request Disable printing of API parameters which could leak private info and were generally not useful Change-Id: I8a8a8d10799df4f61e4465fe60b6c7efbefbd962
# -*- coding: utf-8 -*- # # (C) Pywikipedia bot team, 2007 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' import os import pywikibot.data.api from pywikibot.data.api import Request as _original_Request from pywikibot.data.api import CachedRequest class TestRequest(CachedRequest): def __init__(self, *args, **kwargs): super(TestRequest, self).__init__(0, *args, **kwargs) def _get_cache_dir(self): path = os.path.join(os.path.split(__file__)[0], 'apicache') self._make_dir(path) return path def _expired(self, dt): return False def patch_request(): pywikibot.data.api.Request = TestRequest def unpatch_request(): pywikibot.data.api.Request = _original_Request
<commit_before># -*- coding: utf-8 -*- # # (C) Pywikipedia bot team, 2007 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' import os import pywikibot.data.api from pywikibot.data.api import Request as _original_Request from pywikibot.data.api import CachedRequest class TestRequest(CachedRequest): def __init__(self, *args, **kwargs): super(TestRequest, self).__init__(0, *args, **kwargs) def _get_cache_dir(self): path = os.path.join(os.path.split(__file__)[0], 'apicache') self._make_dir(path) return path def _expired(self, dt): return False def submit(self): cached_available = self._load_cache() if not cached_available: print str(self) return super(TestRequest, self).submit() def patch_request(): pywikibot.data.api.Request = TestRequest def unpatch_request(): pywikibot.data.api.Request = _original_Request <commit_msg>Disable printing of API parameters which could leak private info and were generally not useful Change-Id: I8a8a8d10799df4f61e4465fe60b6c7efbefbd962<commit_after>
# -*- coding: utf-8 -*- # # (C) Pywikipedia bot team, 2007 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' import os import pywikibot.data.api from pywikibot.data.api import Request as _original_Request from pywikibot.data.api import CachedRequest class TestRequest(CachedRequest): def __init__(self, *args, **kwargs): super(TestRequest, self).__init__(0, *args, **kwargs) def _get_cache_dir(self): path = os.path.join(os.path.split(__file__)[0], 'apicache') self._make_dir(path) return path def _expired(self, dt): return False def patch_request(): pywikibot.data.api.Request = TestRequest def unpatch_request(): pywikibot.data.api.Request = _original_Request
# -*- coding: utf-8 -*- # # (C) Pywikipedia bot team, 2007 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' import os import pywikibot.data.api from pywikibot.data.api import Request as _original_Request from pywikibot.data.api import CachedRequest class TestRequest(CachedRequest): def __init__(self, *args, **kwargs): super(TestRequest, self).__init__(0, *args, **kwargs) def _get_cache_dir(self): path = os.path.join(os.path.split(__file__)[0], 'apicache') self._make_dir(path) return path def _expired(self, dt): return False def submit(self): cached_available = self._load_cache() if not cached_available: print str(self) return super(TestRequest, self).submit() def patch_request(): pywikibot.data.api.Request = TestRequest def unpatch_request(): pywikibot.data.api.Request = _original_Request Disable printing of API parameters which could leak private info and were generally not useful Change-Id: I8a8a8d10799df4f61e4465fe60b6c7efbefbd962# -*- coding: utf-8 -*- # # (C) Pywikipedia bot team, 2007 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' import os import pywikibot.data.api from pywikibot.data.api import Request as _original_Request from pywikibot.data.api import CachedRequest class TestRequest(CachedRequest): def __init__(self, *args, **kwargs): super(TestRequest, self).__init__(0, *args, **kwargs) def _get_cache_dir(self): path = os.path.join(os.path.split(__file__)[0], 'apicache') self._make_dir(path) return path def _expired(self, dt): return False def patch_request(): pywikibot.data.api.Request = TestRequest def unpatch_request(): pywikibot.data.api.Request = _original_Request
<commit_before># -*- coding: utf-8 -*- # # (C) Pywikipedia bot team, 2007 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' import os import pywikibot.data.api from pywikibot.data.api import Request as _original_Request from pywikibot.data.api import CachedRequest class TestRequest(CachedRequest): def __init__(self, *args, **kwargs): super(TestRequest, self).__init__(0, *args, **kwargs) def _get_cache_dir(self): path = os.path.join(os.path.split(__file__)[0], 'apicache') self._make_dir(path) return path def _expired(self, dt): return False def submit(self): cached_available = self._load_cache() if not cached_available: print str(self) return super(TestRequest, self).submit() def patch_request(): pywikibot.data.api.Request = TestRequest def unpatch_request(): pywikibot.data.api.Request = _original_Request <commit_msg>Disable printing of API parameters which could leak private info and were generally not useful Change-Id: I8a8a8d10799df4f61e4465fe60b6c7efbefbd962<commit_after># -*- coding: utf-8 -*- # # (C) Pywikipedia bot team, 2007 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' import os import pywikibot.data.api from pywikibot.data.api import Request as _original_Request from pywikibot.data.api import CachedRequest class TestRequest(CachedRequest): def __init__(self, *args, **kwargs): super(TestRequest, self).__init__(0, *args, **kwargs) def _get_cache_dir(self): path = os.path.join(os.path.split(__file__)[0], 'apicache') self._make_dir(path) return path def _expired(self, dt): return False def patch_request(): pywikibot.data.api.Request = TestRequest def unpatch_request(): pywikibot.data.api.Request = _original_Request
96776b33fcf2ebbd2de4748c38d8be9c63fdec71
tests/conftest.py
tests/conftest.py
from django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test' } }, INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'rest_framework', 'tests', ] ) try: from django import setup except ImportError: call_command('syncdb', '--noinput') else: setup() call_command('migrate')
from django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test' } }, INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'rest_framework', 'tests', ] ) try: from django import setup except ImportError: call_command('syncdb', interactive=False) else: setup() call_command('migrate')
Replace --noinput with interactive=False in syncdb command call
Replace --noinput with interactive=False in syncdb command call
Python
bsd-2-clause
yprez/django-rest-assured,pombredanne/django-rest-assured,ydaniv/django-rest-assured
from django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test' } }, INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'rest_framework', 'tests', ] ) try: from django import setup except ImportError: call_command('syncdb', '--noinput') else: setup() call_command('migrate') Replace --noinput with interactive=False in syncdb command call
from django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test' } }, INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'rest_framework', 'tests', ] ) try: from django import setup except ImportError: call_command('syncdb', interactive=False) else: setup() call_command('migrate')
<commit_before>from django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test' } }, INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'rest_framework', 'tests', ] ) try: from django import setup except ImportError: call_command('syncdb', '--noinput') else: setup() call_command('migrate') <commit_msg>Replace --noinput with interactive=False in syncdb command call<commit_after>
from django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test' } }, INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'rest_framework', 'tests', ] ) try: from django import setup except ImportError: call_command('syncdb', interactive=False) else: setup() call_command('migrate')
from django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test' } }, INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'rest_framework', 'tests', ] ) try: from django import setup except ImportError: call_command('syncdb', '--noinput') else: setup() call_command('migrate') Replace --noinput with interactive=False in syncdb command callfrom django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test' } }, INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'rest_framework', 'tests', ] ) try: from django import setup except ImportError: call_command('syncdb', interactive=False) else: setup() call_command('migrate')
<commit_before>from django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test' } }, INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'rest_framework', 'tests', ] ) try: from django import setup except ImportError: call_command('syncdb', '--noinput') else: setup() call_command('migrate') <commit_msg>Replace --noinput with interactive=False in syncdb command call<commit_after>from django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test' } }, INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'rest_framework', 'tests', ] ) try: from django import setup except ImportError: call_command('syncdb', interactive=False) else: setup() call_command('migrate')
40711cb50189c4c39ed5a60c16910646a00f9acc
docker/types/daemon.py
docker/types/daemon.py
import socket try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 class CancellableStream(object): """ Stream wrapper for real-time events, logs, etc. from the server. Example: >>> events = client.events() >>> for event in events: ... print event >>> # and cancel from another thread >>> events.close() """ def __init__(self, stream, response): self._stream = stream self._response = response def __iter__(self): return self def __next__(self): try: return next(self._stream) except urllib3.exceptions.ProtocolError: raise StopIteration except socket.error: raise StopIteration next = __next__ def close(self): """ Closes the event streaming. """ if not self._response.raw.closed: # find the underlying socket object # based on api.client._get_raw_response_socket sock_fp = self._response.raw._fp.fp if hasattr(sock_fp, 'raw'): sock_raw = sock_fp.raw if hasattr(sock_raw, 'sock'): sock = sock_raw.sock elif hasattr(sock_raw, '_sock'): sock = sock_raw._sock else: sock = sock_fp._sock sock.shutdown(socket.SHUT_RDWR) sock.close()
import socket try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 class CancellableStream(object): """ Stream wrapper for real-time events, logs, etc. from the server. Example: >>> events = client.events() >>> for event in events: ... print event >>> # and cancel from another thread >>> events.close() """ def __init__(self, stream, response): self._stream = stream self._response = response def __iter__(self): return self def __next__(self): try: return next(self._stream) except urllib3.exceptions.ProtocolError: raise StopIteration except socket.error: raise StopIteration next = __next__ def close(self): """ Closes the event streaming. """ if not self._response.raw.closed: # find the underlying socket object # based on api.client._get_raw_response_socket sock_fp = self._response.raw._fp.fp if hasattr(sock_fp, 'raw'): sock_raw = sock_fp.raw if hasattr(sock_raw, 'sock'): sock = sock_raw.sock elif hasattr(sock_raw, '_sock'): sock = sock_raw._sock else: sock = sock_fp._sock if isinstance(sock, urllib3.contrib.pyopenssl.WrappedSocket): sock = sock.socket sock.shutdown(socket.SHUT_RDWR) sock.close()
Fix cancellable streams on Windows clients + HTTPS transport
Fix cancellable streams on Windows clients + HTTPS transport Signed-off-by: Joffrey F <2e95f49799afcec0080c0aeb8813776d949e0768@docker.com>
Python
apache-2.0
youhong316/docker-py,docker/docker-py,funkyfuture/docker-py,funkyfuture/docker-py,docker/docker-py,vdemeester/docker-py,youhong316/docker-py,vdemeester/docker-py
import socket try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 class CancellableStream(object): """ Stream wrapper for real-time events, logs, etc. from the server. Example: >>> events = client.events() >>> for event in events: ... print event >>> # and cancel from another thread >>> events.close() """ def __init__(self, stream, response): self._stream = stream self._response = response def __iter__(self): return self def __next__(self): try: return next(self._stream) except urllib3.exceptions.ProtocolError: raise StopIteration except socket.error: raise StopIteration next = __next__ def close(self): """ Closes the event streaming. """ if not self._response.raw.closed: # find the underlying socket object # based on api.client._get_raw_response_socket sock_fp = self._response.raw._fp.fp if hasattr(sock_fp, 'raw'): sock_raw = sock_fp.raw if hasattr(sock_raw, 'sock'): sock = sock_raw.sock elif hasattr(sock_raw, '_sock'): sock = sock_raw._sock else: sock = sock_fp._sock sock.shutdown(socket.SHUT_RDWR) sock.close() Fix cancellable streams on Windows clients + HTTPS transport Signed-off-by: Joffrey F <2e95f49799afcec0080c0aeb8813776d949e0768@docker.com>
import socket try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 class CancellableStream(object): """ Stream wrapper for real-time events, logs, etc. from the server. Example: >>> events = client.events() >>> for event in events: ... print event >>> # and cancel from another thread >>> events.close() """ def __init__(self, stream, response): self._stream = stream self._response = response def __iter__(self): return self def __next__(self): try: return next(self._stream) except urllib3.exceptions.ProtocolError: raise StopIteration except socket.error: raise StopIteration next = __next__ def close(self): """ Closes the event streaming. """ if not self._response.raw.closed: # find the underlying socket object # based on api.client._get_raw_response_socket sock_fp = self._response.raw._fp.fp if hasattr(sock_fp, 'raw'): sock_raw = sock_fp.raw if hasattr(sock_raw, 'sock'): sock = sock_raw.sock elif hasattr(sock_raw, '_sock'): sock = sock_raw._sock else: sock = sock_fp._sock if isinstance(sock, urllib3.contrib.pyopenssl.WrappedSocket): sock = sock.socket sock.shutdown(socket.SHUT_RDWR) sock.close()
<commit_before>import socket try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 class CancellableStream(object): """ Stream wrapper for real-time events, logs, etc. from the server. Example: >>> events = client.events() >>> for event in events: ... print event >>> # and cancel from another thread >>> events.close() """ def __init__(self, stream, response): self._stream = stream self._response = response def __iter__(self): return self def __next__(self): try: return next(self._stream) except urllib3.exceptions.ProtocolError: raise StopIteration except socket.error: raise StopIteration next = __next__ def close(self): """ Closes the event streaming. """ if not self._response.raw.closed: # find the underlying socket object # based on api.client._get_raw_response_socket sock_fp = self._response.raw._fp.fp if hasattr(sock_fp, 'raw'): sock_raw = sock_fp.raw if hasattr(sock_raw, 'sock'): sock = sock_raw.sock elif hasattr(sock_raw, '_sock'): sock = sock_raw._sock else: sock = sock_fp._sock sock.shutdown(socket.SHUT_RDWR) sock.close() <commit_msg>Fix cancellable streams on Windows clients + HTTPS transport Signed-off-by: Joffrey F <2e95f49799afcec0080c0aeb8813776d949e0768@docker.com><commit_after>
import socket try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 class CancellableStream(object): """ Stream wrapper for real-time events, logs, etc. from the server. Example: >>> events = client.events() >>> for event in events: ... print event >>> # and cancel from another thread >>> events.close() """ def __init__(self, stream, response): self._stream = stream self._response = response def __iter__(self): return self def __next__(self): try: return next(self._stream) except urllib3.exceptions.ProtocolError: raise StopIteration except socket.error: raise StopIteration next = __next__ def close(self): """ Closes the event streaming. """ if not self._response.raw.closed: # find the underlying socket object # based on api.client._get_raw_response_socket sock_fp = self._response.raw._fp.fp if hasattr(sock_fp, 'raw'): sock_raw = sock_fp.raw if hasattr(sock_raw, 'sock'): sock = sock_raw.sock elif hasattr(sock_raw, '_sock'): sock = sock_raw._sock else: sock = sock_fp._sock if isinstance(sock, urllib3.contrib.pyopenssl.WrappedSocket): sock = sock.socket sock.shutdown(socket.SHUT_RDWR) sock.close()
import socket try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 class CancellableStream(object): """ Stream wrapper for real-time events, logs, etc. from the server. Example: >>> events = client.events() >>> for event in events: ... print event >>> # and cancel from another thread >>> events.close() """ def __init__(self, stream, response): self._stream = stream self._response = response def __iter__(self): return self def __next__(self): try: return next(self._stream) except urllib3.exceptions.ProtocolError: raise StopIteration except socket.error: raise StopIteration next = __next__ def close(self): """ Closes the event streaming. """ if not self._response.raw.closed: # find the underlying socket object # based on api.client._get_raw_response_socket sock_fp = self._response.raw._fp.fp if hasattr(sock_fp, 'raw'): sock_raw = sock_fp.raw if hasattr(sock_raw, 'sock'): sock = sock_raw.sock elif hasattr(sock_raw, '_sock'): sock = sock_raw._sock else: sock = sock_fp._sock sock.shutdown(socket.SHUT_RDWR) sock.close() Fix cancellable streams on Windows clients + HTTPS transport Signed-off-by: Joffrey F <2e95f49799afcec0080c0aeb8813776d949e0768@docker.com>import socket try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 class CancellableStream(object): """ Stream wrapper for real-time events, logs, etc. from the server. Example: >>> events = client.events() >>> for event in events: ... print event >>> # and cancel from another thread >>> events.close() """ def __init__(self, stream, response): self._stream = stream self._response = response def __iter__(self): return self def __next__(self): try: return next(self._stream) except urllib3.exceptions.ProtocolError: raise StopIteration except socket.error: raise StopIteration next = __next__ def close(self): """ Closes the event streaming. """ if not self._response.raw.closed: # find the underlying socket object # based on api.client._get_raw_response_socket sock_fp = self._response.raw._fp.fp if hasattr(sock_fp, 'raw'): sock_raw = sock_fp.raw if hasattr(sock_raw, 'sock'): sock = sock_raw.sock elif hasattr(sock_raw, '_sock'): sock = sock_raw._sock else: sock = sock_fp._sock if isinstance(sock, urllib3.contrib.pyopenssl.WrappedSocket): sock = sock.socket sock.shutdown(socket.SHUT_RDWR) sock.close()
<commit_before>import socket try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 class CancellableStream(object): """ Stream wrapper for real-time events, logs, etc. from the server. Example: >>> events = client.events() >>> for event in events: ... print event >>> # and cancel from another thread >>> events.close() """ def __init__(self, stream, response): self._stream = stream self._response = response def __iter__(self): return self def __next__(self): try: return next(self._stream) except urllib3.exceptions.ProtocolError: raise StopIteration except socket.error: raise StopIteration next = __next__ def close(self): """ Closes the event streaming. """ if not self._response.raw.closed: # find the underlying socket object # based on api.client._get_raw_response_socket sock_fp = self._response.raw._fp.fp if hasattr(sock_fp, 'raw'): sock_raw = sock_fp.raw if hasattr(sock_raw, 'sock'): sock = sock_raw.sock elif hasattr(sock_raw, '_sock'): sock = sock_raw._sock else: sock = sock_fp._sock sock.shutdown(socket.SHUT_RDWR) sock.close() <commit_msg>Fix cancellable streams on Windows clients + HTTPS transport Signed-off-by: Joffrey F <2e95f49799afcec0080c0aeb8813776d949e0768@docker.com><commit_after>import socket try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 class CancellableStream(object): """ Stream wrapper for real-time events, logs, etc. from the server. Example: >>> events = client.events() >>> for event in events: ... print event >>> # and cancel from another thread >>> events.close() """ def __init__(self, stream, response): self._stream = stream self._response = response def __iter__(self): return self def __next__(self): try: return next(self._stream) except urllib3.exceptions.ProtocolError: raise StopIteration except socket.error: raise StopIteration next = __next__ def close(self): """ Closes the event streaming. """ if not self._response.raw.closed: # find the underlying socket object # based on api.client._get_raw_response_socket sock_fp = self._response.raw._fp.fp if hasattr(sock_fp, 'raw'): sock_raw = sock_fp.raw if hasattr(sock_raw, 'sock'): sock = sock_raw.sock elif hasattr(sock_raw, '_sock'): sock = sock_raw._sock else: sock = sock_fp._sock if isinstance(sock, urllib3.contrib.pyopenssl.WrappedSocket): sock = sock.socket sock.shutdown(socket.SHUT_RDWR) sock.close()
07b7efdc848deeb7634f23cdb878774a99c9c535
ambassador/tests/t_grpc_bridge.py
ambassador/tests/t_grpc_bridge.py
import json from kat.harness import Query from abstract_tests import AmbassadorTest, ServiceType, EGRPC class AcceptanceGrpcBridgeTest(AmbassadorTest): target: ServiceType def init(self): self.target = EGRPC() def config(self): yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Module name: ambassador config: enable_grpc_http11_bridge: True """) yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Mapping grpc: True prefix: /echo.EchoService/ rewrite: /echo.EchoService/ name: {self.target.path.k8s} service: {self.target.path.k8s} """) def queries(self): # [0] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "0" }, expected=200) # [1] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "7" }, expected=200) def check(self): # [0] assert self.results[0].status == 200 assert self.results[0].headers["Grpc-Status"] == ["0"] # [0] assert self.results[1].status == 200 assert self.results[1].headers["Grpc-Status"] == ["7"]
from kat.harness import Query from abstract_tests import AmbassadorTest, ServiceType, EGRPC class AcceptanceGrpcBridgeTest(AmbassadorTest): target: ServiceType def init(self): self.target = EGRPC() def config(self): yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Module name: ambassador config: enable_grpc_http11_bridge: True """) yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Mapping grpc: True prefix: /echo.EchoService/ rewrite: /echo.EchoService/ name: {self.target.path.k8s} service: {self.target.path.k8s} """) def queries(self): # [0] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "0" }, expected=200) # [1] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "7" }, expected=200) def check(self): # [0] assert self.results[0].headers["Grpc-Status"] == ["0"] # [1] assert self.results[1].headers["Grpc-Status"] == ["7"]
Clean up existing gRPC bridge test (make it like t_tcpmapping.py)
Clean up existing gRPC bridge test (make it like t_tcpmapping.py) - Remove redundant HTTP status assertions - Adjust formatting - Remove unused import
Python
apache-2.0
datawire/ambassador,datawire/ambassador,datawire/ambassador,datawire/ambassador,datawire/ambassador
import json from kat.harness import Query from abstract_tests import AmbassadorTest, ServiceType, EGRPC class AcceptanceGrpcBridgeTest(AmbassadorTest): target: ServiceType def init(self): self.target = EGRPC() def config(self): yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Module name: ambassador config: enable_grpc_http11_bridge: True """) yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Mapping grpc: True prefix: /echo.EchoService/ rewrite: /echo.EchoService/ name: {self.target.path.k8s} service: {self.target.path.k8s} """) def queries(self): # [0] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "0" }, expected=200) # [1] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "7" }, expected=200) def check(self): # [0] assert self.results[0].status == 200 assert self.results[0].headers["Grpc-Status"] == ["0"] # [0] assert self.results[1].status == 200 assert self.results[1].headers["Grpc-Status"] == ["7"] Clean up existing gRPC bridge test (make it like t_tcpmapping.py) - Remove redundant HTTP status assertions - Adjust formatting - Remove unused import
from kat.harness import Query from abstract_tests import AmbassadorTest, ServiceType, EGRPC class AcceptanceGrpcBridgeTest(AmbassadorTest): target: ServiceType def init(self): self.target = EGRPC() def config(self): yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Module name: ambassador config: enable_grpc_http11_bridge: True """) yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Mapping grpc: True prefix: /echo.EchoService/ rewrite: /echo.EchoService/ name: {self.target.path.k8s} service: {self.target.path.k8s} """) def queries(self): # [0] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "0" }, expected=200) # [1] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "7" }, expected=200) def check(self): # [0] assert self.results[0].headers["Grpc-Status"] == ["0"] # [1] assert self.results[1].headers["Grpc-Status"] == ["7"]
<commit_before>import json from kat.harness import Query from abstract_tests import AmbassadorTest, ServiceType, EGRPC class AcceptanceGrpcBridgeTest(AmbassadorTest): target: ServiceType def init(self): self.target = EGRPC() def config(self): yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Module name: ambassador config: enable_grpc_http11_bridge: True """) yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Mapping grpc: True prefix: /echo.EchoService/ rewrite: /echo.EchoService/ name: {self.target.path.k8s} service: {self.target.path.k8s} """) def queries(self): # [0] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "0" }, expected=200) # [1] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "7" }, expected=200) def check(self): # [0] assert self.results[0].status == 200 assert self.results[0].headers["Grpc-Status"] == ["0"] # [0] assert self.results[1].status == 200 assert self.results[1].headers["Grpc-Status"] == ["7"] <commit_msg>Clean up existing gRPC bridge test (make it like t_tcpmapping.py) - Remove redundant HTTP status assertions - Adjust formatting - Remove unused import<commit_after>
from kat.harness import Query from abstract_tests import AmbassadorTest, ServiceType, EGRPC class AcceptanceGrpcBridgeTest(AmbassadorTest): target: ServiceType def init(self): self.target = EGRPC() def config(self): yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Module name: ambassador config: enable_grpc_http11_bridge: True """) yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Mapping grpc: True prefix: /echo.EchoService/ rewrite: /echo.EchoService/ name: {self.target.path.k8s} service: {self.target.path.k8s} """) def queries(self): # [0] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "0" }, expected=200) # [1] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "7" }, expected=200) def check(self): # [0] assert self.results[0].headers["Grpc-Status"] == ["0"] # [1] assert self.results[1].headers["Grpc-Status"] == ["7"]
import json from kat.harness import Query from abstract_tests import AmbassadorTest, ServiceType, EGRPC class AcceptanceGrpcBridgeTest(AmbassadorTest): target: ServiceType def init(self): self.target = EGRPC() def config(self): yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Module name: ambassador config: enable_grpc_http11_bridge: True """) yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Mapping grpc: True prefix: /echo.EchoService/ rewrite: /echo.EchoService/ name: {self.target.path.k8s} service: {self.target.path.k8s} """) def queries(self): # [0] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "0" }, expected=200) # [1] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "7" }, expected=200) def check(self): # [0] assert self.results[0].status == 200 assert self.results[0].headers["Grpc-Status"] == ["0"] # [0] assert self.results[1].status == 200 assert self.results[1].headers["Grpc-Status"] == ["7"] Clean up existing gRPC bridge test (make it like t_tcpmapping.py) - Remove redundant HTTP status assertions - Adjust formatting - Remove unused importfrom kat.harness import Query from abstract_tests import AmbassadorTest, ServiceType, EGRPC class AcceptanceGrpcBridgeTest(AmbassadorTest): target: ServiceType def init(self): self.target = EGRPC() def config(self): yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Module name: ambassador config: enable_grpc_http11_bridge: True """) yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Mapping grpc: True prefix: /echo.EchoService/ rewrite: /echo.EchoService/ name: {self.target.path.k8s} service: {self.target.path.k8s} """) def queries(self): # [0] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "0" }, expected=200) # [1] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "7" }, expected=200) def check(self): # [0] assert self.results[0].headers["Grpc-Status"] == ["0"] # [1] assert self.results[1].headers["Grpc-Status"] == ["7"]
<commit_before>import json from kat.harness import Query from abstract_tests import AmbassadorTest, ServiceType, EGRPC class AcceptanceGrpcBridgeTest(AmbassadorTest): target: ServiceType def init(self): self.target = EGRPC() def config(self): yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Module name: ambassador config: enable_grpc_http11_bridge: True """) yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Mapping grpc: True prefix: /echo.EchoService/ rewrite: /echo.EchoService/ name: {self.target.path.k8s} service: {self.target.path.k8s} """) def queries(self): # [0] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "0" }, expected=200) # [1] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "7" }, expected=200) def check(self): # [0] assert self.results[0].status == 200 assert self.results[0].headers["Grpc-Status"] == ["0"] # [0] assert self.results[1].status == 200 assert self.results[1].headers["Grpc-Status"] == ["7"] <commit_msg>Clean up existing gRPC bridge test (make it like t_tcpmapping.py) - Remove redundant HTTP status assertions - Adjust formatting - Remove unused import<commit_after>from kat.harness import Query from abstract_tests import AmbassadorTest, ServiceType, EGRPC class AcceptanceGrpcBridgeTest(AmbassadorTest): target: ServiceType def init(self): self.target = EGRPC() def config(self): yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Module name: ambassador config: enable_grpc_http11_bridge: True """) yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Mapping grpc: True prefix: /echo.EchoService/ rewrite: /echo.EchoService/ name: {self.target.path.k8s} service: {self.target.path.k8s} """) def queries(self): # [0] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "0" }, expected=200) # [1] yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc", "requested-status": "7" }, expected=200) def check(self): # [0] assert self.results[0].headers["Grpc-Status"] == ["0"] # [1] assert self.results[1].headers["Grpc-Status"] == ["7"]
032d1061454482db730e35a17fa058ba1ed5f66a
app/codeselfstudy/models/posts.py
app/codeselfstudy/models/posts.py
import datetime import mongoengine as me # Based on: https://flask-mongoengine.readthedocs.org/en/latest/ class Post(me.Document): title = me.StringField(max_length=120, required=True) created_at = me.DateTimeField(default=datetime.datetime.now, required=True) content = me.StringField(required=True) published = me.BooleanField(required=True) # TODO: make sure this is what we want. It's based on the MongoEngine docs. # Doesn't seem to work #@me.queryset_manager #def live_posts(doc_cls, queryset): #return queryset.filter(published=True)
import datetime import mongoengine as me # Based on: https://flask-mongoengine.readthedocs.org/en/latest/ class Post(me.Document): title = me.StringField(max_length=120, required=True) created_at = me.DateTimeField(default=datetime.datetime.now, required=True) content = me.StringField(required=True) published = me.BooleanField(required=True) slug = me.StringField(max_length=155, required=True) comments = me.ListField(me.EmbeddedDocumentField('Comment')) def get_absolute_url(self): return url_for('post', kwargs={'slug': self.slug}) meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] } # TODO: make sure this is what we want. It's based on the MongoEngine docs. # Doesn't seem to work #@me.queryset_manager #def live_posts(doc_cls, queryset): #return queryset.filter(published=True) class Comment(me.EmbeddedDocument): created_at = me.DateTimeField(default=datetime.datetime.now, required=True) body = me.StringField(verbose_name="Comment", required=True)
Add comment class to models
Add comment class to models
Python
mit
CodeSelfStudy/codeselfstudy_flask,CodeSelfStudy/codeselfstudy_flask,CodeSelfStudy/codeselfstudy_flask,harli123/codeselfstudy_flask,harli123/codeselfstudy_flask,harli123/codeselfstudy_flask
import datetime import mongoengine as me # Based on: https://flask-mongoengine.readthedocs.org/en/latest/ class Post(me.Document): title = me.StringField(max_length=120, required=True) created_at = me.DateTimeField(default=datetime.datetime.now, required=True) content = me.StringField(required=True) published = me.BooleanField(required=True) # TODO: make sure this is what we want. It's based on the MongoEngine docs. # Doesn't seem to work #@me.queryset_manager #def live_posts(doc_cls, queryset): #return queryset.filter(published=True) Add comment class to models
import datetime import mongoengine as me # Based on: https://flask-mongoengine.readthedocs.org/en/latest/ class Post(me.Document): title = me.StringField(max_length=120, required=True) created_at = me.DateTimeField(default=datetime.datetime.now, required=True) content = me.StringField(required=True) published = me.BooleanField(required=True) slug = me.StringField(max_length=155, required=True) comments = me.ListField(me.EmbeddedDocumentField('Comment')) def get_absolute_url(self): return url_for('post', kwargs={'slug': self.slug}) meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] } # TODO: make sure this is what we want. It's based on the MongoEngine docs. # Doesn't seem to work #@me.queryset_manager #def live_posts(doc_cls, queryset): #return queryset.filter(published=True) class Comment(me.EmbeddedDocument): created_at = me.DateTimeField(default=datetime.datetime.now, required=True) body = me.StringField(verbose_name="Comment", required=True)
<commit_before>import datetime import mongoengine as me # Based on: https://flask-mongoengine.readthedocs.org/en/latest/ class Post(me.Document): title = me.StringField(max_length=120, required=True) created_at = me.DateTimeField(default=datetime.datetime.now, required=True) content = me.StringField(required=True) published = me.BooleanField(required=True) # TODO: make sure this is what we want. It's based on the MongoEngine docs. # Doesn't seem to work #@me.queryset_manager #def live_posts(doc_cls, queryset): #return queryset.filter(published=True) <commit_msg>Add comment class to models<commit_after>
import datetime import mongoengine as me # Based on: https://flask-mongoengine.readthedocs.org/en/latest/ class Post(me.Document): title = me.StringField(max_length=120, required=True) created_at = me.DateTimeField(default=datetime.datetime.now, required=True) content = me.StringField(required=True) published = me.BooleanField(required=True) slug = me.StringField(max_length=155, required=True) comments = me.ListField(me.EmbeddedDocumentField('Comment')) def get_absolute_url(self): return url_for('post', kwargs={'slug': self.slug}) meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] } # TODO: make sure this is what we want. It's based on the MongoEngine docs. # Doesn't seem to work #@me.queryset_manager #def live_posts(doc_cls, queryset): #return queryset.filter(published=True) class Comment(me.EmbeddedDocument): created_at = me.DateTimeField(default=datetime.datetime.now, required=True) body = me.StringField(verbose_name="Comment", required=True)
import datetime import mongoengine as me # Based on: https://flask-mongoengine.readthedocs.org/en/latest/ class Post(me.Document): title = me.StringField(max_length=120, required=True) created_at = me.DateTimeField(default=datetime.datetime.now, required=True) content = me.StringField(required=True) published = me.BooleanField(required=True) # TODO: make sure this is what we want. It's based on the MongoEngine docs. # Doesn't seem to work #@me.queryset_manager #def live_posts(doc_cls, queryset): #return queryset.filter(published=True) Add comment class to modelsimport datetime import mongoengine as me # Based on: https://flask-mongoengine.readthedocs.org/en/latest/ class Post(me.Document): title = me.StringField(max_length=120, required=True) created_at = me.DateTimeField(default=datetime.datetime.now, required=True) content = me.StringField(required=True) published = me.BooleanField(required=True) slug = me.StringField(max_length=155, required=True) comments = me.ListField(me.EmbeddedDocumentField('Comment')) def get_absolute_url(self): return url_for('post', kwargs={'slug': self.slug}) meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] } # TODO: make sure this is what we want. It's based on the MongoEngine docs. # Doesn't seem to work #@me.queryset_manager #def live_posts(doc_cls, queryset): #return queryset.filter(published=True) class Comment(me.EmbeddedDocument): created_at = me.DateTimeField(default=datetime.datetime.now, required=True) body = me.StringField(verbose_name="Comment", required=True)
<commit_before>import datetime import mongoengine as me # Based on: https://flask-mongoengine.readthedocs.org/en/latest/ class Post(me.Document): title = me.StringField(max_length=120, required=True) created_at = me.DateTimeField(default=datetime.datetime.now, required=True) content = me.StringField(required=True) published = me.BooleanField(required=True) # TODO: make sure this is what we want. It's based on the MongoEngine docs. # Doesn't seem to work #@me.queryset_manager #def live_posts(doc_cls, queryset): #return queryset.filter(published=True) <commit_msg>Add comment class to models<commit_after>import datetime import mongoengine as me # Based on: https://flask-mongoengine.readthedocs.org/en/latest/ class Post(me.Document): title = me.StringField(max_length=120, required=True) created_at = me.DateTimeField(default=datetime.datetime.now, required=True) content = me.StringField(required=True) published = me.BooleanField(required=True) slug = me.StringField(max_length=155, required=True) comments = me.ListField(me.EmbeddedDocumentField('Comment')) def get_absolute_url(self): return url_for('post', kwargs={'slug': self.slug}) meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] } # TODO: make sure this is what we want. It's based on the MongoEngine docs. # Doesn't seem to work #@me.queryset_manager #def live_posts(doc_cls, queryset): #return queryset.filter(published=True) class Comment(me.EmbeddedDocument): created_at = me.DateTimeField(default=datetime.datetime.now, required=True) body = me.StringField(verbose_name="Comment", required=True)
957422118d31def826d336f26152de1d0399fe4e
py/src/ai/h2o/sparkling/H2OConf.py
py/src/ai/h2o/sparkling/H2OConf.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warnings from ai.h2o.sparkling.ExternalBackendConf import ExternalBackendConf from ai.h2o.sparkling.Initializer import Initializer from ai.h2o.sparkling.InternalBackendConf import InternalBackendConf from ai.h2o.sparkling.SharedBackendConf import SharedBackendConf from pyspark.ml.util import _jvm class H2OConf(SharedBackendConf, InternalBackendConf, ExternalBackendConf): def __init__(self, spark=None): try: if spark is not None: warnings.warn( "Constructor H2OConf(spark) with spark argument is deprecated. Please use just H2OConf(). " "The argument will be removed in release 3.32.") Initializer.load_sparkling_jar() self._jconf = _jvm().org.apache.spark.h2o.H2OConf() except: raise
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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 ai.h2o.sparkling.ExternalBackendConf import ExternalBackendConf from ai.h2o.sparkling.Initializer import Initializer from ai.h2o.sparkling.InternalBackendConf import InternalBackendConf from ai.h2o.sparkling.SharedBackendConf import SharedBackendConf from pyspark.ml.util import _jvm class H2OConf(SharedBackendConf, InternalBackendConf, ExternalBackendConf): def __init__(self): try: Initializer.load_sparkling_jar() self._jconf = _jvm().org.apache.spark.h2o.H2OConf() except: raise
Remove deprecated method H2OContext.getOrCreate with sparkSession or SparkContext argument
[SW-1971][FollowUp] Remove deprecated method H2OContext.getOrCreate with sparkSession or SparkContext argument
Python
apache-2.0
h2oai/sparkling-water,h2oai/sparkling-water,h2oai/sparkling-water,h2oai/sparkling-water
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warnings from ai.h2o.sparkling.ExternalBackendConf import ExternalBackendConf from ai.h2o.sparkling.Initializer import Initializer from ai.h2o.sparkling.InternalBackendConf import InternalBackendConf from ai.h2o.sparkling.SharedBackendConf import SharedBackendConf from pyspark.ml.util import _jvm class H2OConf(SharedBackendConf, InternalBackendConf, ExternalBackendConf): def __init__(self, spark=None): try: if spark is not None: warnings.warn( "Constructor H2OConf(spark) with spark argument is deprecated. Please use just H2OConf(). " "The argument will be removed in release 3.32.") Initializer.load_sparkling_jar() self._jconf = _jvm().org.apache.spark.h2o.H2OConf() except: raise [SW-1971][FollowUp] Remove deprecated method H2OContext.getOrCreate with sparkSession or SparkContext argument
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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 ai.h2o.sparkling.ExternalBackendConf import ExternalBackendConf from ai.h2o.sparkling.Initializer import Initializer from ai.h2o.sparkling.InternalBackendConf import InternalBackendConf from ai.h2o.sparkling.SharedBackendConf import SharedBackendConf from pyspark.ml.util import _jvm class H2OConf(SharedBackendConf, InternalBackendConf, ExternalBackendConf): def __init__(self): try: Initializer.load_sparkling_jar() self._jconf = _jvm().org.apache.spark.h2o.H2OConf() except: raise
<commit_before># # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warnings from ai.h2o.sparkling.ExternalBackendConf import ExternalBackendConf from ai.h2o.sparkling.Initializer import Initializer from ai.h2o.sparkling.InternalBackendConf import InternalBackendConf from ai.h2o.sparkling.SharedBackendConf import SharedBackendConf from pyspark.ml.util import _jvm class H2OConf(SharedBackendConf, InternalBackendConf, ExternalBackendConf): def __init__(self, spark=None): try: if spark is not None: warnings.warn( "Constructor H2OConf(spark) with spark argument is deprecated. Please use just H2OConf(). " "The argument will be removed in release 3.32.") Initializer.load_sparkling_jar() self._jconf = _jvm().org.apache.spark.h2o.H2OConf() except: raise <commit_msg>[SW-1971][FollowUp] Remove deprecated method H2OContext.getOrCreate with sparkSession or SparkContext argument<commit_after>
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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 ai.h2o.sparkling.ExternalBackendConf import ExternalBackendConf from ai.h2o.sparkling.Initializer import Initializer from ai.h2o.sparkling.InternalBackendConf import InternalBackendConf from ai.h2o.sparkling.SharedBackendConf import SharedBackendConf from pyspark.ml.util import _jvm class H2OConf(SharedBackendConf, InternalBackendConf, ExternalBackendConf): def __init__(self): try: Initializer.load_sparkling_jar() self._jconf = _jvm().org.apache.spark.h2o.H2OConf() except: raise
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warnings from ai.h2o.sparkling.ExternalBackendConf import ExternalBackendConf from ai.h2o.sparkling.Initializer import Initializer from ai.h2o.sparkling.InternalBackendConf import InternalBackendConf from ai.h2o.sparkling.SharedBackendConf import SharedBackendConf from pyspark.ml.util import _jvm class H2OConf(SharedBackendConf, InternalBackendConf, ExternalBackendConf): def __init__(self, spark=None): try: if spark is not None: warnings.warn( "Constructor H2OConf(spark) with spark argument is deprecated. Please use just H2OConf(). " "The argument will be removed in release 3.32.") Initializer.load_sparkling_jar() self._jconf = _jvm().org.apache.spark.h2o.H2OConf() except: raise [SW-1971][FollowUp] Remove deprecated method H2OContext.getOrCreate with sparkSession or SparkContext argument# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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 ai.h2o.sparkling.ExternalBackendConf import ExternalBackendConf from ai.h2o.sparkling.Initializer import Initializer from ai.h2o.sparkling.InternalBackendConf import InternalBackendConf from ai.h2o.sparkling.SharedBackendConf import SharedBackendConf from pyspark.ml.util import _jvm class H2OConf(SharedBackendConf, InternalBackendConf, ExternalBackendConf): def __init__(self): try: Initializer.load_sparkling_jar() self._jconf = _jvm().org.apache.spark.h2o.H2OConf() except: raise
<commit_before># # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warnings from ai.h2o.sparkling.ExternalBackendConf import ExternalBackendConf from ai.h2o.sparkling.Initializer import Initializer from ai.h2o.sparkling.InternalBackendConf import InternalBackendConf from ai.h2o.sparkling.SharedBackendConf import SharedBackendConf from pyspark.ml.util import _jvm class H2OConf(SharedBackendConf, InternalBackendConf, ExternalBackendConf): def __init__(self, spark=None): try: if spark is not None: warnings.warn( "Constructor H2OConf(spark) with spark argument is deprecated. Please use just H2OConf(). " "The argument will be removed in release 3.32.") Initializer.load_sparkling_jar() self._jconf = _jvm().org.apache.spark.h2o.H2OConf() except: raise <commit_msg>[SW-1971][FollowUp] Remove deprecated method H2OContext.getOrCreate with sparkSession or SparkContext argument<commit_after># # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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 ai.h2o.sparkling.ExternalBackendConf import ExternalBackendConf from ai.h2o.sparkling.Initializer import Initializer from ai.h2o.sparkling.InternalBackendConf import InternalBackendConf from ai.h2o.sparkling.SharedBackendConf import SharedBackendConf from pyspark.ml.util import _jvm class H2OConf(SharedBackendConf, InternalBackendConf, ExternalBackendConf): def __init__(self): try: Initializer.load_sparkling_jar() self._jconf = _jvm().org.apache.spark.h2o.H2OConf() except: raise
054f9ce0a8d08b0ec740d7b6d26a8b5553962490
src/factories.py
src/factories.py
from chassis.models import db from chassis import models from faker import Factory as Fake from factory.alchemy import SQLAlchemyModelFactory import factory import logging #Suppress factory-boy debug data factory_log = logging.getLogger("factory") factory_log.setLevel(logging.WARNING) faker = Fake.create() class Cat(SQLAlchemyModelFactory): FACTORY_FOR = models.Cat FACTORY_SESSION = db.session id = factory.LazyAttribute(lambda x: faker.unixTime()) born_at = factory.LazyAttribute(lambda x: faker.unixTime()) name = factory.LazyAttribute(lambda x: faker.firstName())
from chassis.models import db from chassis import models from faker import Factory as Fake from factory.alchemy import SQLAlchemyModelFactory import factory import logging #Suppress factory-boy debug data factory_log = logging.getLogger("factory") factory_log.setLevel(logging.WARNING) faker = Fake.create() class Cat(SQLAlchemyModelFactory): FACTORY_FOR = models.Cat FACTORY_SESSION = db.session id = factory.LazyAttribute(lambda x: faker.unix_time()) born_at = factory.LazyAttribute(lambda x: faker.unix_time()) name = factory.LazyAttribute(lambda x: faker.first_name())
Fix faker calls since API changed.
Fix faker calls since API changed.
Python
mit
makmanalp/flask-chassis
from chassis.models import db from chassis import models from faker import Factory as Fake from factory.alchemy import SQLAlchemyModelFactory import factory import logging #Suppress factory-boy debug data factory_log = logging.getLogger("factory") factory_log.setLevel(logging.WARNING) faker = Fake.create() class Cat(SQLAlchemyModelFactory): FACTORY_FOR = models.Cat FACTORY_SESSION = db.session id = factory.LazyAttribute(lambda x: faker.unixTime()) born_at = factory.LazyAttribute(lambda x: faker.unixTime()) name = factory.LazyAttribute(lambda x: faker.firstName()) Fix faker calls since API changed.
from chassis.models import db from chassis import models from faker import Factory as Fake from factory.alchemy import SQLAlchemyModelFactory import factory import logging #Suppress factory-boy debug data factory_log = logging.getLogger("factory") factory_log.setLevel(logging.WARNING) faker = Fake.create() class Cat(SQLAlchemyModelFactory): FACTORY_FOR = models.Cat FACTORY_SESSION = db.session id = factory.LazyAttribute(lambda x: faker.unix_time()) born_at = factory.LazyAttribute(lambda x: faker.unix_time()) name = factory.LazyAttribute(lambda x: faker.first_name())
<commit_before>from chassis.models import db from chassis import models from faker import Factory as Fake from factory.alchemy import SQLAlchemyModelFactory import factory import logging #Suppress factory-boy debug data factory_log = logging.getLogger("factory") factory_log.setLevel(logging.WARNING) faker = Fake.create() class Cat(SQLAlchemyModelFactory): FACTORY_FOR = models.Cat FACTORY_SESSION = db.session id = factory.LazyAttribute(lambda x: faker.unixTime()) born_at = factory.LazyAttribute(lambda x: faker.unixTime()) name = factory.LazyAttribute(lambda x: faker.firstName()) <commit_msg>Fix faker calls since API changed.<commit_after>
from chassis.models import db from chassis import models from faker import Factory as Fake from factory.alchemy import SQLAlchemyModelFactory import factory import logging #Suppress factory-boy debug data factory_log = logging.getLogger("factory") factory_log.setLevel(logging.WARNING) faker = Fake.create() class Cat(SQLAlchemyModelFactory): FACTORY_FOR = models.Cat FACTORY_SESSION = db.session id = factory.LazyAttribute(lambda x: faker.unix_time()) born_at = factory.LazyAttribute(lambda x: faker.unix_time()) name = factory.LazyAttribute(lambda x: faker.first_name())
from chassis.models import db from chassis import models from faker import Factory as Fake from factory.alchemy import SQLAlchemyModelFactory import factory import logging #Suppress factory-boy debug data factory_log = logging.getLogger("factory") factory_log.setLevel(logging.WARNING) faker = Fake.create() class Cat(SQLAlchemyModelFactory): FACTORY_FOR = models.Cat FACTORY_SESSION = db.session id = factory.LazyAttribute(lambda x: faker.unixTime()) born_at = factory.LazyAttribute(lambda x: faker.unixTime()) name = factory.LazyAttribute(lambda x: faker.firstName()) Fix faker calls since API changed.from chassis.models import db from chassis import models from faker import Factory as Fake from factory.alchemy import SQLAlchemyModelFactory import factory import logging #Suppress factory-boy debug data factory_log = logging.getLogger("factory") factory_log.setLevel(logging.WARNING) faker = Fake.create() class Cat(SQLAlchemyModelFactory): FACTORY_FOR = models.Cat FACTORY_SESSION = db.session id = factory.LazyAttribute(lambda x: faker.unix_time()) born_at = factory.LazyAttribute(lambda x: faker.unix_time()) name = factory.LazyAttribute(lambda x: faker.first_name())
<commit_before>from chassis.models import db from chassis import models from faker import Factory as Fake from factory.alchemy import SQLAlchemyModelFactory import factory import logging #Suppress factory-boy debug data factory_log = logging.getLogger("factory") factory_log.setLevel(logging.WARNING) faker = Fake.create() class Cat(SQLAlchemyModelFactory): FACTORY_FOR = models.Cat FACTORY_SESSION = db.session id = factory.LazyAttribute(lambda x: faker.unixTime()) born_at = factory.LazyAttribute(lambda x: faker.unixTime()) name = factory.LazyAttribute(lambda x: faker.firstName()) <commit_msg>Fix faker calls since API changed.<commit_after>from chassis.models import db from chassis import models from faker import Factory as Fake from factory.alchemy import SQLAlchemyModelFactory import factory import logging #Suppress factory-boy debug data factory_log = logging.getLogger("factory") factory_log.setLevel(logging.WARNING) faker = Fake.create() class Cat(SQLAlchemyModelFactory): FACTORY_FOR = models.Cat FACTORY_SESSION = db.session id = factory.LazyAttribute(lambda x: faker.unix_time()) born_at = factory.LazyAttribute(lambda x: faker.unix_time()) name = factory.LazyAttribute(lambda x: faker.first_name())
daf68a1475530f4f0cb2e78e2ccf6ecbca821a8e
rfb_utils/prefs_utils.py
rfb_utils/prefs_utils.py
from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directory
from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: # try looking for all variants of RFB_PREFS_NAME for k, v in bpy.context.preferences.addons.items(): if RFB_PREFS_NAME in k: return v return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directory
Add some fallback code when looking for our prefs object.
Add some fallback code when looking for our prefs object.
Python
mit
prman-pixar/RenderManForBlender,adminradio/RenderManForBlender,prman-pixar/RenderManForBlender
from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directoryAdd some fallback code when looking for our prefs object.
from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: # try looking for all variants of RFB_PREFS_NAME for k, v in bpy.context.preferences.addons.items(): if RFB_PREFS_NAME in k: return v return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directory
<commit_before>from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directory<commit_msg>Add some fallback code when looking for our prefs object.<commit_after>
from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: # try looking for all variants of RFB_PREFS_NAME for k, v in bpy.context.preferences.addons.items(): if RFB_PREFS_NAME in k: return v return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directory
from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directoryAdd some fallback code when looking for our prefs object.from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: # try looking for all variants of RFB_PREFS_NAME for k, v in bpy.context.preferences.addons.items(): if RFB_PREFS_NAME in k: return v return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directory
<commit_before>from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directory<commit_msg>Add some fallback code when looking for our prefs object.<commit_after>from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: # try looking for all variants of RFB_PREFS_NAME for k, v in bpy.context.preferences.addons.items(): if RFB_PREFS_NAME in k: return v return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directory
753b2b6d04d0808e92dec0337d75a821d171e8e6
sahara/tests/__init__.py
sahara/tests/__init__.py
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import oslo_i18n # NOTE(slukjanov): i18n.enable_lazy() must be called before # sahara.utils.i18n._() is called to ensure it has the desired # lazy lookup behavior. oslo_i18n.enable_lazy()
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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 sahara.utils import patches patches.patch_all() import oslo_i18n # NOTE(slukjanov): i18n.enable_lazy() must be called before # sahara.utils.i18n._() is called to ensure it has the desired # lazy lookup behavior. oslo_i18n.enable_lazy()
Apply monkeypatching from eventlet before the tests starts
Apply monkeypatching from eventlet before the tests starts This should prevent issues with classes which may not have been otherwise instrumented (and sahara_engine and sahara_all do the instrumentation at the beginning anyway). Issues have been notices with eventlet 0.20.1 which now instruments subprocess. Change-Id: I17adb877483dbf0b0aa559029c61715d1cef9d7b
Python
apache-2.0
openstack/sahara,openstack/sahara
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import oslo_i18n # NOTE(slukjanov): i18n.enable_lazy() must be called before # sahara.utils.i18n._() is called to ensure it has the desired # lazy lookup behavior. oslo_i18n.enable_lazy() Apply monkeypatching from eventlet before the tests starts This should prevent issues with classes which may not have been otherwise instrumented (and sahara_engine and sahara_all do the instrumentation at the beginning anyway). Issues have been notices with eventlet 0.20.1 which now instruments subprocess. Change-Id: I17adb877483dbf0b0aa559029c61715d1cef9d7b
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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 sahara.utils import patches patches.patch_all() import oslo_i18n # NOTE(slukjanov): i18n.enable_lazy() must be called before # sahara.utils.i18n._() is called to ensure it has the desired # lazy lookup behavior. oslo_i18n.enable_lazy()
<commit_before># Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import oslo_i18n # NOTE(slukjanov): i18n.enable_lazy() must be called before # sahara.utils.i18n._() is called to ensure it has the desired # lazy lookup behavior. oslo_i18n.enable_lazy() <commit_msg>Apply monkeypatching from eventlet before the tests starts This should prevent issues with classes which may not have been otherwise instrumented (and sahara_engine and sahara_all do the instrumentation at the beginning anyway). Issues have been notices with eventlet 0.20.1 which now instruments subprocess. Change-Id: I17adb877483dbf0b0aa559029c61715d1cef9d7b<commit_after>
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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 sahara.utils import patches patches.patch_all() import oslo_i18n # NOTE(slukjanov): i18n.enable_lazy() must be called before # sahara.utils.i18n._() is called to ensure it has the desired # lazy lookup behavior. oslo_i18n.enable_lazy()
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import oslo_i18n # NOTE(slukjanov): i18n.enable_lazy() must be called before # sahara.utils.i18n._() is called to ensure it has the desired # lazy lookup behavior. oslo_i18n.enable_lazy() Apply monkeypatching from eventlet before the tests starts This should prevent issues with classes which may not have been otherwise instrumented (and sahara_engine and sahara_all do the instrumentation at the beginning anyway). Issues have been notices with eventlet 0.20.1 which now instruments subprocess. Change-Id: I17adb877483dbf0b0aa559029c61715d1cef9d7b# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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 sahara.utils import patches patches.patch_all() import oslo_i18n # NOTE(slukjanov): i18n.enable_lazy() must be called before # sahara.utils.i18n._() is called to ensure it has the desired # lazy lookup behavior. oslo_i18n.enable_lazy()
<commit_before># Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import oslo_i18n # NOTE(slukjanov): i18n.enable_lazy() must be called before # sahara.utils.i18n._() is called to ensure it has the desired # lazy lookup behavior. oslo_i18n.enable_lazy() <commit_msg>Apply monkeypatching from eventlet before the tests starts This should prevent issues with classes which may not have been otherwise instrumented (and sahara_engine and sahara_all do the instrumentation at the beginning anyway). Issues have been notices with eventlet 0.20.1 which now instruments subprocess. Change-Id: I17adb877483dbf0b0aa559029c61715d1cef9d7b<commit_after># Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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 sahara.utils import patches patches.patch_all() import oslo_i18n # NOTE(slukjanov): i18n.enable_lazy() must be called before # sahara.utils.i18n._() is called to ensure it has the desired # lazy lookup behavior. oslo_i18n.enable_lazy()
901bd73c61fbc6d9d8971ec1ce12e64100e633cb
base/settings/testing.py
base/settings/testing.py
# -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, }
# -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-celery. # ------------------------------------------------------------------ Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery',] BROKER_URL = 'django://' # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, }
Fix the Celery configuration under test settings.
Fix the Celery configuration under test settings.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
# -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } Fix the Celery configuration under test settings.
# -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-celery. # ------------------------------------------------------------------ Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery',] BROKER_URL = 'django://' # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, }
<commit_before># -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } <commit_msg>Fix the Celery configuration under test settings.<commit_after>
# -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-celery. # ------------------------------------------------------------------ Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery',] BROKER_URL = 'django://' # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, }
# -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } Fix the Celery configuration under test settings.# -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-celery. # ------------------------------------------------------------------ Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery',] BROKER_URL = 'django://' # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, }
<commit_before># -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } <commit_msg>Fix the Celery configuration under test settings.<commit_after># -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-celery. # ------------------------------------------------------------------ Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery',] BROKER_URL = 'django://' # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, }
0b152333c30d061df64376bb036c5fcd20896c36
go/billing/urls.py
go/billing/urls.py
from django.conf.urls import patterns, url from go.billing import views urlpatterns = patterns( '', url( r'^(?P<statement_id>[\d]+)', views.statement_view, name='pdf_statement') )
from django.conf.urls import patterns, url from go.billing import views urlpatterns = patterns( '', url( r'^statement/(?P<statement_id>[\d]+)', views.statement_view, name='pdf_statement') )
Move statement PDF URL off the root of the billing URL namespace.
Move statement PDF URL off the root of the billing URL namespace.
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
from django.conf.urls import patterns, url from go.billing import views urlpatterns = patterns( '', url( r'^(?P<statement_id>[\d]+)', views.statement_view, name='pdf_statement') ) Move statement PDF URL off the root of the billing URL namespace.
from django.conf.urls import patterns, url from go.billing import views urlpatterns = patterns( '', url( r'^statement/(?P<statement_id>[\d]+)', views.statement_view, name='pdf_statement') )
<commit_before>from django.conf.urls import patterns, url from go.billing import views urlpatterns = patterns( '', url( r'^(?P<statement_id>[\d]+)', views.statement_view, name='pdf_statement') ) <commit_msg>Move statement PDF URL off the root of the billing URL namespace.<commit_after>
from django.conf.urls import patterns, url from go.billing import views urlpatterns = patterns( '', url( r'^statement/(?P<statement_id>[\d]+)', views.statement_view, name='pdf_statement') )
from django.conf.urls import patterns, url from go.billing import views urlpatterns = patterns( '', url( r'^(?P<statement_id>[\d]+)', views.statement_view, name='pdf_statement') ) Move statement PDF URL off the root of the billing URL namespace.from django.conf.urls import patterns, url from go.billing import views urlpatterns = patterns( '', url( r'^statement/(?P<statement_id>[\d]+)', views.statement_view, name='pdf_statement') )
<commit_before>from django.conf.urls import patterns, url from go.billing import views urlpatterns = patterns( '', url( r'^(?P<statement_id>[\d]+)', views.statement_view, name='pdf_statement') ) <commit_msg>Move statement PDF URL off the root of the billing URL namespace.<commit_after>from django.conf.urls import patterns, url from go.billing import views urlpatterns = patterns( '', url( r'^statement/(?P<statement_id>[\d]+)', views.statement_view, name='pdf_statement') )
86ec56b0de1e822af2e03fedd2a67a3c555a7d18
versebot/regex.py
versebot/regex.py
""" VerseBot for reddit By Matthieu Grieger regex.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ import re def find_verses(message_body): """ Uses regex to search comment body for verse quotations. Returns a list of matches if found, None otherwise. """ regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+" + r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])") return re.findall(regex, message_body)
""" VerseBot for reddit By Matthieu Grieger regex.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ import re def find_verses(message_body): """ Uses regex to search comment body for verse quotations. Returns a list of matches if found, None otherwise. """ regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+" + r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])") matches = re.findall(regex, message_body) if len(matches) == 0: return None else: return matches
Fix return value from find_verses()
Fix return value from find_verses()
Python
mit
Matthew-Arnold/slack-versebot,Matthew-Arnold/slack-versebot
""" VerseBot for reddit By Matthieu Grieger regex.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ import re def find_verses(message_body): """ Uses regex to search comment body for verse quotations. Returns a list of matches if found, None otherwise. """ regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+" + r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])") return re.findall(regex, message_body) Fix return value from find_verses()
""" VerseBot for reddit By Matthieu Grieger regex.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ import re def find_verses(message_body): """ Uses regex to search comment body for verse quotations. Returns a list of matches if found, None otherwise. """ regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+" + r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])") matches = re.findall(regex, message_body) if len(matches) == 0: return None else: return matches
<commit_before>""" VerseBot for reddit By Matthieu Grieger regex.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ import re def find_verses(message_body): """ Uses regex to search comment body for verse quotations. Returns a list of matches if found, None otherwise. """ regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+" + r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])") return re.findall(regex, message_body) <commit_msg>Fix return value from find_verses()<commit_after>
""" VerseBot for reddit By Matthieu Grieger regex.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ import re def find_verses(message_body): """ Uses regex to search comment body for verse quotations. Returns a list of matches if found, None otherwise. """ regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+" + r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])") matches = re.findall(regex, message_body) if len(matches) == 0: return None else: return matches
""" VerseBot for reddit By Matthieu Grieger regex.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ import re def find_verses(message_body): """ Uses regex to search comment body for verse quotations. Returns a list of matches if found, None otherwise. """ regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+" + r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])") return re.findall(regex, message_body) Fix return value from find_verses()""" VerseBot for reddit By Matthieu Grieger regex.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ import re def find_verses(message_body): """ Uses regex to search comment body for verse quotations. Returns a list of matches if found, None otherwise. """ regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+" + r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])") matches = re.findall(regex, message_body) if len(matches) == 0: return None else: return matches
<commit_before>""" VerseBot for reddit By Matthieu Grieger regex.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ import re def find_verses(message_body): """ Uses regex to search comment body for verse quotations. Returns a list of matches if found, None otherwise. """ regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+" + r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])") return re.findall(regex, message_body) <commit_msg>Fix return value from find_verses()<commit_after>""" VerseBot for reddit By Matthieu Grieger regex.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ import re def find_verses(message_body): """ Uses regex to search comment body for verse quotations. Returns a list of matches if found, None otherwise. """ regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+" + r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])") matches = re.findall(regex, message_body) if len(matches) == 0: return None else: return matches
9bebf1c0cc9c0a03cde23fb1b92ae983f1fc3fa8
examples/check_args.py
examples/check_args.py
from __future__ import print_function @check.arg(0, check.int_value(min=0)) @check.arg(1, check.int_value(min=0)) def add_positive_integers(int1, int2): return int1 + int2 def main(): print(add_positive_integers(1, 5)) print(add_positive_integers(0, 5)) print(add_positive_integers(-1, 5)) if __name__ == '__main__': main()
from __future__ import print_function from collections import defaultdict def check_arg(arg_id, *constraints): return ArgCheckAdder(arg_id, *constraints) def check_int_value(min=None, max=None): def constraint(arg_id, args, kwargs): assert isinstance(args[arg_id], int) assert args[arg_id] >= 0 return constraint class ArgCheckAdder(object): def __init__(self, arg_id, *constraints): self.arg_id = arg_id self.constraints = constraints def __call__(self, func): if hasattr(func, 'checks'): func.checks[self.arg_id].extend(self.constraints) return func else: return CheckedFunction(func, {self.arg_id: self.constraints}) class CheckedFunction(object): def __init__(self, func, checks): self.checks = defaultdict(list) self.checks.update(checks) self.func = func def __call__(self, *args, **kwargs): for arg_id, checks in self.checks.items(): for check in checks: check(arg_id, args, kwargs) self.func(*args, **kwargs) @check_arg(0, check_int_value(min=0)) @check_arg(1, check_int_value(min=0)) def add_positive_integers(int1, int2): return int1 + int2 def main(): print(add_positive_integers(1, 5)) print(add_positive_integers(0, 5)) print(add_positive_integers(-1, 5)) if __name__ == '__main__': main()
Make isolated arg check example
Make isolated arg check example
Python
mit
explosion/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc
from __future__ import print_function @check.arg(0, check.int_value(min=0)) @check.arg(1, check.int_value(min=0)) def add_positive_integers(int1, int2): return int1 + int2 def main(): print(add_positive_integers(1, 5)) print(add_positive_integers(0, 5)) print(add_positive_integers(-1, 5)) if __name__ == '__main__': main() Make isolated arg check example
from __future__ import print_function from collections import defaultdict def check_arg(arg_id, *constraints): return ArgCheckAdder(arg_id, *constraints) def check_int_value(min=None, max=None): def constraint(arg_id, args, kwargs): assert isinstance(args[arg_id], int) assert args[arg_id] >= 0 return constraint class ArgCheckAdder(object): def __init__(self, arg_id, *constraints): self.arg_id = arg_id self.constraints = constraints def __call__(self, func): if hasattr(func, 'checks'): func.checks[self.arg_id].extend(self.constraints) return func else: return CheckedFunction(func, {self.arg_id: self.constraints}) class CheckedFunction(object): def __init__(self, func, checks): self.checks = defaultdict(list) self.checks.update(checks) self.func = func def __call__(self, *args, **kwargs): for arg_id, checks in self.checks.items(): for check in checks: check(arg_id, args, kwargs) self.func(*args, **kwargs) @check_arg(0, check_int_value(min=0)) @check_arg(1, check_int_value(min=0)) def add_positive_integers(int1, int2): return int1 + int2 def main(): print(add_positive_integers(1, 5)) print(add_positive_integers(0, 5)) print(add_positive_integers(-1, 5)) if __name__ == '__main__': main()
<commit_before>from __future__ import print_function @check.arg(0, check.int_value(min=0)) @check.arg(1, check.int_value(min=0)) def add_positive_integers(int1, int2): return int1 + int2 def main(): print(add_positive_integers(1, 5)) print(add_positive_integers(0, 5)) print(add_positive_integers(-1, 5)) if __name__ == '__main__': main() <commit_msg>Make isolated arg check example<commit_after>
from __future__ import print_function from collections import defaultdict def check_arg(arg_id, *constraints): return ArgCheckAdder(arg_id, *constraints) def check_int_value(min=None, max=None): def constraint(arg_id, args, kwargs): assert isinstance(args[arg_id], int) assert args[arg_id] >= 0 return constraint class ArgCheckAdder(object): def __init__(self, arg_id, *constraints): self.arg_id = arg_id self.constraints = constraints def __call__(self, func): if hasattr(func, 'checks'): func.checks[self.arg_id].extend(self.constraints) return func else: return CheckedFunction(func, {self.arg_id: self.constraints}) class CheckedFunction(object): def __init__(self, func, checks): self.checks = defaultdict(list) self.checks.update(checks) self.func = func def __call__(self, *args, **kwargs): for arg_id, checks in self.checks.items(): for check in checks: check(arg_id, args, kwargs) self.func(*args, **kwargs) @check_arg(0, check_int_value(min=0)) @check_arg(1, check_int_value(min=0)) def add_positive_integers(int1, int2): return int1 + int2 def main(): print(add_positive_integers(1, 5)) print(add_positive_integers(0, 5)) print(add_positive_integers(-1, 5)) if __name__ == '__main__': main()
from __future__ import print_function @check.arg(0, check.int_value(min=0)) @check.arg(1, check.int_value(min=0)) def add_positive_integers(int1, int2): return int1 + int2 def main(): print(add_positive_integers(1, 5)) print(add_positive_integers(0, 5)) print(add_positive_integers(-1, 5)) if __name__ == '__main__': main() Make isolated arg check examplefrom __future__ import print_function from collections import defaultdict def check_arg(arg_id, *constraints): return ArgCheckAdder(arg_id, *constraints) def check_int_value(min=None, max=None): def constraint(arg_id, args, kwargs): assert isinstance(args[arg_id], int) assert args[arg_id] >= 0 return constraint class ArgCheckAdder(object): def __init__(self, arg_id, *constraints): self.arg_id = arg_id self.constraints = constraints def __call__(self, func): if hasattr(func, 'checks'): func.checks[self.arg_id].extend(self.constraints) return func else: return CheckedFunction(func, {self.arg_id: self.constraints}) class CheckedFunction(object): def __init__(self, func, checks): self.checks = defaultdict(list) self.checks.update(checks) self.func = func def __call__(self, *args, **kwargs): for arg_id, checks in self.checks.items(): for check in checks: check(arg_id, args, kwargs) self.func(*args, **kwargs) @check_arg(0, check_int_value(min=0)) @check_arg(1, check_int_value(min=0)) def add_positive_integers(int1, int2): return int1 + int2 def main(): print(add_positive_integers(1, 5)) print(add_positive_integers(0, 5)) print(add_positive_integers(-1, 5)) if __name__ == '__main__': main()
<commit_before>from __future__ import print_function @check.arg(0, check.int_value(min=0)) @check.arg(1, check.int_value(min=0)) def add_positive_integers(int1, int2): return int1 + int2 def main(): print(add_positive_integers(1, 5)) print(add_positive_integers(0, 5)) print(add_positive_integers(-1, 5)) if __name__ == '__main__': main() <commit_msg>Make isolated arg check example<commit_after>from __future__ import print_function from collections import defaultdict def check_arg(arg_id, *constraints): return ArgCheckAdder(arg_id, *constraints) def check_int_value(min=None, max=None): def constraint(arg_id, args, kwargs): assert isinstance(args[arg_id], int) assert args[arg_id] >= 0 return constraint class ArgCheckAdder(object): def __init__(self, arg_id, *constraints): self.arg_id = arg_id self.constraints = constraints def __call__(self, func): if hasattr(func, 'checks'): func.checks[self.arg_id].extend(self.constraints) return func else: return CheckedFunction(func, {self.arg_id: self.constraints}) class CheckedFunction(object): def __init__(self, func, checks): self.checks = defaultdict(list) self.checks.update(checks) self.func = func def __call__(self, *args, **kwargs): for arg_id, checks in self.checks.items(): for check in checks: check(arg_id, args, kwargs) self.func(*args, **kwargs) @check_arg(0, check_int_value(min=0)) @check_arg(1, check_int_value(min=0)) def add_positive_integers(int1, int2): return int1 + int2 def main(): print(add_positive_integers(1, 5)) print(add_positive_integers(0, 5)) print(add_positive_integers(-1, 5)) if __name__ == '__main__': main()
f58cce56103b98e783fa0df5bae0ae0985f7dc8e
rmake_plugins/multinode_client/nodetypes.py
rmake_plugins/multinode_client/nodetypes.py
import inspect import sys import types from rmake.lib.apiutils import thaw, freeze class NodeType(object): nodeType = 'UNKNOWN' def __init__(self): pass def freeze(self): return (self.nodeType, self.__dict__) @classmethod def thaw(class_, d): return class_(**d) class Client(NodeType): nodeType = 'CLIENT' _nodeTypes = {} def registerNodeTypes(moduleName): global _nodeTypes for item in sys.modules[moduleName].__dict__.values(): if inspect.isclass(item) and issubclass(item, NodeType): _nodeTypes[item.nodeType] = item registerNodeTypes(__name__) def registerNodeType(class_): _nodeTypes[class_.nodeType] = class_ def thawNodeType(info): nodeType = info[0] return _nodeTypes[nodeType].thaw(info[1])
import inspect import sys import types from rmake.lib.apiutils import thaw, freeze _nodeTypes = {} class _NodeTypeRegistrar(type): def __init__(self, name, bases, dict): type.__init__(self, name, bases, dict) _nodeTypes[self.nodeType] = self class NodeType(object): __metaclass__ = _NodeTypeRegistrar nodeType = 'UNKNOWN' def __init__(self): pass def freeze(self): return (self.nodeType, self.__dict__) @classmethod def thaw(class_, d): return class_(**d) class Client(NodeType): nodeType = 'CLIENT' def thawNodeType(info): nodeType = info[0] return _nodeTypes[nodeType].thaw(info[1])
Use metaclasses to register node types.
Use metaclasses to register node types.
Python
apache-2.0
sassoftware/rmake3,sassoftware/rmake3,sassoftware/rmake,sassoftware/rmake,sassoftware/rmake3,sassoftware/rmake
import inspect import sys import types from rmake.lib.apiutils import thaw, freeze class NodeType(object): nodeType = 'UNKNOWN' def __init__(self): pass def freeze(self): return (self.nodeType, self.__dict__) @classmethod def thaw(class_, d): return class_(**d) class Client(NodeType): nodeType = 'CLIENT' _nodeTypes = {} def registerNodeTypes(moduleName): global _nodeTypes for item in sys.modules[moduleName].__dict__.values(): if inspect.isclass(item) and issubclass(item, NodeType): _nodeTypes[item.nodeType] = item registerNodeTypes(__name__) def registerNodeType(class_): _nodeTypes[class_.nodeType] = class_ def thawNodeType(info): nodeType = info[0] return _nodeTypes[nodeType].thaw(info[1]) Use metaclasses to register node types.
import inspect import sys import types from rmake.lib.apiutils import thaw, freeze _nodeTypes = {} class _NodeTypeRegistrar(type): def __init__(self, name, bases, dict): type.__init__(self, name, bases, dict) _nodeTypes[self.nodeType] = self class NodeType(object): __metaclass__ = _NodeTypeRegistrar nodeType = 'UNKNOWN' def __init__(self): pass def freeze(self): return (self.nodeType, self.__dict__) @classmethod def thaw(class_, d): return class_(**d) class Client(NodeType): nodeType = 'CLIENT' def thawNodeType(info): nodeType = info[0] return _nodeTypes[nodeType].thaw(info[1])
<commit_before>import inspect import sys import types from rmake.lib.apiutils import thaw, freeze class NodeType(object): nodeType = 'UNKNOWN' def __init__(self): pass def freeze(self): return (self.nodeType, self.__dict__) @classmethod def thaw(class_, d): return class_(**d) class Client(NodeType): nodeType = 'CLIENT' _nodeTypes = {} def registerNodeTypes(moduleName): global _nodeTypes for item in sys.modules[moduleName].__dict__.values(): if inspect.isclass(item) and issubclass(item, NodeType): _nodeTypes[item.nodeType] = item registerNodeTypes(__name__) def registerNodeType(class_): _nodeTypes[class_.nodeType] = class_ def thawNodeType(info): nodeType = info[0] return _nodeTypes[nodeType].thaw(info[1]) <commit_msg>Use metaclasses to register node types.<commit_after>
import inspect import sys import types from rmake.lib.apiutils import thaw, freeze _nodeTypes = {} class _NodeTypeRegistrar(type): def __init__(self, name, bases, dict): type.__init__(self, name, bases, dict) _nodeTypes[self.nodeType] = self class NodeType(object): __metaclass__ = _NodeTypeRegistrar nodeType = 'UNKNOWN' def __init__(self): pass def freeze(self): return (self.nodeType, self.__dict__) @classmethod def thaw(class_, d): return class_(**d) class Client(NodeType): nodeType = 'CLIENT' def thawNodeType(info): nodeType = info[0] return _nodeTypes[nodeType].thaw(info[1])
import inspect import sys import types from rmake.lib.apiutils import thaw, freeze class NodeType(object): nodeType = 'UNKNOWN' def __init__(self): pass def freeze(self): return (self.nodeType, self.__dict__) @classmethod def thaw(class_, d): return class_(**d) class Client(NodeType): nodeType = 'CLIENT' _nodeTypes = {} def registerNodeTypes(moduleName): global _nodeTypes for item in sys.modules[moduleName].__dict__.values(): if inspect.isclass(item) and issubclass(item, NodeType): _nodeTypes[item.nodeType] = item registerNodeTypes(__name__) def registerNodeType(class_): _nodeTypes[class_.nodeType] = class_ def thawNodeType(info): nodeType = info[0] return _nodeTypes[nodeType].thaw(info[1]) Use metaclasses to register node types.import inspect import sys import types from rmake.lib.apiutils import thaw, freeze _nodeTypes = {} class _NodeTypeRegistrar(type): def __init__(self, name, bases, dict): type.__init__(self, name, bases, dict) _nodeTypes[self.nodeType] = self class NodeType(object): __metaclass__ = _NodeTypeRegistrar nodeType = 'UNKNOWN' def __init__(self): pass def freeze(self): return (self.nodeType, self.__dict__) @classmethod def thaw(class_, d): return class_(**d) class Client(NodeType): nodeType = 'CLIENT' def thawNodeType(info): nodeType = info[0] return _nodeTypes[nodeType].thaw(info[1])
<commit_before>import inspect import sys import types from rmake.lib.apiutils import thaw, freeze class NodeType(object): nodeType = 'UNKNOWN' def __init__(self): pass def freeze(self): return (self.nodeType, self.__dict__) @classmethod def thaw(class_, d): return class_(**d) class Client(NodeType): nodeType = 'CLIENT' _nodeTypes = {} def registerNodeTypes(moduleName): global _nodeTypes for item in sys.modules[moduleName].__dict__.values(): if inspect.isclass(item) and issubclass(item, NodeType): _nodeTypes[item.nodeType] = item registerNodeTypes(__name__) def registerNodeType(class_): _nodeTypes[class_.nodeType] = class_ def thawNodeType(info): nodeType = info[0] return _nodeTypes[nodeType].thaw(info[1]) <commit_msg>Use metaclasses to register node types.<commit_after>import inspect import sys import types from rmake.lib.apiutils import thaw, freeze _nodeTypes = {} class _NodeTypeRegistrar(type): def __init__(self, name, bases, dict): type.__init__(self, name, bases, dict) _nodeTypes[self.nodeType] = self class NodeType(object): __metaclass__ = _NodeTypeRegistrar nodeType = 'UNKNOWN' def __init__(self): pass def freeze(self): return (self.nodeType, self.__dict__) @classmethod def thaw(class_, d): return class_(**d) class Client(NodeType): nodeType = 'CLIENT' def thawNodeType(info): nodeType = info[0] return _nodeTypes[nodeType].thaw(info[1])
222a87ef324f66baf8113020b41d336c459ab847
stdnum/fi/__init__.py
stdnum/fi/__init__.py
# __init__.py - collection of Finnish numbers # coding: utf-8 # # Copyright (C) 2012 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid
# __init__.py - collection of Finnish numbers # coding: utf-8 # # Copyright (C) 2012 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid from stdnum.fi import hetu as personalid
Add alias to hetu in for finnish personal id code
Add alias to hetu in for finnish personal id code
Python
lgpl-2.1
holvi/python-stdnum,holvi/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum,holvi/python-stdnum,arthurdejong/python-stdnum
# __init__.py - collection of Finnish numbers # coding: utf-8 # # Copyright (C) 2012 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid Add alias to hetu in for finnish personal id code
# __init__.py - collection of Finnish numbers # coding: utf-8 # # Copyright (C) 2012 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid from stdnum.fi import hetu as personalid
<commit_before># __init__.py - collection of Finnish numbers # coding: utf-8 # # Copyright (C) 2012 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid <commit_msg>Add alias to hetu in for finnish personal id code<commit_after>
# __init__.py - collection of Finnish numbers # coding: utf-8 # # Copyright (C) 2012 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid from stdnum.fi import hetu as personalid
# __init__.py - collection of Finnish numbers # coding: utf-8 # # Copyright (C) 2012 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid Add alias to hetu in for finnish personal id code# __init__.py - collection of Finnish numbers # coding: utf-8 # # Copyright (C) 2012 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid from stdnum.fi import hetu as personalid
<commit_before># __init__.py - collection of Finnish numbers # coding: utf-8 # # Copyright (C) 2012 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid <commit_msg>Add alias to hetu in for finnish personal id code<commit_after># __init__.py - collection of Finnish numbers # coding: utf-8 # # Copyright (C) 2012 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Finnish numbers.""" # provide vat as an alias from stdnum.fi import alv as vat from stdnum.fi import ytunnus as businessid from stdnum.fi import hetu as personalid
563a905a48a5d4059463f25c5467a52a9d9c79c5
groove/timezone.py
groove/timezone.py
from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day)
from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) def datetime_aware(year, month, day, hour, minute, second): """ Return a datetime aware object with current local timezone. """ _datetime = datetime(year, month, day, hour, minute, second) return timezone.make_aware(_datetime, timezone.get_current_timezone())
Add function for creating a datetime aware object
Add function for creating a datetime aware object
Python
bsd-2-clause
funkbit/django-groove
from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) Add function for creating a datetime aware object
from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) def datetime_aware(year, month, day, hour, minute, second): """ Return a datetime aware object with current local timezone. """ _datetime = datetime(year, month, day, hour, minute, second) return timezone.make_aware(_datetime, timezone.get_current_timezone())
<commit_before>from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) <commit_msg>Add function for creating a datetime aware object<commit_after>
from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) def datetime_aware(year, month, day, hour, minute, second): """ Return a datetime aware object with current local timezone. """ _datetime = datetime(year, month, day, hour, minute, second) return timezone.make_aware(_datetime, timezone.get_current_timezone())
from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) Add function for creating a datetime aware objectfrom datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) def datetime_aware(year, month, day, hour, minute, second): """ Return a datetime aware object with current local timezone. """ _datetime = datetime(year, month, day, hour, minute, second) return timezone.make_aware(_datetime, timezone.get_current_timezone())
<commit_before>from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) <commit_msg>Add function for creating a datetime aware object<commit_after>from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) def datetime_aware(year, month, day, hour, minute, second): """ Return a datetime aware object with current local timezone. """ _datetime = datetime(year, month, day, hour, minute, second) return timezone.make_aware(_datetime, timezone.get_current_timezone())
b2de891e75dc84e809b9c35222e6bc8fe44c3d37
test_arg.py
test_arg.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division import unittest as ut import numpy as np import ARG.arg as arg class ARGTestCase(ut.TestCase): def test_truisms(self): """Test parameter class""" param = arg.ARGparams() self.assertTrue(isinstance(param.scale, float)) self.assertTrue(isinstance(param.rho, float)) self.assertTrue(isinstance(param.delta, float)) self.assertTrue(isinstance(param.beta(), float)) if __name__ == '__main__': ut.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division import unittest as ut import numpy as np import ARG.arg as arg class ARGTestCase(ut.TestCase): def test_param_class(self): """Test parameter class.""" param = arg.ARGparams() self.assertIsInstance(param.scale, float) self.assertIsInstance(param.rho, float) self.assertIsInstance(param.delta, float) self.assertIsInstance(param.beta(), float) def test_abc_functions(self): """Test functions a, b, c of ARG model.""" argmodel = arg.ARG() uarg = np.linspace(-50, 100, 100) self.assertIsInstance(argmodel.afun(uarg), np.ndarray) self.assertIsInstance(argmodel.bfun(uarg), np.ndarray) self.assertIsInstance(argmodel.cfun(uarg), np.ndarray) if __name__ == '__main__': ut.main()
Test functions a, b, c
Test functions a, b, c
Python
mit
khrapovs/argamma
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division import unittest as ut import numpy as np import ARG.arg as arg class ARGTestCase(ut.TestCase): def test_truisms(self): """Test parameter class""" param = arg.ARGparams() self.assertTrue(isinstance(param.scale, float)) self.assertTrue(isinstance(param.rho, float)) self.assertTrue(isinstance(param.delta, float)) self.assertTrue(isinstance(param.beta(), float)) if __name__ == '__main__': ut.main()Test functions a, b, c
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division import unittest as ut import numpy as np import ARG.arg as arg class ARGTestCase(ut.TestCase): def test_param_class(self): """Test parameter class.""" param = arg.ARGparams() self.assertIsInstance(param.scale, float) self.assertIsInstance(param.rho, float) self.assertIsInstance(param.delta, float) self.assertIsInstance(param.beta(), float) def test_abc_functions(self): """Test functions a, b, c of ARG model.""" argmodel = arg.ARG() uarg = np.linspace(-50, 100, 100) self.assertIsInstance(argmodel.afun(uarg), np.ndarray) self.assertIsInstance(argmodel.bfun(uarg), np.ndarray) self.assertIsInstance(argmodel.cfun(uarg), np.ndarray) if __name__ == '__main__': ut.main()
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division import unittest as ut import numpy as np import ARG.arg as arg class ARGTestCase(ut.TestCase): def test_truisms(self): """Test parameter class""" param = arg.ARGparams() self.assertTrue(isinstance(param.scale, float)) self.assertTrue(isinstance(param.rho, float)) self.assertTrue(isinstance(param.delta, float)) self.assertTrue(isinstance(param.beta(), float)) if __name__ == '__main__': ut.main()<commit_msg>Test functions a, b, c<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division import unittest as ut import numpy as np import ARG.arg as arg class ARGTestCase(ut.TestCase): def test_param_class(self): """Test parameter class.""" param = arg.ARGparams() self.assertIsInstance(param.scale, float) self.assertIsInstance(param.rho, float) self.assertIsInstance(param.delta, float) self.assertIsInstance(param.beta(), float) def test_abc_functions(self): """Test functions a, b, c of ARG model.""" argmodel = arg.ARG() uarg = np.linspace(-50, 100, 100) self.assertIsInstance(argmodel.afun(uarg), np.ndarray) self.assertIsInstance(argmodel.bfun(uarg), np.ndarray) self.assertIsInstance(argmodel.cfun(uarg), np.ndarray) if __name__ == '__main__': ut.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division import unittest as ut import numpy as np import ARG.arg as arg class ARGTestCase(ut.TestCase): def test_truisms(self): """Test parameter class""" param = arg.ARGparams() self.assertTrue(isinstance(param.scale, float)) self.assertTrue(isinstance(param.rho, float)) self.assertTrue(isinstance(param.delta, float)) self.assertTrue(isinstance(param.beta(), float)) if __name__ == '__main__': ut.main()Test functions a, b, c#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division import unittest as ut import numpy as np import ARG.arg as arg class ARGTestCase(ut.TestCase): def test_param_class(self): """Test parameter class.""" param = arg.ARGparams() self.assertIsInstance(param.scale, float) self.assertIsInstance(param.rho, float) self.assertIsInstance(param.delta, float) self.assertIsInstance(param.beta(), float) def test_abc_functions(self): """Test functions a, b, c of ARG model.""" argmodel = arg.ARG() uarg = np.linspace(-50, 100, 100) self.assertIsInstance(argmodel.afun(uarg), np.ndarray) self.assertIsInstance(argmodel.bfun(uarg), np.ndarray) self.assertIsInstance(argmodel.cfun(uarg), np.ndarray) if __name__ == '__main__': ut.main()
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division import unittest as ut import numpy as np import ARG.arg as arg class ARGTestCase(ut.TestCase): def test_truisms(self): """Test parameter class""" param = arg.ARGparams() self.assertTrue(isinstance(param.scale, float)) self.assertTrue(isinstance(param.rho, float)) self.assertTrue(isinstance(param.delta, float)) self.assertTrue(isinstance(param.beta(), float)) if __name__ == '__main__': ut.main()<commit_msg>Test functions a, b, c<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division import unittest as ut import numpy as np import ARG.arg as arg class ARGTestCase(ut.TestCase): def test_param_class(self): """Test parameter class.""" param = arg.ARGparams() self.assertIsInstance(param.scale, float) self.assertIsInstance(param.rho, float) self.assertIsInstance(param.delta, float) self.assertIsInstance(param.beta(), float) def test_abc_functions(self): """Test functions a, b, c of ARG model.""" argmodel = arg.ARG() uarg = np.linspace(-50, 100, 100) self.assertIsInstance(argmodel.afun(uarg), np.ndarray) self.assertIsInstance(argmodel.bfun(uarg), np.ndarray) self.assertIsInstance(argmodel.cfun(uarg), np.ndarray) if __name__ == '__main__': ut.main()
369b0499d02531e7058f4f0d6c5051b9058701aa
metadata_to_json_and_fnamesmap.py
metadata_to_json_and_fnamesmap.py
#! /usr/bin/env python # -*- coding: utf-8 -*- """Turn Excel metadata from SMVK into JSON-file for further processing. Input: Excel-file Processing: strip whitespace etc Output: JSON-file `cypern_metadata.json" containg dict in the current directory """ import pandas as pd import argparse def main(): """Illustrate function-level docstring. Note that all docstrings begin with a one-line summary. The summary is written in the imperative mood ("do", "use", "find", "return", "render", etc) and ends with a period. The method signature is not, in any way, duplicated into the comments (that would be difficult to maintain). All subsequent paragraphs in a docstring are indented exactly the same as the summary line. The same applies to the closing quotation marks. """ try: metadata = pd.read_excel(args.infile) except IOError as e: print("IOError: {}".format(e)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--infile",default="../excel-export.xls") parser.add_argument("--fname-file",default="SMVK-Cypern_2017-01_filename_mappings.csv") parser.add_argument("-outfile", default="SMVK-Cypern_2017-01_metadata.json") args = parser.parse_args() main()
#! /usr/bin/env python # -*- coding: utf-8 -*- """Turn Excel metadata from SMVK into JSON-file for further processing. Input: Excel-file Processing: strip whitespace etc Output: JSON-file `cypern_metadata.json" containg dict in the current directory """ import pandas as pd import argparse def strip(text): try: return text.strip() except AttributeError: return text cypern_converters = {"Fotonummer": strip, "Postnr": strip, "Nyckelord": strip, "Beskrivning": strip, "Land": strip, "foto": strip, "Region, foto": strip, "Ort, foto": strip, "Geograf namn, alternativ": strip, "Fotodatum": strip, "Personnamn / fotograf": strip, "Personnamn / avbildad": strip, "Sökord": strip, "Händelse / var närvarande vid": strip, "Länk": strip} def main(): """Read infile and output json-file and filenames mapping file.""" try: metadata = pd.read_excel(args.infile, sheetname="Cypern", converters=cypern_converters) except IOError as e: print("IOError: {}".format(e)) print(metadata.info()) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--infile",default="../excel-export.xls") parser.add_argument("--fname-file",default="SMVK-Cypern_2017-01_filename_mappings.csv") parser.add_argument("-outfile", default="SMVK-Cypern_2017-01_metadata.json") args = parser.parse_args() main()
Read sheetname 'Cypern' and strip column names
Read sheetname 'Cypern' and strip column names
Python
mit
mattiasostmar/SMVK-Cypern_2017-01
#! /usr/bin/env python # -*- coding: utf-8 -*- """Turn Excel metadata from SMVK into JSON-file for further processing. Input: Excel-file Processing: strip whitespace etc Output: JSON-file `cypern_metadata.json" containg dict in the current directory """ import pandas as pd import argparse def main(): """Illustrate function-level docstring. Note that all docstrings begin with a one-line summary. The summary is written in the imperative mood ("do", "use", "find", "return", "render", etc) and ends with a period. The method signature is not, in any way, duplicated into the comments (that would be difficult to maintain). All subsequent paragraphs in a docstring are indented exactly the same as the summary line. The same applies to the closing quotation marks. """ try: metadata = pd.read_excel(args.infile) except IOError as e: print("IOError: {}".format(e)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--infile",default="../excel-export.xls") parser.add_argument("--fname-file",default="SMVK-Cypern_2017-01_filename_mappings.csv") parser.add_argument("-outfile", default="SMVK-Cypern_2017-01_metadata.json") args = parser.parse_args() main()Read sheetname 'Cypern' and strip column names
#! /usr/bin/env python # -*- coding: utf-8 -*- """Turn Excel metadata from SMVK into JSON-file for further processing. Input: Excel-file Processing: strip whitespace etc Output: JSON-file `cypern_metadata.json" containg dict in the current directory """ import pandas as pd import argparse def strip(text): try: return text.strip() except AttributeError: return text cypern_converters = {"Fotonummer": strip, "Postnr": strip, "Nyckelord": strip, "Beskrivning": strip, "Land": strip, "foto": strip, "Region, foto": strip, "Ort, foto": strip, "Geograf namn, alternativ": strip, "Fotodatum": strip, "Personnamn / fotograf": strip, "Personnamn / avbildad": strip, "Sökord": strip, "Händelse / var närvarande vid": strip, "Länk": strip} def main(): """Read infile and output json-file and filenames mapping file.""" try: metadata = pd.read_excel(args.infile, sheetname="Cypern", converters=cypern_converters) except IOError as e: print("IOError: {}".format(e)) print(metadata.info()) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--infile",default="../excel-export.xls") parser.add_argument("--fname-file",default="SMVK-Cypern_2017-01_filename_mappings.csv") parser.add_argument("-outfile", default="SMVK-Cypern_2017-01_metadata.json") args = parser.parse_args() main()
<commit_before>#! /usr/bin/env python # -*- coding: utf-8 -*- """Turn Excel metadata from SMVK into JSON-file for further processing. Input: Excel-file Processing: strip whitespace etc Output: JSON-file `cypern_metadata.json" containg dict in the current directory """ import pandas as pd import argparse def main(): """Illustrate function-level docstring. Note that all docstrings begin with a one-line summary. The summary is written in the imperative mood ("do", "use", "find", "return", "render", etc) and ends with a period. The method signature is not, in any way, duplicated into the comments (that would be difficult to maintain). All subsequent paragraphs in a docstring are indented exactly the same as the summary line. The same applies to the closing quotation marks. """ try: metadata = pd.read_excel(args.infile) except IOError as e: print("IOError: {}".format(e)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--infile",default="../excel-export.xls") parser.add_argument("--fname-file",default="SMVK-Cypern_2017-01_filename_mappings.csv") parser.add_argument("-outfile", default="SMVK-Cypern_2017-01_metadata.json") args = parser.parse_args() main()<commit_msg>Read sheetname 'Cypern' and strip column names<commit_after>
#! /usr/bin/env python # -*- coding: utf-8 -*- """Turn Excel metadata from SMVK into JSON-file for further processing. Input: Excel-file Processing: strip whitespace etc Output: JSON-file `cypern_metadata.json" containg dict in the current directory """ import pandas as pd import argparse def strip(text): try: return text.strip() except AttributeError: return text cypern_converters = {"Fotonummer": strip, "Postnr": strip, "Nyckelord": strip, "Beskrivning": strip, "Land": strip, "foto": strip, "Region, foto": strip, "Ort, foto": strip, "Geograf namn, alternativ": strip, "Fotodatum": strip, "Personnamn / fotograf": strip, "Personnamn / avbildad": strip, "Sökord": strip, "Händelse / var närvarande vid": strip, "Länk": strip} def main(): """Read infile and output json-file and filenames mapping file.""" try: metadata = pd.read_excel(args.infile, sheetname="Cypern", converters=cypern_converters) except IOError as e: print("IOError: {}".format(e)) print(metadata.info()) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--infile",default="../excel-export.xls") parser.add_argument("--fname-file",default="SMVK-Cypern_2017-01_filename_mappings.csv") parser.add_argument("-outfile", default="SMVK-Cypern_2017-01_metadata.json") args = parser.parse_args() main()
#! /usr/bin/env python # -*- coding: utf-8 -*- """Turn Excel metadata from SMVK into JSON-file for further processing. Input: Excel-file Processing: strip whitespace etc Output: JSON-file `cypern_metadata.json" containg dict in the current directory """ import pandas as pd import argparse def main(): """Illustrate function-level docstring. Note that all docstrings begin with a one-line summary. The summary is written in the imperative mood ("do", "use", "find", "return", "render", etc) and ends with a period. The method signature is not, in any way, duplicated into the comments (that would be difficult to maintain). All subsequent paragraphs in a docstring are indented exactly the same as the summary line. The same applies to the closing quotation marks. """ try: metadata = pd.read_excel(args.infile) except IOError as e: print("IOError: {}".format(e)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--infile",default="../excel-export.xls") parser.add_argument("--fname-file",default="SMVK-Cypern_2017-01_filename_mappings.csv") parser.add_argument("-outfile", default="SMVK-Cypern_2017-01_metadata.json") args = parser.parse_args() main()Read sheetname 'Cypern' and strip column names#! /usr/bin/env python # -*- coding: utf-8 -*- """Turn Excel metadata from SMVK into JSON-file for further processing. Input: Excel-file Processing: strip whitespace etc Output: JSON-file `cypern_metadata.json" containg dict in the current directory """ import pandas as pd import argparse def strip(text): try: return text.strip() except AttributeError: return text cypern_converters = {"Fotonummer": strip, "Postnr": strip, "Nyckelord": strip, "Beskrivning": strip, "Land": strip, "foto": strip, "Region, foto": strip, "Ort, foto": strip, "Geograf namn, alternativ": strip, "Fotodatum": strip, "Personnamn / fotograf": strip, "Personnamn / avbildad": strip, "Sökord": strip, "Händelse / var närvarande vid": strip, "Länk": strip} def main(): """Read infile and output json-file and filenames mapping file.""" try: metadata = pd.read_excel(args.infile, sheetname="Cypern", converters=cypern_converters) except IOError as e: print("IOError: {}".format(e)) print(metadata.info()) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--infile",default="../excel-export.xls") parser.add_argument("--fname-file",default="SMVK-Cypern_2017-01_filename_mappings.csv") parser.add_argument("-outfile", default="SMVK-Cypern_2017-01_metadata.json") args = parser.parse_args() main()
<commit_before>#! /usr/bin/env python # -*- coding: utf-8 -*- """Turn Excel metadata from SMVK into JSON-file for further processing. Input: Excel-file Processing: strip whitespace etc Output: JSON-file `cypern_metadata.json" containg dict in the current directory """ import pandas as pd import argparse def main(): """Illustrate function-level docstring. Note that all docstrings begin with a one-line summary. The summary is written in the imperative mood ("do", "use", "find", "return", "render", etc) and ends with a period. The method signature is not, in any way, duplicated into the comments (that would be difficult to maintain). All subsequent paragraphs in a docstring are indented exactly the same as the summary line. The same applies to the closing quotation marks. """ try: metadata = pd.read_excel(args.infile) except IOError as e: print("IOError: {}".format(e)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--infile",default="../excel-export.xls") parser.add_argument("--fname-file",default="SMVK-Cypern_2017-01_filename_mappings.csv") parser.add_argument("-outfile", default="SMVK-Cypern_2017-01_metadata.json") args = parser.parse_args() main()<commit_msg>Read sheetname 'Cypern' and strip column names<commit_after>#! /usr/bin/env python # -*- coding: utf-8 -*- """Turn Excel metadata from SMVK into JSON-file for further processing. Input: Excel-file Processing: strip whitespace etc Output: JSON-file `cypern_metadata.json" containg dict in the current directory """ import pandas as pd import argparse def strip(text): try: return text.strip() except AttributeError: return text cypern_converters = {"Fotonummer": strip, "Postnr": strip, "Nyckelord": strip, "Beskrivning": strip, "Land": strip, "foto": strip, "Region, foto": strip, "Ort, foto": strip, "Geograf namn, alternativ": strip, "Fotodatum": strip, "Personnamn / fotograf": strip, "Personnamn / avbildad": strip, "Sökord": strip, "Händelse / var närvarande vid": strip, "Länk": strip} def main(): """Read infile and output json-file and filenames mapping file.""" try: metadata = pd.read_excel(args.infile, sheetname="Cypern", converters=cypern_converters) except IOError as e: print("IOError: {}".format(e)) print(metadata.info()) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--infile",default="../excel-export.xls") parser.add_argument("--fname-file",default="SMVK-Cypern_2017-01_filename_mappings.csv") parser.add_argument("-outfile", default="SMVK-Cypern_2017-01_metadata.json") args = parser.parse_args() main()
592bbd24b0711be5c3e87133fc27429c83eabc01
nipype/interfaces/spm/__init__.py
nipype/interfaces/spm/__init__.py
"""Top-level namespace for spm.""" from nipype.interfaces.spm.base import (SpmInfo, SpmMatlabCommandLine, scans_for_fname, scans_for_fnames) from nipype.interfaces.spm.preprocess import (SliceTiming, Realign, Coregister, Normalize, Segment, Smooth) from nipype.interfaces.spm.model import (Level1Design, EstimateModel, EstimateContrast, OneSampleTTest, TwoSampleTTest, MultipleRegression)
Add spm imports at package level. Most tests pass now.
Add spm imports at package level. Most tests pass now. git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1141 ead46cd0-7350-4e37-8683-fc4c6f79bf00
Python
bsd-3-clause
JohnGriffiths/nipype,carolFrohlich/nipype,blakedewey/nipype,christianbrodbeck/nipype,fprados/nipype,FCP-INDI/nipype,carlohamalainen/nipype,grlee77/nipype,dgellis90/nipype,sgiavasis/nipype,rameshvs/nipype,fprados/nipype,blakedewey/nipype,FredLoney/nipype,dgellis90/nipype,carlohamalainen/nipype,dmordom/nipype,sgiavasis/nipype,rameshvs/nipype,pearsonlab/nipype,iglpdc/nipype,mick-d/nipype,glatard/nipype,Leoniela/nipype,mick-d/nipype_source,satra/NiPypeold,dmordom/nipype,FCP-INDI/nipype,wanderine/nipype,carolFrohlich/nipype,arokem/nipype,JohnGriffiths/nipype,Leoniela/nipype,grlee77/nipype,wanderine/nipype,JohnGriffiths/nipype,mick-d/nipype,iglpdc/nipype,sgiavasis/nipype,blakedewey/nipype,dgellis90/nipype,gerddie/nipype,wanderine/nipype,Leoniela/nipype,glatard/nipype,satra/NiPypeold,wanderine/nipype,rameshvs/nipype,arokem/nipype,dmordom/nipype,carolFrohlich/nipype,FCP-INDI/nipype,FredLoney/nipype,grlee77/nipype,fprados/nipype,pearsonlab/nipype,christianbrodbeck/nipype,sgiavasis/nipype,mick-d/nipype_source,mick-d/nipype_source,iglpdc/nipype,pearsonlab/nipype,rameshvs/nipype,glatard/nipype,gerddie/nipype,gerddie/nipype,pearsonlab/nipype,arokem/nipype,carolFrohlich/nipype,blakedewey/nipype,carlohamalainen/nipype,dgellis90/nipype,mick-d/nipype,iglpdc/nipype,FredLoney/nipype,FCP-INDI/nipype,gerddie/nipype,grlee77/nipype,JohnGriffiths/nipype,mick-d/nipype,glatard/nipype,arokem/nipype
Add spm imports at package level. Most tests pass now. git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1141 ead46cd0-7350-4e37-8683-fc4c6f79bf00
"""Top-level namespace for spm.""" from nipype.interfaces.spm.base import (SpmInfo, SpmMatlabCommandLine, scans_for_fname, scans_for_fnames) from nipype.interfaces.spm.preprocess import (SliceTiming, Realign, Coregister, Normalize, Segment, Smooth) from nipype.interfaces.spm.model import (Level1Design, EstimateModel, EstimateContrast, OneSampleTTest, TwoSampleTTest, MultipleRegression)
<commit_before><commit_msg>Add spm imports at package level. Most tests pass now. git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1141 ead46cd0-7350-4e37-8683-fc4c6f79bf00<commit_after>
"""Top-level namespace for spm.""" from nipype.interfaces.spm.base import (SpmInfo, SpmMatlabCommandLine, scans_for_fname, scans_for_fnames) from nipype.interfaces.spm.preprocess import (SliceTiming, Realign, Coregister, Normalize, Segment, Smooth) from nipype.interfaces.spm.model import (Level1Design, EstimateModel, EstimateContrast, OneSampleTTest, TwoSampleTTest, MultipleRegression)
Add spm imports at package level. Most tests pass now. git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1141 ead46cd0-7350-4e37-8683-fc4c6f79bf00"""Top-level namespace for spm.""" from nipype.interfaces.spm.base import (SpmInfo, SpmMatlabCommandLine, scans_for_fname, scans_for_fnames) from nipype.interfaces.spm.preprocess import (SliceTiming, Realign, Coregister, Normalize, Segment, Smooth) from nipype.interfaces.spm.model import (Level1Design, EstimateModel, EstimateContrast, OneSampleTTest, TwoSampleTTest, MultipleRegression)
<commit_before><commit_msg>Add spm imports at package level. Most tests pass now. git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1141 ead46cd0-7350-4e37-8683-fc4c6f79bf00<commit_after>"""Top-level namespace for spm.""" from nipype.interfaces.spm.base import (SpmInfo, SpmMatlabCommandLine, scans_for_fname, scans_for_fnames) from nipype.interfaces.spm.preprocess import (SliceTiming, Realign, Coregister, Normalize, Segment, Smooth) from nipype.interfaces.spm.model import (Level1Design, EstimateModel, EstimateContrast, OneSampleTTest, TwoSampleTTest, MultipleRegression)
0c4bdc2d27fb289979004c7e0a0b9d0bf0a764cf
main.py
main.py
# -*- coding: utf-8 -*- import numpy as np import universe seed = 91231 n_trials = 20 n_steps = 1000 steps_to_reward = 9 max_reward = n_steps // steps_to_reward * 5. uni = universe.Universe('grid_world', world='2d_world0') uni.show() reward = [] for i in range(n_trials): np.random.seed(1234 + i) uni.reset_agent_position() uni.reset_agent_reward() for _ in range(n_steps): uni.step() reward.append(uni._agent._total_reward) print('total reward after {steps} steps: {reward}/{max_reward}'.format(steps=n_steps, reward=uni._agent._total_reward, max_reward=max_reward))
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np import universe seed = 91231 n_trials = 20 n_steps = 1000 steps_to_reward = 14 max_reward = n_steps // steps_to_reward * 5. uni = universe.Universe('grid_world', world='2d_world1') uni.show() reward = [] for i in range(n_trials): reward_trial = [] np.random.seed(1234 + i) uni.reset_agent_position() uni.reset_agent_reward() for _ in range(n_steps): uni.step() reward_trial.append(uni._agent._total_reward) reward.append(reward_trial) print('total reward after {steps} steps: {reward}/{max_reward}'.format(steps=n_steps, reward=uni._agent._total_reward, max_reward=max_reward)) for i in range(n_trials): plt.plot(reward[i]) plt.show()
Add trial cumulative reward plot
Add trial cumulative reward plot
Python
mit
jakobj/python-tdl
# -*- coding: utf-8 -*- import numpy as np import universe seed = 91231 n_trials = 20 n_steps = 1000 steps_to_reward = 9 max_reward = n_steps // steps_to_reward * 5. uni = universe.Universe('grid_world', world='2d_world0') uni.show() reward = [] for i in range(n_trials): np.random.seed(1234 + i) uni.reset_agent_position() uni.reset_agent_reward() for _ in range(n_steps): uni.step() reward.append(uni._agent._total_reward) print('total reward after {steps} steps: {reward}/{max_reward}'.format(steps=n_steps, reward=uni._agent._total_reward, max_reward=max_reward)) Add trial cumulative reward plot
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np import universe seed = 91231 n_trials = 20 n_steps = 1000 steps_to_reward = 14 max_reward = n_steps // steps_to_reward * 5. uni = universe.Universe('grid_world', world='2d_world1') uni.show() reward = [] for i in range(n_trials): reward_trial = [] np.random.seed(1234 + i) uni.reset_agent_position() uni.reset_agent_reward() for _ in range(n_steps): uni.step() reward_trial.append(uni._agent._total_reward) reward.append(reward_trial) print('total reward after {steps} steps: {reward}/{max_reward}'.format(steps=n_steps, reward=uni._agent._total_reward, max_reward=max_reward)) for i in range(n_trials): plt.plot(reward[i]) plt.show()
<commit_before># -*- coding: utf-8 -*- import numpy as np import universe seed = 91231 n_trials = 20 n_steps = 1000 steps_to_reward = 9 max_reward = n_steps // steps_to_reward * 5. uni = universe.Universe('grid_world', world='2d_world0') uni.show() reward = [] for i in range(n_trials): np.random.seed(1234 + i) uni.reset_agent_position() uni.reset_agent_reward() for _ in range(n_steps): uni.step() reward.append(uni._agent._total_reward) print('total reward after {steps} steps: {reward}/{max_reward}'.format(steps=n_steps, reward=uni._agent._total_reward, max_reward=max_reward)) <commit_msg>Add trial cumulative reward plot<commit_after>
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np import universe seed = 91231 n_trials = 20 n_steps = 1000 steps_to_reward = 14 max_reward = n_steps // steps_to_reward * 5. uni = universe.Universe('grid_world', world='2d_world1') uni.show() reward = [] for i in range(n_trials): reward_trial = [] np.random.seed(1234 + i) uni.reset_agent_position() uni.reset_agent_reward() for _ in range(n_steps): uni.step() reward_trial.append(uni._agent._total_reward) reward.append(reward_trial) print('total reward after {steps} steps: {reward}/{max_reward}'.format(steps=n_steps, reward=uni._agent._total_reward, max_reward=max_reward)) for i in range(n_trials): plt.plot(reward[i]) plt.show()
# -*- coding: utf-8 -*- import numpy as np import universe seed = 91231 n_trials = 20 n_steps = 1000 steps_to_reward = 9 max_reward = n_steps // steps_to_reward * 5. uni = universe.Universe('grid_world', world='2d_world0') uni.show() reward = [] for i in range(n_trials): np.random.seed(1234 + i) uni.reset_agent_position() uni.reset_agent_reward() for _ in range(n_steps): uni.step() reward.append(uni._agent._total_reward) print('total reward after {steps} steps: {reward}/{max_reward}'.format(steps=n_steps, reward=uni._agent._total_reward, max_reward=max_reward)) Add trial cumulative reward plot# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np import universe seed = 91231 n_trials = 20 n_steps = 1000 steps_to_reward = 14 max_reward = n_steps // steps_to_reward * 5. uni = universe.Universe('grid_world', world='2d_world1') uni.show() reward = [] for i in range(n_trials): reward_trial = [] np.random.seed(1234 + i) uni.reset_agent_position() uni.reset_agent_reward() for _ in range(n_steps): uni.step() reward_trial.append(uni._agent._total_reward) reward.append(reward_trial) print('total reward after {steps} steps: {reward}/{max_reward}'.format(steps=n_steps, reward=uni._agent._total_reward, max_reward=max_reward)) for i in range(n_trials): plt.plot(reward[i]) plt.show()
<commit_before># -*- coding: utf-8 -*- import numpy as np import universe seed = 91231 n_trials = 20 n_steps = 1000 steps_to_reward = 9 max_reward = n_steps // steps_to_reward * 5. uni = universe.Universe('grid_world', world='2d_world0') uni.show() reward = [] for i in range(n_trials): np.random.seed(1234 + i) uni.reset_agent_position() uni.reset_agent_reward() for _ in range(n_steps): uni.step() reward.append(uni._agent._total_reward) print('total reward after {steps} steps: {reward}/{max_reward}'.format(steps=n_steps, reward=uni._agent._total_reward, max_reward=max_reward)) <commit_msg>Add trial cumulative reward plot<commit_after># -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np import universe seed = 91231 n_trials = 20 n_steps = 1000 steps_to_reward = 14 max_reward = n_steps // steps_to_reward * 5. uni = universe.Universe('grid_world', world='2d_world1') uni.show() reward = [] for i in range(n_trials): reward_trial = [] np.random.seed(1234 + i) uni.reset_agent_position() uni.reset_agent_reward() for _ in range(n_steps): uni.step() reward_trial.append(uni._agent._total_reward) reward.append(reward_trial) print('total reward after {steps} steps: {reward}/{max_reward}'.format(steps=n_steps, reward=uni._agent._total_reward, max_reward=max_reward)) for i in range(n_trials): plt.plot(reward[i]) plt.show()
52c8b8d2676024ff07722115c815ecdd04dd000c
etrago/cluster/analyses/config.py
etrago/cluster/analyses/config.py
# -*- coding: utf-8 -*- """ """ from os import path root_path = '/home/openego/pf_results/' \ 'snapshot-clustering-results-k10-cyclic-withpypsaweighting/' clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path
# -*- coding: utf-8 -*- """ """ from os import path root_path = path.join(path.expanduser('~'),'pf_results/' \ 'snapshot-clustering-results-k10-cyclic/') clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path
Set path automatically to home of user
Set path automatically to home of user
Python
agpl-3.0
openego/eTraGo
# -*- coding: utf-8 -*- """ """ from os import path root_path = '/home/openego/pf_results/' \ 'snapshot-clustering-results-k10-cyclic-withpypsaweighting/' clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path Set path automatically to home of user
# -*- coding: utf-8 -*- """ """ from os import path root_path = path.join(path.expanduser('~'),'pf_results/' \ 'snapshot-clustering-results-k10-cyclic/') clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path
<commit_before># -*- coding: utf-8 -*- """ """ from os import path root_path = '/home/openego/pf_results/' \ 'snapshot-clustering-results-k10-cyclic-withpypsaweighting/' clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path <commit_msg>Set path automatically to home of user<commit_after>
# -*- coding: utf-8 -*- """ """ from os import path root_path = path.join(path.expanduser('~'),'pf_results/' \ 'snapshot-clustering-results-k10-cyclic/') clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path
# -*- coding: utf-8 -*- """ """ from os import path root_path = '/home/openego/pf_results/' \ 'snapshot-clustering-results-k10-cyclic-withpypsaweighting/' clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path Set path automatically to home of user# -*- coding: utf-8 -*- """ """ from os import path root_path = path.join(path.expanduser('~'),'pf_results/' \ 'snapshot-clustering-results-k10-cyclic/') clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path
<commit_before># -*- coding: utf-8 -*- """ """ from os import path root_path = '/home/openego/pf_results/' \ 'snapshot-clustering-results-k10-cyclic-withpypsaweighting/' clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path <commit_msg>Set path automatically to home of user<commit_after># -*- coding: utf-8 -*- """ """ from os import path root_path = path.join(path.expanduser('~'),'pf_results/' \ 'snapshot-clustering-results-k10-cyclic/') clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path
cf9ba0d497127d5261c8bee5eebe0e8f12aabf3a
armstrong/core/arm_wells/views.py
armstrong/core/arm_wells/views.py
from django.core.exceptions import ImproperlyConfigured from django.views.generic import TemplateView class SimpleWellView(TemplateView): def render_to_response(self, context, **response_kwargs): if not 'params' in context: raise ImproperlyConfigured( "Expects `params` to be provided in the context") if not self.template_name: if not 'template_name' in context['params']: raise ImproperlyConfigured( "Expects `template_name` to be provided") else: self.template_name = context['params']['template_name'] if not 'well' in context['params']: raise ImproperlyConfigured("Expects a `well` to be provided") return super(SimpleWellView, self).render_to_response(context, **response_kwargs)
from django.core.exceptions import ImproperlyConfigured from django.views.generic import TemplateView from django.utils.translation import ugettext as _ class SimpleWellView(TemplateView): def render_to_response(self, context, **response_kwargs): if not 'params' in context: raise ImproperlyConfigured( _(u"Expects `params` to be provided in the context")) if not self.template_name: if not 'template_name' in context['params']: raise ImproperlyConfigured( _(u"Expects `template_name` to be provided")) else: self.template_name = context['params']['template_name'] if not 'well' in context['params']: raise ImproperlyConfigured(_(u"Expects a `well` to be provided")) return super(SimpleWellView, self).render_to_response(context, **response_kwargs)
Make these exception messages translatable
Make these exception messages translatable
Python
apache-2.0
armstrong/armstrong.core.arm_wells,dmclain/armstrong.core.arm_wells,armstrong/armstrong.core.arm_wells,texastribune/armstrong.core.arm_wells,texastribune/armstrong.core.arm_wells,dmclain/armstrong.core.arm_wells,armstrong/armstrong.core.arm_wells
from django.core.exceptions import ImproperlyConfigured from django.views.generic import TemplateView class SimpleWellView(TemplateView): def render_to_response(self, context, **response_kwargs): if not 'params' in context: raise ImproperlyConfigured( "Expects `params` to be provided in the context") if not self.template_name: if not 'template_name' in context['params']: raise ImproperlyConfigured( "Expects `template_name` to be provided") else: self.template_name = context['params']['template_name'] if not 'well' in context['params']: raise ImproperlyConfigured("Expects a `well` to be provided") return super(SimpleWellView, self).render_to_response(context, **response_kwargs) Make these exception messages translatable
from django.core.exceptions import ImproperlyConfigured from django.views.generic import TemplateView from django.utils.translation import ugettext as _ class SimpleWellView(TemplateView): def render_to_response(self, context, **response_kwargs): if not 'params' in context: raise ImproperlyConfigured( _(u"Expects `params` to be provided in the context")) if not self.template_name: if not 'template_name' in context['params']: raise ImproperlyConfigured( _(u"Expects `template_name` to be provided")) else: self.template_name = context['params']['template_name'] if not 'well' in context['params']: raise ImproperlyConfigured(_(u"Expects a `well` to be provided")) return super(SimpleWellView, self).render_to_response(context, **response_kwargs)
<commit_before>from django.core.exceptions import ImproperlyConfigured from django.views.generic import TemplateView class SimpleWellView(TemplateView): def render_to_response(self, context, **response_kwargs): if not 'params' in context: raise ImproperlyConfigured( "Expects `params` to be provided in the context") if not self.template_name: if not 'template_name' in context['params']: raise ImproperlyConfigured( "Expects `template_name` to be provided") else: self.template_name = context['params']['template_name'] if not 'well' in context['params']: raise ImproperlyConfigured("Expects a `well` to be provided") return super(SimpleWellView, self).render_to_response(context, **response_kwargs) <commit_msg>Make these exception messages translatable<commit_after>
from django.core.exceptions import ImproperlyConfigured from django.views.generic import TemplateView from django.utils.translation import ugettext as _ class SimpleWellView(TemplateView): def render_to_response(self, context, **response_kwargs): if not 'params' in context: raise ImproperlyConfigured( _(u"Expects `params` to be provided in the context")) if not self.template_name: if not 'template_name' in context['params']: raise ImproperlyConfigured( _(u"Expects `template_name` to be provided")) else: self.template_name = context['params']['template_name'] if not 'well' in context['params']: raise ImproperlyConfigured(_(u"Expects a `well` to be provided")) return super(SimpleWellView, self).render_to_response(context, **response_kwargs)
from django.core.exceptions import ImproperlyConfigured from django.views.generic import TemplateView class SimpleWellView(TemplateView): def render_to_response(self, context, **response_kwargs): if not 'params' in context: raise ImproperlyConfigured( "Expects `params` to be provided in the context") if not self.template_name: if not 'template_name' in context['params']: raise ImproperlyConfigured( "Expects `template_name` to be provided") else: self.template_name = context['params']['template_name'] if not 'well' in context['params']: raise ImproperlyConfigured("Expects a `well` to be provided") return super(SimpleWellView, self).render_to_response(context, **response_kwargs) Make these exception messages translatablefrom django.core.exceptions import ImproperlyConfigured from django.views.generic import TemplateView from django.utils.translation import ugettext as _ class SimpleWellView(TemplateView): def render_to_response(self, context, **response_kwargs): if not 'params' in context: raise ImproperlyConfigured( _(u"Expects `params` to be provided in the context")) if not self.template_name: if not 'template_name' in context['params']: raise ImproperlyConfigured( _(u"Expects `template_name` to be provided")) else: self.template_name = context['params']['template_name'] if not 'well' in context['params']: raise ImproperlyConfigured(_(u"Expects a `well` to be provided")) return super(SimpleWellView, self).render_to_response(context, **response_kwargs)
<commit_before>from django.core.exceptions import ImproperlyConfigured from django.views.generic import TemplateView class SimpleWellView(TemplateView): def render_to_response(self, context, **response_kwargs): if not 'params' in context: raise ImproperlyConfigured( "Expects `params` to be provided in the context") if not self.template_name: if not 'template_name' in context['params']: raise ImproperlyConfigured( "Expects `template_name` to be provided") else: self.template_name = context['params']['template_name'] if not 'well' in context['params']: raise ImproperlyConfigured("Expects a `well` to be provided") return super(SimpleWellView, self).render_to_response(context, **response_kwargs) <commit_msg>Make these exception messages translatable<commit_after>from django.core.exceptions import ImproperlyConfigured from django.views.generic import TemplateView from django.utils.translation import ugettext as _ class SimpleWellView(TemplateView): def render_to_response(self, context, **response_kwargs): if not 'params' in context: raise ImproperlyConfigured( _(u"Expects `params` to be provided in the context")) if not self.template_name: if not 'template_name' in context['params']: raise ImproperlyConfigured( _(u"Expects `template_name` to be provided")) else: self.template_name = context['params']['template_name'] if not 'well' in context['params']: raise ImproperlyConfigured(_(u"Expects a `well` to be provided")) return super(SimpleWellView, self).render_to_response(context, **response_kwargs)
b7f07248834857e89f2f8312785a3a1f343c27c3
quickstart/python/understand/example-2/create_joke_intent.6.x.py
quickstart/python/understand/example-2/create_joke_intent.6.x.py
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) assistant_sid = 'UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Create a new intent named 'tell_a_joke' intent = client.preview.understand \ .assistants(assistant_sid) \ .intents \ .create(unique_name='tell-a-joke') # Provide actions for the new intent joke_actions = { 'actions': [ {'say': 'I was going to look for my missing watch, but I could never find the time.'} ] } # Update the tell-a-joke intent to use this 'say' action. client.preview.understand \ .assistants(assistant_sid) \ .intents(intent.sid) \ .intent_actions().update(joke_actions) print(intent.sid)
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) # Create a new intent named 'tell_a_joke' # Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/assistant/list intent = client.preview.understand \ .assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .intents \ .create(unique_name='tell-a-joke') # Provide actions for the new intent joke_actions = { 'actions': [ {'say': 'I was going to look for my missing watch, but I could never find the time.'} ] } # Update the tell-a-joke intent to use this 'say' action. client.preview.understand \ .assistants(assistant_sid) \ .intents(intent.sid) \ .intent_actions().update(joke_actions) print(intent.sid)
Update to use assistant SID inline
Update to use assistant SID inline Maintaining consistency with the auto-generated code samples for Understand, which don't allow for our variable-named placeholder values
Python
mit
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) assistant_sid = 'UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Create a new intent named 'tell_a_joke' intent = client.preview.understand \ .assistants(assistant_sid) \ .intents \ .create(unique_name='tell-a-joke') # Provide actions for the new intent joke_actions = { 'actions': [ {'say': 'I was going to look for my missing watch, but I could never find the time.'} ] } # Update the tell-a-joke intent to use this 'say' action. client.preview.understand \ .assistants(assistant_sid) \ .intents(intent.sid) \ .intent_actions().update(joke_actions) print(intent.sid) Update to use assistant SID inline Maintaining consistency with the auto-generated code samples for Understand, which don't allow for our variable-named placeholder values
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) # Create a new intent named 'tell_a_joke' # Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/assistant/list intent = client.preview.understand \ .assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .intents \ .create(unique_name='tell-a-joke') # Provide actions for the new intent joke_actions = { 'actions': [ {'say': 'I was going to look for my missing watch, but I could never find the time.'} ] } # Update the tell-a-joke intent to use this 'say' action. client.preview.understand \ .assistants(assistant_sid) \ .intents(intent.sid) \ .intent_actions().update(joke_actions) print(intent.sid)
<commit_before># Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) assistant_sid = 'UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Create a new intent named 'tell_a_joke' intent = client.preview.understand \ .assistants(assistant_sid) \ .intents \ .create(unique_name='tell-a-joke') # Provide actions for the new intent joke_actions = { 'actions': [ {'say': 'I was going to look for my missing watch, but I could never find the time.'} ] } # Update the tell-a-joke intent to use this 'say' action. client.preview.understand \ .assistants(assistant_sid) \ .intents(intent.sid) \ .intent_actions().update(joke_actions) print(intent.sid) <commit_msg>Update to use assistant SID inline Maintaining consistency with the auto-generated code samples for Understand, which don't allow for our variable-named placeholder values<commit_after>
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) # Create a new intent named 'tell_a_joke' # Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/assistant/list intent = client.preview.understand \ .assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .intents \ .create(unique_name='tell-a-joke') # Provide actions for the new intent joke_actions = { 'actions': [ {'say': 'I was going to look for my missing watch, but I could never find the time.'} ] } # Update the tell-a-joke intent to use this 'say' action. client.preview.understand \ .assistants(assistant_sid) \ .intents(intent.sid) \ .intent_actions().update(joke_actions) print(intent.sid)
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) assistant_sid = 'UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Create a new intent named 'tell_a_joke' intent = client.preview.understand \ .assistants(assistant_sid) \ .intents \ .create(unique_name='tell-a-joke') # Provide actions for the new intent joke_actions = { 'actions': [ {'say': 'I was going to look for my missing watch, but I could never find the time.'} ] } # Update the tell-a-joke intent to use this 'say' action. client.preview.understand \ .assistants(assistant_sid) \ .intents(intent.sid) \ .intent_actions().update(joke_actions) print(intent.sid) Update to use assistant SID inline Maintaining consistency with the auto-generated code samples for Understand, which don't allow for our variable-named placeholder values# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) # Create a new intent named 'tell_a_joke' # Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/assistant/list intent = client.preview.understand \ .assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .intents \ .create(unique_name='tell-a-joke') # Provide actions for the new intent joke_actions = { 'actions': [ {'say': 'I was going to look for my missing watch, but I could never find the time.'} ] } # Update the tell-a-joke intent to use this 'say' action. client.preview.understand \ .assistants(assistant_sid) \ .intents(intent.sid) \ .intent_actions().update(joke_actions) print(intent.sid)
<commit_before># Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) assistant_sid = 'UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Create a new intent named 'tell_a_joke' intent = client.preview.understand \ .assistants(assistant_sid) \ .intents \ .create(unique_name='tell-a-joke') # Provide actions for the new intent joke_actions = { 'actions': [ {'say': 'I was going to look for my missing watch, but I could never find the time.'} ] } # Update the tell-a-joke intent to use this 'say' action. client.preview.understand \ .assistants(assistant_sid) \ .intents(intent.sid) \ .intent_actions().update(joke_actions) print(intent.sid) <commit_msg>Update to use assistant SID inline Maintaining consistency with the auto-generated code samples for Understand, which don't allow for our variable-named placeholder values<commit_after># Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) # Create a new intent named 'tell_a_joke' # Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/assistant/list intent = client.preview.understand \ .assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .intents \ .create(unique_name='tell-a-joke') # Provide actions for the new intent joke_actions = { 'actions': [ {'say': 'I was going to look for my missing watch, but I could never find the time.'} ] } # Update the tell-a-joke intent to use this 'say' action. client.preview.understand \ .assistants(assistant_sid) \ .intents(intent.sid) \ .intent_actions().update(joke_actions) print(intent.sid)
2573178fe8051e29dab5bc4463f9ef39aa8c7657
wordcloud/urls.py
wordcloud/urls.py
from django.conf.urls import patterns, url from django.views.generic.base import RedirectView from .views import wordcloud urlpatterns = patterns( '', url(r'^wordcloud/$', wordcloud, name='wordcloud'), url(r'^wordcloud/(?P<max_entries>\d+)/$', wordcloud, name='wordcloud'), # Temporary redirects of old urls url(r'^tagcloud/$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), url(r'^tagcloud/(?P<max_entries>\d+)/$$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), )
from django.conf.urls import patterns, url from django.views.generic.base import RedirectView from .views import wordcloud urlpatterns = patterns( '', url(r'^wordcloud/$', wordcloud, name='wordcloud'), url(r'^wordcloud/(?P<max_entries>\d+)/$', wordcloud, name='wordcloud'), # Temporary redirects of old urls url(r'^tagcloud/$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), url(r'^tagcloud/(?P<max_entries>\d+)/$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), )
Remove an extraneous character from a URL's regular expression
Remove an extraneous character from a URL's regular expression
Python
agpl-3.0
geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola
from django.conf.urls import patterns, url from django.views.generic.base import RedirectView from .views import wordcloud urlpatterns = patterns( '', url(r'^wordcloud/$', wordcloud, name='wordcloud'), url(r'^wordcloud/(?P<max_entries>\d+)/$', wordcloud, name='wordcloud'), # Temporary redirects of old urls url(r'^tagcloud/$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), url(r'^tagcloud/(?P<max_entries>\d+)/$$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), ) Remove an extraneous character from a URL's regular expression
from django.conf.urls import patterns, url from django.views.generic.base import RedirectView from .views import wordcloud urlpatterns = patterns( '', url(r'^wordcloud/$', wordcloud, name='wordcloud'), url(r'^wordcloud/(?P<max_entries>\d+)/$', wordcloud, name='wordcloud'), # Temporary redirects of old urls url(r'^tagcloud/$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), url(r'^tagcloud/(?P<max_entries>\d+)/$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), )
<commit_before>from django.conf.urls import patterns, url from django.views.generic.base import RedirectView from .views import wordcloud urlpatterns = patterns( '', url(r'^wordcloud/$', wordcloud, name='wordcloud'), url(r'^wordcloud/(?P<max_entries>\d+)/$', wordcloud, name='wordcloud'), # Temporary redirects of old urls url(r'^tagcloud/$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), url(r'^tagcloud/(?P<max_entries>\d+)/$$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), ) <commit_msg>Remove an extraneous character from a URL's regular expression<commit_after>
from django.conf.urls import patterns, url from django.views.generic.base import RedirectView from .views import wordcloud urlpatterns = patterns( '', url(r'^wordcloud/$', wordcloud, name='wordcloud'), url(r'^wordcloud/(?P<max_entries>\d+)/$', wordcloud, name='wordcloud'), # Temporary redirects of old urls url(r'^tagcloud/$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), url(r'^tagcloud/(?P<max_entries>\d+)/$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), )
from django.conf.urls import patterns, url from django.views.generic.base import RedirectView from .views import wordcloud urlpatterns = patterns( '', url(r'^wordcloud/$', wordcloud, name='wordcloud'), url(r'^wordcloud/(?P<max_entries>\d+)/$', wordcloud, name='wordcloud'), # Temporary redirects of old urls url(r'^tagcloud/$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), url(r'^tagcloud/(?P<max_entries>\d+)/$$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), ) Remove an extraneous character from a URL's regular expressionfrom django.conf.urls import patterns, url from django.views.generic.base import RedirectView from .views import wordcloud urlpatterns = patterns( '', url(r'^wordcloud/$', wordcloud, name='wordcloud'), url(r'^wordcloud/(?P<max_entries>\d+)/$', wordcloud, name='wordcloud'), # Temporary redirects of old urls url(r'^tagcloud/$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), url(r'^tagcloud/(?P<max_entries>\d+)/$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), )
<commit_before>from django.conf.urls import patterns, url from django.views.generic.base import RedirectView from .views import wordcloud urlpatterns = patterns( '', url(r'^wordcloud/$', wordcloud, name='wordcloud'), url(r'^wordcloud/(?P<max_entries>\d+)/$', wordcloud, name='wordcloud'), # Temporary redirects of old urls url(r'^tagcloud/$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), url(r'^tagcloud/(?P<max_entries>\d+)/$$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), ) <commit_msg>Remove an extraneous character from a URL's regular expression<commit_after>from django.conf.urls import patterns, url from django.views.generic.base import RedirectView from .views import wordcloud urlpatterns = patterns( '', url(r'^wordcloud/$', wordcloud, name='wordcloud'), url(r'^wordcloud/(?P<max_entries>\d+)/$', wordcloud, name='wordcloud'), # Temporary redirects of old urls url(r'^tagcloud/$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), url(r'^tagcloud/(?P<max_entries>\d+)/$', RedirectView.as_view(pattern_name='wordcloud', permanent=True)), )
7cf4578297667bc8b6405e99828818de87e3ba9a
extensions/ExtGameController.py
extensions/ExtGameController.py
from python_cowbull_game.GameController import GameController from python_cowbull_game.GameMode import GameMode class ExtGameController(GameController): additional_modes = [ GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0), GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1) ] def __init__(self): super(ExtGameController, self).__init__(game_modes=self.additional_modes)
from python_cowbull_game.GameController import GameController from python_cowbull_game.GameMode import GameMode class ExtGameController(GameController): additional_modes = [ GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0), GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1) ] def __init__(self, mode=None, game_json=None): super(ExtGameController, self).__init__( game_json=game_json, mode=mode, game_modes=self.additional_modes )
Update extensions and GameController subclass
Update extensions and GameController subclass
Python
apache-2.0
dsandersAzure/python_cowbull_server,dsandersAzure/python_cowbull_server
from python_cowbull_game.GameController import GameController from python_cowbull_game.GameMode import GameMode class ExtGameController(GameController): additional_modes = [ GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0), GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1) ] def __init__(self): super(ExtGameController, self).__init__(game_modes=self.additional_modes) Update extensions and GameController subclass
from python_cowbull_game.GameController import GameController from python_cowbull_game.GameMode import GameMode class ExtGameController(GameController): additional_modes = [ GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0), GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1) ] def __init__(self, mode=None, game_json=None): super(ExtGameController, self).__init__( game_json=game_json, mode=mode, game_modes=self.additional_modes )
<commit_before>from python_cowbull_game.GameController import GameController from python_cowbull_game.GameMode import GameMode class ExtGameController(GameController): additional_modes = [ GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0), GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1) ] def __init__(self): super(ExtGameController, self).__init__(game_modes=self.additional_modes) <commit_msg>Update extensions and GameController subclass<commit_after>
from python_cowbull_game.GameController import GameController from python_cowbull_game.GameMode import GameMode class ExtGameController(GameController): additional_modes = [ GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0), GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1) ] def __init__(self, mode=None, game_json=None): super(ExtGameController, self).__init__( game_json=game_json, mode=mode, game_modes=self.additional_modes )
from python_cowbull_game.GameController import GameController from python_cowbull_game.GameMode import GameMode class ExtGameController(GameController): additional_modes = [ GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0), GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1) ] def __init__(self): super(ExtGameController, self).__init__(game_modes=self.additional_modes) Update extensions and GameController subclassfrom python_cowbull_game.GameController import GameController from python_cowbull_game.GameMode import GameMode class ExtGameController(GameController): additional_modes = [ GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0), GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1) ] def __init__(self, mode=None, game_json=None): super(ExtGameController, self).__init__( game_json=game_json, mode=mode, game_modes=self.additional_modes )
<commit_before>from python_cowbull_game.GameController import GameController from python_cowbull_game.GameMode import GameMode class ExtGameController(GameController): additional_modes = [ GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0), GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1) ] def __init__(self): super(ExtGameController, self).__init__(game_modes=self.additional_modes) <commit_msg>Update extensions and GameController subclass<commit_after>from python_cowbull_game.GameController import GameController from python_cowbull_game.GameMode import GameMode class ExtGameController(GameController): additional_modes = [ GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0), GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1) ] def __init__(self, mode=None, game_json=None): super(ExtGameController, self).__init__( game_json=game_json, mode=mode, game_modes=self.additional_modes )
641a12d42bea5a78f8b1188ea758075fec6ef445
irclogview/urls.py
irclogview/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns('irclogview.views', url(r'^(?P<name>[^/]+)/(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})/$', 'show_log', name='irclogview_show'), url(r'^(?P<name>[^/]+)/$', 'channel_index', name='irclogview_channel'), url(r'^$', 'index', name='irclogview_index'), )
from django.conf.urls.defaults import patterns, url from django.conf import settings urlpatterns = patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) urlpatterns += patterns('irclogview.views', url(r'^(?P<name>[^/]+)/(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})/$', 'show_log', name='irclogview_show'), url(r'^(?P<name>[^/]+)/$', 'channel_index', name='irclogview_channel'), url(r'^$', 'index', name='irclogview_index'), )
Set /media/ as static folder
Set /media/ as static folder
Python
agpl-3.0
BlankOn/irclogview,fajran/irclogview,BlankOn/irclogview,fajran/irclogview
from django.conf.urls.defaults import * urlpatterns = patterns('irclogview.views', url(r'^(?P<name>[^/]+)/(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})/$', 'show_log', name='irclogview_show'), url(r'^(?P<name>[^/]+)/$', 'channel_index', name='irclogview_channel'), url(r'^$', 'index', name='irclogview_index'), ) Set /media/ as static folder
from django.conf.urls.defaults import patterns, url from django.conf import settings urlpatterns = patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) urlpatterns += patterns('irclogview.views', url(r'^(?P<name>[^/]+)/(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})/$', 'show_log', name='irclogview_show'), url(r'^(?P<name>[^/]+)/$', 'channel_index', name='irclogview_channel'), url(r'^$', 'index', name='irclogview_index'), )
<commit_before>from django.conf.urls.defaults import * urlpatterns = patterns('irclogview.views', url(r'^(?P<name>[^/]+)/(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})/$', 'show_log', name='irclogview_show'), url(r'^(?P<name>[^/]+)/$', 'channel_index', name='irclogview_channel'), url(r'^$', 'index', name='irclogview_index'), ) <commit_msg>Set /media/ as static folder<commit_after>
from django.conf.urls.defaults import patterns, url from django.conf import settings urlpatterns = patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) urlpatterns += patterns('irclogview.views', url(r'^(?P<name>[^/]+)/(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})/$', 'show_log', name='irclogview_show'), url(r'^(?P<name>[^/]+)/$', 'channel_index', name='irclogview_channel'), url(r'^$', 'index', name='irclogview_index'), )
from django.conf.urls.defaults import * urlpatterns = patterns('irclogview.views', url(r'^(?P<name>[^/]+)/(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})/$', 'show_log', name='irclogview_show'), url(r'^(?P<name>[^/]+)/$', 'channel_index', name='irclogview_channel'), url(r'^$', 'index', name='irclogview_index'), ) Set /media/ as static folderfrom django.conf.urls.defaults import patterns, url from django.conf import settings urlpatterns = patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) urlpatterns += patterns('irclogview.views', url(r'^(?P<name>[^/]+)/(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})/$', 'show_log', name='irclogview_show'), url(r'^(?P<name>[^/]+)/$', 'channel_index', name='irclogview_channel'), url(r'^$', 'index', name='irclogview_index'), )
<commit_before>from django.conf.urls.defaults import * urlpatterns = patterns('irclogview.views', url(r'^(?P<name>[^/]+)/(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})/$', 'show_log', name='irclogview_show'), url(r'^(?P<name>[^/]+)/$', 'channel_index', name='irclogview_channel'), url(r'^$', 'index', name='irclogview_index'), ) <commit_msg>Set /media/ as static folder<commit_after>from django.conf.urls.defaults import patterns, url from django.conf import settings urlpatterns = patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) urlpatterns += patterns('irclogview.views', url(r'^(?P<name>[^/]+)/(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})/$', 'show_log', name='irclogview_show'), url(r'^(?P<name>[^/]+)/$', 'channel_index', name='irclogview_channel'), url(r'^$', 'index', name='irclogview_index'), )
b32614df983402081cad272f486fcffcd3a18fc1
scripts/tests/data_util_test.py
scripts/tests/data_util_test.py
from data_util import DataManager import sys import data_util import numpy as np sys.path.append("../") # DataInstance = DataManager("../../data/train", "../../data/test", 128) # batch_input, batch_output, is_epoch_increase = DataInstance.get_batch() # print (np.shape(batch_input)) data_util.save_to_disk("../../data/train", "../../data/test")
import sys import numpy as np sys.path.append("../") import data_util # DataInstance = DataManager("../../data/train", "../../data/test", 128) # batch_input, batch_output, is_epoch_increase = DataInstance.get_batch() # print (np.shape(batch_input)) data_util.save_to_disk("../../data/train", "../../data/test")
Fix a bug on loding module
Fix a bug on loding module
Python
apache-2.0
Lucklyric/NLP-NER-CNN
from data_util import DataManager import sys import data_util import numpy as np sys.path.append("../") # DataInstance = DataManager("../../data/train", "../../data/test", 128) # batch_input, batch_output, is_epoch_increase = DataInstance.get_batch() # print (np.shape(batch_input)) data_util.save_to_disk("../../data/train", "../../data/test") Fix a bug on loding module
import sys import numpy as np sys.path.append("../") import data_util # DataInstance = DataManager("../../data/train", "../../data/test", 128) # batch_input, batch_output, is_epoch_increase = DataInstance.get_batch() # print (np.shape(batch_input)) data_util.save_to_disk("../../data/train", "../../data/test")
<commit_before>from data_util import DataManager import sys import data_util import numpy as np sys.path.append("../") # DataInstance = DataManager("../../data/train", "../../data/test", 128) # batch_input, batch_output, is_epoch_increase = DataInstance.get_batch() # print (np.shape(batch_input)) data_util.save_to_disk("../../data/train", "../../data/test") <commit_msg>Fix a bug on loding module<commit_after>
import sys import numpy as np sys.path.append("../") import data_util # DataInstance = DataManager("../../data/train", "../../data/test", 128) # batch_input, batch_output, is_epoch_increase = DataInstance.get_batch() # print (np.shape(batch_input)) data_util.save_to_disk("../../data/train", "../../data/test")
from data_util import DataManager import sys import data_util import numpy as np sys.path.append("../") # DataInstance = DataManager("../../data/train", "../../data/test", 128) # batch_input, batch_output, is_epoch_increase = DataInstance.get_batch() # print (np.shape(batch_input)) data_util.save_to_disk("../../data/train", "../../data/test") Fix a bug on loding moduleimport sys import numpy as np sys.path.append("../") import data_util # DataInstance = DataManager("../../data/train", "../../data/test", 128) # batch_input, batch_output, is_epoch_increase = DataInstance.get_batch() # print (np.shape(batch_input)) data_util.save_to_disk("../../data/train", "../../data/test")
<commit_before>from data_util import DataManager import sys import data_util import numpy as np sys.path.append("../") # DataInstance = DataManager("../../data/train", "../../data/test", 128) # batch_input, batch_output, is_epoch_increase = DataInstance.get_batch() # print (np.shape(batch_input)) data_util.save_to_disk("../../data/train", "../../data/test") <commit_msg>Fix a bug on loding module<commit_after>import sys import numpy as np sys.path.append("../") import data_util # DataInstance = DataManager("../../data/train", "../../data/test", 128) # batch_input, batch_output, is_epoch_increase = DataInstance.get_batch() # print (np.shape(batch_input)) data_util.save_to_disk("../../data/train", "../../data/test")
84254935bc78e86dadcde7ad3a09e8f1036c4051
anytask/index/views.py
anytask/index/views.py
from django.shortcuts import render from schools.models import School def index(request): schools = School.objects.all().filter(is_active=True).order_by('name') # current_year = get_current_year() # courses = Course.objects.filter(is_active=True).order_by('name') # archive_courses = Course.objects.exclude(is_active=True).order_by('year', 'name') context = { 'schools': schools, } return render(request, 'schools_page.html', context) def archive_index(request): schools = School.objects.all().filter(is_active=False).order_by('name') context = { 'schools': schools, } return render(request, 'archived_schools_page.html', context)
from django.shortcuts import render from schools.models import School def index(request): schools = School.objects.all().filter(is_active=True).order_by('name') # current_year = get_current_year() # courses = Course.objects.filter(is_active=True).order_by('name') # archive_courses = Course.objects.exclude(is_active=True).order_by('year', 'name') context = { 'schools': schools, } return render(request, 'schools_page.html', context) def archive_index(request): schools = School.objects.all().filter(is_active=False).order_by('name') context = { 'schools': schools, } return render(request, 'archived_schools_page.html', context)
Delete blank line at end of file
Delete blank line at end of file
Python
mit
znick/anytask,znick/anytask,znick/anytask,znick/anytask
from django.shortcuts import render from schools.models import School def index(request): schools = School.objects.all().filter(is_active=True).order_by('name') # current_year = get_current_year() # courses = Course.objects.filter(is_active=True).order_by('name') # archive_courses = Course.objects.exclude(is_active=True).order_by('year', 'name') context = { 'schools': schools, } return render(request, 'schools_page.html', context) def archive_index(request): schools = School.objects.all().filter(is_active=False).order_by('name') context = { 'schools': schools, } return render(request, 'archived_schools_page.html', context) Delete blank line at end of file
from django.shortcuts import render from schools.models import School def index(request): schools = School.objects.all().filter(is_active=True).order_by('name') # current_year = get_current_year() # courses = Course.objects.filter(is_active=True).order_by('name') # archive_courses = Course.objects.exclude(is_active=True).order_by('year', 'name') context = { 'schools': schools, } return render(request, 'schools_page.html', context) def archive_index(request): schools = School.objects.all().filter(is_active=False).order_by('name') context = { 'schools': schools, } return render(request, 'archived_schools_page.html', context)
<commit_before>from django.shortcuts import render from schools.models import School def index(request): schools = School.objects.all().filter(is_active=True).order_by('name') # current_year = get_current_year() # courses = Course.objects.filter(is_active=True).order_by('name') # archive_courses = Course.objects.exclude(is_active=True).order_by('year', 'name') context = { 'schools': schools, } return render(request, 'schools_page.html', context) def archive_index(request): schools = School.objects.all().filter(is_active=False).order_by('name') context = { 'schools': schools, } return render(request, 'archived_schools_page.html', context) <commit_msg>Delete blank line at end of file<commit_after>
from django.shortcuts import render from schools.models import School def index(request): schools = School.objects.all().filter(is_active=True).order_by('name') # current_year = get_current_year() # courses = Course.objects.filter(is_active=True).order_by('name') # archive_courses = Course.objects.exclude(is_active=True).order_by('year', 'name') context = { 'schools': schools, } return render(request, 'schools_page.html', context) def archive_index(request): schools = School.objects.all().filter(is_active=False).order_by('name') context = { 'schools': schools, } return render(request, 'archived_schools_page.html', context)
from django.shortcuts import render from schools.models import School def index(request): schools = School.objects.all().filter(is_active=True).order_by('name') # current_year = get_current_year() # courses = Course.objects.filter(is_active=True).order_by('name') # archive_courses = Course.objects.exclude(is_active=True).order_by('year', 'name') context = { 'schools': schools, } return render(request, 'schools_page.html', context) def archive_index(request): schools = School.objects.all().filter(is_active=False).order_by('name') context = { 'schools': schools, } return render(request, 'archived_schools_page.html', context) Delete blank line at end of filefrom django.shortcuts import render from schools.models import School def index(request): schools = School.objects.all().filter(is_active=True).order_by('name') # current_year = get_current_year() # courses = Course.objects.filter(is_active=True).order_by('name') # archive_courses = Course.objects.exclude(is_active=True).order_by('year', 'name') context = { 'schools': schools, } return render(request, 'schools_page.html', context) def archive_index(request): schools = School.objects.all().filter(is_active=False).order_by('name') context = { 'schools': schools, } return render(request, 'archived_schools_page.html', context)
<commit_before>from django.shortcuts import render from schools.models import School def index(request): schools = School.objects.all().filter(is_active=True).order_by('name') # current_year = get_current_year() # courses = Course.objects.filter(is_active=True).order_by('name') # archive_courses = Course.objects.exclude(is_active=True).order_by('year', 'name') context = { 'schools': schools, } return render(request, 'schools_page.html', context) def archive_index(request): schools = School.objects.all().filter(is_active=False).order_by('name') context = { 'schools': schools, } return render(request, 'archived_schools_page.html', context) <commit_msg>Delete blank line at end of file<commit_after>from django.shortcuts import render from schools.models import School def index(request): schools = School.objects.all().filter(is_active=True).order_by('name') # current_year = get_current_year() # courses = Course.objects.filter(is_active=True).order_by('name') # archive_courses = Course.objects.exclude(is_active=True).order_by('year', 'name') context = { 'schools': schools, } return render(request, 'schools_page.html', context) def archive_index(request): schools = School.objects.all().filter(is_active=False).order_by('name') context = { 'schools': schools, } return render(request, 'archived_schools_page.html', context)
1941cba46978fb7f8182ddb3eddf2d77002b28f7
api/base/middleware.py
api/base/middleware.py
from framework.transactions import handlers class TokuTransactionsMiddleware(object): """TokuMX transaction middleware.""" def process_request(self, request): handlers.transaction_before_request() def process_response(self, request, response): return handlers.transaction_after_request(response)
from framework.transactions import handlers, commands class TokuTransactionsMiddleware(object): """TokuMX transaction middleware.""" def process_request(self, request): handlers.transaction_before_request() def process_exception(self, request, exception): commands.rollback() def process_response(self, request, response): return handlers.transaction_after_request(response)
Make sure transaction is rolled back if an exception is raised
Make sure transaction is rolled back if an exception is raised
Python
apache-2.0
TomHeatwole/osf.io,asanfilippo7/osf.io,fabianvf/osf.io,chrisseto/osf.io,dplorimer/osf,monikagrabowska/osf.io,chrisseto/osf.io,TomBaxter/osf.io,doublebits/osf.io,cwisecarver/osf.io,cwisecarver/osf.io,icereval/osf.io,jnayak1/osf.io,haoyuchen1992/osf.io,laurenrevere/osf.io,ckc6cz/osf.io,doublebits/osf.io,njantrania/osf.io,danielneis/osf.io,lyndsysimon/osf.io,DanielSBrown/osf.io,wearpants/osf.io,chrisseto/osf.io,jeffreyliu3230/osf.io,saradbowman/osf.io,acshi/osf.io,mfraezz/osf.io,sloria/osf.io,DanielSBrown/osf.io,acshi/osf.io,petermalcolm/osf.io,aaxelb/osf.io,KAsante95/osf.io,erinspace/osf.io,zamattiac/osf.io,reinaH/osf.io,jnayak1/osf.io,acshi/osf.io,jinluyuan/osf.io,cldershem/osf.io,aaxelb/osf.io,MerlinZhang/osf.io,brianjgeiger/osf.io,sbt9uc/osf.io,leb2dg/osf.io,abought/osf.io,MerlinZhang/osf.io,cldershem/osf.io,mattclark/osf.io,binoculars/osf.io,zachjanicki/osf.io,erinspace/osf.io,asanfilippo7/osf.io,jeffreyliu3230/osf.io,kwierman/osf.io,samchrisinger/osf.io,TomHeatwole/osf.io,mluo613/osf.io,Johnetordoff/osf.io,caseyrygt/osf.io,RomanZWang/osf.io,doublebits/osf.io,RomanZWang/osf.io,haoyuchen1992/osf.io,hmoco/osf.io,ZobairAlijan/osf.io,zachjanicki/osf.io,ticklemepierce/osf.io,adlius/osf.io,fabianvf/osf.io,rdhyee/osf.io,reinaH/osf.io,crcresearch/osf.io,CenterForOpenScience/osf.io,mattclark/osf.io,cslzchen/osf.io,jmcarp/osf.io,billyhunt/osf.io,caneruguz/osf.io,TomHeatwole/osf.io,jnayak1/osf.io,mfraezz/osf.io,alexschiller/osf.io,icereval/osf.io,acshi/osf.io,caneruguz/osf.io,SSJohns/osf.io,jolene-esposito/osf.io,petermalcolm/osf.io,danielneis/osf.io,cosenal/osf.io,hmoco/osf.io,acshi/osf.io,KAsante95/osf.io,brandonPurvis/osf.io,crcresearch/osf.io,zamattiac/osf.io,mluke93/osf.io,KAsante95/osf.io,hmoco/osf.io,doublebits/osf.io,arpitar/osf.io,samchrisinger/osf.io,GageGaskins/osf.io,caseyrollins/osf.io,caseyrollins/osf.io,HarryRybacki/osf.io,abought/osf.io,jmcarp/osf.io,caseyrygt/osf.io,jinluyuan/osf.io,ticklemepierce/osf.io,TomHeatwole/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,caseyrollins/osf.io,icereval/osf.io,DanielSBrown/osf.io,jinluyuan/osf.io,Johnetordoff/osf.io,felliott/osf.io,asanfilippo7/osf.io,reinaH/osf.io,amyshi188/osf.io,zamattiac/osf.io,jeffreyliu3230/osf.io,ckc6cz/osf.io,kch8qx/osf.io,fabianvf/osf.io,alexschiller/osf.io,HarryRybacki/osf.io,samanehsan/osf.io,GageGaskins/osf.io,jmcarp/osf.io,chennan47/osf.io,brianjgeiger/osf.io,samanehsan/osf.io,lyndsysimon/osf.io,pattisdr/osf.io,barbour-em/osf.io,leb2dg/osf.io,petermalcolm/osf.io,billyhunt/osf.io,caneruguz/osf.io,mfraezz/osf.io,mfraezz/osf.io,amyshi188/osf.io,amyshi188/osf.io,emetsger/osf.io,HalcyonChimera/osf.io,cldershem/osf.io,jolene-esposito/osf.io,dplorimer/osf,dplorimer/osf,felliott/osf.io,saradbowman/osf.io,cosenal/osf.io,felliott/osf.io,laurenrevere/osf.io,Johnetordoff/osf.io,monikagrabowska/osf.io,felliott/osf.io,erinspace/osf.io,rdhyee/osf.io,cslzchen/osf.io,zachjanicki/osf.io,ticklemepierce/osf.io,hmoco/osf.io,monikagrabowska/osf.io,danielneis/osf.io,lyndsysimon/osf.io,CenterForOpenScience/osf.io,mattclark/osf.io,brandonPurvis/osf.io,ZobairAlijan/osf.io,binoculars/osf.io,zamattiac/osf.io,caseyrygt/osf.io,RomanZWang/osf.io,arpitar/osf.io,sloria/osf.io,samanehsan/osf.io,adlius/osf.io,sloria/osf.io,mluke93/osf.io,jmcarp/osf.io,ZobairAlijan/osf.io,leb2dg/osf.io,abought/osf.io,cldershem/osf.io,ticklemepierce/osf.io,KAsante95/osf.io,Johnetordoff/osf.io,doublebits/osf.io,caneruguz/osf.io,bdyetton/prettychart,emetsger/osf.io,Ghalko/osf.io,adlius/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io,SSJohns/osf.io,ckc6cz/osf.io,Nesiehr/osf.io,emetsger/osf.io,cwisecarver/osf.io,TomBaxter/osf.io,asanfilippo7/osf.io,sbt9uc/osf.io,cosenal/osf.io,MerlinZhang/osf.io,jnayak1/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,binoculars/osf.io,GageGaskins/osf.io,mluo613/osf.io,aaxelb/osf.io,monikagrabowska/osf.io,ckc6cz/osf.io,njantrania/osf.io,alexschiller/osf.io,pattisdr/osf.io,kch8qx/osf.io,sbt9uc/osf.io,mluo613/osf.io,SSJohns/osf.io,mluke93/osf.io,emetsger/osf.io,DanielSBrown/osf.io,kch8qx/osf.io,rdhyee/osf.io,HalcyonChimera/osf.io,laurenrevere/osf.io,monikagrabowska/osf.io,RomanZWang/osf.io,chennan47/osf.io,cslzchen/osf.io,jolene-esposito/osf.io,baylee-d/osf.io,arpitar/osf.io,KAsante95/osf.io,samchrisinger/osf.io,baylee-d/osf.io,jolene-esposito/osf.io,barbour-em/osf.io,kwierman/osf.io,zachjanicki/osf.io,billyhunt/osf.io,Ghalko/osf.io,brianjgeiger/osf.io,bdyetton/prettychart,samchrisinger/osf.io,arpitar/osf.io,fabianvf/osf.io,ZobairAlijan/osf.io,Ghalko/osf.io,danielneis/osf.io,brandonPurvis/osf.io,Nesiehr/osf.io,bdyetton/prettychart,petermalcolm/osf.io,wearpants/osf.io,GageGaskins/osf.io,brandonPurvis/osf.io,rdhyee/osf.io,mluo613/osf.io,mluo613/osf.io,Ghalko/osf.io,RomanZWang/osf.io,cslzchen/osf.io,sbt9uc/osf.io,alexschiller/osf.io,abought/osf.io,haoyuchen1992/osf.io,crcresearch/osf.io,kch8qx/osf.io,barbour-em/osf.io,HarryRybacki/osf.io,chrisseto/osf.io,HarryRybacki/osf.io,barbour-em/osf.io,Nesiehr/osf.io,cosenal/osf.io,chennan47/osf.io,MerlinZhang/osf.io,wearpants/osf.io,reinaH/osf.io,kch8qx/osf.io,bdyetton/prettychart,haoyuchen1992/osf.io,Nesiehr/osf.io,njantrania/osf.io,GageGaskins/osf.io,CenterForOpenScience/osf.io,jeffreyliu3230/osf.io,adlius/osf.io,alexschiller/osf.io,brianjgeiger/osf.io,caseyrygt/osf.io,CenterForOpenScience/osf.io,dplorimer/osf,cwisecarver/osf.io,pattisdr/osf.io,jinluyuan/osf.io,njantrania/osf.io,leb2dg/osf.io,lyndsysimon/osf.io,SSJohns/osf.io,billyhunt/osf.io,mluke93/osf.io,TomBaxter/osf.io,wearpants/osf.io,kwierman/osf.io,kwierman/osf.io,samanehsan/osf.io,billyhunt/osf.io
from framework.transactions import handlers class TokuTransactionsMiddleware(object): """TokuMX transaction middleware.""" def process_request(self, request): handlers.transaction_before_request() def process_response(self, request, response): return handlers.transaction_after_request(response) Make sure transaction is rolled back if an exception is raised
from framework.transactions import handlers, commands class TokuTransactionsMiddleware(object): """TokuMX transaction middleware.""" def process_request(self, request): handlers.transaction_before_request() def process_exception(self, request, exception): commands.rollback() def process_response(self, request, response): return handlers.transaction_after_request(response)
<commit_before>from framework.transactions import handlers class TokuTransactionsMiddleware(object): """TokuMX transaction middleware.""" def process_request(self, request): handlers.transaction_before_request() def process_response(self, request, response): return handlers.transaction_after_request(response) <commit_msg>Make sure transaction is rolled back if an exception is raised<commit_after>
from framework.transactions import handlers, commands class TokuTransactionsMiddleware(object): """TokuMX transaction middleware.""" def process_request(self, request): handlers.transaction_before_request() def process_exception(self, request, exception): commands.rollback() def process_response(self, request, response): return handlers.transaction_after_request(response)
from framework.transactions import handlers class TokuTransactionsMiddleware(object): """TokuMX transaction middleware.""" def process_request(self, request): handlers.transaction_before_request() def process_response(self, request, response): return handlers.transaction_after_request(response) Make sure transaction is rolled back if an exception is raisedfrom framework.transactions import handlers, commands class TokuTransactionsMiddleware(object): """TokuMX transaction middleware.""" def process_request(self, request): handlers.transaction_before_request() def process_exception(self, request, exception): commands.rollback() def process_response(self, request, response): return handlers.transaction_after_request(response)
<commit_before>from framework.transactions import handlers class TokuTransactionsMiddleware(object): """TokuMX transaction middleware.""" def process_request(self, request): handlers.transaction_before_request() def process_response(self, request, response): return handlers.transaction_after_request(response) <commit_msg>Make sure transaction is rolled back if an exception is raised<commit_after>from framework.transactions import handlers, commands class TokuTransactionsMiddleware(object): """TokuMX transaction middleware.""" def process_request(self, request): handlers.transaction_before_request() def process_exception(self, request, exception): commands.rollback() def process_response(self, request, response): return handlers.transaction_after_request(response)
b1c9aaa6551902b285c96c94c269a787701bb020
start_tornado.py
start_tornado.py
from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop import tornado.options import server import os use_https = False if use_https: default_port = 80 else: default_port = 443 tornado.options.define("port", default=default_port, help="run on the given port", type=int) # Overwrite the port from the Heroku run from Procfile. tornado.options.parse_command_line() appPath = os.path.dirname(os.path.realpath(__file__)) if __name__ == '__main__': if use_https: http_server = HTTPServer(WSGIContainer(server.app), ssl_options={ "certfile": appPath + '/ssl.crt', "keyfile": appPath + '/ssl.key' }) else: http_server = HTTPServer(WSGIContainer(server.app)) http_server.listen(tornado.options.options.port) IOLoop.instance().start()
from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop import tornado.options import server import os use_https = False if use_https: default_port = 443 else: default_port = 80 tornado.options.define("port", default=default_port, help="run on the given port", type=int) # Overwrite the port from the Heroku run from Procfile. tornado.options.parse_command_line() appPath = os.path.dirname(os.path.realpath(__file__)) if __name__ == '__main__': if use_https: http_server = HTTPServer(WSGIContainer(server.app), ssl_options={ "certfile": appPath + '/ssl.crt', "keyfile": appPath + '/ssl.key' }) else: http_server = HTTPServer(WSGIContainer(server.app)) http_server.listen(tornado.options.options.port) IOLoop.instance().start()
Correct the check of use HTTPS in Tornado file.
Correct the check of use HTTPS in Tornado file.
Python
apache-2.0
edmundo096/MoodMusic,edmundo096/MoodMusic,edmundo096/MoodMusic
from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop import tornado.options import server import os use_https = False if use_https: default_port = 80 else: default_port = 443 tornado.options.define("port", default=default_port, help="run on the given port", type=int) # Overwrite the port from the Heroku run from Procfile. tornado.options.parse_command_line() appPath = os.path.dirname(os.path.realpath(__file__)) if __name__ == '__main__': if use_https: http_server = HTTPServer(WSGIContainer(server.app), ssl_options={ "certfile": appPath + '/ssl.crt', "keyfile": appPath + '/ssl.key' }) else: http_server = HTTPServer(WSGIContainer(server.app)) http_server.listen(tornado.options.options.port) IOLoop.instance().start()Correct the check of use HTTPS in Tornado file.
from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop import tornado.options import server import os use_https = False if use_https: default_port = 443 else: default_port = 80 tornado.options.define("port", default=default_port, help="run on the given port", type=int) # Overwrite the port from the Heroku run from Procfile. tornado.options.parse_command_line() appPath = os.path.dirname(os.path.realpath(__file__)) if __name__ == '__main__': if use_https: http_server = HTTPServer(WSGIContainer(server.app), ssl_options={ "certfile": appPath + '/ssl.crt', "keyfile": appPath + '/ssl.key' }) else: http_server = HTTPServer(WSGIContainer(server.app)) http_server.listen(tornado.options.options.port) IOLoop.instance().start()
<commit_before>from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop import tornado.options import server import os use_https = False if use_https: default_port = 80 else: default_port = 443 tornado.options.define("port", default=default_port, help="run on the given port", type=int) # Overwrite the port from the Heroku run from Procfile. tornado.options.parse_command_line() appPath = os.path.dirname(os.path.realpath(__file__)) if __name__ == '__main__': if use_https: http_server = HTTPServer(WSGIContainer(server.app), ssl_options={ "certfile": appPath + '/ssl.crt', "keyfile": appPath + '/ssl.key' }) else: http_server = HTTPServer(WSGIContainer(server.app)) http_server.listen(tornado.options.options.port) IOLoop.instance().start()<commit_msg>Correct the check of use HTTPS in Tornado file.<commit_after>
from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop import tornado.options import server import os use_https = False if use_https: default_port = 443 else: default_port = 80 tornado.options.define("port", default=default_port, help="run on the given port", type=int) # Overwrite the port from the Heroku run from Procfile. tornado.options.parse_command_line() appPath = os.path.dirname(os.path.realpath(__file__)) if __name__ == '__main__': if use_https: http_server = HTTPServer(WSGIContainer(server.app), ssl_options={ "certfile": appPath + '/ssl.crt', "keyfile": appPath + '/ssl.key' }) else: http_server = HTTPServer(WSGIContainer(server.app)) http_server.listen(tornado.options.options.port) IOLoop.instance().start()
from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop import tornado.options import server import os use_https = False if use_https: default_port = 80 else: default_port = 443 tornado.options.define("port", default=default_port, help="run on the given port", type=int) # Overwrite the port from the Heroku run from Procfile. tornado.options.parse_command_line() appPath = os.path.dirname(os.path.realpath(__file__)) if __name__ == '__main__': if use_https: http_server = HTTPServer(WSGIContainer(server.app), ssl_options={ "certfile": appPath + '/ssl.crt', "keyfile": appPath + '/ssl.key' }) else: http_server = HTTPServer(WSGIContainer(server.app)) http_server.listen(tornado.options.options.port) IOLoop.instance().start()Correct the check of use HTTPS in Tornado file.from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop import tornado.options import server import os use_https = False if use_https: default_port = 443 else: default_port = 80 tornado.options.define("port", default=default_port, help="run on the given port", type=int) # Overwrite the port from the Heroku run from Procfile. tornado.options.parse_command_line() appPath = os.path.dirname(os.path.realpath(__file__)) if __name__ == '__main__': if use_https: http_server = HTTPServer(WSGIContainer(server.app), ssl_options={ "certfile": appPath + '/ssl.crt', "keyfile": appPath + '/ssl.key' }) else: http_server = HTTPServer(WSGIContainer(server.app)) http_server.listen(tornado.options.options.port) IOLoop.instance().start()
<commit_before>from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop import tornado.options import server import os use_https = False if use_https: default_port = 80 else: default_port = 443 tornado.options.define("port", default=default_port, help="run on the given port", type=int) # Overwrite the port from the Heroku run from Procfile. tornado.options.parse_command_line() appPath = os.path.dirname(os.path.realpath(__file__)) if __name__ == '__main__': if use_https: http_server = HTTPServer(WSGIContainer(server.app), ssl_options={ "certfile": appPath + '/ssl.crt', "keyfile": appPath + '/ssl.key' }) else: http_server = HTTPServer(WSGIContainer(server.app)) http_server.listen(tornado.options.options.port) IOLoop.instance().start()<commit_msg>Correct the check of use HTTPS in Tornado file.<commit_after>from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop import tornado.options import server import os use_https = False if use_https: default_port = 443 else: default_port = 80 tornado.options.define("port", default=default_port, help="run on the given port", type=int) # Overwrite the port from the Heroku run from Procfile. tornado.options.parse_command_line() appPath = os.path.dirname(os.path.realpath(__file__)) if __name__ == '__main__': if use_https: http_server = HTTPServer(WSGIContainer(server.app), ssl_options={ "certfile": appPath + '/ssl.crt', "keyfile": appPath + '/ssl.key' }) else: http_server = HTTPServer(WSGIContainer(server.app)) http_server.listen(tornado.options.options.port) IOLoop.instance().start()
4e7bcc26cb17af3879be62206231ab60d2b45fe5
Code/clientPlayer.py
Code/clientPlayer.py
#!/usr/bin/env python3 import getopt import sys import player from logger import * def usage(): print("clientPlayer -t number [-v number]") print("-t track number") print("-v volume") print("-d set debug mode") def main(): logger = logging.getLogger() try: opts, args = getopt.gnu_getopt(sys.argv, "t:dv") except getopt.GetoptError as err: print(err) usage() sys.exit(1) track = 0 velocity = 40 for o, a in opts: if o == "-t": track = [int(x) for x in a.split(",")] elif o == "-v": velocity = int(a) elif o == "-d": logger.setLevel(logging.DEBUG) logger.debug("Starting debug mode") else: logger.error("Unknown option {0}", o) logger.info("Playing tracks: " + ",".join(map(str, track))) # Start playing sock_player = player.SocketPlayer(track=track, velocity=velocity) sock_player.run() if __name__ == "__main__": try: main() except KeyboardInterrupt: logging.getLogger().info("Shutting down, Thanks for the ride!")
#!/usr/bin/env python3 import getopt import sys import player from logger import * def usage(): print("clientPlayer -t number [-v number]") print("-t track number") print("-v volume") print("-d set debug mode") def main(): logger = logging.getLogger() try: opts, args = getopt.gnu_getopt(sys.argv, "t:dv") except getopt.GetoptError as err: print(err) usage() sys.exit(1) track = [0] velocity = 40 for o, a in opts: if o == "-t": track = [int(x) for x in a.split(",")] elif o == "-v": velocity = int(a) elif o == "-d": logger.setLevel(logging.DEBUG) logger.debug("Starting debug mode") else: logger.error("Unknown option {0}", o) logger.info("Playing tracks: " + ",".join(map(str, track))) # Start playing sock_player = player.SocketPlayer(track=track, velocity=velocity) sock_player.run() if __name__ == "__main__": try: main() except KeyboardInterrupt: logging.getLogger().info("Shutting down, Thanks for the ride!")
Fix bug when no parameter is passed
Fix bug when no parameter is passed
Python
mit
jmigual/projecte2,jmigual/projecte2
#!/usr/bin/env python3 import getopt import sys import player from logger import * def usage(): print("clientPlayer -t number [-v number]") print("-t track number") print("-v volume") print("-d set debug mode") def main(): logger = logging.getLogger() try: opts, args = getopt.gnu_getopt(sys.argv, "t:dv") except getopt.GetoptError as err: print(err) usage() sys.exit(1) track = 0 velocity = 40 for o, a in opts: if o == "-t": track = [int(x) for x in a.split(",")] elif o == "-v": velocity = int(a) elif o == "-d": logger.setLevel(logging.DEBUG) logger.debug("Starting debug mode") else: logger.error("Unknown option {0}", o) logger.info("Playing tracks: " + ",".join(map(str, track))) # Start playing sock_player = player.SocketPlayer(track=track, velocity=velocity) sock_player.run() if __name__ == "__main__": try: main() except KeyboardInterrupt: logging.getLogger().info("Shutting down, Thanks for the ride!") Fix bug when no parameter is passed
#!/usr/bin/env python3 import getopt import sys import player from logger import * def usage(): print("clientPlayer -t number [-v number]") print("-t track number") print("-v volume") print("-d set debug mode") def main(): logger = logging.getLogger() try: opts, args = getopt.gnu_getopt(sys.argv, "t:dv") except getopt.GetoptError as err: print(err) usage() sys.exit(1) track = [0] velocity = 40 for o, a in opts: if o == "-t": track = [int(x) for x in a.split(",")] elif o == "-v": velocity = int(a) elif o == "-d": logger.setLevel(logging.DEBUG) logger.debug("Starting debug mode") else: logger.error("Unknown option {0}", o) logger.info("Playing tracks: " + ",".join(map(str, track))) # Start playing sock_player = player.SocketPlayer(track=track, velocity=velocity) sock_player.run() if __name__ == "__main__": try: main() except KeyboardInterrupt: logging.getLogger().info("Shutting down, Thanks for the ride!")
<commit_before>#!/usr/bin/env python3 import getopt import sys import player from logger import * def usage(): print("clientPlayer -t number [-v number]") print("-t track number") print("-v volume") print("-d set debug mode") def main(): logger = logging.getLogger() try: opts, args = getopt.gnu_getopt(sys.argv, "t:dv") except getopt.GetoptError as err: print(err) usage() sys.exit(1) track = 0 velocity = 40 for o, a in opts: if o == "-t": track = [int(x) for x in a.split(",")] elif o == "-v": velocity = int(a) elif o == "-d": logger.setLevel(logging.DEBUG) logger.debug("Starting debug mode") else: logger.error("Unknown option {0}", o) logger.info("Playing tracks: " + ",".join(map(str, track))) # Start playing sock_player = player.SocketPlayer(track=track, velocity=velocity) sock_player.run() if __name__ == "__main__": try: main() except KeyboardInterrupt: logging.getLogger().info("Shutting down, Thanks for the ride!") <commit_msg>Fix bug when no parameter is passed<commit_after>
#!/usr/bin/env python3 import getopt import sys import player from logger import * def usage(): print("clientPlayer -t number [-v number]") print("-t track number") print("-v volume") print("-d set debug mode") def main(): logger = logging.getLogger() try: opts, args = getopt.gnu_getopt(sys.argv, "t:dv") except getopt.GetoptError as err: print(err) usage() sys.exit(1) track = [0] velocity = 40 for o, a in opts: if o == "-t": track = [int(x) for x in a.split(",")] elif o == "-v": velocity = int(a) elif o == "-d": logger.setLevel(logging.DEBUG) logger.debug("Starting debug mode") else: logger.error("Unknown option {0}", o) logger.info("Playing tracks: " + ",".join(map(str, track))) # Start playing sock_player = player.SocketPlayer(track=track, velocity=velocity) sock_player.run() if __name__ == "__main__": try: main() except KeyboardInterrupt: logging.getLogger().info("Shutting down, Thanks for the ride!")
#!/usr/bin/env python3 import getopt import sys import player from logger import * def usage(): print("clientPlayer -t number [-v number]") print("-t track number") print("-v volume") print("-d set debug mode") def main(): logger = logging.getLogger() try: opts, args = getopt.gnu_getopt(sys.argv, "t:dv") except getopt.GetoptError as err: print(err) usage() sys.exit(1) track = 0 velocity = 40 for o, a in opts: if o == "-t": track = [int(x) for x in a.split(",")] elif o == "-v": velocity = int(a) elif o == "-d": logger.setLevel(logging.DEBUG) logger.debug("Starting debug mode") else: logger.error("Unknown option {0}", o) logger.info("Playing tracks: " + ",".join(map(str, track))) # Start playing sock_player = player.SocketPlayer(track=track, velocity=velocity) sock_player.run() if __name__ == "__main__": try: main() except KeyboardInterrupt: logging.getLogger().info("Shutting down, Thanks for the ride!") Fix bug when no parameter is passed#!/usr/bin/env python3 import getopt import sys import player from logger import * def usage(): print("clientPlayer -t number [-v number]") print("-t track number") print("-v volume") print("-d set debug mode") def main(): logger = logging.getLogger() try: opts, args = getopt.gnu_getopt(sys.argv, "t:dv") except getopt.GetoptError as err: print(err) usage() sys.exit(1) track = [0] velocity = 40 for o, a in opts: if o == "-t": track = [int(x) for x in a.split(",")] elif o == "-v": velocity = int(a) elif o == "-d": logger.setLevel(logging.DEBUG) logger.debug("Starting debug mode") else: logger.error("Unknown option {0}", o) logger.info("Playing tracks: " + ",".join(map(str, track))) # Start playing sock_player = player.SocketPlayer(track=track, velocity=velocity) sock_player.run() if __name__ == "__main__": try: main() except KeyboardInterrupt: logging.getLogger().info("Shutting down, Thanks for the ride!")
<commit_before>#!/usr/bin/env python3 import getopt import sys import player from logger import * def usage(): print("clientPlayer -t number [-v number]") print("-t track number") print("-v volume") print("-d set debug mode") def main(): logger = logging.getLogger() try: opts, args = getopt.gnu_getopt(sys.argv, "t:dv") except getopt.GetoptError as err: print(err) usage() sys.exit(1) track = 0 velocity = 40 for o, a in opts: if o == "-t": track = [int(x) for x in a.split(",")] elif o == "-v": velocity = int(a) elif o == "-d": logger.setLevel(logging.DEBUG) logger.debug("Starting debug mode") else: logger.error("Unknown option {0}", o) logger.info("Playing tracks: " + ",".join(map(str, track))) # Start playing sock_player = player.SocketPlayer(track=track, velocity=velocity) sock_player.run() if __name__ == "__main__": try: main() except KeyboardInterrupt: logging.getLogger().info("Shutting down, Thanks for the ride!") <commit_msg>Fix bug when no parameter is passed<commit_after>#!/usr/bin/env python3 import getopt import sys import player from logger import * def usage(): print("clientPlayer -t number [-v number]") print("-t track number") print("-v volume") print("-d set debug mode") def main(): logger = logging.getLogger() try: opts, args = getopt.gnu_getopt(sys.argv, "t:dv") except getopt.GetoptError as err: print(err) usage() sys.exit(1) track = [0] velocity = 40 for o, a in opts: if o == "-t": track = [int(x) for x in a.split(",")] elif o == "-v": velocity = int(a) elif o == "-d": logger.setLevel(logging.DEBUG) logger.debug("Starting debug mode") else: logger.error("Unknown option {0}", o) logger.info("Playing tracks: " + ",".join(map(str, track))) # Start playing sock_player = player.SocketPlayer(track=track, velocity=velocity) sock_player.run() if __name__ == "__main__": try: main() except KeyboardInterrupt: logging.getLogger().info("Shutting down, Thanks for the ride!")
2394de5f46d264e2a585b6cd4b87e4a45c99cfeb
cast_convert/__init__.py
cast_convert/__init__.py
from . import * from .convert import * from .media_info import * from .watch import *
__version__ = '0.1.5.18' from .cmd import cmd as command from .watch import * from . import * from .convert import * from .media_info import * @click.command(help="Print version") def version(): print(__version__) command.add_command(version)
Add version and version command
Add version and version command
Python
agpl-3.0
thismachinechills/cast_convert
from . import * from .convert import * from .media_info import * from .watch import * Add version and version command
__version__ = '0.1.5.18' from .cmd import cmd as command from .watch import * from . import * from .convert import * from .media_info import * @click.command(help="Print version") def version(): print(__version__) command.add_command(version)
<commit_before>from . import * from .convert import * from .media_info import * from .watch import * <commit_msg>Add version and version command<commit_after>
__version__ = '0.1.5.18' from .cmd import cmd as command from .watch import * from . import * from .convert import * from .media_info import * @click.command(help="Print version") def version(): print(__version__) command.add_command(version)
from . import * from .convert import * from .media_info import * from .watch import * Add version and version command__version__ = '0.1.5.18' from .cmd import cmd as command from .watch import * from . import * from .convert import * from .media_info import * @click.command(help="Print version") def version(): print(__version__) command.add_command(version)
<commit_before>from . import * from .convert import * from .media_info import * from .watch import * <commit_msg>Add version and version command<commit_after>__version__ = '0.1.5.18' from .cmd import cmd as command from .watch import * from . import * from .convert import * from .media_info import * @click.command(help="Print version") def version(): print(__version__) command.add_command(version)
073fc87b0641685bf228ca530927d793c919d40d
hoomd/filter/custom.py
hoomd/filter/custom.py
"""Contains a class for custom particle filters in Python.""" from abc import ABCMeta, abstractmethod class CustomFilter(metaclass=ABCMeta): """Abstract base class for custom particle filters. The class allows the definition of particle filters in Python (see `hoomd.filter.ParticleFilter`. """ @abstractmethod def __call__(self, state): """Return the local particle tags that match the filter. This can either return the tags that are local to an MPI rank or the tags of all particles that match in the entire state. Tag numbers in a `hoomd.Snapshot` object are just their index. Note: The exact requirements for custom filters is that the set union of the returned arrays from each MPI rank be all particles that match the filter. For general use, it is recommended, however, that each rank only return the tags for particles that are in the local MPI rank (excluding ghost particles). Args: state (`hoomd.State`): The simulation state to return the filtered tags from. Returns: (*N*,) `numpy.ndarray` of `numpy.uint64`: An array of MPI local tags that match the filter. """ pass @abstractmethod def __hash__(self): """A hashed value to represent this instance. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass @abstractmethod def __eq__(self, other): """Whether this filter and another filter are equal. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass
"""Contains a class for custom particle filters in Python.""" from abc import ABC, abstractmethod from collections.abc import Hashable, Callable class CustomFilter(Hashable, Callable): """Abstract base class for custom particle filters. The class allows the definition of particle filters in Python (see `hoomd.filter.ParticleFilter`. """ @abstractmethod def __call__(self, state): """Return the local particle tags that match the filter. This can either return the tags that are local to an MPI rank or the tags of all particles that match in the entire state. Tag numbers in a `hoomd.Snapshot` object are just their index. Note: The exact requirements for custom filters is that the set union of the returned arrays from each MPI rank be all particles that match the filter. For general use, it is recommended, however, that each rank only return the tags for particles that are in the local MPI rank (excluding ghost particles). Args: state (`hoomd.State`): The simulation state to return the filtered tags from. Returns: (*N*,) `numpy.ndarray` of `numpy.uint64`: An array of MPI local tags that match the filter. """ pass @abstractmethod def __hash__(self): """A hashed value to represent this instance. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass @abstractmethod def __eq__(self, other): """Whether this filter and another filter are equal. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass
Change the inherited classes of hoomd.filter.CustomFilter
Change the inherited classes of hoomd.filter.CustomFilter CustomFilter inherits now from Hashable and Callable
Python
bsd-3-clause
joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue
"""Contains a class for custom particle filters in Python.""" from abc import ABCMeta, abstractmethod class CustomFilter(metaclass=ABCMeta): """Abstract base class for custom particle filters. The class allows the definition of particle filters in Python (see `hoomd.filter.ParticleFilter`. """ @abstractmethod def __call__(self, state): """Return the local particle tags that match the filter. This can either return the tags that are local to an MPI rank or the tags of all particles that match in the entire state. Tag numbers in a `hoomd.Snapshot` object are just their index. Note: The exact requirements for custom filters is that the set union of the returned arrays from each MPI rank be all particles that match the filter. For general use, it is recommended, however, that each rank only return the tags for particles that are in the local MPI rank (excluding ghost particles). Args: state (`hoomd.State`): The simulation state to return the filtered tags from. Returns: (*N*,) `numpy.ndarray` of `numpy.uint64`: An array of MPI local tags that match the filter. """ pass @abstractmethod def __hash__(self): """A hashed value to represent this instance. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass @abstractmethod def __eq__(self, other): """Whether this filter and another filter are equal. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass Change the inherited classes of hoomd.filter.CustomFilter CustomFilter inherits now from Hashable and Callable
"""Contains a class for custom particle filters in Python.""" from abc import ABC, abstractmethod from collections.abc import Hashable, Callable class CustomFilter(Hashable, Callable): """Abstract base class for custom particle filters. The class allows the definition of particle filters in Python (see `hoomd.filter.ParticleFilter`. """ @abstractmethod def __call__(self, state): """Return the local particle tags that match the filter. This can either return the tags that are local to an MPI rank or the tags of all particles that match in the entire state. Tag numbers in a `hoomd.Snapshot` object are just their index. Note: The exact requirements for custom filters is that the set union of the returned arrays from each MPI rank be all particles that match the filter. For general use, it is recommended, however, that each rank only return the tags for particles that are in the local MPI rank (excluding ghost particles). Args: state (`hoomd.State`): The simulation state to return the filtered tags from. Returns: (*N*,) `numpy.ndarray` of `numpy.uint64`: An array of MPI local tags that match the filter. """ pass @abstractmethod def __hash__(self): """A hashed value to represent this instance. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass @abstractmethod def __eq__(self, other): """Whether this filter and another filter are equal. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass
<commit_before>"""Contains a class for custom particle filters in Python.""" from abc import ABCMeta, abstractmethod class CustomFilter(metaclass=ABCMeta): """Abstract base class for custom particle filters. The class allows the definition of particle filters in Python (see `hoomd.filter.ParticleFilter`. """ @abstractmethod def __call__(self, state): """Return the local particle tags that match the filter. This can either return the tags that are local to an MPI rank or the tags of all particles that match in the entire state. Tag numbers in a `hoomd.Snapshot` object are just their index. Note: The exact requirements for custom filters is that the set union of the returned arrays from each MPI rank be all particles that match the filter. For general use, it is recommended, however, that each rank only return the tags for particles that are in the local MPI rank (excluding ghost particles). Args: state (`hoomd.State`): The simulation state to return the filtered tags from. Returns: (*N*,) `numpy.ndarray` of `numpy.uint64`: An array of MPI local tags that match the filter. """ pass @abstractmethod def __hash__(self): """A hashed value to represent this instance. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass @abstractmethod def __eq__(self, other): """Whether this filter and another filter are equal. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass <commit_msg>Change the inherited classes of hoomd.filter.CustomFilter CustomFilter inherits now from Hashable and Callable<commit_after>
"""Contains a class for custom particle filters in Python.""" from abc import ABC, abstractmethod from collections.abc import Hashable, Callable class CustomFilter(Hashable, Callable): """Abstract base class for custom particle filters. The class allows the definition of particle filters in Python (see `hoomd.filter.ParticleFilter`. """ @abstractmethod def __call__(self, state): """Return the local particle tags that match the filter. This can either return the tags that are local to an MPI rank or the tags of all particles that match in the entire state. Tag numbers in a `hoomd.Snapshot` object are just their index. Note: The exact requirements for custom filters is that the set union of the returned arrays from each MPI rank be all particles that match the filter. For general use, it is recommended, however, that each rank only return the tags for particles that are in the local MPI rank (excluding ghost particles). Args: state (`hoomd.State`): The simulation state to return the filtered tags from. Returns: (*N*,) `numpy.ndarray` of `numpy.uint64`: An array of MPI local tags that match the filter. """ pass @abstractmethod def __hash__(self): """A hashed value to represent this instance. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass @abstractmethod def __eq__(self, other): """Whether this filter and another filter are equal. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass
"""Contains a class for custom particle filters in Python.""" from abc import ABCMeta, abstractmethod class CustomFilter(metaclass=ABCMeta): """Abstract base class for custom particle filters. The class allows the definition of particle filters in Python (see `hoomd.filter.ParticleFilter`. """ @abstractmethod def __call__(self, state): """Return the local particle tags that match the filter. This can either return the tags that are local to an MPI rank or the tags of all particles that match in the entire state. Tag numbers in a `hoomd.Snapshot` object are just their index. Note: The exact requirements for custom filters is that the set union of the returned arrays from each MPI rank be all particles that match the filter. For general use, it is recommended, however, that each rank only return the tags for particles that are in the local MPI rank (excluding ghost particles). Args: state (`hoomd.State`): The simulation state to return the filtered tags from. Returns: (*N*,) `numpy.ndarray` of `numpy.uint64`: An array of MPI local tags that match the filter. """ pass @abstractmethod def __hash__(self): """A hashed value to represent this instance. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass @abstractmethod def __eq__(self, other): """Whether this filter and another filter are equal. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass Change the inherited classes of hoomd.filter.CustomFilter CustomFilter inherits now from Hashable and Callable"""Contains a class for custom particle filters in Python.""" from abc import ABC, abstractmethod from collections.abc import Hashable, Callable class CustomFilter(Hashable, Callable): """Abstract base class for custom particle filters. The class allows the definition of particle filters in Python (see `hoomd.filter.ParticleFilter`. """ @abstractmethod def __call__(self, state): """Return the local particle tags that match the filter. This can either return the tags that are local to an MPI rank or the tags of all particles that match in the entire state. Tag numbers in a `hoomd.Snapshot` object are just their index. Note: The exact requirements for custom filters is that the set union of the returned arrays from each MPI rank be all particles that match the filter. For general use, it is recommended, however, that each rank only return the tags for particles that are in the local MPI rank (excluding ghost particles). Args: state (`hoomd.State`): The simulation state to return the filtered tags from. Returns: (*N*,) `numpy.ndarray` of `numpy.uint64`: An array of MPI local tags that match the filter. """ pass @abstractmethod def __hash__(self): """A hashed value to represent this instance. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass @abstractmethod def __eq__(self, other): """Whether this filter and another filter are equal. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass
<commit_before>"""Contains a class for custom particle filters in Python.""" from abc import ABCMeta, abstractmethod class CustomFilter(metaclass=ABCMeta): """Abstract base class for custom particle filters. The class allows the definition of particle filters in Python (see `hoomd.filter.ParticleFilter`. """ @abstractmethod def __call__(self, state): """Return the local particle tags that match the filter. This can either return the tags that are local to an MPI rank or the tags of all particles that match in the entire state. Tag numbers in a `hoomd.Snapshot` object are just their index. Note: The exact requirements for custom filters is that the set union of the returned arrays from each MPI rank be all particles that match the filter. For general use, it is recommended, however, that each rank only return the tags for particles that are in the local MPI rank (excluding ghost particles). Args: state (`hoomd.State`): The simulation state to return the filtered tags from. Returns: (*N*,) `numpy.ndarray` of `numpy.uint64`: An array of MPI local tags that match the filter. """ pass @abstractmethod def __hash__(self): """A hashed value to represent this instance. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass @abstractmethod def __eq__(self, other): """Whether this filter and another filter are equal. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass <commit_msg>Change the inherited classes of hoomd.filter.CustomFilter CustomFilter inherits now from Hashable and Callable<commit_after>"""Contains a class for custom particle filters in Python.""" from abc import ABC, abstractmethod from collections.abc import Hashable, Callable class CustomFilter(Hashable, Callable): """Abstract base class for custom particle filters. The class allows the definition of particle filters in Python (see `hoomd.filter.ParticleFilter`. """ @abstractmethod def __call__(self, state): """Return the local particle tags that match the filter. This can either return the tags that are local to an MPI rank or the tags of all particles that match in the entire state. Tag numbers in a `hoomd.Snapshot` object are just their index. Note: The exact requirements for custom filters is that the set union of the returned arrays from each MPI rank be all particles that match the filter. For general use, it is recommended, however, that each rank only return the tags for particles that are in the local MPI rank (excluding ghost particles). Args: state (`hoomd.State`): The simulation state to return the filtered tags from. Returns: (*N*,) `numpy.ndarray` of `numpy.uint64`: An array of MPI local tags that match the filter. """ pass @abstractmethod def __hash__(self): """A hashed value to represent this instance. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass @abstractmethod def __eq__(self, other): """Whether this filter and another filter are equal. This is necessary to allow for proper caching of filter tags internally in HOOMD-blue. """ pass
27f409721a9f59b61d6fe01bad11733a7559bda0
hotohete/production.py
hotohete/production.py
import dj_database_url from hotohete.settings import * db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) ALLOWED_HOSTS = [ 'hotohete.herokuapp.com', 'localhost', '127.0.0.1' ]
import dj_database_url from hotohete.settings import * db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) ALLOWED_HOSTS = [ 'hotohete.herokuapp.com', 'hotohetestaging.herokuapp.com', 'localhost', '127.0.0.1' ]
Add stating to allowed hosts
Add stating to allowed hosts
Python
mit
wen96/hotohete,wen96/hotohete,wen96/hotohete,wen96/hotohete
import dj_database_url from hotohete.settings import * db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) ALLOWED_HOSTS = [ 'hotohete.herokuapp.com', 'localhost', '127.0.0.1' ] Add stating to allowed hosts
import dj_database_url from hotohete.settings import * db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) ALLOWED_HOSTS = [ 'hotohete.herokuapp.com', 'hotohetestaging.herokuapp.com', 'localhost', '127.0.0.1' ]
<commit_before>import dj_database_url from hotohete.settings import * db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) ALLOWED_HOSTS = [ 'hotohete.herokuapp.com', 'localhost', '127.0.0.1' ] <commit_msg>Add stating to allowed hosts<commit_after>
import dj_database_url from hotohete.settings import * db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) ALLOWED_HOSTS = [ 'hotohete.herokuapp.com', 'hotohetestaging.herokuapp.com', 'localhost', '127.0.0.1' ]
import dj_database_url from hotohete.settings import * db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) ALLOWED_HOSTS = [ 'hotohete.herokuapp.com', 'localhost', '127.0.0.1' ] Add stating to allowed hostsimport dj_database_url from hotohete.settings import * db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) ALLOWED_HOSTS = [ 'hotohete.herokuapp.com', 'hotohetestaging.herokuapp.com', 'localhost', '127.0.0.1' ]
<commit_before>import dj_database_url from hotohete.settings import * db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) ALLOWED_HOSTS = [ 'hotohete.herokuapp.com', 'localhost', '127.0.0.1' ] <commit_msg>Add stating to allowed hosts<commit_after>import dj_database_url from hotohete.settings import * db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) ALLOWED_HOSTS = [ 'hotohete.herokuapp.com', 'hotohetestaging.herokuapp.com', 'localhost', '127.0.0.1' ]
4723e5aaf60d7fcf823d5fa72b67ef3331daa049
extruder/extrude_template.py
extruder/extrude_template.py
from __future__ import print_function, division, absolute_import from argparse import ArgumentParser def main(args=None): if args is None: parser = ArgumentParser('Tool for generating skeleton package-' 'building directory.') parser.add_argument('--appveyor-secret', default='Fill me in', help="Appveyor secret containing BINSTAR_TOKEN") parser.add_argument('--travis-secret', default='Fill me in', help="Travis-CI secret containing BINSTAR_TOKEN") args = parser.parse_args() if __name__ == '__main__': main()
from __future__ import print_function, division, absolute_import from argparse import ArgumentParser import os import shutil from jinja2 import Environment, FileSystemLoader def main(args=None): """ Copy all of the files needed from the source distribution to the current directory. """ if args is None: parser = ArgumentParser('Tool for generating skeleton package-' 'building directory. All files created in the ' 'current directory.') parser.add_argument('--appveyor-secret', default='Fill me in', help="Appveyor secret containing BINSTAR_TOKEN") parser.add_argument('--travis-secret', default='Fill me in', help="Travis-CI secret containing BINSTAR_TOKEN") args = parser.parse_args() skeleton_base_path = os.path.dirname(os.path.abspath(__file__)) skeleton_file_dir = os.path.join(skeleton_base_path, 'data', 'template-build-files') for ci_file in ['.travis.yml', 'appveyor.yml']: jinja_env = Environment(loader=FileSystemLoader(skeleton_file_dir)) tpl = jinja_env.get_template(ci_file) rendered = tpl.render(appveyor_binstar_token=args.appveyor_secret, travis_binstar_token=args.travis_secret) with open(ci_file, 'w') as f: f.write(rendered) shutil.copy(os.path.join(skeleton_file_dir, 'requirements.yml'), '.') template_folder = 'recipe-templates' shutil.copytree(os.path.join(skeleton_file_dir, template_folder), template_folder) if __name__ == '__main__': main()
Implement script for creating skeleton build setup
Implement script for creating skeleton build setup
Python
bsd-3-clause
astropy/conda-build-tools,astropy/conda-build-tools
from __future__ import print_function, division, absolute_import from argparse import ArgumentParser def main(args=None): if args is None: parser = ArgumentParser('Tool for generating skeleton package-' 'building directory.') parser.add_argument('--appveyor-secret', default='Fill me in', help="Appveyor secret containing BINSTAR_TOKEN") parser.add_argument('--travis-secret', default='Fill me in', help="Travis-CI secret containing BINSTAR_TOKEN") args = parser.parse_args() if __name__ == '__main__': main() Implement script for creating skeleton build setup
from __future__ import print_function, division, absolute_import from argparse import ArgumentParser import os import shutil from jinja2 import Environment, FileSystemLoader def main(args=None): """ Copy all of the files needed from the source distribution to the current directory. """ if args is None: parser = ArgumentParser('Tool for generating skeleton package-' 'building directory. All files created in the ' 'current directory.') parser.add_argument('--appveyor-secret', default='Fill me in', help="Appveyor secret containing BINSTAR_TOKEN") parser.add_argument('--travis-secret', default='Fill me in', help="Travis-CI secret containing BINSTAR_TOKEN") args = parser.parse_args() skeleton_base_path = os.path.dirname(os.path.abspath(__file__)) skeleton_file_dir = os.path.join(skeleton_base_path, 'data', 'template-build-files') for ci_file in ['.travis.yml', 'appveyor.yml']: jinja_env = Environment(loader=FileSystemLoader(skeleton_file_dir)) tpl = jinja_env.get_template(ci_file) rendered = tpl.render(appveyor_binstar_token=args.appveyor_secret, travis_binstar_token=args.travis_secret) with open(ci_file, 'w') as f: f.write(rendered) shutil.copy(os.path.join(skeleton_file_dir, 'requirements.yml'), '.') template_folder = 'recipe-templates' shutil.copytree(os.path.join(skeleton_file_dir, template_folder), template_folder) if __name__ == '__main__': main()
<commit_before>from __future__ import print_function, division, absolute_import from argparse import ArgumentParser def main(args=None): if args is None: parser = ArgumentParser('Tool for generating skeleton package-' 'building directory.') parser.add_argument('--appveyor-secret', default='Fill me in', help="Appveyor secret containing BINSTAR_TOKEN") parser.add_argument('--travis-secret', default='Fill me in', help="Travis-CI secret containing BINSTAR_TOKEN") args = parser.parse_args() if __name__ == '__main__': main() <commit_msg>Implement script for creating skeleton build setup<commit_after>
from __future__ import print_function, division, absolute_import from argparse import ArgumentParser import os import shutil from jinja2 import Environment, FileSystemLoader def main(args=None): """ Copy all of the files needed from the source distribution to the current directory. """ if args is None: parser = ArgumentParser('Tool for generating skeleton package-' 'building directory. All files created in the ' 'current directory.') parser.add_argument('--appveyor-secret', default='Fill me in', help="Appveyor secret containing BINSTAR_TOKEN") parser.add_argument('--travis-secret', default='Fill me in', help="Travis-CI secret containing BINSTAR_TOKEN") args = parser.parse_args() skeleton_base_path = os.path.dirname(os.path.abspath(__file__)) skeleton_file_dir = os.path.join(skeleton_base_path, 'data', 'template-build-files') for ci_file in ['.travis.yml', 'appveyor.yml']: jinja_env = Environment(loader=FileSystemLoader(skeleton_file_dir)) tpl = jinja_env.get_template(ci_file) rendered = tpl.render(appveyor_binstar_token=args.appveyor_secret, travis_binstar_token=args.travis_secret) with open(ci_file, 'w') as f: f.write(rendered) shutil.copy(os.path.join(skeleton_file_dir, 'requirements.yml'), '.') template_folder = 'recipe-templates' shutil.copytree(os.path.join(skeleton_file_dir, template_folder), template_folder) if __name__ == '__main__': main()
from __future__ import print_function, division, absolute_import from argparse import ArgumentParser def main(args=None): if args is None: parser = ArgumentParser('Tool for generating skeleton package-' 'building directory.') parser.add_argument('--appveyor-secret', default='Fill me in', help="Appveyor secret containing BINSTAR_TOKEN") parser.add_argument('--travis-secret', default='Fill me in', help="Travis-CI secret containing BINSTAR_TOKEN") args = parser.parse_args() if __name__ == '__main__': main() Implement script for creating skeleton build setupfrom __future__ import print_function, division, absolute_import from argparse import ArgumentParser import os import shutil from jinja2 import Environment, FileSystemLoader def main(args=None): """ Copy all of the files needed from the source distribution to the current directory. """ if args is None: parser = ArgumentParser('Tool for generating skeleton package-' 'building directory. All files created in the ' 'current directory.') parser.add_argument('--appveyor-secret', default='Fill me in', help="Appveyor secret containing BINSTAR_TOKEN") parser.add_argument('--travis-secret', default='Fill me in', help="Travis-CI secret containing BINSTAR_TOKEN") args = parser.parse_args() skeleton_base_path = os.path.dirname(os.path.abspath(__file__)) skeleton_file_dir = os.path.join(skeleton_base_path, 'data', 'template-build-files') for ci_file in ['.travis.yml', 'appveyor.yml']: jinja_env = Environment(loader=FileSystemLoader(skeleton_file_dir)) tpl = jinja_env.get_template(ci_file) rendered = tpl.render(appveyor_binstar_token=args.appveyor_secret, travis_binstar_token=args.travis_secret) with open(ci_file, 'w') as f: f.write(rendered) shutil.copy(os.path.join(skeleton_file_dir, 'requirements.yml'), '.') template_folder = 'recipe-templates' shutil.copytree(os.path.join(skeleton_file_dir, template_folder), template_folder) if __name__ == '__main__': main()
<commit_before>from __future__ import print_function, division, absolute_import from argparse import ArgumentParser def main(args=None): if args is None: parser = ArgumentParser('Tool for generating skeleton package-' 'building directory.') parser.add_argument('--appveyor-secret', default='Fill me in', help="Appveyor secret containing BINSTAR_TOKEN") parser.add_argument('--travis-secret', default='Fill me in', help="Travis-CI secret containing BINSTAR_TOKEN") args = parser.parse_args() if __name__ == '__main__': main() <commit_msg>Implement script for creating skeleton build setup<commit_after>from __future__ import print_function, division, absolute_import from argparse import ArgumentParser import os import shutil from jinja2 import Environment, FileSystemLoader def main(args=None): """ Copy all of the files needed from the source distribution to the current directory. """ if args is None: parser = ArgumentParser('Tool for generating skeleton package-' 'building directory. All files created in the ' 'current directory.') parser.add_argument('--appveyor-secret', default='Fill me in', help="Appveyor secret containing BINSTAR_TOKEN") parser.add_argument('--travis-secret', default='Fill me in', help="Travis-CI secret containing BINSTAR_TOKEN") args = parser.parse_args() skeleton_base_path = os.path.dirname(os.path.abspath(__file__)) skeleton_file_dir = os.path.join(skeleton_base_path, 'data', 'template-build-files') for ci_file in ['.travis.yml', 'appveyor.yml']: jinja_env = Environment(loader=FileSystemLoader(skeleton_file_dir)) tpl = jinja_env.get_template(ci_file) rendered = tpl.render(appveyor_binstar_token=args.appveyor_secret, travis_binstar_token=args.travis_secret) with open(ci_file, 'w') as f: f.write(rendered) shutil.copy(os.path.join(skeleton_file_dir, 'requirements.yml'), '.') template_folder = 'recipe-templates' shutil.copytree(os.path.join(skeleton_file_dir, template_folder), template_folder) if __name__ == '__main__': main()
7a7856d9ec56de91325c7bf7c62ff25c0241badc
tests/test_connect.py
tests/test_connect.py
import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4'
import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4' def test_connect_with_statement(): with pypuppetdb.connect() as puppetdb: assert puppetdb.version == 'v4'
Add test for creating connection with 'with' statement.
Add test for creating connection with 'with' statement.
Python
apache-2.0
puppet-community/pypuppetdb,voxpupuli/pypuppetdb
import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4' Add test for creating connection with 'with' statement.
import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4' def test_connect_with_statement(): with pypuppetdb.connect() as puppetdb: assert puppetdb.version == 'v4'
<commit_before>import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4' <commit_msg>Add test for creating connection with 'with' statement.<commit_after>
import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4' def test_connect_with_statement(): with pypuppetdb.connect() as puppetdb: assert puppetdb.version == 'v4'
import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4' Add test for creating connection with 'with' statement.import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4' def test_connect_with_statement(): with pypuppetdb.connect() as puppetdb: assert puppetdb.version == 'v4'
<commit_before>import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4' <commit_msg>Add test for creating connection with 'with' statement.<commit_after>import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4' def test_connect_with_statement(): with pypuppetdb.connect() as puppetdb: assert puppetdb.version == 'v4'
da1518d1e810ca227e84f110d4d42d1480040bc8
tests/test_twitter.py
tests/test_twitter.py
# -*- coding: utf-8 -*- import pytest import tweepy import vcr from secrets import TWITTER_ACCESS, TWITTER_SECRET from secrets import TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET class TestTweepyIntegration(): """Test class to ensure tweepy functionality works as expected""" # Class level client to use across tests auth = tweepy.OAuthHandler(TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET) auth.set_access_token(TWITTER_ACCESS, TWITTER_SECRET) @vcr.use_cassette('fixtures/vcr_cassettes/twitter.yaml') def test_authd(self): api = tweepy.API(self.auth) assert api.verify_credentials() is not False if __name__ == '__main__': pytest.main()
# -*- coding: utf-8 -*- import pytest import vcr from inet.sources.twitter import api class TestTweepyIntegration(): """Test class to ensure tweepy functionality works as expected""" @vcr.use_cassette('fixtures/vcr_cassettes/twitter.yaml') def test_authd(self): assert api.verify_credentials() is not False if __name__ == '__main__': pytest.main()
Change tests to pull in twitter client from package
Change tests to pull in twitter client from package
Python
mit
nestauk/inet
# -*- coding: utf-8 -*- import pytest import tweepy import vcr from secrets import TWITTER_ACCESS, TWITTER_SECRET from secrets import TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET class TestTweepyIntegration(): """Test class to ensure tweepy functionality works as expected""" # Class level client to use across tests auth = tweepy.OAuthHandler(TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET) auth.set_access_token(TWITTER_ACCESS, TWITTER_SECRET) @vcr.use_cassette('fixtures/vcr_cassettes/twitter.yaml') def test_authd(self): api = tweepy.API(self.auth) assert api.verify_credentials() is not False if __name__ == '__main__': pytest.main() Change tests to pull in twitter client from package
# -*- coding: utf-8 -*- import pytest import vcr from inet.sources.twitter import api class TestTweepyIntegration(): """Test class to ensure tweepy functionality works as expected""" @vcr.use_cassette('fixtures/vcr_cassettes/twitter.yaml') def test_authd(self): assert api.verify_credentials() is not False if __name__ == '__main__': pytest.main()
<commit_before># -*- coding: utf-8 -*- import pytest import tweepy import vcr from secrets import TWITTER_ACCESS, TWITTER_SECRET from secrets import TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET class TestTweepyIntegration(): """Test class to ensure tweepy functionality works as expected""" # Class level client to use across tests auth = tweepy.OAuthHandler(TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET) auth.set_access_token(TWITTER_ACCESS, TWITTER_SECRET) @vcr.use_cassette('fixtures/vcr_cassettes/twitter.yaml') def test_authd(self): api = tweepy.API(self.auth) assert api.verify_credentials() is not False if __name__ == '__main__': pytest.main() <commit_msg>Change tests to pull in twitter client from package<commit_after>
# -*- coding: utf-8 -*- import pytest import vcr from inet.sources.twitter import api class TestTweepyIntegration(): """Test class to ensure tweepy functionality works as expected""" @vcr.use_cassette('fixtures/vcr_cassettes/twitter.yaml') def test_authd(self): assert api.verify_credentials() is not False if __name__ == '__main__': pytest.main()
# -*- coding: utf-8 -*- import pytest import tweepy import vcr from secrets import TWITTER_ACCESS, TWITTER_SECRET from secrets import TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET class TestTweepyIntegration(): """Test class to ensure tweepy functionality works as expected""" # Class level client to use across tests auth = tweepy.OAuthHandler(TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET) auth.set_access_token(TWITTER_ACCESS, TWITTER_SECRET) @vcr.use_cassette('fixtures/vcr_cassettes/twitter.yaml') def test_authd(self): api = tweepy.API(self.auth) assert api.verify_credentials() is not False if __name__ == '__main__': pytest.main() Change tests to pull in twitter client from package# -*- coding: utf-8 -*- import pytest import vcr from inet.sources.twitter import api class TestTweepyIntegration(): """Test class to ensure tweepy functionality works as expected""" @vcr.use_cassette('fixtures/vcr_cassettes/twitter.yaml') def test_authd(self): assert api.verify_credentials() is not False if __name__ == '__main__': pytest.main()
<commit_before># -*- coding: utf-8 -*- import pytest import tweepy import vcr from secrets import TWITTER_ACCESS, TWITTER_SECRET from secrets import TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET class TestTweepyIntegration(): """Test class to ensure tweepy functionality works as expected""" # Class level client to use across tests auth = tweepy.OAuthHandler(TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET) auth.set_access_token(TWITTER_ACCESS, TWITTER_SECRET) @vcr.use_cassette('fixtures/vcr_cassettes/twitter.yaml') def test_authd(self): api = tweepy.API(self.auth) assert api.verify_credentials() is not False if __name__ == '__main__': pytest.main() <commit_msg>Change tests to pull in twitter client from package<commit_after># -*- coding: utf-8 -*- import pytest import vcr from inet.sources.twitter import api class TestTweepyIntegration(): """Test class to ensure tweepy functionality works as expected""" @vcr.use_cassette('fixtures/vcr_cassettes/twitter.yaml') def test_authd(self): assert api.verify_credentials() is not False if __name__ == '__main__': pytest.main()
bfc0ce1298b9fe7a640dc31c6e5729d1c6360945
langs/pystartup.py
langs/pystartup.py
# Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Set an environment variable to point to it: "export PYTHONSTARTUP=foo" # # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full # path to your home directory. import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(path=historyPath): import readline readline.write_history_file(path) if os.path.exists(historyPath): readline.read_history_file(historyPath) readline.parse_and_bind("tab: complete") readline.parse_and_bind(r"\C-a: beginning-of-line") readline.parse_and_bind(r"\C-e: end-of-line") atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath # vim: ft=python
# Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Set an environment variable to point to it: "export PYTHONSTARTUP=foo" # # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full # path to your home directory. import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(path=historyPath): import readline readline.write_history_file(path) if os.path.exists(historyPath): readline.read_history_file(historyPath) try: import __builtin__ except ImportError: import builtins as __builtin__ __builtin__.true = True __builtin__.false = False __builtin__.null = None readline.parse_and_bind("tab: complete") readline.parse_and_bind(r"\C-a: beginning-of-line") readline.parse_and_bind(r"\C-e: end-of-line") atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath # vim: ft=python
Add json true/false/none in python repl
Add json true/false/none in python repl https://mobile.twitter.com/mitsuhiko/status/1229385843585974272/photo/2
Python
mit
keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles
# Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Set an environment variable to point to it: "export PYTHONSTARTUP=foo" # # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full # path to your home directory. import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(path=historyPath): import readline readline.write_history_file(path) if os.path.exists(historyPath): readline.read_history_file(historyPath) readline.parse_and_bind("tab: complete") readline.parse_and_bind(r"\C-a: beginning-of-line") readline.parse_and_bind(r"\C-e: end-of-line") atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath # vim: ft=python Add json true/false/none in python repl https://mobile.twitter.com/mitsuhiko/status/1229385843585974272/photo/2
# Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Set an environment variable to point to it: "export PYTHONSTARTUP=foo" # # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full # path to your home directory. import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(path=historyPath): import readline readline.write_history_file(path) if os.path.exists(historyPath): readline.read_history_file(historyPath) try: import __builtin__ except ImportError: import builtins as __builtin__ __builtin__.true = True __builtin__.false = False __builtin__.null = None readline.parse_and_bind("tab: complete") readline.parse_and_bind(r"\C-a: beginning-of-line") readline.parse_and_bind(r"\C-e: end-of-line") atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath # vim: ft=python
<commit_before># Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Set an environment variable to point to it: "export PYTHONSTARTUP=foo" # # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full # path to your home directory. import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(path=historyPath): import readline readline.write_history_file(path) if os.path.exists(historyPath): readline.read_history_file(historyPath) readline.parse_and_bind("tab: complete") readline.parse_and_bind(r"\C-a: beginning-of-line") readline.parse_and_bind(r"\C-e: end-of-line") atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath # vim: ft=python <commit_msg>Add json true/false/none in python repl https://mobile.twitter.com/mitsuhiko/status/1229385843585974272/photo/2<commit_after>
# Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Set an environment variable to point to it: "export PYTHONSTARTUP=foo" # # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full # path to your home directory. import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(path=historyPath): import readline readline.write_history_file(path) if os.path.exists(historyPath): readline.read_history_file(historyPath) try: import __builtin__ except ImportError: import builtins as __builtin__ __builtin__.true = True __builtin__.false = False __builtin__.null = None readline.parse_and_bind("tab: complete") readline.parse_and_bind(r"\C-a: beginning-of-line") readline.parse_and_bind(r"\C-e: end-of-line") atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath # vim: ft=python
# Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Set an environment variable to point to it: "export PYTHONSTARTUP=foo" # # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full # path to your home directory. import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(path=historyPath): import readline readline.write_history_file(path) if os.path.exists(historyPath): readline.read_history_file(historyPath) readline.parse_and_bind("tab: complete") readline.parse_and_bind(r"\C-a: beginning-of-line") readline.parse_and_bind(r"\C-e: end-of-line") atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath # vim: ft=python Add json true/false/none in python repl https://mobile.twitter.com/mitsuhiko/status/1229385843585974272/photo/2# Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Set an environment variable to point to it: "export PYTHONSTARTUP=foo" # # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full # path to your home directory. import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(path=historyPath): import readline readline.write_history_file(path) if os.path.exists(historyPath): readline.read_history_file(historyPath) try: import __builtin__ except ImportError: import builtins as __builtin__ __builtin__.true = True __builtin__.false = False __builtin__.null = None readline.parse_and_bind("tab: complete") readline.parse_and_bind(r"\C-a: beginning-of-line") readline.parse_and_bind(r"\C-e: end-of-line") atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath # vim: ft=python
<commit_before># Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Set an environment variable to point to it: "export PYTHONSTARTUP=foo" # # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full # path to your home directory. import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(path=historyPath): import readline readline.write_history_file(path) if os.path.exists(historyPath): readline.read_history_file(historyPath) readline.parse_and_bind("tab: complete") readline.parse_and_bind(r"\C-a: beginning-of-line") readline.parse_and_bind(r"\C-e: end-of-line") atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath # vim: ft=python <commit_msg>Add json true/false/none in python repl https://mobile.twitter.com/mitsuhiko/status/1229385843585974272/photo/2<commit_after># Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Set an environment variable to point to it: "export PYTHONSTARTUP=foo" # # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full # path to your home directory. import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(path=historyPath): import readline readline.write_history_file(path) if os.path.exists(historyPath): readline.read_history_file(historyPath) try: import __builtin__ except ImportError: import builtins as __builtin__ __builtin__.true = True __builtin__.false = False __builtin__.null = None readline.parse_and_bind("tab: complete") readline.parse_and_bind(r"\C-a: beginning-of-line") readline.parse_and_bind(r"\C-e: end-of-line") atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath # vim: ft=python
2489ed6ff3d812888de4a0a2c45995389499d648
thread_output_ctrl.py
thread_output_ctrl.py
import Queue import wx, wx.stc from editor_fonts import init_stc_style class ThreadOutputCtrl(wx.stc.StyledTextCtrl): def __init__(self, parent, style=wx.TE_READONLY): wx.stc.StyledTextCtrl.__init__(self, parent) init_stc_style(self) self.SetIndent(4) self.SetTabWidth(8) self.SetUseTabs(False) self.queue = Queue.Queue(1024) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__OnTimer, self.timer) def __OnTimer(self, evt): self.flush() def flush(self): lines = "".join(self.queue.get_nowait() for _ in xrange(self.queue.qsize())) if lines: self.AppendText(lines) def start(self, interval=100): self.timer.Start(interval) def stop(self): self.timer.Stop() wx.CallAfter(self.flush) def write(self, s): self.queue.put(s) def IsEmpty(self): return self.GetTextLength() == 0
import threading import wx, wx.stc from editor_fonts import init_stc_style class ThreadOutputCtrl(wx.stc.StyledTextCtrl): def __init__(self, parent, style=wx.TE_READONLY): wx.stc.StyledTextCtrl.__init__(self, parent) init_stc_style(self) self.SetIndent(4) self.SetTabWidth(8) self.SetUseTabs(False) self.__lock = threading.Lock() self.__queue = [] self.__timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__OnTimer, self.__timer) def __OnTimer(self, evt): self.flush() def flush(self): with self.__lock: queue, self.__queue = self.__queue, [] lines = "".join(queue) if lines: self.AppendText(lines) def start(self, interval=100): self.__timer.Start(interval) def stop(self): self.__timer.Stop() wx.CallAfter(self.flush) def write(self, s): with self.__lock: self.__queue.append(s) def IsEmpty(self): return self.GetTextLength() == 0
Use a lock-protected list instead of a Queue.
Use a lock-protected list instead of a Queue.
Python
mit
shaurz/devo
import Queue import wx, wx.stc from editor_fonts import init_stc_style class ThreadOutputCtrl(wx.stc.StyledTextCtrl): def __init__(self, parent, style=wx.TE_READONLY): wx.stc.StyledTextCtrl.__init__(self, parent) init_stc_style(self) self.SetIndent(4) self.SetTabWidth(8) self.SetUseTabs(False) self.queue = Queue.Queue(1024) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__OnTimer, self.timer) def __OnTimer(self, evt): self.flush() def flush(self): lines = "".join(self.queue.get_nowait() for _ in xrange(self.queue.qsize())) if lines: self.AppendText(lines) def start(self, interval=100): self.timer.Start(interval) def stop(self): self.timer.Stop() wx.CallAfter(self.flush) def write(self, s): self.queue.put(s) def IsEmpty(self): return self.GetTextLength() == 0 Use a lock-protected list instead of a Queue.
import threading import wx, wx.stc from editor_fonts import init_stc_style class ThreadOutputCtrl(wx.stc.StyledTextCtrl): def __init__(self, parent, style=wx.TE_READONLY): wx.stc.StyledTextCtrl.__init__(self, parent) init_stc_style(self) self.SetIndent(4) self.SetTabWidth(8) self.SetUseTabs(False) self.__lock = threading.Lock() self.__queue = [] self.__timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__OnTimer, self.__timer) def __OnTimer(self, evt): self.flush() def flush(self): with self.__lock: queue, self.__queue = self.__queue, [] lines = "".join(queue) if lines: self.AppendText(lines) def start(self, interval=100): self.__timer.Start(interval) def stop(self): self.__timer.Stop() wx.CallAfter(self.flush) def write(self, s): with self.__lock: self.__queue.append(s) def IsEmpty(self): return self.GetTextLength() == 0
<commit_before>import Queue import wx, wx.stc from editor_fonts import init_stc_style class ThreadOutputCtrl(wx.stc.StyledTextCtrl): def __init__(self, parent, style=wx.TE_READONLY): wx.stc.StyledTextCtrl.__init__(self, parent) init_stc_style(self) self.SetIndent(4) self.SetTabWidth(8) self.SetUseTabs(False) self.queue = Queue.Queue(1024) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__OnTimer, self.timer) def __OnTimer(self, evt): self.flush() def flush(self): lines = "".join(self.queue.get_nowait() for _ in xrange(self.queue.qsize())) if lines: self.AppendText(lines) def start(self, interval=100): self.timer.Start(interval) def stop(self): self.timer.Stop() wx.CallAfter(self.flush) def write(self, s): self.queue.put(s) def IsEmpty(self): return self.GetTextLength() == 0 <commit_msg>Use a lock-protected list instead of a Queue.<commit_after>
import threading import wx, wx.stc from editor_fonts import init_stc_style class ThreadOutputCtrl(wx.stc.StyledTextCtrl): def __init__(self, parent, style=wx.TE_READONLY): wx.stc.StyledTextCtrl.__init__(self, parent) init_stc_style(self) self.SetIndent(4) self.SetTabWidth(8) self.SetUseTabs(False) self.__lock = threading.Lock() self.__queue = [] self.__timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__OnTimer, self.__timer) def __OnTimer(self, evt): self.flush() def flush(self): with self.__lock: queue, self.__queue = self.__queue, [] lines = "".join(queue) if lines: self.AppendText(lines) def start(self, interval=100): self.__timer.Start(interval) def stop(self): self.__timer.Stop() wx.CallAfter(self.flush) def write(self, s): with self.__lock: self.__queue.append(s) def IsEmpty(self): return self.GetTextLength() == 0
import Queue import wx, wx.stc from editor_fonts import init_stc_style class ThreadOutputCtrl(wx.stc.StyledTextCtrl): def __init__(self, parent, style=wx.TE_READONLY): wx.stc.StyledTextCtrl.__init__(self, parent) init_stc_style(self) self.SetIndent(4) self.SetTabWidth(8) self.SetUseTabs(False) self.queue = Queue.Queue(1024) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__OnTimer, self.timer) def __OnTimer(self, evt): self.flush() def flush(self): lines = "".join(self.queue.get_nowait() for _ in xrange(self.queue.qsize())) if lines: self.AppendText(lines) def start(self, interval=100): self.timer.Start(interval) def stop(self): self.timer.Stop() wx.CallAfter(self.flush) def write(self, s): self.queue.put(s) def IsEmpty(self): return self.GetTextLength() == 0 Use a lock-protected list instead of a Queue.import threading import wx, wx.stc from editor_fonts import init_stc_style class ThreadOutputCtrl(wx.stc.StyledTextCtrl): def __init__(self, parent, style=wx.TE_READONLY): wx.stc.StyledTextCtrl.__init__(self, parent) init_stc_style(self) self.SetIndent(4) self.SetTabWidth(8) self.SetUseTabs(False) self.__lock = threading.Lock() self.__queue = [] self.__timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__OnTimer, self.__timer) def __OnTimer(self, evt): self.flush() def flush(self): with self.__lock: queue, self.__queue = self.__queue, [] lines = "".join(queue) if lines: self.AppendText(lines) def start(self, interval=100): self.__timer.Start(interval) def stop(self): self.__timer.Stop() wx.CallAfter(self.flush) def write(self, s): with self.__lock: self.__queue.append(s) def IsEmpty(self): return self.GetTextLength() == 0
<commit_before>import Queue import wx, wx.stc from editor_fonts import init_stc_style class ThreadOutputCtrl(wx.stc.StyledTextCtrl): def __init__(self, parent, style=wx.TE_READONLY): wx.stc.StyledTextCtrl.__init__(self, parent) init_stc_style(self) self.SetIndent(4) self.SetTabWidth(8) self.SetUseTabs(False) self.queue = Queue.Queue(1024) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__OnTimer, self.timer) def __OnTimer(self, evt): self.flush() def flush(self): lines = "".join(self.queue.get_nowait() for _ in xrange(self.queue.qsize())) if lines: self.AppendText(lines) def start(self, interval=100): self.timer.Start(interval) def stop(self): self.timer.Stop() wx.CallAfter(self.flush) def write(self, s): self.queue.put(s) def IsEmpty(self): return self.GetTextLength() == 0 <commit_msg>Use a lock-protected list instead of a Queue.<commit_after>import threading import wx, wx.stc from editor_fonts import init_stc_style class ThreadOutputCtrl(wx.stc.StyledTextCtrl): def __init__(self, parent, style=wx.TE_READONLY): wx.stc.StyledTextCtrl.__init__(self, parent) init_stc_style(self) self.SetIndent(4) self.SetTabWidth(8) self.SetUseTabs(False) self.__lock = threading.Lock() self.__queue = [] self.__timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__OnTimer, self.__timer) def __OnTimer(self, evt): self.flush() def flush(self): with self.__lock: queue, self.__queue = self.__queue, [] lines = "".join(queue) if lines: self.AppendText(lines) def start(self, interval=100): self.__timer.Start(interval) def stop(self): self.__timer.Stop() wx.CallAfter(self.flush) def write(self, s): with self.__lock: self.__queue.append(s) def IsEmpty(self): return self.GetTextLength() == 0
3a11712925ca1038a1c8c8c8eef29ca4d5fd1c6f
test/functionalities/command_script/import/rdar-12586188/TestRdar12586188.py
test/functionalities/command_script/import/rdar-12586188/TestRdar12586188.py
"""Check that we handle an ImportError in a special way when command script importing files.""" import os, sys, time import unittest2 import lldb from lldbtest import * class Rdar12586188TestCase(TestBase): mydir = os.path.join("functionalities", "command_script", "import", "rdar-12586188") @python_api_test def test_rdar12586188_command(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.run_test() def setUp(self): # Call super's setUp(). TestBase.setUp(self) def run_test(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.expect("command script import ./fail12586188.py --allow-reload", error=True, substrs = ['error: module importing failed: I do not want to be imported']) self.expect("command script import ./fail212586188.py --allow-reload", error=True, substrs = ['error: module importing failed: Python raised an error while importing module']) if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
"""Check that we handle an ImportError in a special way when command script importing files.""" import os, sys, time import unittest2 import lldb from lldbtest import * class Rdar12586188TestCase(TestBase): mydir = os.path.join("functionalities", "command_script", "import", "rdar-12586188") @python_api_test def test_rdar12586188_command(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.run_test() def setUp(self): # Call super's setUp(). TestBase.setUp(self) def run_test(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.expect("command script import ./fail12586188.py --allow-reload", error=True, substrs = ['error: module importing failed: I do not want to be imported']) self.expect("command script import ./fail212586188.py --allow-reload", error=True, substrs = ['error: module importing failed: Python error raised while importing module: I do not want to be imported']) if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
Fix expected error message in test.
Fix expected error message in test. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@168220 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb
"""Check that we handle an ImportError in a special way when command script importing files.""" import os, sys, time import unittest2 import lldb from lldbtest import * class Rdar12586188TestCase(TestBase): mydir = os.path.join("functionalities", "command_script", "import", "rdar-12586188") @python_api_test def test_rdar12586188_command(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.run_test() def setUp(self): # Call super's setUp(). TestBase.setUp(self) def run_test(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.expect("command script import ./fail12586188.py --allow-reload", error=True, substrs = ['error: module importing failed: I do not want to be imported']) self.expect("command script import ./fail212586188.py --allow-reload", error=True, substrs = ['error: module importing failed: Python raised an error while importing module']) if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main() Fix expected error message in test. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@168220 91177308-0d34-0410-b5e6-96231b3b80d8
"""Check that we handle an ImportError in a special way when command script importing files.""" import os, sys, time import unittest2 import lldb from lldbtest import * class Rdar12586188TestCase(TestBase): mydir = os.path.join("functionalities", "command_script", "import", "rdar-12586188") @python_api_test def test_rdar12586188_command(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.run_test() def setUp(self): # Call super's setUp(). TestBase.setUp(self) def run_test(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.expect("command script import ./fail12586188.py --allow-reload", error=True, substrs = ['error: module importing failed: I do not want to be imported']) self.expect("command script import ./fail212586188.py --allow-reload", error=True, substrs = ['error: module importing failed: Python error raised while importing module: I do not want to be imported']) if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
<commit_before>"""Check that we handle an ImportError in a special way when command script importing files.""" import os, sys, time import unittest2 import lldb from lldbtest import * class Rdar12586188TestCase(TestBase): mydir = os.path.join("functionalities", "command_script", "import", "rdar-12586188") @python_api_test def test_rdar12586188_command(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.run_test() def setUp(self): # Call super's setUp(). TestBase.setUp(self) def run_test(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.expect("command script import ./fail12586188.py --allow-reload", error=True, substrs = ['error: module importing failed: I do not want to be imported']) self.expect("command script import ./fail212586188.py --allow-reload", error=True, substrs = ['error: module importing failed: Python raised an error while importing module']) if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main() <commit_msg>Fix expected error message in test. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@168220 91177308-0d34-0410-b5e6-96231b3b80d8<commit_after>
"""Check that we handle an ImportError in a special way when command script importing files.""" import os, sys, time import unittest2 import lldb from lldbtest import * class Rdar12586188TestCase(TestBase): mydir = os.path.join("functionalities", "command_script", "import", "rdar-12586188") @python_api_test def test_rdar12586188_command(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.run_test() def setUp(self): # Call super's setUp(). TestBase.setUp(self) def run_test(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.expect("command script import ./fail12586188.py --allow-reload", error=True, substrs = ['error: module importing failed: I do not want to be imported']) self.expect("command script import ./fail212586188.py --allow-reload", error=True, substrs = ['error: module importing failed: Python error raised while importing module: I do not want to be imported']) if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
"""Check that we handle an ImportError in a special way when command script importing files.""" import os, sys, time import unittest2 import lldb from lldbtest import * class Rdar12586188TestCase(TestBase): mydir = os.path.join("functionalities", "command_script", "import", "rdar-12586188") @python_api_test def test_rdar12586188_command(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.run_test() def setUp(self): # Call super's setUp(). TestBase.setUp(self) def run_test(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.expect("command script import ./fail12586188.py --allow-reload", error=True, substrs = ['error: module importing failed: I do not want to be imported']) self.expect("command script import ./fail212586188.py --allow-reload", error=True, substrs = ['error: module importing failed: Python raised an error while importing module']) if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main() Fix expected error message in test. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@168220 91177308-0d34-0410-b5e6-96231b3b80d8"""Check that we handle an ImportError in a special way when command script importing files.""" import os, sys, time import unittest2 import lldb from lldbtest import * class Rdar12586188TestCase(TestBase): mydir = os.path.join("functionalities", "command_script", "import", "rdar-12586188") @python_api_test def test_rdar12586188_command(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.run_test() def setUp(self): # Call super's setUp(). TestBase.setUp(self) def run_test(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.expect("command script import ./fail12586188.py --allow-reload", error=True, substrs = ['error: module importing failed: I do not want to be imported']) self.expect("command script import ./fail212586188.py --allow-reload", error=True, substrs = ['error: module importing failed: Python error raised while importing module: I do not want to be imported']) if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
<commit_before>"""Check that we handle an ImportError in a special way when command script importing files.""" import os, sys, time import unittest2 import lldb from lldbtest import * class Rdar12586188TestCase(TestBase): mydir = os.path.join("functionalities", "command_script", "import", "rdar-12586188") @python_api_test def test_rdar12586188_command(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.run_test() def setUp(self): # Call super's setUp(). TestBase.setUp(self) def run_test(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.expect("command script import ./fail12586188.py --allow-reload", error=True, substrs = ['error: module importing failed: I do not want to be imported']) self.expect("command script import ./fail212586188.py --allow-reload", error=True, substrs = ['error: module importing failed: Python raised an error while importing module']) if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main() <commit_msg>Fix expected error message in test. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@168220 91177308-0d34-0410-b5e6-96231b3b80d8<commit_after>"""Check that we handle an ImportError in a special way when command script importing files.""" import os, sys, time import unittest2 import lldb from lldbtest import * class Rdar12586188TestCase(TestBase): mydir = os.path.join("functionalities", "command_script", "import", "rdar-12586188") @python_api_test def test_rdar12586188_command(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.run_test() def setUp(self): # Call super's setUp(). TestBase.setUp(self) def run_test(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.expect("command script import ./fail12586188.py --allow-reload", error=True, substrs = ['error: module importing failed: I do not want to be imported']) self.expect("command script import ./fail212586188.py --allow-reload", error=True, substrs = ['error: module importing failed: Python error raised while importing module: I do not want to be imported']) if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
a877a578f0e71f9d667b5845c96b913ea51fa195
masquerade/urls.py
masquerade/urls.py
try: from django.conf.urls import url except ImportError: from django.core.urlresolvers import reverse from masquerade.views import mask, unmask urlpatterns = [ url(r'^mask/$', mask, name='masquerade-mask'), url(r'^unmask/$', unmask, name='masquerade-unmask'), ]
try: from django.urls import url except ImportError: from django.core.urlresolvers import reverse from masquerade.views import mask, unmask urlpatterns = [ url(r'^mask/$', mask, name='masquerade-mask'), url(r'^unmask/$', unmask, name='masquerade-unmask'), ]
Fix a bad import path
Fix a bad import path
Python
apache-2.0
erikcw/django-masquerade,erikcw/django-masquerade,erikcw/django-masquerade
try: from django.conf.urls import url except ImportError: from django.core.urlresolvers import reverse from masquerade.views import mask, unmask urlpatterns = [ url(r'^mask/$', mask, name='masquerade-mask'), url(r'^unmask/$', unmask, name='masquerade-unmask'), ] Fix a bad import path
try: from django.urls import url except ImportError: from django.core.urlresolvers import reverse from masquerade.views import mask, unmask urlpatterns = [ url(r'^mask/$', mask, name='masquerade-mask'), url(r'^unmask/$', unmask, name='masquerade-unmask'), ]
<commit_before>try: from django.conf.urls import url except ImportError: from django.core.urlresolvers import reverse from masquerade.views import mask, unmask urlpatterns = [ url(r'^mask/$', mask, name='masquerade-mask'), url(r'^unmask/$', unmask, name='masquerade-unmask'), ] <commit_msg>Fix a bad import path<commit_after>
try: from django.urls import url except ImportError: from django.core.urlresolvers import reverse from masquerade.views import mask, unmask urlpatterns = [ url(r'^mask/$', mask, name='masquerade-mask'), url(r'^unmask/$', unmask, name='masquerade-unmask'), ]
try: from django.conf.urls import url except ImportError: from django.core.urlresolvers import reverse from masquerade.views import mask, unmask urlpatterns = [ url(r'^mask/$', mask, name='masquerade-mask'), url(r'^unmask/$', unmask, name='masquerade-unmask'), ] Fix a bad import pathtry: from django.urls import url except ImportError: from django.core.urlresolvers import reverse from masquerade.views import mask, unmask urlpatterns = [ url(r'^mask/$', mask, name='masquerade-mask'), url(r'^unmask/$', unmask, name='masquerade-unmask'), ]
<commit_before>try: from django.conf.urls import url except ImportError: from django.core.urlresolvers import reverse from masquerade.views import mask, unmask urlpatterns = [ url(r'^mask/$', mask, name='masquerade-mask'), url(r'^unmask/$', unmask, name='masquerade-unmask'), ] <commit_msg>Fix a bad import path<commit_after>try: from django.urls import url except ImportError: from django.core.urlresolvers import reverse from masquerade.views import mask, unmask urlpatterns = [ url(r'^mask/$', mask, name='masquerade-mask'), url(r'^unmask/$', unmask, name='masquerade-unmask'), ]
336313ac982b9de278aca6e0f74f6820ef5b2526
landlab/grid/structured_quad/tests/test_links.py
landlab/grid/structured_quad/tests/test_links.py
import numpy as np from numpy.testing import assert_array_equal from nose.tools import raises, assert_true from landlab.grid.structured_quad.nodes import status_with_perimeter_as_boundary from landlab.grid.structured_quad.links import active_link_ids from landlab.grid.base import CORE_NODE, FIXED_VALUE_BOUNDARY, CLOSED_BOUNDARY def test_active_links_ids(): status = np.empty((4, 5), dtype=int) status.fill(CLOSED_BOUNDARY) status[1, 2] = status[1, 3] = status[2, 2] = status[2, 3] = CORE_NODE link_ids = active_link_ids((4, 5), status) assert_array_equal(link_ids, [7, 8, 21, 25]) assert_true(str(link_ids.dtype).startswith('int')) def test_active_links_with_edge_boundaries(): status = status_with_perimeter_as_boundary((3, 4)) link_ids = active_link_ids((3, 4), status) assert_array_equal(link_ids, [1, 2, 5, 6, 11, 12, 13]) assert_true(str(link_ids.dtype).startswith('int')) @raises(ValueError) def test_active_link_ids_with_shape_mismatch(): active_link_ids((3, 4), np.zeros(3))
import numpy as np from numpy.testing import assert_array_equal from nose.tools import raises, assert_equal from landlab.grid.structured_quad.nodes import status_with_perimeter_as_boundary from landlab.grid.structured_quad.links import active_link_ids from landlab.grid.base import CORE_NODE, FIXED_VALUE_BOUNDARY, CLOSED_BOUNDARY def test_active_links_ids(): status = np.empty((4, 5), dtype=int) status.fill(CLOSED_BOUNDARY) status[1, 2] = status[1, 3] = status[2, 2] = status[2, 3] = CORE_NODE link_ids = active_link_ids((4, 5), status) assert_array_equal(link_ids, [7, 8, 21, 25]) assert_equal(link_ids.dtype, np.int) def test_active_links_with_edge_boundaries(): status = status_with_perimeter_as_boundary((3, 4)) link_ids = active_link_ids((3, 4), status) assert_array_equal(link_ids, [1, 2, 5, 6, 11, 12, 13]) assert_equal(link_ids.dtype, np.int) @raises(ValueError) def test_active_link_ids_with_shape_mismatch(): active_link_ids((3, 4), np.zeros(3))
Test of index arrays of type int.
Test of index arrays of type int.
Python
mit
ManuSchmi88/landlab,amandersillinois/landlab,SiccarPoint/landlab,cmshobe/landlab,amandersillinois/landlab,SiccarPoint/landlab,cmshobe/landlab,laijingtao/landlab,RondaStrauch/landlab,Carralex/landlab,Carralex/landlab,ManuSchmi88/landlab,cmshobe/landlab,Carralex/landlab,landlab/landlab,csherwood-usgs/landlab,ManuSchmi88/landlab,landlab/landlab,laijingtao/landlab,RondaStrauch/landlab,decvalts/landlab,RondaStrauch/landlab,decvalts/landlab,landlab/landlab,csherwood-usgs/landlab
import numpy as np from numpy.testing import assert_array_equal from nose.tools import raises, assert_true from landlab.grid.structured_quad.nodes import status_with_perimeter_as_boundary from landlab.grid.structured_quad.links import active_link_ids from landlab.grid.base import CORE_NODE, FIXED_VALUE_BOUNDARY, CLOSED_BOUNDARY def test_active_links_ids(): status = np.empty((4, 5), dtype=int) status.fill(CLOSED_BOUNDARY) status[1, 2] = status[1, 3] = status[2, 2] = status[2, 3] = CORE_NODE link_ids = active_link_ids((4, 5), status) assert_array_equal(link_ids, [7, 8, 21, 25]) assert_true(str(link_ids.dtype).startswith('int')) def test_active_links_with_edge_boundaries(): status = status_with_perimeter_as_boundary((3, 4)) link_ids = active_link_ids((3, 4), status) assert_array_equal(link_ids, [1, 2, 5, 6, 11, 12, 13]) assert_true(str(link_ids.dtype).startswith('int')) @raises(ValueError) def test_active_link_ids_with_shape_mismatch(): active_link_ids((3, 4), np.zeros(3)) Test of index arrays of type int.
import numpy as np from numpy.testing import assert_array_equal from nose.tools import raises, assert_equal from landlab.grid.structured_quad.nodes import status_with_perimeter_as_boundary from landlab.grid.structured_quad.links import active_link_ids from landlab.grid.base import CORE_NODE, FIXED_VALUE_BOUNDARY, CLOSED_BOUNDARY def test_active_links_ids(): status = np.empty((4, 5), dtype=int) status.fill(CLOSED_BOUNDARY) status[1, 2] = status[1, 3] = status[2, 2] = status[2, 3] = CORE_NODE link_ids = active_link_ids((4, 5), status) assert_array_equal(link_ids, [7, 8, 21, 25]) assert_equal(link_ids.dtype, np.int) def test_active_links_with_edge_boundaries(): status = status_with_perimeter_as_boundary((3, 4)) link_ids = active_link_ids((3, 4), status) assert_array_equal(link_ids, [1, 2, 5, 6, 11, 12, 13]) assert_equal(link_ids.dtype, np.int) @raises(ValueError) def test_active_link_ids_with_shape_mismatch(): active_link_ids((3, 4), np.zeros(3))
<commit_before>import numpy as np from numpy.testing import assert_array_equal from nose.tools import raises, assert_true from landlab.grid.structured_quad.nodes import status_with_perimeter_as_boundary from landlab.grid.structured_quad.links import active_link_ids from landlab.grid.base import CORE_NODE, FIXED_VALUE_BOUNDARY, CLOSED_BOUNDARY def test_active_links_ids(): status = np.empty((4, 5), dtype=int) status.fill(CLOSED_BOUNDARY) status[1, 2] = status[1, 3] = status[2, 2] = status[2, 3] = CORE_NODE link_ids = active_link_ids((4, 5), status) assert_array_equal(link_ids, [7, 8, 21, 25]) assert_true(str(link_ids.dtype).startswith('int')) def test_active_links_with_edge_boundaries(): status = status_with_perimeter_as_boundary((3, 4)) link_ids = active_link_ids((3, 4), status) assert_array_equal(link_ids, [1, 2, 5, 6, 11, 12, 13]) assert_true(str(link_ids.dtype).startswith('int')) @raises(ValueError) def test_active_link_ids_with_shape_mismatch(): active_link_ids((3, 4), np.zeros(3)) <commit_msg>Test of index arrays of type int.<commit_after>
import numpy as np from numpy.testing import assert_array_equal from nose.tools import raises, assert_equal from landlab.grid.structured_quad.nodes import status_with_perimeter_as_boundary from landlab.grid.structured_quad.links import active_link_ids from landlab.grid.base import CORE_NODE, FIXED_VALUE_BOUNDARY, CLOSED_BOUNDARY def test_active_links_ids(): status = np.empty((4, 5), dtype=int) status.fill(CLOSED_BOUNDARY) status[1, 2] = status[1, 3] = status[2, 2] = status[2, 3] = CORE_NODE link_ids = active_link_ids((4, 5), status) assert_array_equal(link_ids, [7, 8, 21, 25]) assert_equal(link_ids.dtype, np.int) def test_active_links_with_edge_boundaries(): status = status_with_perimeter_as_boundary((3, 4)) link_ids = active_link_ids((3, 4), status) assert_array_equal(link_ids, [1, 2, 5, 6, 11, 12, 13]) assert_equal(link_ids.dtype, np.int) @raises(ValueError) def test_active_link_ids_with_shape_mismatch(): active_link_ids((3, 4), np.zeros(3))
import numpy as np from numpy.testing import assert_array_equal from nose.tools import raises, assert_true from landlab.grid.structured_quad.nodes import status_with_perimeter_as_boundary from landlab.grid.structured_quad.links import active_link_ids from landlab.grid.base import CORE_NODE, FIXED_VALUE_BOUNDARY, CLOSED_BOUNDARY def test_active_links_ids(): status = np.empty((4, 5), dtype=int) status.fill(CLOSED_BOUNDARY) status[1, 2] = status[1, 3] = status[2, 2] = status[2, 3] = CORE_NODE link_ids = active_link_ids((4, 5), status) assert_array_equal(link_ids, [7, 8, 21, 25]) assert_true(str(link_ids.dtype).startswith('int')) def test_active_links_with_edge_boundaries(): status = status_with_perimeter_as_boundary((3, 4)) link_ids = active_link_ids((3, 4), status) assert_array_equal(link_ids, [1, 2, 5, 6, 11, 12, 13]) assert_true(str(link_ids.dtype).startswith('int')) @raises(ValueError) def test_active_link_ids_with_shape_mismatch(): active_link_ids((3, 4), np.zeros(3)) Test of index arrays of type int.import numpy as np from numpy.testing import assert_array_equal from nose.tools import raises, assert_equal from landlab.grid.structured_quad.nodes import status_with_perimeter_as_boundary from landlab.grid.structured_quad.links import active_link_ids from landlab.grid.base import CORE_NODE, FIXED_VALUE_BOUNDARY, CLOSED_BOUNDARY def test_active_links_ids(): status = np.empty((4, 5), dtype=int) status.fill(CLOSED_BOUNDARY) status[1, 2] = status[1, 3] = status[2, 2] = status[2, 3] = CORE_NODE link_ids = active_link_ids((4, 5), status) assert_array_equal(link_ids, [7, 8, 21, 25]) assert_equal(link_ids.dtype, np.int) def test_active_links_with_edge_boundaries(): status = status_with_perimeter_as_boundary((3, 4)) link_ids = active_link_ids((3, 4), status) assert_array_equal(link_ids, [1, 2, 5, 6, 11, 12, 13]) assert_equal(link_ids.dtype, np.int) @raises(ValueError) def test_active_link_ids_with_shape_mismatch(): active_link_ids((3, 4), np.zeros(3))
<commit_before>import numpy as np from numpy.testing import assert_array_equal from nose.tools import raises, assert_true from landlab.grid.structured_quad.nodes import status_with_perimeter_as_boundary from landlab.grid.structured_quad.links import active_link_ids from landlab.grid.base import CORE_NODE, FIXED_VALUE_BOUNDARY, CLOSED_BOUNDARY def test_active_links_ids(): status = np.empty((4, 5), dtype=int) status.fill(CLOSED_BOUNDARY) status[1, 2] = status[1, 3] = status[2, 2] = status[2, 3] = CORE_NODE link_ids = active_link_ids((4, 5), status) assert_array_equal(link_ids, [7, 8, 21, 25]) assert_true(str(link_ids.dtype).startswith('int')) def test_active_links_with_edge_boundaries(): status = status_with_perimeter_as_boundary((3, 4)) link_ids = active_link_ids((3, 4), status) assert_array_equal(link_ids, [1, 2, 5, 6, 11, 12, 13]) assert_true(str(link_ids.dtype).startswith('int')) @raises(ValueError) def test_active_link_ids_with_shape_mismatch(): active_link_ids((3, 4), np.zeros(3)) <commit_msg>Test of index arrays of type int.<commit_after>import numpy as np from numpy.testing import assert_array_equal from nose.tools import raises, assert_equal from landlab.grid.structured_quad.nodes import status_with_perimeter_as_boundary from landlab.grid.structured_quad.links import active_link_ids from landlab.grid.base import CORE_NODE, FIXED_VALUE_BOUNDARY, CLOSED_BOUNDARY def test_active_links_ids(): status = np.empty((4, 5), dtype=int) status.fill(CLOSED_BOUNDARY) status[1, 2] = status[1, 3] = status[2, 2] = status[2, 3] = CORE_NODE link_ids = active_link_ids((4, 5), status) assert_array_equal(link_ids, [7, 8, 21, 25]) assert_equal(link_ids.dtype, np.int) def test_active_links_with_edge_boundaries(): status = status_with_perimeter_as_boundary((3, 4)) link_ids = active_link_ids((3, 4), status) assert_array_equal(link_ids, [1, 2, 5, 6, 11, 12, 13]) assert_equal(link_ids.dtype, np.int) @raises(ValueError) def test_active_link_ids_with_shape_mismatch(): active_link_ids((3, 4), np.zeros(3))
4036ef2ac8435070d8850e1dab4187890bccd7c5
mayavi/__init__.py
mayavi/__init__.py
# Author: Prabhu Ramachandran, Gael Varoquaux # Copyright (c) 2004-2014, Enthought, Inc. # License: BSD Style. """ A tool for easy and interactive visualization of data. Part of the Mayavi project of the Enthought Tool Suite. """ __version__ = '4.4.4.dev0' __requires__ = [ 'apptools', 'traits', 'traitsui', ] __extras_require__ = { 'app': [ 'envisage', ], } # Try forcing the use of wx 2.8 before any other import. import sys if not 'wx' in sys.modules: try: # Try forcing the use of wx 2.8 from traits.etsconfig.api import ETSConfig if ETSConfig.toolkit in ('wx', ''): import wxversion wxversion.ensureMinimal('2.8') except ImportError: """ wxversion not installed """
# Author: Prabhu Ramachandran, Gael Varoquaux # Copyright (c) 2004-2014, Enthought, Inc. # License: BSD Style. """ A tool for easy and interactive visualization of data. Part of the Mayavi project of the Enthought Tool Suite. """ __version__ = '4.4.3' __requires__ = [ 'apptools', 'traits', 'traitsui', ] __extras_require__ = { 'app': [ 'envisage', ], } # Try forcing the use of wx 2.8 before any other import. import sys if not 'wx' in sys.modules: try: # Try forcing the use of wx 2.8 from traits.etsconfig.api import ETSConfig if ETSConfig.toolkit in ('wx', ''): import wxversion wxversion.ensureMinimal('2.8') except ImportError: """ wxversion not installed """
Revert "Bump up dev version to 4.4.4.dev0"
Revert "Bump up dev version to 4.4.4.dev0" This reverts commit c65f7d3b9305fad3037f3086256927b2e1c1f43e.
Python
bsd-3-clause
dmsurti/mayavi,dmsurti/mayavi
# Author: Prabhu Ramachandran, Gael Varoquaux # Copyright (c) 2004-2014, Enthought, Inc. # License: BSD Style. """ A tool for easy and interactive visualization of data. Part of the Mayavi project of the Enthought Tool Suite. """ __version__ = '4.4.4.dev0' __requires__ = [ 'apptools', 'traits', 'traitsui', ] __extras_require__ = { 'app': [ 'envisage', ], } # Try forcing the use of wx 2.8 before any other import. import sys if not 'wx' in sys.modules: try: # Try forcing the use of wx 2.8 from traits.etsconfig.api import ETSConfig if ETSConfig.toolkit in ('wx', ''): import wxversion wxversion.ensureMinimal('2.8') except ImportError: """ wxversion not installed """ Revert "Bump up dev version to 4.4.4.dev0" This reverts commit c65f7d3b9305fad3037f3086256927b2e1c1f43e.
# Author: Prabhu Ramachandran, Gael Varoquaux # Copyright (c) 2004-2014, Enthought, Inc. # License: BSD Style. """ A tool for easy and interactive visualization of data. Part of the Mayavi project of the Enthought Tool Suite. """ __version__ = '4.4.3' __requires__ = [ 'apptools', 'traits', 'traitsui', ] __extras_require__ = { 'app': [ 'envisage', ], } # Try forcing the use of wx 2.8 before any other import. import sys if not 'wx' in sys.modules: try: # Try forcing the use of wx 2.8 from traits.etsconfig.api import ETSConfig if ETSConfig.toolkit in ('wx', ''): import wxversion wxversion.ensureMinimal('2.8') except ImportError: """ wxversion not installed """
<commit_before># Author: Prabhu Ramachandran, Gael Varoquaux # Copyright (c) 2004-2014, Enthought, Inc. # License: BSD Style. """ A tool for easy and interactive visualization of data. Part of the Mayavi project of the Enthought Tool Suite. """ __version__ = '4.4.4.dev0' __requires__ = [ 'apptools', 'traits', 'traitsui', ] __extras_require__ = { 'app': [ 'envisage', ], } # Try forcing the use of wx 2.8 before any other import. import sys if not 'wx' in sys.modules: try: # Try forcing the use of wx 2.8 from traits.etsconfig.api import ETSConfig if ETSConfig.toolkit in ('wx', ''): import wxversion wxversion.ensureMinimal('2.8') except ImportError: """ wxversion not installed """ <commit_msg>Revert "Bump up dev version to 4.4.4.dev0" This reverts commit c65f7d3b9305fad3037f3086256927b2e1c1f43e.<commit_after>
# Author: Prabhu Ramachandran, Gael Varoquaux # Copyright (c) 2004-2014, Enthought, Inc. # License: BSD Style. """ A tool for easy and interactive visualization of data. Part of the Mayavi project of the Enthought Tool Suite. """ __version__ = '4.4.3' __requires__ = [ 'apptools', 'traits', 'traitsui', ] __extras_require__ = { 'app': [ 'envisage', ], } # Try forcing the use of wx 2.8 before any other import. import sys if not 'wx' in sys.modules: try: # Try forcing the use of wx 2.8 from traits.etsconfig.api import ETSConfig if ETSConfig.toolkit in ('wx', ''): import wxversion wxversion.ensureMinimal('2.8') except ImportError: """ wxversion not installed """
# Author: Prabhu Ramachandran, Gael Varoquaux # Copyright (c) 2004-2014, Enthought, Inc. # License: BSD Style. """ A tool for easy and interactive visualization of data. Part of the Mayavi project of the Enthought Tool Suite. """ __version__ = '4.4.4.dev0' __requires__ = [ 'apptools', 'traits', 'traitsui', ] __extras_require__ = { 'app': [ 'envisage', ], } # Try forcing the use of wx 2.8 before any other import. import sys if not 'wx' in sys.modules: try: # Try forcing the use of wx 2.8 from traits.etsconfig.api import ETSConfig if ETSConfig.toolkit in ('wx', ''): import wxversion wxversion.ensureMinimal('2.8') except ImportError: """ wxversion not installed """ Revert "Bump up dev version to 4.4.4.dev0" This reverts commit c65f7d3b9305fad3037f3086256927b2e1c1f43e.# Author: Prabhu Ramachandran, Gael Varoquaux # Copyright (c) 2004-2014, Enthought, Inc. # License: BSD Style. """ A tool for easy and interactive visualization of data. Part of the Mayavi project of the Enthought Tool Suite. """ __version__ = '4.4.3' __requires__ = [ 'apptools', 'traits', 'traitsui', ] __extras_require__ = { 'app': [ 'envisage', ], } # Try forcing the use of wx 2.8 before any other import. import sys if not 'wx' in sys.modules: try: # Try forcing the use of wx 2.8 from traits.etsconfig.api import ETSConfig if ETSConfig.toolkit in ('wx', ''): import wxversion wxversion.ensureMinimal('2.8') except ImportError: """ wxversion not installed """
<commit_before># Author: Prabhu Ramachandran, Gael Varoquaux # Copyright (c) 2004-2014, Enthought, Inc. # License: BSD Style. """ A tool for easy and interactive visualization of data. Part of the Mayavi project of the Enthought Tool Suite. """ __version__ = '4.4.4.dev0' __requires__ = [ 'apptools', 'traits', 'traitsui', ] __extras_require__ = { 'app': [ 'envisage', ], } # Try forcing the use of wx 2.8 before any other import. import sys if not 'wx' in sys.modules: try: # Try forcing the use of wx 2.8 from traits.etsconfig.api import ETSConfig if ETSConfig.toolkit in ('wx', ''): import wxversion wxversion.ensureMinimal('2.8') except ImportError: """ wxversion not installed """ <commit_msg>Revert "Bump up dev version to 4.4.4.dev0" This reverts commit c65f7d3b9305fad3037f3086256927b2e1c1f43e.<commit_after># Author: Prabhu Ramachandran, Gael Varoquaux # Copyright (c) 2004-2014, Enthought, Inc. # License: BSD Style. """ A tool for easy and interactive visualization of data. Part of the Mayavi project of the Enthought Tool Suite. """ __version__ = '4.4.3' __requires__ = [ 'apptools', 'traits', 'traitsui', ] __extras_require__ = { 'app': [ 'envisage', ], } # Try forcing the use of wx 2.8 before any other import. import sys if not 'wx' in sys.modules: try: # Try forcing the use of wx 2.8 from traits.etsconfig.api import ETSConfig if ETSConfig.toolkit in ('wx', ''): import wxversion wxversion.ensureMinimal('2.8') except ImportError: """ wxversion not installed """
2be4b1b67ca17a400c6d22e8e29e0a4f1c69c0cc
dakota_utils/models/hydrotrend.py
dakota_utils/models/hydrotrend.py
#! /usr/bin/env python # # A module for working with HydroTrend. # # Mark Piper (mark.piper@colorado.edu) import numpy as np def load_series(output_file): ''' Reads a column of text containing HydroTrend output. Returns a numpy array, or None on an error. ''' try: series = np.loadtxt(output_file, skiprows=2) except (IOError, StopIteration): pass else: return(series)
#! /usr/bin/env python # # A module for working with HydroTrend. # # Mark Piper (mark.piper@colorado.edu) from subprocess import call import numpy as np def load(output_file): ''' Reads a column of text containing HydroTrend output. Returns a numpy array, or None on an error. ''' try: series = np.loadtxt(output_file, skiprows=2) except (IOError, StopIteration): pass else: return(series) def call(input_dir, output_dir): ''' Invokes HydroTrend through the shell. ''' call(['hydrotrend', '--in-dir', input_dir, '--out-dir', output_dir])
Add call() function, rename load() function
Add call() function, rename load() function Slowly encapsulating the run_hydrotrend.py script used in the Dakota experiments.
Python
mit
mdpiper/dakota-experiments,mdpiper/dakota-experiments,mcflugen/dakota-experiments,mdpiper/dakota-experiments,mcflugen/dakota-experiments
#! /usr/bin/env python # # A module for working with HydroTrend. # # Mark Piper (mark.piper@colorado.edu) import numpy as np def load_series(output_file): ''' Reads a column of text containing HydroTrend output. Returns a numpy array, or None on an error. ''' try: series = np.loadtxt(output_file, skiprows=2) except (IOError, StopIteration): pass else: return(series) Add call() function, rename load() function Slowly encapsulating the run_hydrotrend.py script used in the Dakota experiments.
#! /usr/bin/env python # # A module for working with HydroTrend. # # Mark Piper (mark.piper@colorado.edu) from subprocess import call import numpy as np def load(output_file): ''' Reads a column of text containing HydroTrend output. Returns a numpy array, or None on an error. ''' try: series = np.loadtxt(output_file, skiprows=2) except (IOError, StopIteration): pass else: return(series) def call(input_dir, output_dir): ''' Invokes HydroTrend through the shell. ''' call(['hydrotrend', '--in-dir', input_dir, '--out-dir', output_dir])
<commit_before>#! /usr/bin/env python # # A module for working with HydroTrend. # # Mark Piper (mark.piper@colorado.edu) import numpy as np def load_series(output_file): ''' Reads a column of text containing HydroTrend output. Returns a numpy array, or None on an error. ''' try: series = np.loadtxt(output_file, skiprows=2) except (IOError, StopIteration): pass else: return(series) <commit_msg>Add call() function, rename load() function Slowly encapsulating the run_hydrotrend.py script used in the Dakota experiments.<commit_after>
#! /usr/bin/env python # # A module for working with HydroTrend. # # Mark Piper (mark.piper@colorado.edu) from subprocess import call import numpy as np def load(output_file): ''' Reads a column of text containing HydroTrend output. Returns a numpy array, or None on an error. ''' try: series = np.loadtxt(output_file, skiprows=2) except (IOError, StopIteration): pass else: return(series) def call(input_dir, output_dir): ''' Invokes HydroTrend through the shell. ''' call(['hydrotrend', '--in-dir', input_dir, '--out-dir', output_dir])
#! /usr/bin/env python # # A module for working with HydroTrend. # # Mark Piper (mark.piper@colorado.edu) import numpy as np def load_series(output_file): ''' Reads a column of text containing HydroTrend output. Returns a numpy array, or None on an error. ''' try: series = np.loadtxt(output_file, skiprows=2) except (IOError, StopIteration): pass else: return(series) Add call() function, rename load() function Slowly encapsulating the run_hydrotrend.py script used in the Dakota experiments.#! /usr/bin/env python # # A module for working with HydroTrend. # # Mark Piper (mark.piper@colorado.edu) from subprocess import call import numpy as np def load(output_file): ''' Reads a column of text containing HydroTrend output. Returns a numpy array, or None on an error. ''' try: series = np.loadtxt(output_file, skiprows=2) except (IOError, StopIteration): pass else: return(series) def call(input_dir, output_dir): ''' Invokes HydroTrend through the shell. ''' call(['hydrotrend', '--in-dir', input_dir, '--out-dir', output_dir])
<commit_before>#! /usr/bin/env python # # A module for working with HydroTrend. # # Mark Piper (mark.piper@colorado.edu) import numpy as np def load_series(output_file): ''' Reads a column of text containing HydroTrend output. Returns a numpy array, or None on an error. ''' try: series = np.loadtxt(output_file, skiprows=2) except (IOError, StopIteration): pass else: return(series) <commit_msg>Add call() function, rename load() function Slowly encapsulating the run_hydrotrend.py script used in the Dakota experiments.<commit_after>#! /usr/bin/env python # # A module for working with HydroTrend. # # Mark Piper (mark.piper@colorado.edu) from subprocess import call import numpy as np def load(output_file): ''' Reads a column of text containing HydroTrend output. Returns a numpy array, or None on an error. ''' try: series = np.loadtxt(output_file, skiprows=2) except (IOError, StopIteration): pass else: return(series) def call(input_dir, output_dir): ''' Invokes HydroTrend through the shell. ''' call(['hydrotrend', '--in-dir', input_dir, '--out-dir', output_dir])
c231987c532885fa7bc5e8d2afc8b7a30a2ce297
bayesian_methods_for_hackers/simulate_messages_ch02.py
bayesian_methods_for_hackers/simulate_messages_ch02.py
import json import matplotlib import numpy as np import pymc as pm from matplotlib import pyplot as plt def main(): matplotlibrc_path = '/home/noel/repo/playground/matplotlibrc.json' matplotlib.rcParams.update(json.load(open(matplotlibrc_path))) tau = pm.rdiscrete_uniform(0, 80) print tau alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) print lambda_1, lambda_2 data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] def plot_artificial_sms_dataset(): tau = pm.rdiscrete_uniform(0, 80) alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] plt.bar(np.arange(80), data, color="#348ABD") plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed") plt.xlim(0, 80) plt.title("More example of artificial datasets") for i in range(1, 5): plt.subplot(4, 1, i) plot_artificial_sms_dataset() plt.show() if __name__ == '__main__': main()
import json import matplotlib import numpy as np import pymc as pm from matplotlib import pyplot as plt def main(): tau = pm.rdiscrete_uniform(0, 80) print tau alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) print lambda_1, lambda_2 data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] def plot_artificial_sms_dataset(): tau = pm.rdiscrete_uniform(0, 80) alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] plt.bar(np.arange(80), data, color="#348ABD") plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed") plt.xlim(0, 80) plt.title("More example of artificial datasets") for i in range(1, 5): plt.subplot(4, 1, i) plot_artificial_sms_dataset() plt.show() if __name__ == '__main__': main()
Change of repo name. Update effected paths
Change of repo name. Update effected paths
Python
mit
noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit
import json import matplotlib import numpy as np import pymc as pm from matplotlib import pyplot as plt def main(): matplotlibrc_path = '/home/noel/repo/playground/matplotlibrc.json' matplotlib.rcParams.update(json.load(open(matplotlibrc_path))) tau = pm.rdiscrete_uniform(0, 80) print tau alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) print lambda_1, lambda_2 data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] def plot_artificial_sms_dataset(): tau = pm.rdiscrete_uniform(0, 80) alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] plt.bar(np.arange(80), data, color="#348ABD") plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed") plt.xlim(0, 80) plt.title("More example of artificial datasets") for i in range(1, 5): plt.subplot(4, 1, i) plot_artificial_sms_dataset() plt.show() if __name__ == '__main__': main() Change of repo name. Update effected paths
import json import matplotlib import numpy as np import pymc as pm from matplotlib import pyplot as plt def main(): tau = pm.rdiscrete_uniform(0, 80) print tau alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) print lambda_1, lambda_2 data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] def plot_artificial_sms_dataset(): tau = pm.rdiscrete_uniform(0, 80) alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] plt.bar(np.arange(80), data, color="#348ABD") plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed") plt.xlim(0, 80) plt.title("More example of artificial datasets") for i in range(1, 5): plt.subplot(4, 1, i) plot_artificial_sms_dataset() plt.show() if __name__ == '__main__': main()
<commit_before>import json import matplotlib import numpy as np import pymc as pm from matplotlib import pyplot as plt def main(): matplotlibrc_path = '/home/noel/repo/playground/matplotlibrc.json' matplotlib.rcParams.update(json.load(open(matplotlibrc_path))) tau = pm.rdiscrete_uniform(0, 80) print tau alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) print lambda_1, lambda_2 data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] def plot_artificial_sms_dataset(): tau = pm.rdiscrete_uniform(0, 80) alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] plt.bar(np.arange(80), data, color="#348ABD") plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed") plt.xlim(0, 80) plt.title("More example of artificial datasets") for i in range(1, 5): plt.subplot(4, 1, i) plot_artificial_sms_dataset() plt.show() if __name__ == '__main__': main() <commit_msg>Change of repo name. Update effected paths<commit_after>
import json import matplotlib import numpy as np import pymc as pm from matplotlib import pyplot as plt def main(): tau = pm.rdiscrete_uniform(0, 80) print tau alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) print lambda_1, lambda_2 data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] def plot_artificial_sms_dataset(): tau = pm.rdiscrete_uniform(0, 80) alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] plt.bar(np.arange(80), data, color="#348ABD") plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed") plt.xlim(0, 80) plt.title("More example of artificial datasets") for i in range(1, 5): plt.subplot(4, 1, i) plot_artificial_sms_dataset() plt.show() if __name__ == '__main__': main()
import json import matplotlib import numpy as np import pymc as pm from matplotlib import pyplot as plt def main(): matplotlibrc_path = '/home/noel/repo/playground/matplotlibrc.json' matplotlib.rcParams.update(json.load(open(matplotlibrc_path))) tau = pm.rdiscrete_uniform(0, 80) print tau alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) print lambda_1, lambda_2 data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] def plot_artificial_sms_dataset(): tau = pm.rdiscrete_uniform(0, 80) alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] plt.bar(np.arange(80), data, color="#348ABD") plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed") plt.xlim(0, 80) plt.title("More example of artificial datasets") for i in range(1, 5): plt.subplot(4, 1, i) plot_artificial_sms_dataset() plt.show() if __name__ == '__main__': main() Change of repo name. Update effected pathsimport json import matplotlib import numpy as np import pymc as pm from matplotlib import pyplot as plt def main(): tau = pm.rdiscrete_uniform(0, 80) print tau alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) print lambda_1, lambda_2 data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] def plot_artificial_sms_dataset(): tau = pm.rdiscrete_uniform(0, 80) alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] plt.bar(np.arange(80), data, color="#348ABD") plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed") plt.xlim(0, 80) plt.title("More example of artificial datasets") for i in range(1, 5): plt.subplot(4, 1, i) plot_artificial_sms_dataset() plt.show() if __name__ == '__main__': main()
<commit_before>import json import matplotlib import numpy as np import pymc as pm from matplotlib import pyplot as plt def main(): matplotlibrc_path = '/home/noel/repo/playground/matplotlibrc.json' matplotlib.rcParams.update(json.load(open(matplotlibrc_path))) tau = pm.rdiscrete_uniform(0, 80) print tau alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) print lambda_1, lambda_2 data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] def plot_artificial_sms_dataset(): tau = pm.rdiscrete_uniform(0, 80) alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] plt.bar(np.arange(80), data, color="#348ABD") plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed") plt.xlim(0, 80) plt.title("More example of artificial datasets") for i in range(1, 5): plt.subplot(4, 1, i) plot_artificial_sms_dataset() plt.show() if __name__ == '__main__': main() <commit_msg>Change of repo name. Update effected paths<commit_after>import json import matplotlib import numpy as np import pymc as pm from matplotlib import pyplot as plt def main(): tau = pm.rdiscrete_uniform(0, 80) print tau alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) print lambda_1, lambda_2 data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] def plot_artificial_sms_dataset(): tau = pm.rdiscrete_uniform(0, 80) alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] plt.bar(np.arange(80), data, color="#348ABD") plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed") plt.xlim(0, 80) plt.title("More example of artificial datasets") for i in range(1, 5): plt.subplot(4, 1, i) plot_artificial_sms_dataset() plt.show() if __name__ == '__main__': main()
7310fdd86cebd1c8b28d960f0211e350fbf07a62
handlers/login.py
handlers/login.py
from rorn.Box import LoginBox, ErrorBox, WarningBox, SuccessBox from rorn.Session import delay from User import User from Button import Button from utils import * @get('login') def login(handler, request): handler.title('Login') if handler.session['user']: print WarningBox('Logged In', 'You are already logged in as %s' % handler.session['user']) else: print LoginBox() @post('login') def loginPost(handler, request, p_username, p_password): handler.title('Login') user = User.load(username = p_username, password = User.crypt(p_username, p_password)) if user: handler.session['user'] = user delay(handler, SuccessBox("Login Complete", "Logged in as %s" % user)) redirect('/') else: delay(handler, ErrorBox("Login Failed", "Invalid username/password combination")) redirect('/') @get('logout') def logout(handler, request): print "<form method=\"post\" action=\"/logout\">" print Button('Logout', type = 'submit').negative() print "</form>" @post('logout') def logoutPost(handler, request): if handler.session['user']: del handler.session['user'] redirect('/') else: print ErrorBox("Logout Failed", "You are not logged in")
from rorn.Box import LoginBox, ErrorBox, WarningBox, SuccessBox from rorn.Session import delay from User import User from Button import Button from utils import * @get('login') def login(handler, request): handler.title('Login') if handler.session['user']: print WarningBox('Logged In', 'You are already logged in as %s' % handler.session['user']) else: print LoginBox() @post('login') def loginPost(handler, request, p_username, p_password): handler.title('Login') user = User.load(username = p_username, password = User.crypt(p_username, p_password)) if user: if user.resetkey: user.resetkey = None user.save() handler.session['user'] = user delay(handler, SuccessBox("Login Complete", "Logged in as %s" % user)) redirect('/') else: delay(handler, ErrorBox("Login Failed", "Invalid username/password combination")) redirect('/') @get('logout') def logout(handler, request): print "<form method=\"post\" action=\"/logout\">" print Button('Logout', type = 'submit').negative() print "</form>" @post('logout') def logoutPost(handler, request): if handler.session['user']: del handler.session['user'] redirect('/') else: print ErrorBox("Logout Failed", "You are not logged in")
Clear reset key on user activity
Clear reset key on user activity
Python
mit
mrozekma/Sprint,mrozekma/Sprint,mrozekma/Sprint
from rorn.Box import LoginBox, ErrorBox, WarningBox, SuccessBox from rorn.Session import delay from User import User from Button import Button from utils import * @get('login') def login(handler, request): handler.title('Login') if handler.session['user']: print WarningBox('Logged In', 'You are already logged in as %s' % handler.session['user']) else: print LoginBox() @post('login') def loginPost(handler, request, p_username, p_password): handler.title('Login') user = User.load(username = p_username, password = User.crypt(p_username, p_password)) if user: handler.session['user'] = user delay(handler, SuccessBox("Login Complete", "Logged in as %s" % user)) redirect('/') else: delay(handler, ErrorBox("Login Failed", "Invalid username/password combination")) redirect('/') @get('logout') def logout(handler, request): print "<form method=\"post\" action=\"/logout\">" print Button('Logout', type = 'submit').negative() print "</form>" @post('logout') def logoutPost(handler, request): if handler.session['user']: del handler.session['user'] redirect('/') else: print ErrorBox("Logout Failed", "You are not logged in") Clear reset key on user activity
from rorn.Box import LoginBox, ErrorBox, WarningBox, SuccessBox from rorn.Session import delay from User import User from Button import Button from utils import * @get('login') def login(handler, request): handler.title('Login') if handler.session['user']: print WarningBox('Logged In', 'You are already logged in as %s' % handler.session['user']) else: print LoginBox() @post('login') def loginPost(handler, request, p_username, p_password): handler.title('Login') user = User.load(username = p_username, password = User.crypt(p_username, p_password)) if user: if user.resetkey: user.resetkey = None user.save() handler.session['user'] = user delay(handler, SuccessBox("Login Complete", "Logged in as %s" % user)) redirect('/') else: delay(handler, ErrorBox("Login Failed", "Invalid username/password combination")) redirect('/') @get('logout') def logout(handler, request): print "<form method=\"post\" action=\"/logout\">" print Button('Logout', type = 'submit').negative() print "</form>" @post('logout') def logoutPost(handler, request): if handler.session['user']: del handler.session['user'] redirect('/') else: print ErrorBox("Logout Failed", "You are not logged in")
<commit_before>from rorn.Box import LoginBox, ErrorBox, WarningBox, SuccessBox from rorn.Session import delay from User import User from Button import Button from utils import * @get('login') def login(handler, request): handler.title('Login') if handler.session['user']: print WarningBox('Logged In', 'You are already logged in as %s' % handler.session['user']) else: print LoginBox() @post('login') def loginPost(handler, request, p_username, p_password): handler.title('Login') user = User.load(username = p_username, password = User.crypt(p_username, p_password)) if user: handler.session['user'] = user delay(handler, SuccessBox("Login Complete", "Logged in as %s" % user)) redirect('/') else: delay(handler, ErrorBox("Login Failed", "Invalid username/password combination")) redirect('/') @get('logout') def logout(handler, request): print "<form method=\"post\" action=\"/logout\">" print Button('Logout', type = 'submit').negative() print "</form>" @post('logout') def logoutPost(handler, request): if handler.session['user']: del handler.session['user'] redirect('/') else: print ErrorBox("Logout Failed", "You are not logged in") <commit_msg>Clear reset key on user activity<commit_after>
from rorn.Box import LoginBox, ErrorBox, WarningBox, SuccessBox from rorn.Session import delay from User import User from Button import Button from utils import * @get('login') def login(handler, request): handler.title('Login') if handler.session['user']: print WarningBox('Logged In', 'You are already logged in as %s' % handler.session['user']) else: print LoginBox() @post('login') def loginPost(handler, request, p_username, p_password): handler.title('Login') user = User.load(username = p_username, password = User.crypt(p_username, p_password)) if user: if user.resetkey: user.resetkey = None user.save() handler.session['user'] = user delay(handler, SuccessBox("Login Complete", "Logged in as %s" % user)) redirect('/') else: delay(handler, ErrorBox("Login Failed", "Invalid username/password combination")) redirect('/') @get('logout') def logout(handler, request): print "<form method=\"post\" action=\"/logout\">" print Button('Logout', type = 'submit').negative() print "</form>" @post('logout') def logoutPost(handler, request): if handler.session['user']: del handler.session['user'] redirect('/') else: print ErrorBox("Logout Failed", "You are not logged in")
from rorn.Box import LoginBox, ErrorBox, WarningBox, SuccessBox from rorn.Session import delay from User import User from Button import Button from utils import * @get('login') def login(handler, request): handler.title('Login') if handler.session['user']: print WarningBox('Logged In', 'You are already logged in as %s' % handler.session['user']) else: print LoginBox() @post('login') def loginPost(handler, request, p_username, p_password): handler.title('Login') user = User.load(username = p_username, password = User.crypt(p_username, p_password)) if user: handler.session['user'] = user delay(handler, SuccessBox("Login Complete", "Logged in as %s" % user)) redirect('/') else: delay(handler, ErrorBox("Login Failed", "Invalid username/password combination")) redirect('/') @get('logout') def logout(handler, request): print "<form method=\"post\" action=\"/logout\">" print Button('Logout', type = 'submit').negative() print "</form>" @post('logout') def logoutPost(handler, request): if handler.session['user']: del handler.session['user'] redirect('/') else: print ErrorBox("Logout Failed", "You are not logged in") Clear reset key on user activityfrom rorn.Box import LoginBox, ErrorBox, WarningBox, SuccessBox from rorn.Session import delay from User import User from Button import Button from utils import * @get('login') def login(handler, request): handler.title('Login') if handler.session['user']: print WarningBox('Logged In', 'You are already logged in as %s' % handler.session['user']) else: print LoginBox() @post('login') def loginPost(handler, request, p_username, p_password): handler.title('Login') user = User.load(username = p_username, password = User.crypt(p_username, p_password)) if user: if user.resetkey: user.resetkey = None user.save() handler.session['user'] = user delay(handler, SuccessBox("Login Complete", "Logged in as %s" % user)) redirect('/') else: delay(handler, ErrorBox("Login Failed", "Invalid username/password combination")) redirect('/') @get('logout') def logout(handler, request): print "<form method=\"post\" action=\"/logout\">" print Button('Logout', type = 'submit').negative() print "</form>" @post('logout') def logoutPost(handler, request): if handler.session['user']: del handler.session['user'] redirect('/') else: print ErrorBox("Logout Failed", "You are not logged in")
<commit_before>from rorn.Box import LoginBox, ErrorBox, WarningBox, SuccessBox from rorn.Session import delay from User import User from Button import Button from utils import * @get('login') def login(handler, request): handler.title('Login') if handler.session['user']: print WarningBox('Logged In', 'You are already logged in as %s' % handler.session['user']) else: print LoginBox() @post('login') def loginPost(handler, request, p_username, p_password): handler.title('Login') user = User.load(username = p_username, password = User.crypt(p_username, p_password)) if user: handler.session['user'] = user delay(handler, SuccessBox("Login Complete", "Logged in as %s" % user)) redirect('/') else: delay(handler, ErrorBox("Login Failed", "Invalid username/password combination")) redirect('/') @get('logout') def logout(handler, request): print "<form method=\"post\" action=\"/logout\">" print Button('Logout', type = 'submit').negative() print "</form>" @post('logout') def logoutPost(handler, request): if handler.session['user']: del handler.session['user'] redirect('/') else: print ErrorBox("Logout Failed", "You are not logged in") <commit_msg>Clear reset key on user activity<commit_after>from rorn.Box import LoginBox, ErrorBox, WarningBox, SuccessBox from rorn.Session import delay from User import User from Button import Button from utils import * @get('login') def login(handler, request): handler.title('Login') if handler.session['user']: print WarningBox('Logged In', 'You are already logged in as %s' % handler.session['user']) else: print LoginBox() @post('login') def loginPost(handler, request, p_username, p_password): handler.title('Login') user = User.load(username = p_username, password = User.crypt(p_username, p_password)) if user: if user.resetkey: user.resetkey = None user.save() handler.session['user'] = user delay(handler, SuccessBox("Login Complete", "Logged in as %s" % user)) redirect('/') else: delay(handler, ErrorBox("Login Failed", "Invalid username/password combination")) redirect('/') @get('logout') def logout(handler, request): print "<form method=\"post\" action=\"/logout\">" print Button('Logout', type = 'submit').negative() print "</form>" @post('logout') def logoutPost(handler, request): if handler.session['user']: del handler.session['user'] redirect('/') else: print ErrorBox("Logout Failed", "You are not logged in")
018eab65881a2279efca88e1448dba0708a4dfe1
django_excel_to_model/management/commands/model_create_utils/django_tables2_utils.py
django_excel_to_model/management/commands/model_create_utils/django_tables2_utils.py
from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}} ) table_attributes = {"Meta": table_meta_class} table_data = {} for data_key in data_dict.keys(): attr_name = c.refine_attr_name(data_key) table_attributes[attr_name] = tables.Column(verbose_name=data_key) table_data[attr_name] = data_dict[data_key] item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes) return item_table_class([table_data])
from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}, "orderable": False, }) table_attributes = {"Meta": table_meta_class} table_data = {} for data_key in data_dict.keys(): attr_name = c.refine_attr_name(data_key) table_attributes[attr_name] = tables.Column(verbose_name=data_key) table_data[attr_name] = data_dict[data_key] item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes) return item_table_class([table_data])
Remove sort function by default for table generated from dict.
Remove sort function by default for table generated from dict.
Python
bsd-3-clause
weijia/django-excel-to-model,weijia/django-excel-to-model
from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}} ) table_attributes = {"Meta": table_meta_class} table_data = {} for data_key in data_dict.keys(): attr_name = c.refine_attr_name(data_key) table_attributes[attr_name] = tables.Column(verbose_name=data_key) table_data[attr_name] = data_dict[data_key] item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes) return item_table_class([table_data]) Remove sort function by default for table generated from dict.
from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}, "orderable": False, }) table_attributes = {"Meta": table_meta_class} table_data = {} for data_key in data_dict.keys(): attr_name = c.refine_attr_name(data_key) table_attributes[attr_name] = tables.Column(verbose_name=data_key) table_data[attr_name] = data_dict[data_key] item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes) return item_table_class([table_data])
<commit_before>from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}} ) table_attributes = {"Meta": table_meta_class} table_data = {} for data_key in data_dict.keys(): attr_name = c.refine_attr_name(data_key) table_attributes[attr_name] = tables.Column(verbose_name=data_key) table_data[attr_name] = data_dict[data_key] item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes) return item_table_class([table_data]) <commit_msg>Remove sort function by default for table generated from dict.<commit_after>
from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}, "orderable": False, }) table_attributes = {"Meta": table_meta_class} table_data = {} for data_key in data_dict.keys(): attr_name = c.refine_attr_name(data_key) table_attributes[attr_name] = tables.Column(verbose_name=data_key) table_data[attr_name] = data_dict[data_key] item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes) return item_table_class([table_data])
from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}} ) table_attributes = {"Meta": table_meta_class} table_data = {} for data_key in data_dict.keys(): attr_name = c.refine_attr_name(data_key) table_attributes[attr_name] = tables.Column(verbose_name=data_key) table_data[attr_name] = data_dict[data_key] item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes) return item_table_class([table_data]) Remove sort function by default for table generated from dict.from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}, "orderable": False, }) table_attributes = {"Meta": table_meta_class} table_data = {} for data_key in data_dict.keys(): attr_name = c.refine_attr_name(data_key) table_attributes[attr_name] = tables.Column(verbose_name=data_key) table_data[attr_name] = data_dict[data_key] item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes) return item_table_class([table_data])
<commit_before>from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}} ) table_attributes = {"Meta": table_meta_class} table_data = {} for data_key in data_dict.keys(): attr_name = c.refine_attr_name(data_key) table_attributes[attr_name] = tables.Column(verbose_name=data_key) table_data[attr_name] = data_dict[data_key] item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes) return item_table_class([table_data]) <commit_msg>Remove sort function by default for table generated from dict.<commit_after>from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}, "orderable": False, }) table_attributes = {"Meta": table_meta_class} table_data = {} for data_key in data_dict.keys(): attr_name = c.refine_attr_name(data_key) table_attributes[attr_name] = tables.Column(verbose_name=data_key) table_data[attr_name] = data_dict[data_key] item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes) return item_table_class([table_data])