commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
c43820a2e26dd4f87c36b986a9a0af80b409f659
sentence_extractor.py
sentence_extractor.py
import textract import sys import os import re import random ################################### # Extracts text from a pdf file and # selects one sentence, which it # then prints. # # Created by Fredrik Omstedt. ################################### # Extracts texts from pdf files. If given a directory, the # program will return texts from all pdf files in that directory. def extractTexts(): file = sys.argv[1] texts = [] if os.path.isdir(file): for f in os.listdir(file): if re.match(r'^.*\.pdf$', f): texts.append(textract.process(file + "/" + f)) else: texts.append(textract.process(file)) return texts # Chooses one sentence randomly from each of the given texts. def selectSentences(texts): chosen_sentences = [] for text in texts: sentence_structure = re.compile(r'([A-Z][^\.!?]*[\.!?])', re.M) sentences = sentence_structure.findall(text) chosen_sentences.append( sentences[random.randint(0, len(sentences)-1)].replace("\n", " ") ) return chosen_sentences def main(): texts = extractTexts() sentences = selectSentences(texts) for sentence in sentences: print(sentence) print("\n") if __name__ == '__main__': main()
import textract import sys import os import re import random ################################### # Extracts text from a pdf file and # selects one sentence, which it # then prints. # # Created by Fredrik Omstedt. ################################### # Extracts texts from pdf files. If given a directory, the # program will return texts from all pdf files in that directory. def extractTexts(): file = sys.argv[1] texts = [] if os.path.isdir(file): for f in os.listdir(file): if re.match(r'^.*\.pdf$', f): texts.append(textract.process(file + "/" + f)) else: texts.append(textract.process(file)) return texts # Chooses one sentence randomly from each of the given texts. def selectSentences(texts): chosen_sentences = [] for text in texts: sentence_structure = re.compile(r'([A-Z\xc4\xc5\xd6][^\.!?]*[\.!?])', re.M) sentences = sentence_structure.findall(text) chosen_sentences.append( sentences[random.randint(0, len(sentences)-1)].replace("\n", " ") ) return chosen_sentences def main(): texts = extractTexts() sentences = selectSentences(texts) for sentence in sentences: print(sentence) print("\n") if __name__ == '__main__': main()
Update regex to match sentences starting with ÅÄÖ
Update regex to match sentences starting with ÅÄÖ
Python
mit
Xaril/sentence-extractor,Xaril/sentence-extractor
--- +++ @@ -29,7 +29,7 @@ def selectSentences(texts): chosen_sentences = [] for text in texts: - sentence_structure = re.compile(r'([A-Z][^\.!?]*[\.!?])', re.M) + sentence_structure = re.compile(r'([A-Z\xc4\xc5\xd6][^\.!?]*[\.!?])', re.M) sentences = sentence_structure.findall(text) chosen_sentences.append( sentences[random.randint(0, len(sentences)-1)].replace("\n", " ")
b2f6a318434f33f39c9d3bc6e738b6b0eba508c9
tensorflow_cloud/__init__.py
tensorflow_cloud/__init__.py
# Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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 __future__ import absolute_import from __future__ import division from __future__ import print_function __version__ = "0.1.3" from .machine_config import AcceleratorType from .machine_config import COMMON_MACHINE_CONFIGS from .machine_config import MachineConfig from .run import run from .remote import remote
# Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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 __future__ import absolute_import from __future__ import division from __future__ import print_function __version__ = "0.1.3" from .machine_config import AcceleratorType from .machine_config import COMMON_MACHINE_CONFIGS from .machine_config import MachineConfig from .run import run from .run import remote
Allow user access to remote flag
Allow user access to remote flag
Python
apache-2.0
tensorflow/cloud,tensorflow/cloud
--- +++ @@ -22,4 +22,4 @@ from .machine_config import COMMON_MACHINE_CONFIGS from .machine_config import MachineConfig from .run import run -from .remote import remote +from .run import remote
c8cc1f8e0e9b6d7dfb29ff9aef04bf2b5867cceb
genomediff/records.py
genomediff/records.py
class Metadata(object): def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "Metadata({}, {})".format(repr(self.name), repr(self.value)) def __eq__(self, other): return self.__dict__ == other.__dict__ class Record(object): def __init__(self, type, id, document=None, parent_ids=None, **extra): self.document = document self.type = type self.id = id self.parent_ids = parent_ids self._extra = extra @property def parents(self): if not self.parent_ids is None: return [self.document[pid] for pid in self.parent_ids] else: return [] def __getattr__(self, item): return self._extra[item] def __repr__(self): return "Record('{}', {}, {}, {})".format(self.type, self.id, self.parent_ids, ', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items())) def __eq__(self, other): return self.__dict__ == other.__dict__
class Metadata(object): def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "Metadata({}, {})".format(repr(self.name), repr(self.value)) def __eq__(self, other): return self.__dict__ == other.__dict__ class Record(object): def __init__(self, type, id, document=None, parent_ids=None, **attributes): self.document = document self.type = type self.id = id self.parent_ids = parent_ids self.attributes = attributes @property def parents(self): if not self.parent_ids is None: return [self.document[pid] for pid in self.parent_ids] else: return [] def __getattr__(self, item): try: return self.attributes[item] except KeyError: raise AttributeError def __repr__(self): return "Record('{}', {}, {}, {})".format(self.type, self.id, self.parent_ids, ', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items())) def __eq__(self, other): return self.__dict__ == other.__dict__
Raise AttributeError if key does not exist when trying to get it from a Record
Raise AttributeError if key does not exist when trying to get it from a Record
Python
mit
biosustain/genomediff-python
--- +++ @@ -11,12 +11,12 @@ class Record(object): - def __init__(self, type, id, document=None, parent_ids=None, **extra): + def __init__(self, type, id, document=None, parent_ids=None, **attributes): self.document = document self.type = type self.id = id self.parent_ids = parent_ids - self._extra = extra + self.attributes = attributes @property def parents(self): @@ -26,13 +26,18 @@ return [] def __getattr__(self, item): - return self._extra[item] + try: + return self.attributes[item] + except KeyError: + raise AttributeError - def __repr__(self): - return "Record('{}', {}, {}, {})".format(self.type, - self.id, - self.parent_ids, - ', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items())) - def __eq__(self, other): - return self.__dict__ == other.__dict__ +def __repr__(self): + return "Record('{}', {}, {}, {})".format(self.type, + self.id, + self.parent_ids, + ', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items())) + + +def __eq__(self, other): + return self.__dict__ == other.__dict__
9aace6d89642e5025692b25e2c6253544ed580a6
social_auth/models.py
social_auth/models.py
"""Social auth models""" from django.db import models from django.contrib.auth.models import User class UserSocialAuth(models.Model): """Social Auth association model""" user = models.ForeignKey(User, related_name='social_auth') provider = models.CharField(max_length=32) uid = models.TextField() class Meta: """Meta data""" unique_together = ('provider', 'uid') class Nonce(models.Model): """One use numbers""" server_url = models.TextField() timestamp = models.IntegerField() salt = models.CharField(max_length=40) class Association(models.Model): """OpenId account association""" server_url = models.TextField(max_length=2047) handle = models.CharField(max_length=255) secret = models.TextField(max_length=255) # Stored base64 encoded issued = models.IntegerField() lifetime = models.IntegerField() assoc_type = models.TextField(max_length=64)
"""Social auth models""" from django.db import models from django.contrib.auth.models import User class UserSocialAuth(models.Model): """Social Auth association model""" user = models.ForeignKey(User, related_name='social_auth') provider = models.CharField(max_length=32) uid = models.TextField() class Meta: """Meta data""" unique_together = ('provider', 'uid') class Nonce(models.Model): """One use numbers""" server_url = models.TextField() timestamp = models.IntegerField() salt = models.CharField(max_length=40) class Association(models.Model): """OpenId account association""" server_url = models.TextField() handle = models.CharField(max_length=255) secret = models.CharField(max_length=255) # Stored base64 encoded issued = models.IntegerField() lifetime = models.IntegerField() assoc_type = models.CharField(max_length=64)
Remove max_length from TextFields and replace short text fields with CharFields
Remove max_length from TextFields and replace short text fields with CharFields
Python
bsd-3-clause
michael-borisov/django-social-auth,krvss/django-social-auth,thesealion/django-social-auth,lovehhf/django-social-auth,sk7/django-social-auth,dongguangming/django-social-auth,czpython/django-social-auth,beswarm/django-social-auth,adw0rd/django-social-auth,MjAbuz/django-social-auth,VishvajitP/django-social-auth,MjAbuz/django-social-auth,brianmckinneyrocks/django-social-auth,beswarm/django-social-auth,thesealion/django-social-auth,mayankcu/Django-social,vxvinh1511/django-social-auth,vuchau/django-social-auth,1st/django-social-auth,WW-Digital/django-social-auth,omab/django-social-auth,omab/django-social-auth,caktus/django-social-auth,vuchau/django-social-auth,limdauto/django-social-auth,antoviaque/django-social-auth-norel,vxvinh1511/django-social-auth,qas612820704/django-social-auth,gustavoam/django-social-auth,michael-borisov/django-social-auth,dongguangming/django-social-auth,limdauto/django-social-auth,duoduo369/django-social-auth,caktus/django-social-auth,gustavoam/django-social-auth,VishvajitP/django-social-auth,qas612820704/django-social-auth,getsentry/django-social-auth,lovehhf/django-social-auth,brianmckinneyrocks/django-social-auth
--- +++ @@ -23,9 +23,9 @@ class Association(models.Model): """OpenId account association""" - server_url = models.TextField(max_length=2047) + server_url = models.TextField() handle = models.CharField(max_length=255) - secret = models.TextField(max_length=255) # Stored base64 encoded + secret = models.CharField(max_length=255) # Stored base64 encoded issued = models.IntegerField() lifetime = models.IntegerField() - assoc_type = models.TextField(max_length=64) + assoc_type = models.CharField(max_length=64)
eca73e0c57042593f7e65446e26e63790c5cf2aa
notes/admin.py
notes/admin.py
# # Copyright (c) 2009 Brad Taylor <[email protected]> # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from snowy.accounts.models import UserProfile from snowy.notes.models import Note, NoteTag from reversion.admin import VersionAdmin from django.contrib import admin class NoteAdmin(VersionAdmin): list_display = ('created', 'author', 'title') search_fields = ['content', 'title'] prepopulated_fields = {'slug': ('title',)} admin.site.register(Note, NoteAdmin) admin.site.register(NoteTag) admin.site.register(UserProfile)
# # Copyright (c) 2009 Brad Taylor <[email protected]> # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from snowy.accounts.models import UserProfile from snowy.notes.models import Note, NoteTag #from reversion.admin import VersionAdmin from django.contrib import admin #class NoteAdmin(VersionAdmin): class NoteAdmin(admin.ModelAdmin): list_display = ('created', 'author', 'title') search_fields = ['content', 'title'] prepopulated_fields = {'slug': ('title',)} admin.site.register(Note, NoteAdmin) admin.site.register(NoteTag) admin.site.register(UserProfile)
Complete removal of reversion usage
Complete removal of reversion usage
Python
agpl-3.0
leonhandreke/snowy,NoUsername/PrivateNotesExperimental,jaredjennings/snowy,GNOME/snowy,sandyarmstrong/snowy,syskill/snowy,syskill/snowy,NoUsername/PrivateNotesExperimental,sandyarmstrong/snowy,jaredjennings/snowy,jaredjennings/snowy,widox/snowy,jaredjennings/snowy,nekohayo/snowy,nekohayo/snowy,widox/snowy,GNOME/snowy,leonhandreke/snowy
--- +++ @@ -17,10 +17,11 @@ from snowy.accounts.models import UserProfile from snowy.notes.models import Note, NoteTag -from reversion.admin import VersionAdmin +#from reversion.admin import VersionAdmin from django.contrib import admin -class NoteAdmin(VersionAdmin): +#class NoteAdmin(VersionAdmin): +class NoteAdmin(admin.ModelAdmin): list_display = ('created', 'author', 'title') search_fields = ['content', 'title'] prepopulated_fields = {'slug': ('title',)}
630ba21f3b08dcd2685297b057cbee4b6abee6f7
us_ignite/sections/models.py
us_ignite/sections/models.py
from django.db import models class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) image = models.ImageField(upload_to="sponsor") order = models.IntegerField(default=0) class Meta: ordering = ('order', ) def __unicode__(self): return self.name
from django.db import models class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) image = models.ImageField( upload_to="sponsor", help_text='This image is not post processed. ' 'Please make sure it has the right design specs.') order = models.IntegerField(default=0) class Meta: ordering = ('order', ) def __unicode__(self): return self.name
Add help text describing the image field functionality.
Add help text describing the image field functionality.
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
--- +++ @@ -4,7 +4,9 @@ class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) - image = models.ImageField(upload_to="sponsor") + image = models.ImageField( + upload_to="sponsor", help_text='This image is not post processed. ' + 'Please make sure it has the right design specs.') order = models.IntegerField(default=0) class Meta:
5edeb2e484eae8ac81898f92369f06dfed78908c
tests/test_KociembaSolver.py
tests/test_KociembaSolver.py
from src.Move import Move from src.NaiveCube import NaiveCube from src.Cubie import Cube from src.Solver import Kociemba import timeout_decorator import unittest class TestKociembaSolver(unittest.TestCase): @timeout_decorator.timeout(300) def _test_solution(self, c): solver = Kociemba.KociembaSolver(c) return solver.solution() def test_solution(self): for i in range(10): c = Cube() cr = Cube() c.shuffle(i) solution = self._test_solution(c) for s in solution: c.move(s) # Align faces while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']: c.move(Move('Y')) for cubie in cr.cubies: for facing in cr.cubies[cubie].facings: self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing]) def test_timeout(self): c = Cube() nc = NaiveCube() nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy") c.from_naive_cube(nc) with self.assertRaises(Kociemba.Search.TimeoutError): solver = Kociemba.KociembaSolver(c) solver.solution(timeOut = 1)
from src.Move import Move from src.NaiveCube import NaiveCube from src.Cubie import Cube from src.Solver import Kociemba import timeout_decorator import unittest class TestKociembaSolver(unittest.TestCase): @timeout_decorator.timeout(300) def _test_solution(self, c): solver = Kociemba.KociembaSolver(c) return solver.solution() def test_solution(self): for i in range(100): c = Cube() cr = Cube() c.shuffle(i) solution = self._test_solution(c) for s in solution: c.move(s) # Align faces while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']: c.move(Move('Y')) for cubie in cr.cubies: for facing in cr.cubies[cubie].facings: self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing]) def test_timeout(self): c = Cube() nc = NaiveCube() nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy") c.from_naive_cube(nc) with self.assertRaises(Kociemba.Search.TimeoutError): solver = Kociemba.KociembaSolver(c) solver.solution(timeOut = 1)
Increase number of Kociemba test iterations to 100
Increase number of Kociemba test iterations to 100
Python
mit
Wiston999/python-rubik
--- +++ @@ -13,7 +13,7 @@ return solver.solution() def test_solution(self): - for i in range(10): + for i in range(100): c = Cube() cr = Cube() c.shuffle(i)
850d5189d3159f7cab6c509a2dd58c9f427c0bfc
examples/python/find_events.py
examples/python/find_events.py
from gi.repository import Zeitgeist log = Zeitgeist.Log.get_default() def callback (x): print x log.get_events([x for x in xrange(100)], None, callback, None)
from gi.repository import Zeitgeist, Gtk log = Zeitgeist.Log.get_default() def callback (x): print x log.get_events([x for x in xrange(100)], None, callback, None) Gtk.main()
Add loop to the python example
Add loop to the python example
Python
lgpl-2.1
freedesktop-unofficial-mirror/zeitgeist__zeitgeist,freedesktop-unofficial-mirror/zeitgeist__zeitgeist,freedesktop-unofficial-mirror/zeitgeist__zeitgeist,freedesktop-unofficial-mirror/zeitgeist__zeitgeist,freedesktop-unofficial-mirror/zeitgeist__zeitgeist
--- +++ @@ -1,7 +1,8 @@ -from gi.repository import Zeitgeist +from gi.repository import Zeitgeist, Gtk log = Zeitgeist.Log.get_default() def callback (x): print x -log.get_events([x for x in xrange(100)], None, callback, None) +log.get_events([x for x in xrange(100)], None, callback, None) +Gtk.main()
79a33e6e0de55dcfd602a58ef5adfabe7895915e
mysite/urls.py
mysite/urls.py
from django.conf.urls import include, url from django.conf import settings from django.contrib import admin from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls from wagtail.wagtailcore import urls as wagtail_urls urlpatterns = [ url(r'^django-admin/', include(admin.site.urls)), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', 'search.views.search', name='search'), url(r'', include(wagtail_urls)), ] if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView # Serve static and media files from development server urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf.urls import include, url from django.conf import settings from django.contrib import admin from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls from wagtail.wagtailcore import urls as wagtail_urls from wagtail.wagtailimages import urls as wagtailimages_urls urlpatterns = [ url(r'^django-admin/', include(admin.site.urls)), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', 'search.views.search', name='search'), url(r'', include(wagtail_urls)), url(r'^images/', include(wagtailimages_urls)), ] if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView # Serve static and media files from development server urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Add an entry in URLs configuration for image support.
Add an entry in URLs configuration for image support.
Python
mit
yostan/mysite,yostan/mysite
--- +++ @@ -5,6 +5,8 @@ from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls from wagtail.wagtailcore import urls as wagtail_urls + +from wagtail.wagtailimages import urls as wagtailimages_urls urlpatterns = [ @@ -16,6 +18,8 @@ url(r'^search/$', 'search.views.search', name='search'), url(r'', include(wagtail_urls)), + + url(r'^images/', include(wagtailimages_urls)), ]
9cfd402c8f95c016953eda752e1bd91302d6c8c0
translations/lantmateriet.py
translations/lantmateriet.py
def filterTags(attrs): res = {} if 'NAMN' in attrs: res['name'] = attrs['NAMN'] if 'TATNR' in attrs: res['ref:se:scb'] = attrs['TATNR'] if attrs.get('BEF') is not None: bef = int(attrs.get('BEF')) # This is an approximation based on http://wiki.openstreetmap.org/wiki/Key:place # and the observed values of nodes in OpenStreetMap itself for cities and towns # around Sweden. # This seems to be around where OSM sets city status for Sweden if bef >= 30000: res['place'] = 'city' elif bef >= 6000: res['place'] = 'town' elif bef >= 200: res['place'] = 'village' return res
def filterTags(attrs): res = {} if 'NAMN' in attrs: res['name'] = attrs['NAMN'] if 'TATNR' in attrs: res['ref:se:scb'] = attrs['TATNR'] if attrs.get('BEF') is not None: bef = int(attrs.get('BEF')) # This is an approximation based on http://wiki.openstreetmap.org/wiki/Key:place # and the observed values of nodes in OpenStreetMap itself for cities and towns # around Sweden. # This seems to be around where OSM sets city status for Sweden if bef >= 30000: res['place'] = 'city' elif bef >= 6000: res['place'] = 'town' elif bef >= 200: res['place'] = 'village' res['population'] = str(bef) return res
Add population to the tags
LM: Add population to the tags
Python
bsd-3-clause
andpe/swegov-to-osm
--- +++ @@ -23,4 +23,6 @@ elif bef >= 200: res['place'] = 'village' + res['population'] = str(bef) + return res
d13c674a7286f1af9cd13babe2cb5c429b5b3bfa
scripts/update_guide_stats.py
scripts/update_guide_stats.py
#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst from mica.stats import update_guide_stats update_guide_stats.main() import os table_file = mica.stats.guide_stats.TABLE_FILE file_stat = os.stat(table_file) if file_stat.st_size > 200e6: print(""" Warning: {tfile} is larger than 200MB and may need Warning: to be manually repacked (i.e.): Warning: Warning: ptrepack --chunkshape=auto --propindexes --keep-source-filters {tfile} compressed.h5 Warning: cp compressed.h5 {tfile} """.format(tfile=table_file))
#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst import os import argparse from mica.stats import update_guide_stats import mica.stats.guide_stats # Cheat and pass options directly. Needs entrypoint scripts opt = argparse.Namespace(datafile=mica.stats.guide_stats.TABLE_FILE, obsid=None, check_missing=False, start=None, stop=None) update_guide_stats.update(opt) table_file = mica.stats.guide_stats.TABLE_FILE file_stat = os.stat(table_file) if file_stat.st_size > 200e6: print(""" Warning: {tfile} is larger than 200MB and may need Warning: to be manually repacked (i.e.): Warning: Warning: ptrepack --chunkshape=auto --propindexes --keep-source-filters {tfile} compressed.h5 Warning: cp compressed.h5 {tfile} """.format(tfile=table_file))
Update guide stat script to pass datafile
Update guide stat script to pass datafile
Python
bsd-3-clause
sot/mica,sot/mica
--- +++ @@ -1,10 +1,17 @@ #!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst +import os +import argparse from mica.stats import update_guide_stats -update_guide_stats.main() +import mica.stats.guide_stats -import os +# Cheat and pass options directly. Needs entrypoint scripts +opt = argparse.Namespace(datafile=mica.stats.guide_stats.TABLE_FILE, + obsid=None, check_missing=False, start=None, stop=None) +update_guide_stats.update(opt) + + table_file = mica.stats.guide_stats.TABLE_FILE file_stat = os.stat(table_file) if file_stat.st_size > 200e6:
7f6bb0706b24f8664937e9d991ffe01b2d62279e
varify/context_processors.py
varify/context_processors.py
import os import logging from django.conf import settings log = logging.getLogger(__name__) def static(request): "Shorthand static URLs. In debug mode, the JavaScript is not minified." static_url = settings.STATIC_URL prefix = 'src' if settings.DEBUG else 'min' return { 'CSS_URL': os.path.join(static_url, 'stylesheets/css'), 'IMAGES_URL': os.path.join(static_url, 'images'), 'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix), } def alamut(request): return { 'ALAMUT_URL': settings.ALAMUT_URL, } def sentry(request): SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN', None) if SENTRY_PUBLIC_DSN: return { 'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN } log.warning('SENTRY_PUBLIC_DSN not defined in settings.')
import os import logging from django.conf import settings log = logging.getLogger(__name__) def static(request): "Shorthand static URLs. In debug mode, the JavaScript is not minified." static_url = settings.STATIC_URL prefix = 'src' if settings.DEBUG else 'min' return { 'CSS_URL': os.path.join(static_url, 'stylesheets/css'), 'IMAGES_URL': os.path.join(static_url, 'images'), 'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix), } def alamut(request): return { 'ALAMUT_URL': settings.ALAMUT_URL, } def sentry(request): SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN', None) if not SENTRY_PUBLIC_DSN: log.warning('SENTRY_PUBLIC_DSN not defined in settings.') return { 'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN }
Return dict object from sentry processor regardless of setting existence
Return dict object from sentry processor regardless of setting existence
Python
bsd-2-clause
chop-dbhi/varify,chop-dbhi/varify,chop-dbhi/varify,chop-dbhi/varify
--- +++ @@ -25,9 +25,9 @@ def sentry(request): SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN', None) - if SENTRY_PUBLIC_DSN: - return { - 'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN - } + if not SENTRY_PUBLIC_DSN: + log.warning('SENTRY_PUBLIC_DSN not defined in settings.') - log.warning('SENTRY_PUBLIC_DSN not defined in settings.') + return { + 'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN + }
f624ca7894037361c441d4c5834e4a1fe66c991d
ipaqe_provision_hosts/utils.py
ipaqe_provision_hosts/utils.py
# Author: Milan Kubik import logging import yaml from ipaqe_provision_hosts.errors import IPAQEProvisionerError log = logging.getLogger(__name__) class ConfigLoadError(IPAQEProvisionerError): pass def load_yaml(path): try: with open(path, mode='r') as f: return yaml.load(f) except OSError: log.error('Error reading file %s', path) raise ConfigLoadError except yaml.YAMLError as e: log.error("YAML error:\n%s", e) raise ConfigLoadError def load_config(path=None): """Load configuration The configuration is loaded from the given path or from the default path in /etc. """ etc_path = '/etc/ipaqe-provision-hosts/config.yaml' path = path or etc_path log.info("Loading configuration file %s", path) return load_yaml(path) def load_topology(path): """Load the topology file""" log.info("Loading topology file %s", path) return load_yaml(path)
# Author: Milan Kubik import logging import yaml from ipaqe_provision_hosts.errors import IPAQEProvisionerError log = logging.getLogger(__name__) class ConfigLoadError(IPAQEProvisionerError): pass def load_yaml(path): try: with open(path, mode='r') as f: return yaml.load(f) except OSError: log.error('Error reading file %s', path) raise ConfigLoadError except yaml.YAMLError as e: log.error("YAML error:\n%s", e) raise ConfigLoadError def load_config(path=None): """Load configuration The configuration is loaded from the given path or from the default path in /etc. """ etc_path = '/etc/ipaqe-provision-hosts/config.yaml' path = path or etc_path log.info("Loading configuration file %s", path) return load_yaml(path) def load_topology(path): """Load the topology file""" log.info("Loading topology file %s", path) return load_yaml(path) def get_os_version(): """Get the OS version from /etc/os-release The function returns pair (ID, VERSION_ID). If the OS does not have VERSION_ID, it will be None """ try: log.debug('Reading os-release') with open('/ect/os-release') as f: os_release = dict([ line.strip().split('=') for line in f.readlines() if line ]) return (os_release['ID'], os_release.get('VERSION_ID')) except IOError: log.error('The file /etc/os-release was not found.') raise IPAQEProvisionerError except KeyError: log.error("The key ID of os-release was not found.") raise IPAQEProvisionerError
Add simple parser for os-release to get OS version
Add simple parser for os-release to get OS version
Python
mit
apophys/ipaqe-provision-hosts
--- +++ @@ -43,3 +43,26 @@ """Load the topology file""" log.info("Loading topology file %s", path) return load_yaml(path) + + +def get_os_version(): + """Get the OS version from /etc/os-release + + The function returns pair (ID, VERSION_ID). + If the OS does not have VERSION_ID, it will be None + """ + + try: + log.debug('Reading os-release') + with open('/ect/os-release') as f: + os_release = dict([ + line.strip().split('=') for line in f.readlines() if line + ]) + + return (os_release['ID'], os_release.get('VERSION_ID')) + except IOError: + log.error('The file /etc/os-release was not found.') + raise IPAQEProvisionerError + except KeyError: + log.error("The key ID of os-release was not found.") + raise IPAQEProvisionerError
5914b9a4d1d086f1a92309c0895aa7dd11761776
conf_site/accounts/tests/test_registration.py
conf_site/accounts/tests/test_registration.py
from factory import Faker, fuzzy from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse class UserRegistrationTestCase(TestCase): def test_registration_view(self): """Verify that user registration view loads properly.""" response = self.client.get(reverse("account_signup")) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "account/signup.html") def test_user_registration(self): """Ensure that user registration works properly.""" EMAIL = Faker("email").generate() PASSWORD = fuzzy.FuzzyText(length=16) test_user_data = { "password1": PASSWORD, "password2": PASSWORD, "email": EMAIL, "email2": EMAIL, } # Verify that POSTing user data to the registration view # succeeds / returns the right HTTP status code. response = self.client.post( reverse("account_signup"), test_user_data) # Successful form submission will cause the HTTP status code # to be "302 Found", not "200 OK". self.assertEqual(response.status_code, 302) # Verify that a User has been successfully created. user_model = get_user_model() user_model.objects.get(email=EMAIL)
from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from factory import fuzzy from faker import Faker class UserRegistrationTestCase(TestCase): def test_registration_view(self): """Verify that user registration view loads properly.""" response = self.client.get(reverse("account_signup")) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "account/signup.html") def test_user_registration(self): """Ensure that user registration works properly.""" EMAIL = Faker().email() PASSWORD = fuzzy.FuzzyText(length=16) test_user_data = { "password1": PASSWORD, "password2": PASSWORD, "email": EMAIL, "email2": EMAIL, } # Verify that POSTing user data to the registration view # succeeds / returns the right HTTP status code. response = self.client.post( reverse("account_signup"), test_user_data) # Successful form submission will cause the HTTP status code # to be "302 Found", not "200 OK". self.assertEqual(response.status_code, 302) # Verify that a User has been successfully created. user_model = get_user_model() user_model.objects.get(email=EMAIL)
Change imports in user registration test.
Change imports in user registration test.
Python
mit
pydata/conf_site,pydata/conf_site,pydata/conf_site
--- +++ @@ -1,8 +1,9 @@ -from factory import Faker, fuzzy - from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse + +from factory import fuzzy +from faker import Faker class UserRegistrationTestCase(TestCase): @@ -14,7 +15,7 @@ def test_user_registration(self): """Ensure that user registration works properly.""" - EMAIL = Faker("email").generate() + EMAIL = Faker().email() PASSWORD = fuzzy.FuzzyText(length=16) test_user_data = { "password1": PASSWORD,
9a7100aaf0207fe93b28d7e473a4b5c1cd6061fe
vumi/application/__init__.py
vumi/application/__init__.py
"""The vumi.application API.""" __all__ = ["ApplicationWorker", "SessionManager"] from vumi.application.base import ApplicationWorker from vumi.application.session import SessionManager
"""The vumi.application API.""" __all__ = ["ApplicationWorker", "SessionManager", "TagpoolManager"] from vumi.application.base import ApplicationWorker from vumi.application.session import SessionManager from vumi.application.tagpool import TagpoolManager
Add TagpoolManager to vumi.application API.
Add TagpoolManager to vumi.application API.
Python
bsd-3-clause
vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,TouK/vumi,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,harrissoerja/vumi
--- +++ @@ -1,6 +1,7 @@ """The vumi.application API.""" -__all__ = ["ApplicationWorker", "SessionManager"] +__all__ = ["ApplicationWorker", "SessionManager", "TagpoolManager"] from vumi.application.base import ApplicationWorker from vumi.application.session import SessionManager +from vumi.application.tagpool import TagpoolManager
2479b4a51b733ce8ba989d8f01b48791492d9f21
cogs/utils/dataIO.py
cogs/utils/dataIO.py
import redis_collections import threading import time import __main__ class RedisDict(redis_collections.Dict): def __init__(self, **kwargs): super().__init__(**kwargs) self.die = False self.thread = threading.Thread(target=self.update_loop, daemon=True, name=kwargs['key']) self.thread.start() self.prev = None def update_loop(self): time.sleep(2) while not self.die: if self.prev != repr(self): self.prev = repr(self) self.sync() time.sleep(0.1) else: self.cache.clear() time.sleep(0.1) class dataIO: @staticmethod def save_json(filename, content): pass # "oops" @staticmethod def load_json(filename): return RedisDict(key=filename, redis=__main__.redis_conn, writeback=True)
import redis_collections import threading import time # noinspection PyUnresolvedReferences import __main__ class RedisDict(redis_collections.Dict): def __init__(self, **kwargs): super().__init__(**kwargs) self.die = False self.thread = threading.Thread(target=self.update_loop, daemon=True, name=kwargs['key']) self.thread.start() self.rthread = threading.Thread(target=self.refresh_loop, daemon=True, name=kwargs['key']) self.rthread.start() self.prev = None db = str(self.redis.connection_pool.connection_kwargs['db']) self.pubsub_format = 'liara.{}.{}'.format(db, kwargs['key']) def update_loop(self): time.sleep(2) while not self.die: if self.prev != str(self.cache): self.prev = str(self.cache) self.sync() self.redis.publish(self.pubsub_format, 'update') time.sleep(0.01) else: time.sleep(0.01) def refresh_loop(self): time.sleep(2) pubsub = self.redis.pubsub() pubsub.subscribe([self.pubsub_format]) for message in pubsub.listen(): if message['type'] == 'message': self.cache.clear() self.cache = dict(self) self.prev = str(self.cache) class dataIO: @staticmethod def save_json(filename, content): pass # "oops" @staticmethod def load_json(filename): return RedisDict(key=filename, redis=__main__.redis_conn, writeback=True)
Make config sync more efficient
Make config sync more efficient
Python
mit
Thessia/Liara
--- +++ @@ -1,6 +1,7 @@ import redis_collections import threading import time +# noinspection PyUnresolvedReferences import __main__ @@ -10,18 +11,32 @@ self.die = False self.thread = threading.Thread(target=self.update_loop, daemon=True, name=kwargs['key']) self.thread.start() + self.rthread = threading.Thread(target=self.refresh_loop, daemon=True, name=kwargs['key']) + self.rthread.start() self.prev = None + db = str(self.redis.connection_pool.connection_kwargs['db']) + self.pubsub_format = 'liara.{}.{}'.format(db, kwargs['key']) def update_loop(self): time.sleep(2) while not self.die: - if self.prev != repr(self): - self.prev = repr(self) + if self.prev != str(self.cache): + self.prev = str(self.cache) self.sync() - time.sleep(0.1) + self.redis.publish(self.pubsub_format, 'update') + time.sleep(0.01) else: + time.sleep(0.01) + + def refresh_loop(self): + time.sleep(2) + pubsub = self.redis.pubsub() + pubsub.subscribe([self.pubsub_format]) + for message in pubsub.listen(): + if message['type'] == 'message': self.cache.clear() - time.sleep(0.1) + self.cache = dict(self) + self.prev = str(self.cache) class dataIO:
87a3025196b0b3429cab1f439cd10728e99d982f
skimage/transform/__init__.py
skimage/transform/__init__.py
from .hough_transform import * from .radon_transform import * from .finite_radon_transform import * from .integral import * from ._geometric import (warp, warp_coords, estimate_transform, SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) from ._warps import swirl, homography
from .hough_transform import * from .radon_transform import * from .finite_radon_transform import * from .integral import * from ._geometric import (warp, warp_coords, estimate_transform, SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) from ._warps import swirl, homography, resize, rotate
Add missing imports in transform module.
BUG: Add missing imports in transform module.
Python
bsd-3-clause
emon10005/scikit-image,bsipocz/scikit-image,blink1073/scikit-image,youprofit/scikit-image,rjeli/scikit-image,SamHames/scikit-image,almarklein/scikit-image,rjeli/scikit-image,emon10005/scikit-image,almarklein/scikit-image,youprofit/scikit-image,chintak/scikit-image,almarklein/scikit-image,paalge/scikit-image,vighneshbirodkar/scikit-image,juliusbierk/scikit-image,jwiggins/scikit-image,michaelaye/scikit-image,warmspringwinds/scikit-image,almarklein/scikit-image,SamHames/scikit-image,WarrenWeckesser/scikits-image,blink1073/scikit-image,newville/scikit-image,keflavich/scikit-image,warmspringwinds/scikit-image,vighneshbirodkar/scikit-image,Midafi/scikit-image,juliusbierk/scikit-image,michaelaye/scikit-image,keflavich/scikit-image,rjeli/scikit-image,bennlich/scikit-image,Britefury/scikit-image,ofgulban/scikit-image,ajaybhat/scikit-image,SamHames/scikit-image,robintw/scikit-image,ofgulban/scikit-image,dpshelio/scikit-image,WarrenWeckesser/scikits-image,GaZ3ll3/scikit-image,Hiyorimi/scikit-image,robintw/scikit-image,oew1v07/scikit-image,chriscrosscutler/scikit-image,jwiggins/scikit-image,Midafi/scikit-image,chintak/scikit-image,michaelpacer/scikit-image,michaelpacer/scikit-image,ClinicalGraphics/scikit-image,chriscrosscutler/scikit-image,oew1v07/scikit-image,ajaybhat/scikit-image,vighneshbirodkar/scikit-image,pratapvardhan/scikit-image,Britefury/scikit-image,bennlich/scikit-image,chintak/scikit-image,paalge/scikit-image,pratapvardhan/scikit-image,SamHames/scikit-image,paalge/scikit-image,ClinicalGraphics/scikit-image,chintak/scikit-image,GaZ3ll3/scikit-image,bsipocz/scikit-image,dpshelio/scikit-image,ofgulban/scikit-image,newville/scikit-image,Hiyorimi/scikit-image
--- +++ @@ -6,4 +6,5 @@ SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) -from ._warps import swirl, homography +from ._warps import swirl, homography, resize, rotate +
ed3c03ac4f213f3882e28f25ae0596a7021928cd
test/ParseableInterface/Inputs/make-unreadable.py
test/ParseableInterface/Inputs/make-unreadable.py
import platform import subprocess import sys if platform.system() == 'Windows': import ctypes AdvAPI32 = ctypes.windll.Advapi32 from ctypes.wintypes import POINTER UNLEN = 256 GetUserNameW = AdvAPI32.GetUserNameW GetUserNameW.argtypes = ( ctypes.c_wchar_p, # _In_Out_ lpBuffer POINTER(ctypes.c_uint) # _In_out_ pcBuffer ) GetUserNameW.restype = ctypes.c_uint buffer = ctypes.create_unicode_buffer(UNLEN + 1) size = ctypes.c_uint(len(buffer)) GetUserNameW(buffer, ctypes.byref(size)) for path in sys.argv[1:]: subprocess.call(['icacls', path, '/deny', '{}:(R)'.format(buffer.value)]) else: for path in sys.argv[1:]: subprocess.call(['chmod', 'a-r', path])
import platform import subprocess import sys if platform.system() == 'Windows': import ctypes AdvAPI32 = ctypes.windll.Advapi32 from ctypes.wintypes import POINTER UNLEN = 256 GetUserNameW = AdvAPI32.GetUserNameW GetUserNameW.argtypes = ( ctypes.c_wchar_p, # _In_Out_ lpBuffer POINTER(ctypes.c_uint) # _In_out_ pcBuffer ) GetUserNameW.restype = ctypes.c_uint buffer = ctypes.create_unicode_buffer(UNLEN + 1) size = ctypes.c_uint(len(buffer)) GetUserNameW(buffer, ctypes.byref(size)) # For NetworkService, Host$ is returned, so we choose have to turn it back # into something that icacls understands. if not buffer.value.endswith('$'): user_name = buffer.value else: user_name = 'NT AUTHORITY\\NetworkService' for path in sys.argv[1:]: subprocess.call(['icacls', path, '/deny', '{}:(R)'.format(user_name)]) else: for path in sys.argv[1:]: subprocess.call(['chmod', 'a-r', path])
Fix handling of Network Service username.
[windows] Fix handling of Network Service username. In Windows Server 2016 at least, the Network Service user (the one being used by the CI machine) is returned as Host$, which icacls doesn't understand. Turn the name into something that icacls if we get a name that ends with a dollar.
Python
apache-2.0
atrick/swift,hooman/swift,harlanhaskins/swift,shahmishal/swift,stephentyrone/swift,jmgc/swift,devincoughlin/swift,ahoppen/swift,tkremenek/swift,xedin/swift,shahmishal/swift,xwu/swift,xedin/swift,harlanhaskins/swift,harlanhaskins/swift,sschiau/swift,shajrawi/swift,karwa/swift,gribozavr/swift,apple/swift,CodaFi/swift,ahoppen/swift,lorentey/swift,nathawes/swift,JGiola/swift,allevato/swift,airspeedswift/swift,harlanhaskins/swift,hooman/swift,karwa/swift,rudkx/swift,CodaFi/swift,gregomni/swift,lorentey/swift,sschiau/swift,shajrawi/swift,karwa/swift,parkera/swift,tkremenek/swift,sschiau/swift,devincoughlin/swift,xedin/swift,aschwaighofer/swift,airspeedswift/swift,jmgc/swift,nathawes/swift,lorentey/swift,tkremenek/swift,allevato/swift,jmgc/swift,xwu/swift,JGiola/swift,ahoppen/swift,shahmishal/swift,tkremenek/swift,roambotics/swift,benlangmuir/swift,roambotics/swift,hooman/swift,atrick/swift,gribozavr/swift,gregomni/swift,glessard/swift,xedin/swift,apple/swift,jckarter/swift,gregomni/swift,karwa/swift,benlangmuir/swift,sschiau/swift,xedin/swift,stephentyrone/swift,aschwaighofer/swift,jckarter/swift,CodaFi/swift,lorentey/swift,CodaFi/swift,lorentey/swift,harlanhaskins/swift,tkremenek/swift,karwa/swift,gribozavr/swift,nathawes/swift,gregomni/swift,tkremenek/swift,JGiola/swift,nathawes/swift,JGiola/swift,parkera/swift,gregomni/swift,aschwaighofer/swift,airspeedswift/swift,CodaFi/swift,karwa/swift,apple/swift,shajrawi/swift,atrick/swift,stephentyrone/swift,hooman/swift,apple/swift,xwu/swift,parkera/swift,CodaFi/swift,glessard/swift,devincoughlin/swift,glessard/swift,hooman/swift,rudkx/swift,ahoppen/swift,harlanhaskins/swift,sschiau/swift,hooman/swift,allevato/swift,shajrawi/swift,ahoppen/swift,allevato/swift,devincoughlin/swift,shajrawi/swift,devincoughlin/swift,nathawes/swift,JGiola/swift,rudkx/swift,devincoughlin/swift,benlangmuir/swift,parkera/swift,roambotics/swift,rudkx/swift,jmgc/swift,xwu/swift,xedin/swift,roambotics/swift,aschwaighofer/swift,jmgc/swift,airspeedswift/swift,shahmishal/swift,stephentyrone/swift,gribozavr/swift,karwa/swift,devincoughlin/swift,gribozavr/swift,nathawes/swift,roambotics/swift,benlangmuir/swift,rudkx/swift,shahmishal/swift,xwu/swift,glessard/swift,karwa/swift,aschwaighofer/swift,allevato/swift,parkera/swift,glessard/swift,atrick/swift,tkremenek/swift,gribozavr/swift,sschiau/swift,jmgc/swift,benlangmuir/swift,jckarter/swift,jckarter/swift,shahmishal/swift,allevato/swift,gregomni/swift,airspeedswift/swift,parkera/swift,shahmishal/swift,gribozavr/swift,sschiau/swift,jckarter/swift,JGiola/swift,harlanhaskins/swift,xedin/swift,allevato/swift,jckarter/swift,sschiau/swift,nathawes/swift,airspeedswift/swift,xedin/swift,lorentey/swift,glessard/swift,devincoughlin/swift,atrick/swift,lorentey/swift,aschwaighofer/swift,CodaFi/swift,gribozavr/swift,roambotics/swift,shajrawi/swift,rudkx/swift,airspeedswift/swift,lorentey/swift,stephentyrone/swift,apple/swift,aschwaighofer/swift,xwu/swift,xwu/swift,benlangmuir/swift,ahoppen/swift,atrick/swift,jckarter/swift,parkera/swift,parkera/swift,shajrawi/swift,hooman/swift,shahmishal/swift,stephentyrone/swift,shajrawi/swift,jmgc/swift,stephentyrone/swift,apple/swift
--- +++ @@ -21,10 +21,16 @@ buffer = ctypes.create_unicode_buffer(UNLEN + 1) size = ctypes.c_uint(len(buffer)) GetUserNameW(buffer, ctypes.byref(size)) + # For NetworkService, Host$ is returned, so we choose have to turn it back + # into something that icacls understands. + if not buffer.value.endswith('$'): + user_name = buffer.value + else: + user_name = 'NT AUTHORITY\\NetworkService' for path in sys.argv[1:]: subprocess.call(['icacls', path, '/deny', - '{}:(R)'.format(buffer.value)]) + '{}:(R)'.format(user_name)]) else: for path in sys.argv[1:]: subprocess.call(['chmod', 'a-r', path])
8f68e3f3ab63d67d3e7fc1c8cd63c6c9d03729a2
Channels/News_Channel/lz77.py
Channels/News_Channel/lz77.py
import glob import os import subprocess """This is used to decompress the news.bin files.""" def decompress(file): with open(file, "rb") as source_file: read = source_file.read() tail = read[320:] with open(file + ".2", "w+") as dest_file: dest_file.write(tail) FNULL = open(os.devnull, "w+") decompress = subprocess.call(["mono", "--runtime=v4.0.30319", "DSDecmp.exe", "-d", file + ".2", file + ".3"], stdout=FNULL, stderr=subprocess.STDOUT) remove = os.remove(file + ".2") move = subprocess.call(["mv", file + ".3", file + ".2"], stdout=FNULL, stderr=subprocess.STDOUT) open_hex = subprocess.call(["open", "-a", "Hex Fiend", file + ".2"], stdout=FNULL, stderr=subprocess.STDOUT) for file in glob.glob("news.bin.*"): if os.path.exists(file): decompress(file) for file in glob.glob("*.bin"): if os.path.exists(file): decompress(file)
import glob import os import subprocess """This is used to decompress the news.bin files.""" def decompress(file): with open(file, "rb") as source_file: read = source_file.read() tail = read[320:] with open(file + ".2", "w+") as dest_file: dest_file.write(tail) FNULL = open(os.devnull, "w+") decompress = subprocess.call(["mono", "--runtime=v4.0.30319", "DSDecmp.exe", "-d", file + ".2", file + ".3"], stdout=FNULL, stderr=subprocess.STDOUT) remove = os.remove(file + ".2") move = subprocess.call(["mv", file + ".3", file + ".2"], stdout=FNULL, stderr=subprocess.STDOUT) open_hex = subprocess.call(["open", "-a", "Hex Fiend", file + ".2"], stdout=FNULL, stderr=subprocess.STDOUT) // This is to open the news files in the Mac hex editor I use called Hex Fiend. for file in glob.glob("news.bin.*"): if os.path.exists(file): decompress(file) for file in glob.glob("*.bin"): if os.path.exists(file): decompress(file)
Comment about the hex part
Comment about the hex part
Python
agpl-3.0
RiiConnect24/File-Maker,RiiConnect24/File-Maker
--- +++ @@ -18,7 +18,7 @@ decompress = subprocess.call(["mono", "--runtime=v4.0.30319", "DSDecmp.exe", "-d", file + ".2", file + ".3"], stdout=FNULL, stderr=subprocess.STDOUT) remove = os.remove(file + ".2") move = subprocess.call(["mv", file + ".3", file + ".2"], stdout=FNULL, stderr=subprocess.STDOUT) - open_hex = subprocess.call(["open", "-a", "Hex Fiend", file + ".2"], stdout=FNULL, stderr=subprocess.STDOUT) + open_hex = subprocess.call(["open", "-a", "Hex Fiend", file + ".2"], stdout=FNULL, stderr=subprocess.STDOUT) // This is to open the news files in the Mac hex editor I use called Hex Fiend. for file in glob.glob("news.bin.*"): if os.path.exists(file):
794a75ed410fe39ba2376ebcab75d21cc5e9fee0
common/safeprint.py
common/safeprint.py
import multiprocessing, sys, datetime print_lock = multiprocessing.Lock() def safeprint(content): with print_lock: sys.stdout.write(("[" + str(multiprocessing.current_process().pid) + "] " + datetime.datetime.now().strftime('%H%M%S') + ": " + str(content) + '\r\n'))
import multiprocessing, sys, datetime print_lock = multiprocessing.RLock() def safeprint(content): string = "[" + str(multiprocessing.current_process().pid) + "] " + datetime.datetime.now().strftime('%H%M%S') + ": " + str(content) + '\r\n' with print_lock: sys.stdout.write(string)
Reduce the amount of time locking
Reduce the amount of time locking
Python
mit
gappleto97/Senior-Project
--- +++ @@ -1,6 +1,7 @@ import multiprocessing, sys, datetime -print_lock = multiprocessing.Lock() +print_lock = multiprocessing.RLock() def safeprint(content): + string = "[" + str(multiprocessing.current_process().pid) + "] " + datetime.datetime.now().strftime('%H%M%S') + ": " + str(content) + '\r\n' with print_lock: - sys.stdout.write(("[" + str(multiprocessing.current_process().pid) + "] " + datetime.datetime.now().strftime('%H%M%S') + ": " + str(content) + '\r\n')) + sys.stdout.write(string)
b79ed827f7211efbcdef95286bf2d4113d6e8b88
posts/views.py
posts/views.py
from django.shortcuts import get_object_or_404 from django.views.generic.dates import ArchiveIndexView from django.views.generic.edit import FormView from .models import Entry, Category from .forms import ContactForm class CategoryView(ArchiveIndexView): model = Entry date_field = 'date' paginate_by = 20 template_name = 'posts/entry_category.html' def get(self, request, slug, **kwargs): self.kwargs['category'] = get_object_or_404(Category, slug=slug) return super().get(request, kwargs) def get_queryset(self): return Entry.objects.filter(category=self.kwargs['category']) def get_context_data(self, **kwargs): result = super().get_context_data(**kwargs) result['category'] = self.kwargs['category'] return result class ContactView(FormView): template_name = 'contact.html' form_class = ContactForm success_url = '/kontakt/' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.send_email() return super().form_valid(form)
from django.shortcuts import get_object_or_404 from django.views.generic.dates import ArchiveIndexView from django.views.generic.edit import FormView from .models import Entry, Category from .forms import ContactForm class CategoryView(ArchiveIndexView): model = Entry date_field = 'date' paginate_by = 20 template_name = 'posts/entry_category.html' def get(self, request, slug, **kwargs): self.kwargs['category'] = get_object_or_404(Category, slug=slug) return super().get(request, kwargs) def get_queryset(self): return super().get_queryset().filter(category=self.kwargs['category']) def get_context_data(self, **kwargs): result = super().get_context_data(**kwargs) result['category'] = self.kwargs['category'] return result class ContactView(FormView): template_name = 'contact.html' form_class = ContactForm success_url = '/kontakt/' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.send_email() return super().form_valid(form)
Fix ordering of category view
Fix ordering of category view Signed-off-by: Michal Čihař <[email protected]>
Python
agpl-3.0
nijel/photoblog,nijel/photoblog
--- +++ @@ -16,7 +16,7 @@ return super().get(request, kwargs) def get_queryset(self): - return Entry.objects.filter(category=self.kwargs['category']) + return super().get_queryset().filter(category=self.kwargs['category']) def get_context_data(self, **kwargs): result = super().get_context_data(**kwargs)
df99ee50e7d7a677aec4e30af10283399a8edb8c
dlstats/configuration.py
dlstats/configuration.py
import configobj import validate import os def _get_filename(): """Return the configuration file path.""" appname = 'dlstats' if os.name == 'posix': if os.path.isfile(os.environ["HOME"]+'/.'+appname): return os.environ["HOME"]+'/.'+appname elif os.path.isfile('/etc/'+appname): return '/etc/'+appname else: raise FileNotFoundError('No configuration file found.') elif os.name == 'mac': return ("%s/Library/Application Support/%s" % (os.environ["HOME"], appname)) elif os.name == 'nt': return ("%s\Application Data\%s" % (os.environ["HOMEPATH"], appname)) else: raise UnsupportedOSError(os.name) configuration_filename = _get_filename() _configspec = """ [General] logging_directory = string() socket_directory = string() [MongoDB] host = ip_addr() port = integer() max_pool_size = integer() socketTimeoutMS = integer() connectTimeoutMS = integer() waitQueueTimeout = integer() waitQueueMultiple = integer() auto_start_request = boolean() use_greenlets = boolean() [ElasticSearch] host = integer() port = integer() [Fetchers] [[Eurostat]] url_table_of_contents = string()""" configuration = configobj.ConfigObj(configuration_filename, configspec=_configspec.split('\n')) validator = validate.Validator() configuration.validate(validator) configuration = configuration.dict()
import configobj import validate import os def _get_filename(): """Return the configuration file path.""" appname = 'dlstats' if os.name == 'posix': if "HOME" in os.environ: if os.path.isfile(os.environ["HOME"]+'/.'+appname): return os.environ["HOME"]+'/.'+appname if os.path.isfile('/etc/'+appname): return '/etc/'+appname else: raise FileNotFoundError('No configuration file found.') elif os.name == 'mac': return ("%s/Library/Application Support/%s" % (os.environ["HOME"], appname)) elif os.name == 'nt': return ("%s\Application Data\%s" % (os.environ["HOMEPATH"], appname)) else: raise UnsupportedOSError(os.name) configuration_filename = _get_filename() _configspec = """ [General] logging_directory = string() socket_directory = string() [MongoDB] host = ip_addr() port = integer() max_pool_size = integer() socketTimeoutMS = integer() connectTimeoutMS = integer() waitQueueTimeout = integer() waitQueueMultiple = integer() auto_start_request = boolean() use_greenlets = boolean() [ElasticSearch] host = integer() port = integer() [Fetchers] [[Eurostat]] url_table_of_contents = string()""" configuration = configobj.ConfigObj(configuration_filename, configspec=_configspec.split('\n')) validator = validate.Validator() configuration.validate(validator) configuration = configuration.dict()
Test for environment variable existence
Test for environment variable existence
Python
agpl-3.0
Widukind/dlstats,MichelJuillard/dlstats,MichelJuillard/dlstats,mmalter/dlstats,mmalter/dlstats,Widukind/dlstats,mmalter/dlstats,MichelJuillard/dlstats
--- +++ @@ -6,9 +6,10 @@ """Return the configuration file path.""" appname = 'dlstats' if os.name == 'posix': - if os.path.isfile(os.environ["HOME"]+'/.'+appname): - return os.environ["HOME"]+'/.'+appname - elif os.path.isfile('/etc/'+appname): + if "HOME" in os.environ: + if os.path.isfile(os.environ["HOME"]+'/.'+appname): + return os.environ["HOME"]+'/.'+appname + if os.path.isfile('/etc/'+appname): return '/etc/'+appname else: raise FileNotFoundError('No configuration file found.')
3838e44a397fdb4b605ead875b7c6ebc5787644d
jal_stats/stats/serializers.py
jal_stats/stats/serializers.py
from rest_framework import serializers from .models import Activity, Datapoint class ActivitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Activity fields = ('user', 'full_description', 'units', 'url') class DatapointSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Datapoint fields = ('user', 'activity', 'reps', 'timestamp', 'url')
from rest_framework import serializers from .models import Activity, Datapoint class ActivitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Activity fields = ('id', 'user', 'full_description', 'units', 'url') class DatapointSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Datapoint fields = ('id', 'user', 'activity', 'reps', 'timestamp', 'url')
Add 'id' to both Serializers
Add 'id' to both Serializers
Python
mit
jal-stats/django
--- +++ @@ -5,10 +5,10 @@ class ActivitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Activity - fields = ('user', 'full_description', 'units', 'url') + fields = ('id', 'user', 'full_description', 'units', 'url') class DatapointSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Datapoint - fields = ('user', 'activity', 'reps', 'timestamp', 'url') + fields = ('id', 'user', 'activity', 'reps', 'timestamp', 'url')
ec1e0cd1fa8bab59750032942643a7abc8700642
cspreports/models.py
cspreports/models.py
#LIBRARIES from django.db import models from django.utils.html import escape from django.utils.safestring import mark_safe class CSPReport(models.Model): class Meta(object): ordering = ('-created',) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) json = models.TextField() def json_as_html(self): """ Print out self.json in a nice way. """ # To avoid circular import from cspreports import utils formatted_json = utils.format_report(self.json) return mark_safe(u"<pre>\n%s</pre>" % escape(formatted_json))
# STANDARD LIB import json #LIBRARIES from django.db import models from django.utils.html import escape from django.utils.safestring import mark_safe class CSPReport(models.Model): class Meta(object): ordering = ('-created',) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) json = models.TextField() @property def data(self): """ Returns self.json loaded as a python object. """ try: data = self._data except AttributeError: data = self._data = json.loads(self.json) return data def json_as_html(self): """ Print out self.json in a nice way. """ # To avoid circular import from cspreports import utils formatted_json = utils.format_report(self.json) return mark_safe(u"<pre>\n%s</pre>" % escape(formatted_json))
Revert removing data which is still used
Revert removing data which is still used This was removed in b1bc34e9a83cb3af5dd11baa1236f2b65ab823f9 but is still used in admin.py.
Python
mit
adamalton/django-csp-reports
--- +++ @@ -1,3 +1,6 @@ +# STANDARD LIB +import json + #LIBRARIES from django.db import models from django.utils.html import escape @@ -13,6 +16,15 @@ modified = models.DateTimeField(auto_now=True) json = models.TextField() + @property + def data(self): + """ Returns self.json loaded as a python object. """ + try: + data = self._data + except AttributeError: + data = self._data = json.loads(self.json) + return data + def json_as_html(self): """ Print out self.json in a nice way. """
271b4cd3795cbe0e5e013ac53c3ea26ca08e7a1a
IPython/utils/importstring.py
IPython/utils/importstring.py
# encoding: utf-8 """ A simple utility to import something by its string name. Authors: * Brian Granger """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Functions and classes #----------------------------------------------------------------------------- def import_item(name): """Import and return bar given the string foo.bar.""" package = '.'.join(name.split('.')[0:-1]) obj = name.split('.')[-1] # Note: the original code for this was the following. We've left it # visible for now in case the new implementation shows any problems down # the road, to make it easier on anyone looking for a problem. This code # should be removed once we're comfortable we didn't break anything. ## execString = 'from %s import %s' % (package, obj) ## try: ## exec execString ## except SyntaxError: ## raise ImportError("Invalid class specification: %s" % name) ## exec 'temp = %s' % obj ## return temp if package: module = __import__(package,fromlist=[obj]) return module.__dict__[obj] else: return __import__(obj)
# encoding: utf-8 """ A simple utility to import something by its string name. Authors: * Brian Granger """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Functions and classes #----------------------------------------------------------------------------- def import_item(name): """Import and return bar given the string foo.bar.""" package = '.'.join(name.split('.')[0:-1]) obj = name.split('.')[-1] # Note: the original code for this was the following. We've left it # visible for now in case the new implementation shows any problems down # the road, to make it easier on anyone looking for a problem. This code # should be removed once we're comfortable we didn't break anything. ## execString = 'from %s import %s' % (package, obj) ## try: ## exec execString ## except SyntaxError: ## raise ImportError("Invalid class specification: %s" % name) ## exec 'temp = %s' % obj ## return temp if package: module = __import__(package,fromlist=[obj]) try: pak = module.__dict__[obj] except KeyError: raise ImportError('No module named %s' % obj) return pak else: return __import__(obj)
Fix error in test suite startup with dotted import names.
Fix error in test suite startup with dotted import names. Detected first on ubuntu 12.04, but the bug is generic, we just hadn't seen it before. Will push straight to master as this will begin causing problems as more people upgrade.
Python
bsd-3-clause
ipython/ipython,ipython/ipython
--- +++ @@ -38,6 +38,10 @@ if package: module = __import__(package,fromlist=[obj]) - return module.__dict__[obj] + try: + pak = module.__dict__[obj] + except KeyError: + raise ImportError('No module named %s' % obj) + return pak else: return __import__(obj)
14869bd8c58a393caec488e95d51c282ccf23d0d
katagawa/sql/__init__.py
katagawa/sql/__init__.py
""" SQL generators for Katagawa. """ import abc import typing class Token(abc.ABC): """ Base class for a token. """ def __init__(self, subtokens: typing.List['Token']): """ :param subtokens: Any subtokens this token has. """ self.subtokens = subtokens @abc.abstractproperty def name(self): """ Returns the name of the token. """ @abc.abstractmethod def generate_sql(self): """ Generate SQL from this statement. :return: The generated SQL. """
""" SQL generators for Katagawa. """ import abc import typing class Token(abc.ABC): """ Base class for a token. """ __slots__ = () def __init__(self, subtokens: typing.List['Token']): """ :param subtokens: Any subtokens this token has. """ self.subtokens = subtokens @abc.abstractproperty def name(self): """ Returns the name of the token. This is a unique identifier, but is not always related to the actual SQL underneath it. """ @abc.abstractmethod def generate_sql(self): """ Generate SQL from this statement. :return: The generated SQL. """ class Aliased(Token): """ Mixin class for an aliased token. """ __slots__ = ("alias",) def __init__(self, subtokens: typing.List['Token'], alias: str): """ :param subtokens: Any subtokens this token has. :param alias: The alias this token has. """ super().__init__(subtokens) self.alias = alias
Add aliased ABC for tokens with an alias.
Add aliased ABC for tokens with an alias.
Python
mit
SunDwarf/asyncqlio
--- +++ @@ -9,6 +9,9 @@ """ Base class for a token. """ + + __slots__ = () + def __init__(self, subtokens: typing.List['Token']): """ :param subtokens: Any subtokens this token has. @@ -19,6 +22,8 @@ def name(self): """ Returns the name of the token. + + This is a unique identifier, but is not always related to the actual SQL underneath it. """ @abc.abstractmethod @@ -27,3 +32,20 @@ Generate SQL from this statement. :return: The generated SQL. """ + + +class Aliased(Token): + """ + Mixin class for an aliased token. + """ + + __slots__ = ("alias",) + + def __init__(self, subtokens: typing.List['Token'], alias: str): + """ + :param subtokens: Any subtokens this token has. + :param alias: The alias this token has. + """ + super().__init__(subtokens) + + self.alias = alias
7844df0c4f32c9cc1f5833aba4712680461f77b5
test/on_yubikey/cli_piv/test_misc.py
test/on_yubikey/cli_piv/test_misc.py
import unittest from ..framework import cli_test_suite from .util import DEFAULT_MANAGEMENT_KEY @cli_test_suite def additional_tests(ykman_cli): class Misc(unittest.TestCase): def setUp(self): ykman_cli('piv', 'reset', '-f') def test_info(self): output = ykman_cli('piv', 'info') self.assertIn('PIV version:', output) def test_reset(self): output = ykman_cli('piv', 'reset', '-f') self.assertIn('Success!', output) def test_write_read_object(self): ykman_cli( 'piv', 'write-object', '-m', DEFAULT_MANAGEMENT_KEY, '0x5f0001', '-', input='test data') output = ykman_cli('piv', 'read-object', '0x5f0001') self.assertEqual('test data\n', output) return [Misc]
import unittest from ykman.piv import OBJ from .util import DEFAULT_MANAGEMENT_KEY from ..framework import cli_test_suite from .util import DEFAULT_MANAGEMENT_KEY @cli_test_suite def additional_tests(ykman_cli): class Misc(unittest.TestCase): def setUp(self): ykman_cli('piv', 'reset', '-f') def test_info(self): output = ykman_cli('piv', 'info') self.assertIn('PIV version:', output) def test_reset(self): output = ykman_cli('piv', 'reset', '-f') self.assertIn('Success!', output) def test_write_read_object(self): ykman_cli( 'piv', 'write-object', '-m', DEFAULT_MANAGEMENT_KEY, '0x5f0001', '-', input='test data') output = ykman_cli('piv', 'read-object', '0x5f0001') self.assertEqual('test data\n', output) def test_export_invalid_certificate_fails(self): ykman_cli('piv', 'write-object', hex(OBJ.AUTHENTICATION), '-', '-m', DEFAULT_MANAGEMENT_KEY, input='Kom ihåg att du aldrig får snyta dig i mattan!') with self.assertRaises(SystemExit): ykman_cli('piv', 'export-certificate', hex(OBJ.AUTHENTICATION), '-') def test_info_with_invalid_certificate_does_not_crash(self): ykman_cli('piv', 'write-object', hex(OBJ.AUTHENTICATION), '-', '-m', DEFAULT_MANAGEMENT_KEY, input='Kom ihåg att du aldrig får snyta dig i mattan!') ykman_cli('piv', 'info') return [Misc]
Test that invalid cert crashes export-certificate but not info
Test that invalid cert crashes export-certificate but not info
Python
bsd-2-clause
Yubico/yubikey-manager,Yubico/yubikey-manager
--- +++ @@ -1,5 +1,7 @@ import unittest +from ykman.piv import OBJ +from .util import DEFAULT_MANAGEMENT_KEY from ..framework import cli_test_suite from .util import DEFAULT_MANAGEMENT_KEY @@ -27,4 +29,19 @@ output = ykman_cli('piv', 'read-object', '0x5f0001') self.assertEqual('test data\n', output) + def test_export_invalid_certificate_fails(self): + ykman_cli('piv', 'write-object', hex(OBJ.AUTHENTICATION), '-', + '-m', DEFAULT_MANAGEMENT_KEY, + input='Kom ihåg att du aldrig får snyta dig i mattan!') + + with self.assertRaises(SystemExit): + ykman_cli('piv', 'export-certificate', + hex(OBJ.AUTHENTICATION), '-') + + def test_info_with_invalid_certificate_does_not_crash(self): + ykman_cli('piv', 'write-object', hex(OBJ.AUTHENTICATION), '-', + '-m', DEFAULT_MANAGEMENT_KEY, + input='Kom ihåg att du aldrig får snyta dig i mattan!') + ykman_cli('piv', 'info') + return [Misc]
1c3c092afae1946e72a87cca8792bd012bee23e4
ktbs_bench/utils/decorators.py
ktbs_bench/utils/decorators.py
from functools import wraps from inspect import getcallargs from timer import Timer def bench(f): """Times a function given specific arguments.""" # TODO mettre args (n_repeat, func) qui execute n_repeat fois et applique un reduce(res, func) @wraps(f) def wrapped(*args, **kwargs): timer = Timer(tick_now=False) timer.start() f(*args, **kwargs) timer.stop() res = [call_signature(f, *args, **kwargs), timer.get_times()['real']] # TODO penser a quel temps garder return res return wrapped def call_signature(f, *args, **kwargs): """Return a string representation of a function call.""" call_args = getcallargs(f, *args, **kwargs) return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()])
from functools import wraps from inspect import getcallargs from timer import Timer def bench(f): """Decorator to time a function. Parameters ---------- f : function The function to time. Returns ------- call_signature : str The signature of the function call, with parameter names and values. time : float The real time taken to execute the function, in second. Examples -------- >>> @bench ... def square_list(numbers): ... for ind_num in range(len(numbers)): ... numbers[ind_num] *= numbers[ind_num] ... return numbers >>> call_sig, time = square_list(range(10)) >>> call_sig 'numbers=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]' >>> 0 < time < 1 # benched function is not computationally intensive so time should be less than 1 s True """ @wraps(f) def wrapped(*args, **kwargs): """Actual benchmark takes place here.""" call_sig = call_signature(f, *args, **kwargs) timer = Timer(tick_now=False) timer.start() f(*args, **kwargs) timer.stop() res = [call_sig, timer.get_times()['real']] return res return wrapped def call_signature(f, *args, **kwargs): """Return a string representation of a function call. Parameters ---------- f : function The function to get the call signature from. args : list List of arguments. kwargs : dict Dictionary of argument names and values. Returns ------- out : str String representation of the function call Examples -------- >>> def square(num): ... return num*num >>> call_signature(square, 4) 'num=4' """ call_args = getcallargs(f, *args, **kwargs) return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()])
Add docstrings and fix call of call_signature.
Add docstrings and fix call of call_signature. For the fix: call_signature has been moved before executing the actual call, if the call is made before then it might change arguments if they are references.
Python
mit
ktbs/ktbs-bench,ktbs/ktbs-bench
--- +++ @@ -5,24 +5,73 @@ def bench(f): - """Times a function given specific arguments.""" + """Decorator to time a function. - # TODO mettre args (n_repeat, func) qui execute n_repeat fois et applique un reduce(res, func) + Parameters + ---------- + f : function + The function to time. + + Returns + ------- + call_signature : str + The signature of the function call, with parameter names and values. + time : float + The real time taken to execute the function, in second. + + Examples + -------- + >>> @bench + ... def square_list(numbers): + ... for ind_num in range(len(numbers)): + ... numbers[ind_num] *= numbers[ind_num] + ... return numbers + >>> call_sig, time = square_list(range(10)) + >>> call_sig + 'numbers=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]' + >>> 0 < time < 1 # benched function is not computationally intensive so time should be less than 1 s + True + """ + @wraps(f) def wrapped(*args, **kwargs): + """Actual benchmark takes place here.""" + call_sig = call_signature(f, *args, **kwargs) + timer = Timer(tick_now=False) timer.start() f(*args, **kwargs) timer.stop() - res = [call_signature(f, *args, **kwargs), - timer.get_times()['real']] # TODO penser a quel temps garder + res = [call_sig, timer.get_times()['real']] return res return wrapped def call_signature(f, *args, **kwargs): - """Return a string representation of a function call.""" + """Return a string representation of a function call. + + Parameters + ---------- + f : function + The function to get the call signature from. + args : list + List of arguments. + kwargs : dict + Dictionary of argument names and values. + + Returns + ------- + out : str + String representation of the function call + + Examples + -------- + >>> def square(num): + ... return num*num + >>> call_signature(square, 4) + 'num=4' + """ call_args = getcallargs(f, *args, **kwargs) return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()])
15be3bd492a0808713c6ae6981ecb99acacd5297
allauth/socialaccount/providers/trello/provider.py
allauth/socialaccount/providers/trello/provider.py
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider class TrelloAccount(ProviderAccount): def get_profile_url(self): return None def get_avatar_url(self): return None class TrelloProvider(OAuthProvider): id = 'trello' name = 'Trello' account_class = TrelloAccount def get_default_scope(self): return ['read'] def extract_uid(self, data): return data['id'] def get_auth_params(self, request, action): data = super(TrelloProvider, self).get_auth_params(request, action) app = self.get_app(request) data['type'] = 'web_server' data['name'] = app.name # define here for how long it will be, this can be configured on the # social app data['expiration'] = 'never' return data provider_classes = [TrelloProvider]
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider class TrelloAccount(ProviderAccount): def get_profile_url(self): return None def get_avatar_url(self): return None class TrelloProvider(OAuthProvider): id = 'trello' name = 'Trello' account_class = TrelloAccount def get_default_scope(self): return ['read'] def extract_uid(self, data): return data['id'] def get_auth_params(self, request, action): data = super(TrelloProvider, self).get_auth_params(request, action) app = self.get_app(request) data['type'] = 'web_server' data['name'] = app.name data['scope'] = self.get_scope(request) # define here for how long it will be, this can be configured on the # social app data['expiration'] = 'never' return data provider_classes = [TrelloProvider]
Use 'scope' in TrelloProvider auth params. Allows overriding from django settings.
feat(TrelloProvider): Use 'scope' in TrelloProvider auth params. Allows overriding from django settings.
Python
mit
AltSchool/django-allauth,AltSchool/django-allauth,AltSchool/django-allauth
--- +++ @@ -26,6 +26,7 @@ app = self.get_app(request) data['type'] = 'web_server' data['name'] = app.name + data['scope'] = self.get_scope(request) # define here for how long it will be, this can be configured on the # social app data['expiration'] = 'never'
d7fc84f6e92cb2f6bc3006971258d655059f9fb1
lemur/dns_providers/schemas.py
lemur/dns_providers/schemas.py
from marshmallow import fields from lemur.common.fields import ArrowDateTime from lemur.common.schema import LemurInputSchema, LemurOutputSchema class DnsProvidersNestedOutputSchema(LemurOutputSchema): __envelope__ = False id = fields.Integer() name = fields.String() providerType = fields.String() description = fields.String() credentials = fields.String() api_endpoint = fields.String() date_created = ArrowDateTime() class DnsProvidersNestedInputSchema(LemurInputSchema): __envelope__ = False name = fields.String() description = fields.String() provider_type = fields.Dict() dns_provider_output_schema = DnsProvidersNestedOutputSchema() dns_provider_input_schema = DnsProvidersNestedInputSchema()
from marshmallow import fields from lemur.common.fields import ArrowDateTime from lemur.common.schema import LemurInputSchema, LemurOutputSchema class DnsProvidersNestedOutputSchema(LemurOutputSchema): __envelope__ = False id = fields.Integer() name = fields.String() provider_type = fields.String() description = fields.String() credentials = fields.String() api_endpoint = fields.String() date_created = ArrowDateTime() class DnsProvidersNestedInputSchema(LemurInputSchema): __envelope__ = False name = fields.String() description = fields.String() provider_type = fields.Dict() dns_provider_output_schema = DnsProvidersNestedOutputSchema() dns_provider_input_schema = DnsProvidersNestedInputSchema()
Fix dns-providers type missing from schema
Fix dns-providers type missing from schema
Python
apache-2.0
Netflix/lemur,Netflix/lemur,Netflix/lemur,Netflix/lemur
--- +++ @@ -8,7 +8,7 @@ __envelope__ = False id = fields.Integer() name = fields.String() - providerType = fields.String() + provider_type = fields.String() description = fields.String() credentials = fields.String() api_endpoint = fields.String()
a35b6e46bd9d443f07391f37f5e0e384e37608bb
nbgrader/tests/test_nbgrader_feedback.py
nbgrader/tests/test_nbgrader_feedback.py
from .base import TestBase from nbgrader.api import Gradebook import os class TestNbgraderFeedback(TestBase): def _setup_db(self): dbpath = self._init_db() gb = Gradebook(dbpath) gb.add_assignment("Problem Set 1") gb.add_student("foo") gb.add_student("bar") return dbpath def test_help(self): """Does the help display without error?""" with self._temp_cwd(): self._run_command("nbgrader feedback --help-all") def test_single_file(self): """Can feedback be generated for an unchanged assignment?""" with self._temp_cwd(["files/submitted-unchanged.ipynb"]): dbpath = self._setup_db() self._run_command( 'nbgrader autograde submitted-unchanged.ipynb ' '--db="{}" ' '--assignment="Problem Set 1" ' '--AssignmentExporter.notebook_id=teacher ' '--student=foo'.format(dbpath)) self._run_command( 'nbgrader feedback submitted-unchanged.nbconvert.ipynb ' '--db="{}" ' '--assignment="Problem Set 1" ' '--AssignmentExporter.notebook_id=teacher ' '--student=foo'.format(dbpath)) assert os.path.exists('submitted-unchanged.nbconvert.nbconvert.html')
from .base import TestBase from nbgrader.api import Gradebook import os import shutil class TestNbgraderFeedback(TestBase): def _setup_db(self): dbpath = self._init_db() gb = Gradebook(dbpath) gb.add_assignment("ps1") gb.add_student("foo") return dbpath def test_help(self): """Does the help display without error?""" with self._temp_cwd(): self._run_command("nbgrader feedback --help-all") def test_single_file(self): """Can feedback be generated for an unchanged assignment?""" with self._temp_cwd(["files/submitted-unchanged.ipynb"]): dbpath = self._setup_db() os.makedirs('source/ps1') shutil.copy('submitted-unchanged.ipynb', 'source/ps1/p1.ipynb') self._run_command('nbgrader assign ps1 --db="{}" '.format(dbpath)) os.makedirs('submitted/foo/ps1') shutil.move('submitted-unchanged.ipynb', 'submitted/foo/ps1/p1.ipynb') self._run_command('nbgrader autograde ps1 --db="{}" '.format(dbpath)) self._run_command('nbgrader feedback ps1 --db="{}" '.format(dbpath)) assert os.path.exists('feedback/foo/ps1/p1.html')
Update tests for nbgrader feedback
Update tests for nbgrader feedback
Python
bsd-3-clause
jhamrick/nbgrader,alope107/nbgrader,ellisonbg/nbgrader,EdwardJKim/nbgrader,modulexcite/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,jdfreder/nbgrader,MatKallada/nbgrader,jupyter/nbgrader,MatKallada/nbgrader,jupyter/nbgrader,dementrock/nbgrader,jhamrick/nbgrader,EdwardJKim/nbgrader,jupyter/nbgrader,jupyter/nbgrader,modulexcite/nbgrader,jhamrick/nbgrader,alope107/nbgrader,jdfreder/nbgrader,EdwardJKim/nbgrader,jupyter/nbgrader,dementrock/nbgrader,ellisonbg/nbgrader,jhamrick/nbgrader,ellisonbg/nbgrader
--- +++ @@ -2,15 +2,15 @@ from nbgrader.api import Gradebook import os +import shutil class TestNbgraderFeedback(TestBase): def _setup_db(self): dbpath = self._init_db() gb = Gradebook(dbpath) - gb.add_assignment("Problem Set 1") + gb.add_assignment("ps1") gb.add_student("foo") - gb.add_student("bar") return dbpath def test_help(self): @@ -22,18 +22,14 @@ """Can feedback be generated for an unchanged assignment?""" with self._temp_cwd(["files/submitted-unchanged.ipynb"]): dbpath = self._setup_db() - self._run_command( - 'nbgrader autograde submitted-unchanged.ipynb ' - '--db="{}" ' - '--assignment="Problem Set 1" ' - '--AssignmentExporter.notebook_id=teacher ' - '--student=foo'.format(dbpath)) - self._run_command( - 'nbgrader feedback submitted-unchanged.nbconvert.ipynb ' - '--db="{}" ' - '--assignment="Problem Set 1" ' - '--AssignmentExporter.notebook_id=teacher ' - '--student=foo'.format(dbpath)) + os.makedirs('source/ps1') + shutil.copy('submitted-unchanged.ipynb', 'source/ps1/p1.ipynb') + self._run_command('nbgrader assign ps1 --db="{}" '.format(dbpath)) - assert os.path.exists('submitted-unchanged.nbconvert.nbconvert.html') + os.makedirs('submitted/foo/ps1') + shutil.move('submitted-unchanged.ipynb', 'submitted/foo/ps1/p1.ipynb') + self._run_command('nbgrader autograde ps1 --db="{}" '.format(dbpath)) + self._run_command('nbgrader feedback ps1 --db="{}" '.format(dbpath)) + + assert os.path.exists('feedback/foo/ps1/p1.html')
0749c47bb280230ae5b1e2cda23773d3b10b2491
redis_check.py
redis_check.py
#!/usr/bin/env python3 import sys import redis import redis.exceptions host = sys.argv[1] host = host.strip('\r\n') port = 6379 timeout = 5 try: db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout) i = db.info() ver = i.get('redis_version') siz = db.dbsize() print('[+] {0}:{1} - {2}({3})'.format(host, port, ver, siz)) except redis.exceptions.ResponseError as e: print('[+] {0}:{1} - {2}'.format(host, port, e)) except redis.exceptions.ConnectionError: print('[-] {0}:{1} - Connection Error'.format(host, port)) except redis.exceptions.TimeoutError: print('[-] {0}:{1} - Timeout'.format(host, port)) except redis.exceptions.InvalidResponse: print('[-] {0}:{1} - Invalid Response'.format(host, port))
#!/usr/bin/env python3 import sys import redis import redis.exceptions host = sys.argv[1] host = host.strip('\r\n') port = 6379 timeout = 5 try: db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout) i = db.info() ver = i.get('redis_version') siz = db.dbsize() print('[+] {0}:{1}:{2}'.format(host, ver, siz)) except redis.exceptions.ResponseError as e: print('[+] {0}::{1}'.format(host, e)) except redis.exceptions.ConnectionError: print('[-] {0}::Connection Error'.format(host)) except redis.exceptions.TimeoutError: print('[-] {0}::Timeout'.format(host)) except redis.exceptions.InvalidResponse: print('[-] {0}::Invalid Response'.format(host))
Make output easier to parse with cli tools.
Make output easier to parse with cli tools.
Python
bsd-3-clause
averagesecurityguy/research
--- +++ @@ -15,16 +15,16 @@ ver = i.get('redis_version') siz = db.dbsize() - print('[+] {0}:{1} - {2}({3})'.format(host, port, ver, siz)) + print('[+] {0}:{1}:{2}'.format(host, ver, siz)) except redis.exceptions.ResponseError as e: - print('[+] {0}:{1} - {2}'.format(host, port, e)) + print('[+] {0}::{1}'.format(host, e)) except redis.exceptions.ConnectionError: - print('[-] {0}:{1} - Connection Error'.format(host, port)) + print('[-] {0}::Connection Error'.format(host)) except redis.exceptions.TimeoutError: - print('[-] {0}:{1} - Timeout'.format(host, port)) + print('[-] {0}::Timeout'.format(host)) except redis.exceptions.InvalidResponse: - print('[-] {0}:{1} - Invalid Response'.format(host, port)) + print('[-] {0}::Invalid Response'.format(host))
95a78f801a094861832d2a27fc69866f99b44af4
github_list_repos.py
github_list_repos.py
#!/usr/bin/env python """ List repositories on Github belonging to organisations, teams, etc """ # Technical Debt # -------------- # Known Bugs # ---------- import argparse import codetools import textwrap gh = codetools.github(authfile='~/.sq_github_token') # Argument Parsing # ---------------- parser = argparse.ArgumentParser( prog='github_list_repos', formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent(''' List repositories on Github using various criteria Examples: github_list_repos.py lsst '''), epilog='Part of codekit: https://github.com/lsst-sqre/sqre-codekit' ) parser.add_argument('organisation') parser.add_argument('--teams', action='store_true') parser.add_argument('--hide') opt = parser.parse_args() # Do Something # ------------ org = gh.organization(opt.organisation) for repo in org.iter_repos(): if not opt.teams: print repo.name else: teamnames = [t.name for t in repo.iter_teams()] if opt.hide: teamnames.remove(opt.hide) print repo.name + " : " + "\t".join(teamnames)
#!/usr/bin/env python """ List repositories on Github belonging to organisations, teams, etc """ # Technical Debt # -------------- # Known Bugs # ---------- import argparse import codetools import os import textwrap debug = os.getenv("DM_SQUARE_DEBUG") gh = codetools.github(authfile='~/.sq_github_token') # Argument Parsing # ---------------- parser = argparse.ArgumentParser( prog='github_list_repos', formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent(''' List repositories on Github using various criteria Examples: github_list_repos lsst github_list_repos --teams --hide 'Data Management' --hide 'Owners' lsst '''), epilog='Part of codekit: https://github.com/lsst-sqre/sqre-codekit' ) parser.add_argument('organisation') parser.add_argument('--teams', action='store_true', help='include team ownership info') parser.add_argument('--hide', action='append', help='hide a specific team from the output (implies --team)') opt = parser.parse_args() if opt.hide: opt.teams = True # Do Something # ------------ org = gh.organization(opt.organisation) for repo in org.iter_repos(): if not opt.teams: print repo.name else: teamnames = [t.name for t in repo.iter_teams() if t.name not in opt.hide] print repo.name.ljust(40) + " ".join(teamnames)
Allow multiple --hide options to be used
Allow multiple --hide options to be used Also: imply --team if --hide more pythonic
Python
mit
lsst-sqre/sqre-codekit,lsst-sqre/sqre-codekit
--- +++ @@ -12,7 +12,10 @@ import argparse import codetools +import os import textwrap + +debug = os.getenv("DM_SQUARE_DEBUG") gh = codetools.github(authfile='~/.sq_github_token') @@ -28,7 +31,9 @@ Examples: - github_list_repos.py lsst + github_list_repos lsst + + github_list_repos --teams --hide 'Data Management' --hide 'Owners' lsst '''), epilog='Part of codekit: https://github.com/lsst-sqre/sqre-codekit' @@ -36,11 +41,16 @@ parser.add_argument('organisation') -parser.add_argument('--teams', action='store_true') +parser.add_argument('--teams', action='store_true', + help='include team ownership info') -parser.add_argument('--hide') +parser.add_argument('--hide', action='append', + help='hide a specific team from the output (implies --team)') opt = parser.parse_args() + +if opt.hide: + opt.teams = True # Do Something # ------------ @@ -53,18 +63,5 @@ print repo.name else: - teamnames = [t.name for t in repo.iter_teams()] - - if opt.hide: - teamnames.remove(opt.hide) - - print repo.name + " : " + "\t".join(teamnames) - - - - - - - - - + teamnames = [t.name for t in repo.iter_teams() if t.name not in opt.hide] + print repo.name.ljust(40) + " ".join(teamnames)
8e53b65b5f28a02f8ee980b9f53a57e7cdd077bd
main.py
main.py
import places from character import Character import actions import options from multiple_choice import MultipleChoice def combat(character): """ takes in a character, returns outcome of fight """ return actions.Attack(character.person).get_outcome(character) def main(): """ The goal is to have the main function operate as follows: Set up the initial state Display the initial message Display the initial options Choose an action Get an outcome Display results of the outcomes Outcome changes game state """ character = Character() character.place = places.tavern choices = MultipleChoice() options.set_initial_actions(choices) print("\n---The St. George Game---\n") print("You are in a tavern. The local assassins hate you.") while character.alive and character.alone and not character.lose: action = choices.choose_action() if not character.threatened or action.combat_action: outcome = action.get_outcome(character) else: outcome = combat(character) if not character.alive: break outcome.execute() options.add_actions(choices, character, outcome) choices.generate_actions(character) if __name__ == "__main__": main()
import places from character import Character import actions import options from multiple_choice import MultipleChoice def main(): """ The goal is to have the main function operate as follows: Set up the initial state Display the initial message Display the initial options Choose an action Get an outcome Display results of the outcomes Outcome changes game state """ character = Character(place=places.tavern) choices = MultipleChoice() options.set_initial_actions(choices) print("\n---The St. George Game---\n") print("You are in a tavern. The local assassins hate you.") while character.alive and character.alone and not character.lose: action = choices.choose_action() if not character.threatened or action.combat_action: outcome = action.get_outcome(character) else: outcome = actions.Attack(character.person).get_outcome(character) outcome.execute() options.add_actions(choices, character, outcome) choices.generate_actions(character) if __name__ == "__main__": main()
Refactor combat code to be more concise
Refactor combat code to be more concise
Python
apache-2.0
SageBerg/St.GeorgeGame,SageBerg/St.GeorgeGame,SageBerg/St.GeorgeGame,SageBerg/St.GeorgeGame
--- +++ @@ -3,13 +3,6 @@ import actions import options from multiple_choice import MultipleChoice - - -def combat(character): - """ - takes in a character, returns outcome of fight - """ - return actions.Attack(character.person).get_outcome(character) def main(): @@ -23,8 +16,7 @@ Display results of the outcomes Outcome changes game state """ - character = Character() - character.place = places.tavern + character = Character(place=places.tavern) choices = MultipleChoice() options.set_initial_actions(choices) print("\n---The St. George Game---\n") @@ -34,9 +26,7 @@ if not character.threatened or action.combat_action: outcome = action.get_outcome(character) else: - outcome = combat(character) - if not character.alive: - break + outcome = actions.Attack(character.person).get_outcome(character) outcome.execute() options.add_actions(choices, character, outcome) choices.generate_actions(character)
75d6e88de0ed8f8cb081de15ce0d3949a78c9ded
efselab/build.py
efselab/build.py
#!/usr/bin/env python3 from distutils.core import setup, Extension MODULES_TO_BUILD = ["fasthash", "suc", "lemmatize"] for module in MODULES_TO_BUILD: setup( name=module, ext_modules=[ Extension( name=module, sources=['%s.c' % module], libraries=[], extra_compile_args=['-Wall', '-Wno-unused-function'], extra_link_args=[] ) ], script_args=['build_ext', '--inplace'] )
#!/usr/bin/env python3 from distutils.core import setup, Extension MODULES_TO_BUILD = ["fasthash", "suc", "lemmatize"] def main(): for module in MODULES_TO_BUILD: setup( name=module, ext_modules=[ Extension( name=module, sources=['%s.c' % module], libraries=[], extra_compile_args=['-Wall', '-Wno-unused-function'], extra_link_args=[] ) ], script_args=['build_ext', '--inplace'] ) if __name__ == '__main__': main()
Put module in method to enable calls from libraries.
Put module in method to enable calls from libraries. Former-commit-id: e614cec07ee71723be5b114163fe835961f6811c
Python
mit
EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger
--- +++ @@ -3,17 +3,21 @@ MODULES_TO_BUILD = ["fasthash", "suc", "lemmatize"] -for module in MODULES_TO_BUILD: - setup( - name=module, - ext_modules=[ - Extension( - name=module, - sources=['%s.c' % module], - libraries=[], - extra_compile_args=['-Wall', '-Wno-unused-function'], - extra_link_args=[] - ) - ], - script_args=['build_ext', '--inplace'] - ) +def main(): + for module in MODULES_TO_BUILD: + setup( + name=module, + ext_modules=[ + Extension( + name=module, + sources=['%s.c' % module], + libraries=[], + extra_compile_args=['-Wall', '-Wno-unused-function'], + extra_link_args=[] + ) + ], + script_args=['build_ext', '--inplace'] + ) + +if __name__ == '__main__': + main()
f4b0493edc949f6c31e120f8c005fc8ea99f9ede
markwiki/tests/test_factory.py
markwiki/tests/test_factory.py
# Copyright (c) 2014, Matt Layman '''Tests for the StorageFactory.''' import unittest from markwiki.exceptions import ConfigurationError from markwiki.storage.factory import UserStorageFactory from markwiki.storage.fs.user import FileUserStorage class InitializeException(Exception): '''An exception to ensure storage initialization was invoked.''' class FakeUserStorage(object): def __init__(self, config): '''Do nothing.''' def initialize(self): raise InitializeException() class TestUserStorageFactory(unittest.TestCase): def setUp(self): self.factory = UserStorageFactory() def test_get_storage(self): config = { 'MARKWIKI_HOME': 'nothing', 'STORAGE_TYPE': 'file' } storage = self.factory._get_storage(config) self.assertIsInstance(storage, FileUserStorage) def test_invalid_storage(self): config = {} self.assertRaises(ConfigurationError, self.factory.get_storage, config) def test_storage_initializes(self): config = {'STORAGE_TYPE': 'file'} types = {'file': FakeUserStorage} factory = UserStorageFactory(storage_types=types) self.assertRaises(InitializeException, factory.get_storage, config)
# Copyright (c) 2014, Matt Layman '''Tests for the StorageFactory.''' import unittest from markwiki.exceptions import ConfigurationError from markwiki.storage.factory import UserStorageFactory from markwiki.storage.fs.user import FileUserStorage class InitializeException(Exception): '''An exception to ensure storage initialization was invoked.''' class FakeUserStorage(object): def __init__(self, config): '''Do nothing.''' def initialize(self): raise InitializeException() class TestUserStorageFactory(unittest.TestCase): def setUp(self): self.factory = UserStorageFactory() def test_get_storage(self): config = { 'MARKWIKI_HOME': 'nothing', 'STORAGE_TYPE': 'file' } storage = self.factory._get_storage(config) self.assertTrue(isinstance(storage, FileUserStorage)) def test_invalid_storage(self): config = {} self.assertRaises(ConfigurationError, self.factory.get_storage, config) def test_storage_initializes(self): config = {'STORAGE_TYPE': 'file'} types = {'file': FakeUserStorage} factory = UserStorageFactory(storage_types=types) self.assertRaises(InitializeException, factory.get_storage, config)
Make the unit tests work with 2.6.
Make the unit tests work with 2.6.
Python
bsd-2-clause
mblayman/markwiki,mblayman/markwiki
--- +++ @@ -33,7 +33,7 @@ } storage = self.factory._get_storage(config) - self.assertIsInstance(storage, FileUserStorage) + self.assertTrue(isinstance(storage, FileUserStorage)) def test_invalid_storage(self): config = {}
1763b533bf33a8e450b4cf8d6f55d4ffaf6b2bea
tests/window/WINDOW_CAPTION.py
tests/window/WINDOW_CAPTION.py
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(200, 200) w2 = window.Window(200, 200) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main()
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(400, 200, resizable=True) w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main()
Make windows bigger in this test so the captions can be read.
Make windows bigger in this test so the captions can be read. Index: tests/window/WINDOW_CAPTION.py =================================================================== --- tests/window/WINDOW_CAPTION.py (revision 777) +++ tests/window/WINDOW_CAPTION.py (working copy) @@ -19,8 +19,8 @@ class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): - w1 = window.Window(200, 200) - w2 = window.Window(200, 200) + w1 = window.Window(400, 200, resizable=True) + w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?')
Python
bsd-3-clause
mammadori/pyglet,oktayacikalin/pyglet,oktayacikalin/pyglet,theblacklion/pyglet,mammadori/pyglet,oktayacikalin/pyglet,theblacklion/pyglet,oktayacikalin/pyglet,mammadori/pyglet,theblacklion/pyglet,theblacklion/pyglet,oktayacikalin/pyglet,mammadori/pyglet,theblacklion/pyglet
--- +++ @@ -19,8 +19,8 @@ class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): - w1 = window.Window(200, 200) - w2 = window.Window(200, 200) + w1 = window.Window(400, 200, resizable=True) + w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?')
486d7e76c76e79a44c0ed199724f0dc349e7539a
thelma/db/schema/tables/plannedworklistmember.py
thelma/db/schema/tables/plannedworklistmember.py
""" Planned worklist member table. """ from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import Table from sqlalchemy.schema import PrimaryKeyConstraint __docformat__ = 'reStructuredText en' __all__ = ['create_table'] def create_table(metadata, planned_worklist_tbl, planned_liquid_transfer_tbl): "Table factory." tbl = Table('planned_worklist_member', metadata, Column('planned_worklist_id', Integer, ForeignKey(planned_worklist_tbl.c.planned_worklist_id, onupdate='CASCADE', ondelete='CASCADE'), nullable=False), Column('planned_liquid_transfer_id', Integer, ForeignKey(planned_liquid_transfer_tbl.c.\ planned_liquid_transfer_id, onupdate='CASCADE', ondelete='CASCADE'), nullable=False), ) PrimaryKeyConstraint(tbl.c.planned_worklist_id, tbl.c.planned_liquid_transfer_id) return tbl
""" Planned worklist member table. """ from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import Table from sqlalchemy.schema import PrimaryKeyConstraint __docformat__ = 'reStructuredText en' __all__ = ['create_table'] def create_table(metadata, planned_worklist_tbl, planned_liquid_transfer_tbl): "Table factory." tbl = Table('planned_worklist_member', metadata, Column('planned_worklist_id', Integer, ForeignKey(planned_worklist_tbl.c.planned_worklist_id, onupdate='CASCADE', ondelete='CASCADE'), nullable=False), Column('planned_liquid_transfer_id', Integer, ForeignKey(planned_liquid_transfer_tbl.c.\ planned_liquid_transfer_id, onupdate='CASCADE', ondelete='NO ACTION'), nullable=False), ) PrimaryKeyConstraint(tbl.c.planned_worklist_id, tbl.c.planned_liquid_transfer_id) return tbl
Adjust deleting cascade for planned liquid transfers
Adjust deleting cascade for planned liquid transfers
Python
mit
helixyte/TheLMA,helixyte/TheLMA
--- +++ @@ -21,7 +21,7 @@ Column('planned_liquid_transfer_id', Integer, ForeignKey(planned_liquid_transfer_tbl.c.\ planned_liquid_transfer_id, - onupdate='CASCADE', ondelete='CASCADE'), + onupdate='CASCADE', ondelete='NO ACTION'), nullable=False), ) PrimaryKeyConstraint(tbl.c.planned_worklist_id,
10f72ab0428ddf51b47bc95b64b2a532c8e670a5
auth0/v2/authentication/enterprise.py
auth0/v2/authentication/enterprise.py
import requests class Enterprise(object): def __init__(self, domain): self.domain = domain def saml_login(self, client_id, connection): """ """ return requests.get( 'https://%s/samlp/%s' % (self.domain, client_id), params={'connection': connection} ) def saml_metadata(self,
from .base import AuthenticationBase class Enterprise(AuthenticationBase): def __init__(self, domain): self.domain = domain def saml_metadata(self, client_id): return self.get(url='https://%s/samlp/metadata/%s' % (self.domain, client_id)) def wsfed_metadata(self): url = 'https://%s/wsfed/FederationMetadata' \ '/2007-06/FederationMetadata.xml' return self.get(url=url % self.domain)
Refactor Enterprise class to use AuthenticationBase
Refactor Enterprise class to use AuthenticationBase
Python
mit
auth0/auth0-python,auth0/auth0-python
--- +++ @@ -1,18 +1,17 @@ -import requests +from .base import AuthenticationBase -class Enterprise(object): +class Enterprise(AuthenticationBase): def __init__(self, domain): self.domain = domain - def saml_login(self, client_id, connection): - """ - """ + def saml_metadata(self, client_id): + return self.get(url='https://%s/samlp/metadata/%s' % (self.domain, + client_id)) - return requests.get( - 'https://%s/samlp/%s' % (self.domain, client_id), - params={'connection': connection} - ) + def wsfed_metadata(self): + url = 'https://%s/wsfed/FederationMetadata' \ + '/2007-06/FederationMetadata.xml' - def saml_metadata(self, + return self.get(url=url % self.domain)
acec9342e392fed103e5d6b78470251d2cf535d6
timpani/webserver/webserver.py
timpani/webserver/webserver.py
import flask import os.path import datetime import urllib.parse from .. import configmanager from . import controllers FILE_LOCATION = os.path.abspath(os.path.dirname(__file__)) STATIC_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../static")) CONFIG_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../configs/")) configs = configmanager.ConfigManager(configPath = CONFIG_PATH) authConfig = configs["auth"] app = flask.Flask(__name__, static_folder = STATIC_PATH) app.secret_key = authConfig["signing_key"] app.register_blueprint(controllers.user.blueprint) app.register_blueprint(controllers.admin.blueprint)
import flask import os.path import datetime import urllib.parse from .. import database from .. import configmanager from . import controllers FILE_LOCATION = os.path.abspath(os.path.dirname(__file__)) STATIC_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../static")) CONFIG_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../configs/")) configs = configmanager.ConfigManager(configPath = CONFIG_PATH) authConfig = configs["auth"] app = flask.Flask(__name__, static_folder = STATIC_PATH) app.secret_key = authConfig["signing_key"] app.register_blueprint(controllers.user.blueprint) app.register_blueprint(controllers.admin.blueprint) @app.teardown_request def teardown_request(exception = None): databaseConnection = database.ConnectionManager.getConnection("main") databaseConnection.session.close()
Add teardown request instead of usesDatabase decorator
Add teardown request instead of usesDatabase decorator
Python
mit
ollien/Timpani,ollien/Timpani,ollien/Timpani
--- +++ @@ -2,6 +2,7 @@ import os.path import datetime import urllib.parse +from .. import database from .. import configmanager from . import controllers @@ -16,3 +17,8 @@ app.secret_key = authConfig["signing_key"] app.register_blueprint(controllers.user.blueprint) app.register_blueprint(controllers.admin.blueprint) + [email protected]_request +def teardown_request(exception = None): + databaseConnection = database.ConnectionManager.getConnection("main") + databaseConnection.session.close()
967ec17d15f07191e6d42fc122eb5e731605ad67
git_code_debt/repo_parser.py
git_code_debt/repo_parser.py
import collections import contextlib import shutil import subprocess import tempfile from util.iter import chunk_iter Commit = collections.namedtuple('Commit', ['sha', 'date', 'name']) class RepoParser(object): def __init__(self, git_repo, ref): self.git_repo = git_repo self.ref = ref self.tempdir = None @contextlib.contextmanager def repo_checked_out(self): assert not self.tempdir self.tempdir = tempfile.mkdtemp(suffix='temp-repo') try: subprocess.call( ['git', 'clone', self.git_repo, self.tempdir], stdout=None, ) subprocess.call( ['git', 'checkout', self.ref], cwd=self.tempdir, stdout=None, ) yield finally: shutil.rmtree(self.tempdir) self.tempdir = None def get_commit_shas(self, since=None): """Returns a list of Commit objects. Args: since - (optional) A timestamp to look from. """ assert self.tempdir cmd = ['git', 'log', self.ref, '--topo-order', '--format=%H%n%at%n%cN'] if since: cmd += ['--after={0}'.format(since)] output = subprocess.check_output( cmd, cwd=self.tempdir, ) commits = [] for sha, date, name in chunk_iter(output.splitlines(), 3): commits.append(Commit(sha, int(date), name)) return commits
import collections import contextlib import shutil import subprocess import tempfile from util.iter import chunk_iter Commit = collections.namedtuple('Commit', ['sha', 'date', 'name']) class RepoParser(object): def __init__(self, git_repo): self.git_repo = git_repo self.tempdir = None @contextlib.contextmanager def repo_checked_out(self): assert not self.tempdir self.tempdir = tempfile.mkdtemp(suffix='temp-repo') try: subprocess.check_call( ['git', 'clone', self.git_repo, self.tempdir], stdout=None, ) yield finally: shutil.rmtree(self.tempdir) self.tempdir = None def get_commit_shas(self, since=None): """Returns a list of Commit objects. Args: since - (optional) A timestamp to look from. """ assert self.tempdir cmd = ['git', 'log', 'master', '--first-parent', '--format=%H%n%at%n%cN'] if since: cmd += ['--after={0}'.format(since)] output = subprocess.check_output( cmd, cwd=self.tempdir, ) commits = [] for sha, date, name in chunk_iter(output.splitlines(), 3): commits.append(Commit(sha, int(date), name)) return commits
Change sha fetching to use --parent-only and removed ref parameter
Change sha fetching to use --parent-only and removed ref parameter
Python
mit
ucarion/git-code-debt,Yelp/git-code-debt,ucarion/git-code-debt,ucarion/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt
--- +++ @@ -11,9 +11,8 @@ class RepoParser(object): - def __init__(self, git_repo, ref): + def __init__(self, git_repo): self.git_repo = git_repo - self.ref = ref self.tempdir = None @contextlib.contextmanager @@ -21,13 +20,8 @@ assert not self.tempdir self.tempdir = tempfile.mkdtemp(suffix='temp-repo') try: - subprocess.call( + subprocess.check_call( ['git', 'clone', self.git_repo, self.tempdir], - stdout=None, - ) - subprocess.call( - ['git', 'checkout', self.ref], - cwd=self.tempdir, stdout=None, ) yield @@ -43,7 +37,7 @@ """ assert self.tempdir - cmd = ['git', 'log', self.ref, '--topo-order', '--format=%H%n%at%n%cN'] + cmd = ['git', 'log', 'master', '--first-parent', '--format=%H%n%at%n%cN'] if since: cmd += ['--after={0}'.format(since)]
a1583d181170302df72fc0a97e5db7f6300061b3
tests/__init__.py
tests/__init__.py
#
import os DATADIR = os.path.abspath('docs/data') FILES = ['test_uk.shp', 'test_uk.shx', 'test_uk.dbf', 'test_uk.prj'] def create_zipfile(zipfilename): import zipfile with zipfile.ZipFile(zipfilename, 'w') as zip: for filename in FILES: zip.write(os.path.join(DATADIR, filename), filename) def create_tarfile(tarfilename): import tarfile with tarfile.open(tarfilename, 'w') as tar: for filename in FILES: tar.add(os.path.join(DATADIR, filename), arcname='testing/%s' % filename) def create_jsonfile(jsonfilename): import json import fiona from fiona.crs import from_string from fiona.tool import crs_uri with fiona.collection(os.path.join(DATADIR, FILES[0]), 'r') as source: features = [feat for feat in source] crs = ' '.join('+%s=%s' % (k,v) for k,v in source.crs.items()) my_layer = {'type': 'FeatureCollection', 'features': features, 'crs': { 'type': 'name', 'properties': { 'name':crs_uri(from_string(crs))}}} with open(jsonfilename, 'w') as f: f.write(json.dumps(my_layer)) def setup(): """Setup function for nosetests to create test files if they do not exist """ zipfile = os.path.join(DATADIR, 'test_uk.zip') tarfile = os.path.join(DATADIR, 'test_uk.tar') jsonfile = os.path.join(DATADIR, 'test_uk.json') if not os.path.exists(zipfile): create_zipfile(zipfile) if not os.path.exists(tarfile): create_tarfile(tarfile) if not os.path.exists(jsonfile): create_jsonfile(jsonfile)
Create derived test data files if they do not exist when running nosetests
Create derived test data files if they do not exist when running nosetests
Python
bsd-3-clause
perrygeo/Fiona,rbuffat/Fiona,perrygeo/Fiona,johanvdw/Fiona,Toblerity/Fiona,rbuffat/Fiona,Toblerity/Fiona
--- +++ @@ -1 +1,45 @@ -# +import os + +DATADIR = os.path.abspath('docs/data') +FILES = ['test_uk.shp', 'test_uk.shx', 'test_uk.dbf', 'test_uk.prj'] + +def create_zipfile(zipfilename): + import zipfile + with zipfile.ZipFile(zipfilename, 'w') as zip: + for filename in FILES: + zip.write(os.path.join(DATADIR, filename), filename) + +def create_tarfile(tarfilename): + import tarfile + with tarfile.open(tarfilename, 'w') as tar: + for filename in FILES: + tar.add(os.path.join(DATADIR, filename), arcname='testing/%s' % filename) + +def create_jsonfile(jsonfilename): + import json + import fiona + from fiona.crs import from_string + from fiona.tool import crs_uri + with fiona.collection(os.path.join(DATADIR, FILES[0]), 'r') as source: + features = [feat for feat in source] + crs = ' '.join('+%s=%s' % (k,v) for k,v in source.crs.items()) + my_layer = {'type': 'FeatureCollection', + 'features': features, + 'crs': { 'type': 'name', + 'properties': { + 'name':crs_uri(from_string(crs))}}} + with open(jsonfilename, 'w') as f: + f.write(json.dumps(my_layer)) + +def setup(): + """Setup function for nosetests to create test files if they do not exist + """ + zipfile = os.path.join(DATADIR, 'test_uk.zip') + tarfile = os.path.join(DATADIR, 'test_uk.tar') + jsonfile = os.path.join(DATADIR, 'test_uk.json') + if not os.path.exists(zipfile): + create_zipfile(zipfile) + if not os.path.exists(tarfile): + create_tarfile(tarfile) + if not os.path.exists(jsonfile): + create_jsonfile(jsonfile)
822afb73e35d4f1651ee44e974dcc51deaacb361
tests/conftest.py
tests/conftest.py
from pathlib import Path import pytest from sqlalchemy import create_engine from testcontainers import PostgresContainer as _PostgresContainer tests_dir = Path(__file__).parents[0].resolve() test_schema_file = Path(tests_dir, 'data', 'test-schema.sql') class PostgresContainer(_PostgresContainer): POSTGRES_USER = 'alice' POSTGRES_DB = 'db1' @pytest.fixture(scope='session') def postgres_url(): postgres_container = PostgresContainer("postgres:latest") with postgres_container as postgres: yield postgres.get_connection_url() @pytest.fixture(scope='session') def engine(postgres_url): return create_engine(postgres_url) @pytest.fixture(scope='session') def schema(engine): with test_schema_file.open() as fp: engine.execute(fp.read()) @pytest.fixture def connection(engine, schema): with engine.connect() as conn: yield conn
from pathlib import Path import pytest from sqlalchemy import create_engine from testcontainers import PostgresContainer as _PostgresContainer tests_dir = Path(__file__).parents[0].resolve() test_schema_file = Path(tests_dir, 'data', 'test-schema.sql') class PostgresContainer(_PostgresContainer): POSTGRES_USER = 'alice' POSTGRES_DB = 'db1' @pytest.fixture(scope='session') def postgres_url(): postgres_container = PostgresContainer("postgres:latest") with postgres_container as postgres: yield postgres.get_connection_url() @pytest.fixture(scope='session') def engine(postgres_url): return create_engine(postgres_url) @pytest.fixture(scope='session') def pg_schema(engine): with test_schema_file.open() as fp: engine.execute(fp.read()) @pytest.fixture def connection(engine, pg_schema): with engine.connect() as conn: yield conn
Rename schema fixture to free up parameter name
Rename schema fixture to free up parameter name
Python
mit
RazerM/pg_grant,RazerM/pg_grant
--- +++ @@ -26,12 +26,12 @@ @pytest.fixture(scope='session') -def schema(engine): +def pg_schema(engine): with test_schema_file.open() as fp: engine.execute(fp.read()) @pytest.fixture -def connection(engine, schema): +def connection(engine, pg_schema): with engine.connect() as conn: yield conn
34031f2b16303bcff69a7b52ec3e85ce35103c96
src/hunter/const.py
src/hunter/const.py
import collections import os import site import sys from distutils.sysconfig import get_python_lib SITE_PACKAGES_PATHS = set() if hasattr(site, 'getsitepackages'): SITE_PACKAGES_PATHS.update(site.getsitepackages()) if hasattr(site, 'getusersitepackages'): SITE_PACKAGES_PATHS.add(site.getusersitepackages()) SITE_PACKAGES_PATHS.add(get_python_lib()) SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS) SYS_PREFIX_PATHS = set(( sys.prefix, sys.exec_prefix, os.path.dirname(os.__file__), os.path.dirname(collections.__file__), )) for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix': if hasattr(sys, prop): SYS_PREFIX_PATHS.add(getattr(sys, prop)) SYS_PREFIX_PATHS = tuple(SYS_PREFIX_PATHS)
import collections import os import site import sys from distutils.sysconfig import get_python_lib SITE_PACKAGES_PATHS = set() if hasattr(site, 'getsitepackages'): SITE_PACKAGES_PATHS.update(site.getsitepackages()) if hasattr(site, 'getusersitepackages'): SITE_PACKAGES_PATHS.add(site.getusersitepackages()) SITE_PACKAGES_PATHS.add(get_python_lib()) SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS) SYS_PREFIX_PATHS = { sys.prefix, sys.exec_prefix, os.path.dirname(os.__file__), os.path.dirname(collections.__file__), } for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix': if hasattr(sys, prop): SYS_PREFIX_PATHS.add(getattr(sys, prop)) SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
Sort by longest path (assuming stdlib stuff will be in the longest).
Sort by longest path (assuming stdlib stuff will be in the longest).
Python
bsd-2-clause
ionelmc/python-hunter
--- +++ @@ -12,13 +12,14 @@ SITE_PACKAGES_PATHS.add(get_python_lib()) SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS) -SYS_PREFIX_PATHS = set(( +SYS_PREFIX_PATHS = { sys.prefix, sys.exec_prefix, os.path.dirname(os.__file__), os.path.dirname(collections.__file__), -)) +} for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix': if hasattr(sys, prop): SYS_PREFIX_PATHS.add(getattr(sys, prop)) -SYS_PREFIX_PATHS = tuple(SYS_PREFIX_PATHS) + +SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
9d8e3b650d02537c0693a2a5ebe4b17ce1be24ae
rml/lattice.py
rml/lattice.py
class Lattice(object): def __init__(self, name): self.name = name self._elements = [] def __getitem__(self, i): return self._elements[i] def __len__(self): ''' Get the number of elements in the lattice ''' return len(self._elements) def __str__(self): print(self._elements) def get_length(self): ''' Get the length of the lattice in meters ''' total_length = 0 for e in self._elements: total_length += e.get_length() return total_length def add_element(self, element): ''' Add an element to the lattice # TODO: modify method to accept a set() arg ''' self._elements.append(element) def get_elements(self, family='*'): ''' Get all elements of a lattice from a specified family. If no family is specified, return all elements ''' if family == '*': return self._elements matched_elements = list() for element in self._elements: if family in element.families: matched_elements.append(element) return matched_elements
class Lattice(object): def __init__(self, name): self.name = name self._elements = [] def __getitem__(self, i): return self._elements[i] def __len__(self): ''' Get the number of elements in the lattice ''' return len(self._elements) def __str__(self): print(self._elements) def get_length(self): ''' Get the length of the lattice in meters ''' total_length = 0 for e in self._elements: total_length += e.get_length() return total_length def add_element(self, element): ''' Add an element to the lattice # TODO: modify method to accept a set() arg ''' self._elements.append(element) def get_elements(self, family='*'): ''' Get all elements of a lattice from a specified family. If no family is specified, return all elements ''' if family == '*': return self._elements matched_elements = list() for element in self._elements: if family in element.families: matched_elements.append(element) return matched_elements def get_all_families(self): families = set() for element in self._elements: for family in element.families: families.add(family) return families
Add method to get all families of currently loaded elements
Add method to get all families of currently loaded elements
Python
apache-2.0
willrogers/pml,willrogers/pml,razvanvasile/RML
--- +++ @@ -41,3 +41,11 @@ if family in element.families: matched_elements.append(element) return matched_elements + + def get_all_families(self): + families = set() + for element in self._elements: + for family in element.families: + families.add(family) + + return families
d1edcb2f59d96168e94ec748633221a2d5f95b99
colorise/color_tools.py
colorise/color_tools.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Functions for converting and comparing colors.""" import colorsys import math import operator def hls_to_rgb(hue, lightness, saturation): """Convert HLS (hue, lightness, saturation) values to RGB.""" return tuple(int(math.ceil(c * 255.)) for c in colorsys.hls_to_rgb(hue, lightness, saturation)) def hsv_to_rgb(hue, saturation, value): """Convert HSV (hue, saturation, value) values to RGB.""" return tuple(int(c * 255.) for c in colorsys.hsv_to_rgb(hue/360., saturation/100., value/100.)) def color_difference(rgb1, rgb2): """Return the sums of component differences between two colors.""" return sum(abs(i - j) for i, j in zip(rgb1, rgb2)) def color_distance(rgb1, rgb2): """Compute the Euclidian distance between two colors.""" r1, g1, b1 = rgb1 r2, g2, b2 = rgb2 return math.sqrt((r2 - r1)**2 + (g2 - g1)**2 + (b2 - b1)**2) def closest_color(rgb, clut): """Return the CLUT index of the closest RGB color to a given RGB tuple.""" # Generate a list of tuples of CLUT indices and the color difference value indexed_diffs = ((idx, color_difference(rgb, clut[idx])) for idx in clut) return min(indexed_diffs, key=operator.itemgetter(1))[0]
#!/usr/bin/env python # -*- coding: utf-8 -*- """Functions for converting and comparing colors.""" import colorsys import math import operator def hls_to_rgb(hue, lightness, saturation): """Convert HLS (hue, lightness, saturation) values to RGB.""" return tuple(int(math.ceil(c * 255.)) for c in colorsys.hls_to_rgb(hue, lightness, saturation)) def hsv_to_rgb(hue, saturation, value): """Convert HSV (hue, saturation, value) values to RGB.""" return tuple(int(c * 255.) for c in colorsys.hsv_to_rgb(hue/360., saturation/100., value/100.)) def color_difference(rgb1, rgb2): """Return the sums of component differences between two colors.""" return sum(abs(i - j) for i, j in zip(rgb1, rgb2)) def closest_color(rgb, clut): """Return the CLUT index of the closest RGB color to a given RGB tuple.""" # Generate a list of tuples of CLUT indices and the color difference value indexed_diffs = ((idx, color_difference(rgb, clut[idx])) for idx in clut) return min(indexed_diffs, key=operator.itemgetter(1))[0]
Remove unused color distance function
Remove unused color distance function
Python
bsd-3-clause
MisanthropicBit/colorise
--- +++ @@ -27,14 +27,6 @@ return sum(abs(i - j) for i, j in zip(rgb1, rgb2)) -def color_distance(rgb1, rgb2): - """Compute the Euclidian distance between two colors.""" - r1, g1, b1 = rgb1 - r2, g2, b2 = rgb2 - - return math.sqrt((r2 - r1)**2 + (g2 - g1)**2 + (b2 - b1)**2) - - def closest_color(rgb, clut): """Return the CLUT index of the closest RGB color to a given RGB tuple.""" # Generate a list of tuples of CLUT indices and the color difference value
2c0ff93e3ef5e6914a85e4fc3443f0432337854e
text_processor.py
text_processor.py
from urllib.request import urlopen def fetch_words(): with urlopen('http://sixty-north.com/c/t.txt') as story: story_words = [] word_list = '' for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(word) wordCursor = 0 print("Word Count", len(story_words)) while wordCursor < len(story_words): paragraphCursor = 0 while paragraphCursor < 6: if (wordCursor + paragraphCursor) == len(story_words): break word_list += story_words[wordCursor + paragraphCursor] + ' ' paragraphCursor += 1 wordCursor += paragraphCursor word_list += '\n' return word_list def print_words(word_list): print(word_list) if __name__ == '__main__': print(fetch_words())
from urllib.request import urlopen def fetch_words(): with urlopen('http://sixty-north.com/c/t.txt') as story: story_words = [] word_list = '' for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(word) wordCursor = 0 print("Word Count", len(story_words)) while wordCursor < len(story_words): paragraphCursor = 0 while paragraphCursor < 6: if (wordCursor + paragraphCursor) == len(story_words): break word_list += story_words[wordCursor + paragraphCursor] + ' ' paragraphCursor += 1 wordCursor += paragraphCursor word_list += '\n' return word_list def print_words(word_list): print(word_list) def main(): print(fetch_words()) if __name__ == '__main__': main()
Move main execution to function
Move main execution to function
Python
mit
kentoj/python-fundamentals
--- +++ @@ -26,5 +26,9 @@ def print_words(word_list): print(word_list) + +def main(): + print(fetch_words()) + if __name__ == '__main__': - print(fetch_words()) + main()
83ceca04758c6546c41d5bc7f96583d838f25e11
src/mmw/apps/user/backends.py
src/mmw/apps/user/backends.py
# -*- coding: utf-8 -*- from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.backends import BaseBackend from django.contrib.auth.models import User from apps.user.models import ItsiUser, ConcordUser class SSOAuthenticationBackend(BaseBackend): """ A custom authentication back-end for Single Sign On providers. Before we can call django.contrib.auth.login on an SSO user, we must first authenticate them. This must be done using a custom authentication back- end, which sets the backend attribute on the user model. This class should be instantiated with an SSO provider user model, such as ItsiUser or ConcordUser, before it can be used. """ def __init__(self, model, field): self.SSOUserModel = model self.SSOField = field def authenticate(self, sso_id=None): if sso_id is not None: try: query = {self.SSOField: sso_id} user = self.SSOUserModel.objects.get(**query).user return user except ObjectDoesNotExist: return None return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None class ItsiAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ItsiAuthenticationBackend, self).__init__( ItsiUser, 'itsi_id') class ConcordAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ConcordAuthenticationBackend, self).__init__( ConcordUser, 'concord_id')
# -*- coding: utf-8 -*- from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.backends import BaseBackend from django.contrib.auth.models import User from apps.user.models import ItsiUser, ConcordUser class SSOAuthenticationBackend(BaseBackend): """ A custom authentication back-end for Single Sign On providers. Before we can call django.contrib.auth.login on an SSO user, we must first authenticate them. This must be done using a custom authentication back- end, which sets the backend attribute on the user model. This class should be instantiated with an SSO provider user model, such as ItsiUser or ConcordUser, before it can be used. """ def __init__(self, model, field): self.SSOUserModel = model self.SSOField = field def authenticate(self, request=None, sso_id=None): if sso_id is not None: try: query = {self.SSOField: sso_id} user = self.SSOUserModel.objects.get(**query).user return user except ObjectDoesNotExist: return None return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None class ItsiAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ItsiAuthenticationBackend, self).__init__( ItsiUser, 'itsi_id') class ConcordAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ConcordAuthenticationBackend, self).__init__( ConcordUser, 'concord_id')
Add request parameter to backend.authenticate
Add request parameter to backend.authenticate Without this, the signature of our custom backend does not match that of the function call. This signature is tested in django.contrib.auth.authenticate here: https://github.com/django/django/blob/fdf209eab8949ddc345aa0212b349c79fc6fdebb/django/contrib/auth/__init__.py#L69 and `request` was added to that signature in Django 1.11 in https://github.com/django/django/commit/4b9330ccc04575f9e5126529ec355a450d12e77c. With this, the Concord users are authenticated correctly.
Python
apache-2.0
WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed
--- +++ @@ -21,7 +21,7 @@ self.SSOUserModel = model self.SSOField = field - def authenticate(self, sso_id=None): + def authenticate(self, request=None, sso_id=None): if sso_id is not None: try: query = {self.SSOField: sso_id}
e3919de815594c73c35c265380c66ef14a51acbd
__init__.py
__init__.py
import sys import marshal import os.path if not hasattr(sys, 'implementation'): raise ImportError('Python 3.3 or newer is required') PY_TAG = sys.implementation.cache_tag PY_VERSION = sys.hexversion if PY_TAG is None: # Never seen this to be true, but Python documentation # mentions that it's possible. raise ImportError('cannot load the bundle since module caching is disabled') __file__ = os.path.join(__path__[0], 'bundle', PY_TAG + '.dgbundle') try: with open(__file__, 'rb') as _fd: for _c in marshal.load(_fd): eval(_c) except IOError: raise ImportError('`{}.dgbundle` is inaccessible'.format(PY_TAG)) except Exception: raise ImportError('`{}.dgbundle` is corrupt'.format(PY_TAG))
import sys import marshal import os.path if not hasattr(sys, 'implementation'): raise ImportError('Python 3.3 or newer is required') if sys.implementation.cache_tag is None: raise ImportError('cannot load the bundle since module caching is disabled') PY_TAG = sys.implementation.cache_tag PY_VERSION = sys.hexversion BUNDLE_DIR = os.path.join(__path__[0], 'bundle') BUNDLE_FILE = os.path.join(BUNDLE_DIR, PY_TAG + '.dgbundle') if not os.path.exists(BUNDLE_FILE): raise ImportError('unsupported platform: {}'.format(PY_TAG)) with open(BUNDLE_FILE, 'rb') as _fd: for _c in marshal.load(_fd): eval(_c) del _c del _fd
Rewrite the initial bootstrapping mechanism.
Rewrite the initial bootstrapping mechanism.
Python
mit
pyos/dg
--- +++ @@ -6,21 +6,20 @@ if not hasattr(sys, 'implementation'): raise ImportError('Python 3.3 or newer is required') -PY_TAG = sys.implementation.cache_tag -PY_VERSION = sys.hexversion - -if PY_TAG is None: - # Never seen this to be true, but Python documentation - # mentions that it's possible. +if sys.implementation.cache_tag is None: raise ImportError('cannot load the bundle since module caching is disabled') -__file__ = os.path.join(__path__[0], 'bundle', PY_TAG + '.dgbundle') +PY_TAG = sys.implementation.cache_tag +PY_VERSION = sys.hexversion +BUNDLE_DIR = os.path.join(__path__[0], 'bundle') +BUNDLE_FILE = os.path.join(BUNDLE_DIR, PY_TAG + '.dgbundle') -try: - with open(__file__, 'rb') as _fd: - for _c in marshal.load(_fd): - eval(_c) -except IOError: - raise ImportError('`{}.dgbundle` is inaccessible'.format(PY_TAG)) -except Exception: - raise ImportError('`{}.dgbundle` is corrupt'.format(PY_TAG)) +if not os.path.exists(BUNDLE_FILE): + raise ImportError('unsupported platform: {}'.format(PY_TAG)) + +with open(BUNDLE_FILE, 'rb') as _fd: + for _c in marshal.load(_fd): + eval(_c) + +del _c +del _fd
638b8be8a07262803c087e796e40a51858c08983
__init__.py
__init__.py
from . import LayerView def getMetaData(): return { "name": "LayerView", "type": "View" } def register(app): return LayerView.LayerView()
from . import LayerView def getMetaData(): return { 'type': 'view', 'plugin': { "name": "Layer View" }, 'view': { 'name': 'Layers' } } def register(app): return LayerView.LayerView()
Update plugin metadata to the new format
Update plugin metadata to the new format
Python
agpl-3.0
totalretribution/Cura,markwal/Cura,quillford/Cura,DeskboxBrazil/Cura,lo0ol/Ultimaker-Cura,senttech/Cura,bq/Ultimaker-Cura,ad1217/Cura,fieldOfView/Cura,fieldOfView/Cura,DeskboxBrazil/Cura,Curahelper/Cura,Curahelper/Cura,hmflash/Cura,bq/Ultimaker-Cura,hmflash/Cura,markwal/Cura,quillford/Cura,derekhe/Cura,totalretribution/Cura,lo0ol/Ultimaker-Cura,ynotstartups/Wanhao,fxtentacle/Cura,fxtentacle/Cura,senttech/Cura,ynotstartups/Wanhao,derekhe/Cura,ad1217/Cura
--- +++ @@ -1,7 +1,15 @@ from . import LayerView def getMetaData(): - return { "name": "LayerView", "type": "View" } + return { + 'type': 'view', + 'plugin': { + "name": "Layer View" + }, + 'view': { + 'name': 'Layers' + } + } def register(app): return LayerView.LayerView()
badba5070ac40a70de2be47b6d58afd0364ed7fe
staticassets/views.py
staticassets/views.py
import mimetypes from django.http import HttpResponse, HttpResponseNotModified, Http404 from django.contrib.staticfiles.views import serve as staticfiles_serve from django.views.static import was_modified_since, http_date from staticassets import finder, settings def serve(request, path, **kwargs): mimetype, encoding = mimetypes.guess_type(path) if not mimetype in settings.MIMETYPES.values(): return staticfiles_serve(request, path, **kwargs) bundle = request.GET.get('bundle') in ('1', 't', 'true') asset = finder.find(path, bundle=bundle) if not asset: raise Http404("Static asset not found") # Respect the If-Modified-Since header. modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE') if not was_modified_since(modified_since, asset.mtime, asset.size): return HttpResponseNotModified(mimetype=asset.attributes.content_type) response = HttpResponse(asset.content, mimetype=asset.attributes.content_type) response['Last-Modified'] = http_date(asset.mtime) response['Content-Length'] = asset.size return response
import mimetypes from django.http import HttpResponse, HttpResponseNotModified, Http404 from django.contrib.staticfiles.views import serve as staticfiles_serve from django.views.static import was_modified_since, http_date from staticassets import finder, settings def serve(request, path, **kwargs): mimetype, encoding = mimetypes.guess_type(path) if not mimetype in settings.MIMETYPES.values(): return staticfiles_serve(request, path, **kwargs) bundle = request.GET.get('bundle') in ('1', 't', 'true') asset = finder.find(path, bundle=bundle) if not asset: raise Http404("Static asset not found") # Respect the If-Modified-Since header. modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE') if not was_modified_since(modified_since, asset.mtime, asset.size): return HttpResponseNotModified(content_type=asset.attributes.content_type) response = HttpResponse(asset.content, content_type=asset.attributes.content_type) response['Last-Modified'] = http_date(asset.mtime) response['Content-Length'] = asset.size return response
Use correct argument for content type in serve view
Use correct argument for content type in serve view
Python
mit
davidelias/django-staticassets,davidelias/django-staticassets,davidelias/django-staticassets
--- +++ @@ -20,9 +20,9 @@ # Respect the If-Modified-Since header. modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE') if not was_modified_since(modified_since, asset.mtime, asset.size): - return HttpResponseNotModified(mimetype=asset.attributes.content_type) + return HttpResponseNotModified(content_type=asset.attributes.content_type) - response = HttpResponse(asset.content, mimetype=asset.attributes.content_type) + response = HttpResponse(asset.content, content_type=asset.attributes.content_type) response['Last-Modified'] = http_date(asset.mtime) response['Content-Length'] = asset.size
d74e134ca63b7d3cd053d21168ca526a493999df
mysql.py
mysql.py
#!/usr/bin/env python # # igcollect - Mysql Status # # Copyright (c) 2016, InnoGames GmbH # import time import socket import MySQLdb hostname = socket.gethostname().replace(".", "_") now = str(int(time.time())) db = MySQLdb.connect(host = 'localhost', read_default_file='/etc/mysql/my.cnf') cur = db.cursor() # Check for global status cur.execute("show global status") for row in cur.fetchall(): if row[1].isdigit(): print "servers.{0}.software.mysql.status.{1} {2} {3}".format(hostname, row[0], row[1], now) cur.execute("show variables") for row in cur.fetchall(): if row[1].isdigit(): print "servers.{0}.software.mysql.variables.{1} {2} {3}".format(hostname, row[0], row[1], now)
#!/usr/bin/env python # # igcollect - Mysql Status # # Copyright (c) 2016, InnoGames GmbH # import time import socket import MySQLdb hostname = socket.gethostname().replace(".", "_") now = str(int(time.time())) db = MySQLdb.connect(user = 'root', host = 'localhost', read_default_file='/etc/mysql/my.cnf') cur = db.cursor() # Check for global status cur.execute("show global status") for row in cur.fetchall(): if row[1].isdigit(): print "servers.{0}.software.mysql.status.{1} {2} {3}".format(hostname, row[0], row[1], now) cur.execute("show variables") for row in cur.fetchall(): if row[1].isdigit(): print "servers.{0}.software.mysql.variables.{1} {2} {3}".format(hostname, row[0], row[1], now)
Use root user to connect
Use root user to connect
Python
mit
innogames/igcollect
--- +++ @@ -12,7 +12,7 @@ hostname = socket.gethostname().replace(".", "_") now = str(int(time.time())) -db = MySQLdb.connect(host = 'localhost', read_default_file='/etc/mysql/my.cnf') +db = MySQLdb.connect(user = 'root', host = 'localhost', read_default_file='/etc/mysql/my.cnf') cur = db.cursor() # Check for global status
297f42a2013428c2f6caefdf83735cc4a528e225
caching.py
caching.py
import os import cPickle as pickle try: DATA_DIR = os.path.dirname(os.path.realpath(__file__)) except: DATA_DIR = os.getcwd() cache_path = lambda name: os.path.join(DATA_DIR, '%s.cache' % name) def get_cache(name): return pickle.load(open(cache_path(name), 'r')) def save_cache(obj, name): pickle.dump(obj, open(cache_path(name), 'w'), protocol=-1)
import os import cPickle as pickle home_dir = os.path.expanduser('~') DATA_DIR = os.path.join(home_dir, '.tax_resolve') if not os.path.exists(DATA_DIR): try: os.mkdir(DATA_DIR) except: DATA_DIR = os.getcwd() cache_path = lambda name: os.path.join(DATA_DIR, '%s.cache' % name) def get_cache(name): return pickle.load(open(cache_path(name), 'r')) def save_cache(obj, name): pickle.dump(obj, open(cache_path(name), 'w'), protocol=-1)
Use user's local application data directory instead of the module path.
Use user's local application data directory instead of the module path.
Python
mit
bendmorris/tax_resolve
--- +++ @@ -1,9 +1,13 @@ import os import cPickle as pickle -try: DATA_DIR = os.path.dirname(os.path.realpath(__file__)) -except: DATA_DIR = os.getcwd() +home_dir = os.path.expanduser('~') +DATA_DIR = os.path.join(home_dir, '.tax_resolve') +if not os.path.exists(DATA_DIR): + try: + os.mkdir(DATA_DIR) + except: DATA_DIR = os.getcwd() cache_path = lambda name: os.path.join(DATA_DIR, '%s.cache' % name)
310cebbe1f4a4d92c8f181d7e4de9cc4f75a14dc
indra/assemblers/__init__.py
indra/assemblers/__init__.py
try: from pysb_assembler import PysbAssembler except ImportError: pass try: from graph_assembler import GraphAssembler except ImportError: pass try: from sif_assembler import SifAssembler except ImportError: pass try: from cx_assembler import CxAssembler except ImportError: pass try: from english_assembler import EnglishAssembler except ImportError: pass try: from sbgn_assembler import SBGNAssembler except ImportError: pass try: from index_card_assembler import IndexCardAssembler except ImportError: pass
try: from indra.assemblers.pysb_assembler import PysbAssembler except ImportError: pass try: from indra.assemblers.graph_assembler import GraphAssembler except ImportError: pass try: from indra.assemblers.sif_assembler import SifAssembler except ImportError: pass try: from indra.assemblers.cx_assembler import CxAssembler except ImportError: pass try: from indra.assemblers.english_assembler import EnglishAssembler except ImportError: pass try: from indra.assemblers.sbgn_assembler import SBGNAssembler except ImportError: pass try: from indra.assemblers.index_card_assembler import IndexCardAssembler except ImportError: pass
Update to absolute imports in assemblers
Update to absolute imports in assemblers
Python
bsd-2-clause
johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/indra,pvtodorov/indra,pvtodorov/indra,pvtodorov/indra,johnbachman/indra,bgyori/indra,jmuhlich/indra,pvtodorov/indra,sorgerlab/indra,jmuhlich/indra,johnbachman/belpy,johnbachman/belpy,sorgerlab/belpy,johnbachman/indra,sorgerlab/belpy,johnbachman/belpy,jmuhlich/indra,bgyori/indra,sorgerlab/indra
--- +++ @@ -1,28 +1,28 @@ try: - from pysb_assembler import PysbAssembler + from indra.assemblers.pysb_assembler import PysbAssembler except ImportError: pass try: - from graph_assembler import GraphAssembler + from indra.assemblers.graph_assembler import GraphAssembler except ImportError: pass try: - from sif_assembler import SifAssembler + from indra.assemblers.sif_assembler import SifAssembler except ImportError: pass try: - from cx_assembler import CxAssembler + from indra.assemblers.cx_assembler import CxAssembler except ImportError: pass try: - from english_assembler import EnglishAssembler + from indra.assemblers.english_assembler import EnglishAssembler except ImportError: pass try: - from sbgn_assembler import SBGNAssembler + from indra.assemblers.sbgn_assembler import SBGNAssembler except ImportError: pass try: - from index_card_assembler import IndexCardAssembler + from indra.assemblers.index_card_assembler import IndexCardAssembler except ImportError: pass
d150db290a72590e0f7cf9dae485bf98901bb2c2
web_ui/helpers.py
web_ui/helpers.py
from web_ui import app from flask import session from datetime import datetime # For calculating scores epoch = datetime.utcfromtimestamp(0) epoch_seconds = lambda dt: (dt - epoch).total_seconds() - 1356048000 def score(star_object): import random return random.random() * 100 - random.random() * 10 def get_active_persona(): from nucleus.models import Persona """ Return the currently active persona or 0 if there is no controlled persona. """ if 'active_persona' not in session or session['active_persona'] is None: """Activate first Persona with a private key""" controlled_persona = Persona.query.filter('sign_private != ""').first() if controlled_persona is None: return "" else: session['active_persona'] = controlled_persona.id return session['active_persona'] def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
from web_ui import app from flask import session from datetime import datetime # For calculating scores epoch = datetime.utcfromtimestamp(0) epoch_seconds = lambda dt: (dt - epoch).total_seconds() - 1356048000 def score(star_object): import random return random.random() * 100 - random.random() * 10 def get_active_persona(): from nucleus.models import Persona """ Return the currently active persona or 0 if there is no controlled persona. """ if 'active_persona' not in session or session['active_persona'] is None: """Activate first Persona with a private key""" controlled_persona = Persona.query.filter('sign_private != ""').first() if controlled_persona is None: return "" else: session['active_persona'] = controlled_persona.id return session['active_persona'] def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS'] def reset_userdata(): """Reset all userdata files""" import os for fileid in ["DATABASE", "SECRET_KEY_FILE", "PASSWORD_HASH_FILE"]: try: os.remove(app.config[fileid]) except OSError: app.logger.warning("RESET: {} not found".format(fileid)) else: app.logger.warning("RESET: {} deleted")
Add helper method for resetting user data
Add helper method for resetting user data
Python
apache-2.0
ciex/souma,ciex/souma,ciex/souma
--- +++ @@ -32,3 +32,16 @@ def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS'] + + +def reset_userdata(): + """Reset all userdata files""" + import os + + for fileid in ["DATABASE", "SECRET_KEY_FILE", "PASSWORD_HASH_FILE"]: + try: + os.remove(app.config[fileid]) + except OSError: + app.logger.warning("RESET: {} not found".format(fileid)) + else: + app.logger.warning("RESET: {} deleted")
312a742e31fb33b43a946da0016db201ca809799
seria/utils.py
seria/utils.py
# -*- coding: utf-8 -*- def str_to_num(i, exact_match=True): """ Attempts to convert a str to either an int or float """ # TODO: Cleanup -- this is really ugly if not isinstance(i, str): return i try: _ = int(i) if not exact_match: return _ elif str(_) == i: return _ else: pass except ValueError: pass try: _ = float(i) if not exact_match: return _ elif str(_) == i: return _ else: pass except ValueError: pass return i def set_defaults(kwargs, defaults): for k, v in defaults.items(): if k not in kwargs: kwargs[k] = v
# -*- coding: utf-8 -*- def str_to_num(i, exact_match=True): """ Attempts to convert a str to either an int or float """ # TODO: Cleanup -- this is really ugly if not isinstance(i, str): return i try: if not exact_match: return int(i) elif str(int(i)) == i: return int(i) elif str(float(i)) == i: return float(i) else: pass except ValueError: pass return i def set_defaults(kwargs, defaults): for k, v in defaults.items(): if k not in kwargs: kwargs[k] = v
Refactor str_to_num to be more concise
Refactor str_to_num to be more concise Functionally nothing has changed. We just need not try twice nor define the variable _ twice.
Python
mit
rtluckie/seria
--- +++ @@ -8,21 +8,12 @@ if not isinstance(i, str): return i try: - _ = int(i) if not exact_match: - return _ - elif str(_) == i: - return _ - else: - pass - except ValueError: - pass - try: - _ = float(i) - if not exact_match: - return _ - elif str(_) == i: - return _ + return int(i) + elif str(int(i)) == i: + return int(i) + elif str(float(i)) == i: + return float(i) else: pass except ValueError:
7180aba7ce183e64ef12e4fc384408036c2fe901
product_template_tree_prices/__init__.py
product_template_tree_prices/__init__.py
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in module root # directory ############################################################################## from . import product # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in module root # directory ############################################################################## # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
FIX produ template tree prices
FIX produ template tree prices
Python
agpl-3.0
ingadhoc/product,ingadhoc/product
--- +++ @@ -3,6 +3,5 @@ # For copyright and license notices, see __openerp__.py file in module root # directory ############################################################################## -from . import product # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
186a72b91798b11d13ea7f2538141f620b0787a8
tests/test_metrics.py
tests/test_metrics.py
import json from . import TestCase class MetricsTests(TestCase): def test_find(self): url = '/metrics/find' response = self.app.get(url) self.assertEqual(response.status_code, 400) response = self.app.get(url, query_string={'query': 'test'}) self.assertJSON(response, []) def test_expand(self): url = '/metrics/expand' response = self.app.get(url) self.assertJSON(response, {'errors': {'query': 'this parameter is required.'}}, status_code=400) response = self.app.get(url, query_string={'query': 'test'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.data.decode('utf-8')), {'results': []})
from . import TestCase class MetricsTests(TestCase): def test_find(self): url = '/metrics/find' response = self.app.get(url) self.assertEqual(response.status_code, 400) response = self.app.get(url, query_string={'query': 'test'}) self.assertJSON(response, []) def test_expand(self): url = '/metrics/expand' response = self.app.get(url) self.assertJSON(response, {'errors': {'query': 'this parameter is required.'}}, status_code=400) response = self.app.get(url, query_string={'query': 'test'}) self.assertJSON(response, {'results': []}) def test_noop(self): url = '/dashboard/find' response = self.app.get(url) self.assertJSON(response, {'dashboards': []}) url = '/dashboard/load/foo' response = self.app.get(url) self.assertJSON(response, {'error': "Dashboard 'foo' does not exist."}, status_code=404) url = '/events/get_data' response = self.app.get(url) self.assertJSON(response, [])
Add test for noop routes
Add test for noop routes
Python
apache-2.0
vladimir-smirnov-sociomantic/graphite-api,michaelrice/graphite-api,GeorgeJahad/graphite-api,vladimir-smirnov-sociomantic/graphite-api,michaelrice/graphite-api,alphapigger/graphite-api,raintank/graphite-api,hubrick/graphite-api,rackerlabs/graphite-api,Knewton/graphite-api,raintank/graphite-api,Knewton/graphite-api,bogus-py/graphite-api,cybem/graphite-api-iow,DaveBlooman/graphite-api,rackerlabs/graphite-api,brutasse/graphite-api,DaveBlooman/graphite-api,hubrick/graphite-api,raintank/graphite-api,tpeng/graphite-api,winguru/graphite-api,winguru/graphite-api,bogus-py/graphite-api,tpeng/graphite-api,cybem/graphite-api-iow,absalon-james/graphite-api,alphapigger/graphite-api,absalon-james/graphite-api,brutasse/graphite-api,GeorgeJahad/graphite-api
--- +++ @@ -1,5 +1,3 @@ -import json - from . import TestCase @@ -22,6 +20,18 @@ status_code=400) response = self.app.get(url, query_string={'query': 'test'}) - self.assertEqual(response.status_code, 200) - self.assertEqual(json.loads(response.data.decode('utf-8')), - {'results': []}) + self.assertJSON(response, {'results': []}) + + def test_noop(self): + url = '/dashboard/find' + response = self.app.get(url) + self.assertJSON(response, {'dashboards': []}) + + url = '/dashboard/load/foo' + response = self.app.get(url) + self.assertJSON(response, {'error': "Dashboard 'foo' does not exist."}, + status_code=404) + + url = '/events/get_data' + response = self.app.get(url) + self.assertJSON(response, [])
2410255e846c5fbd756ed97868299e1674c89467
flash_example.py
flash_example.py
from BlinkyTape import BlinkyTape bb = BlinkyTape('/dev/tty.usbmodemfa131') while True: for x in range(60): bb.sendPixel(10, 10, 10) bb.show() for x in range(60): bb.sendPixel(0, 0, 0) bb.show()
from BlinkyTape import BlinkyTape import time #bb = BlinkyTape('/dev/tty.usbmodemfa131') bb = BlinkyTape('COM8') while True: for x in range(60): bb.sendPixel(100, 100, 100) bb.show() time.sleep(.5) for x in range(60): bb.sendPixel(0, 0, 0) bb.show() time.sleep(.5)
Set it to flash black and white every second
Set it to flash black and white every second
Python
mit
Blinkinlabs/BlinkyTape_Python,jpsingleton/BlinkyTape_Python,railsagainstignorance/blinkytape
--- +++ @@ -1,13 +1,19 @@ from BlinkyTape import BlinkyTape +import time -bb = BlinkyTape('/dev/tty.usbmodemfa131') +#bb = BlinkyTape('/dev/tty.usbmodemfa131') +bb = BlinkyTape('COM8') while True: for x in range(60): - bb.sendPixel(10, 10, 10) + bb.sendPixel(100, 100, 100) bb.show() + + time.sleep(.5) for x in range(60): bb.sendPixel(0, 0, 0) bb.show() + + time.sleep(.5)
251a0d1b1df0fd857a86878ecb7e4c6bc26a93ef
paci/helpers/display_helper.py
paci/helpers/display_helper.py
"""Helper to output stuff""" from tabulate import tabulate def print_list(header, entries): """Prints out a list""" print(tabulate(entries, header, tablefmt="grid")) def std_input(text, default): """Get input or return default if none is given.""" return input(text.format(default)) or default
"""Helper to output stuff""" from tabulate import tabulate def print_list(header, entries): """Prints out a list""" print(tabulate(entries, header, tablefmt="grid")) def print_table(entries): """Prints out a table""" print(tabulate(entries, tablefmt="plain")) def std_input(text, default): """Get input or return default if none is given.""" return input(text.format(default)) or default
Add function to just print a simple table
Add function to just print a simple table
Python
mit
tradebyte/paci,tradebyte/paci
--- +++ @@ -8,6 +8,11 @@ print(tabulate(entries, header, tablefmt="grid")) +def print_table(entries): + """Prints out a table""" + print(tabulate(entries, tablefmt="plain")) + + def std_input(text, default): """Get input or return default if none is given.""" return input(text.format(default)) or default
bb768ef543469395ccbd0b2761442d9dcfa8e0c5
testanalyzer/analyze_repos.py
testanalyzer/analyze_repos.py
import pandas as pd import shutil import utils as u import validators from analyzer import Analyzer from git import Repo if __name__ == "__main__": repos = pd.read_pickle("data/test.pkl") for _, repo in repos.iterrows(): if not validators.url(repo["url"]): print("Error: Invalid URL.") exit(1) project_name = u.get_name_from_url(repo["url"]) print("Cloning {}...".format(project_name)) Repo.clone_from(repo["url"], project_name) print("Analyzing...") analyzer = Analyzer(project_name) code_counts, test_counts = analyzer.run() print(code_counts) print(test_counts) shutil.rmtree(project_name)
import pandas as pd import shutil import utils as u import validators from analyzer import Analyzer from git import Repo if __name__ == "__main__": repos = pd.read_pickle("data/repos.pkl") repos["code_lines"] = 0 repos["code_classes"] = 0 repos["code_functions"] = 0 repos["test_lines"] = 0 repos["test_classes"] = 0 repos["test_functions"] = 0 for i, repo in repos.iterrows(): if not validators.url(repo["url"]): print("Error: Invalid URL.") exit(1) project_name = u.get_name_from_url(repo["url"]) print("Cloning {}...".format(project_name)) Repo.clone_from(repo["url"], project_name) print("Analyzing...") analyzer = Analyzer(project_name) code_counts, test_counts = analyzer.run() repos.set_value(i, "code_lines", code_counts["line_count"]) repos.set_value(i, "code_classes", code_counts["class_count"]) repos.set_value(i, "code_functions", code_counts["function_count"]) repos.set_value(i, "test_lines", test_counts["line_count"]) repos.set_value(i, "test_classes", test_counts["class_count"]) repos.set_value(i, "test_functions", test_counts["function_count"]) shutil.rmtree(project_name) repos.to_pickle("data/dataset.pkl")
Update dataframe with counts and serialize
Update dataframe with counts and serialize
Python
mpl-2.0
CheriPai/TestAnalyzer,CheriPai/TestAnalyzer,CheriPai/TestAnalyzer
--- +++ @@ -7,9 +7,15 @@ if __name__ == "__main__": - repos = pd.read_pickle("data/test.pkl") + repos = pd.read_pickle("data/repos.pkl") + repos["code_lines"] = 0 + repos["code_classes"] = 0 + repos["code_functions"] = 0 + repos["test_lines"] = 0 + repos["test_classes"] = 0 + repos["test_functions"] = 0 - for _, repo in repos.iterrows(): + for i, repo in repos.iterrows(): if not validators.url(repo["url"]): print("Error: Invalid URL.") exit(1) @@ -21,7 +27,13 @@ print("Analyzing...") analyzer = Analyzer(project_name) code_counts, test_counts = analyzer.run() - print(code_counts) - print(test_counts) + repos.set_value(i, "code_lines", code_counts["line_count"]) + repos.set_value(i, "code_classes", code_counts["class_count"]) + repos.set_value(i, "code_functions", code_counts["function_count"]) + repos.set_value(i, "test_lines", test_counts["line_count"]) + repos.set_value(i, "test_classes", test_counts["class_count"]) + repos.set_value(i, "test_functions", test_counts["function_count"]) shutil.rmtree(project_name) + + repos.to_pickle("data/dataset.pkl")
05d498cc1f216ba722ce887b212ac5e750fb0c8d
tests/test_player_creation.py
tests/test_player_creation.py
from webtest import TestApp import dropshot def test_create_player(): app = TestApp(dropshot.app) params = {'username': 'chapmang', 'password': 'deadparrot', 'email': '[email protected]'} app.post('/players', params) res = app.get('/players') assert res.status_int == 200
from webtest import TestApp import dropshot def test_create_player(): app = TestApp(dropshot.app) params = {'username': 'chapmang', 'password': 'deadparrot', 'email': '[email protected]'} expected = {'count': 1, 'offset': 0, 'players': [ {'gamesPlayed': 0, 'username': 'chapmang'} ]} app.post('/players', params) res = app.get('/players') assert res.status_int == 200 assert res.content_type == 'application/json' assert res.json == expected
Make player creation test check for valid response.
Make player creation test check for valid response.
Python
mit
dropshot/dropshot-server
--- +++ @@ -1,14 +1,25 @@ from webtest import TestApp import dropshot + def test_create_player(): app = TestApp(dropshot.app) + params = {'username': 'chapmang', 'password': 'deadparrot', 'email': '[email protected]'} + + expected = {'count': 1, + 'offset': 0, + 'players': [ + {'gamesPlayed': 0, + 'username': 'chapmang'} + ]} app.post('/players', params) res = app.get('/players') assert res.status_int == 200 + assert res.content_type == 'application/json' + assert res.json == expected
fc904d8fd02cecfb2c3d69d6101caaab7b224e93
_bin/person_list_generator.py
_bin/person_list_generator.py
# Console outputs a person list import os import csv with open('tmp/person_list_input.csv') as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: print """ - role: {} name: {}""".format(row[0], row[1])
# Console outputs a person list import os import csv with open('tmp/person_list_input.csv') as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: stream = open('tmp/person_list_output.yml', 'a') stream.write( """ - role: {}\n name: {}\n""".format(row[0], row[1]) ) stream.close()
Make person list generator output to file
Make person list generator output to file The console was going beyond the terminal history limit for 14-15
Python
mit
johnathan99j/history-project,johnathan99j/history-project,newtheatre/history-project,newtheatre/history-project,johnathan99j/history-project,newtheatre/history-project,johnathan99j/history-project,newtheatre/history-project,johnathan99j/history-project,newtheatre/history-project
--- +++ @@ -6,6 +6,8 @@ with open('tmp/person_list_input.csv') as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: - print """ - role: {} - name: {}""".format(row[0], row[1]) + stream = open('tmp/person_list_output.yml', 'a') + stream.write( """ - role: {}\n name: {}\n""".format(row[0], row[1]) + ) + stream.close()
10b9d412c26b90bb86fe1abd04c3fe0f86826104
pelicanconf_with_pagination.py
pelicanconf_with_pagination.py
from pelicanconf import * # Over-ride so there is paging. DEFAULT_PAGINATION = 5
import sys # Hack for Travis, where local imports don't work. if '' not in sys.path: sys.path.insert(0, '') from pelicanconf import * # Over-ride so there is paging. DEFAULT_PAGINATION = 5
Fix Python import path on Travis.
Fix Python import path on Travis.
Python
apache-2.0
dhermes/bossylobster-blog,dhermes/bossylobster-blog,dhermes/bossylobster-blog,dhermes/bossylobster-blog,dhermes/bossylobster-blog,dhermes/bossylobster-blog,dhermes/bossylobster-blog
--- +++ @@ -1,3 +1,8 @@ +import sys +# Hack for Travis, where local imports don't work. +if '' not in sys.path: + sys.path.insert(0, '') + from pelicanconf import * # Over-ride so there is paging.
c6ecf6160664bc61cf6dc213af1f2fe3fd6a3617
editorsnotes/djotero/models.py
editorsnotes/djotero/models.py
from django.db import models from editorsnotes.main.models import Document import utils import json class ZoteroLink(models.Model): doc = models.OneToOneField(Document, related_name='_zotero_link') zotero_url = models.URLField() zotero_data = models.TextField(blank=True) date_information = models.TextField(blank=True) def __str__(self): return 'Zotero data: %s' % self.doc.__str__() def get_zotero_fields(self): z = json.loads(self.zotero_data) z['itemType'] = utils.type_map['readable'][z['itemType']] if self.date_information: date_parts = json.loads(self.date_information) for part in date_parts: z[part] = date_parts[part] if z['creators']: names = utils.resolve_names(z, 'facets') z.pop('creators') output = z.items() for name in names: for creator_type, creator_value in name.items(): output.append((creator_type, creator_value)) else: output = z.items() return output
from django.db import models from editorsnotes.main.models import Document import utils import json class ZoteroLink(models.Model): doc = models.OneToOneField(Document, related_name='_zotero_link') zotero_url = models.URLField(blank=True) zotero_data = models.TextField() date_information = models.TextField(blank=True) def __str__(self): return 'Zotero data: %s' % self.doc.__str__() def get_zotero_fields(self): z = json.loads(self.zotero_data) z['itemType'] = utils.type_map['readable'][z['itemType']] if self.date_information: date_parts = json.loads(self.date_information) for part in date_parts: z[part] = date_parts[part] if z['creators']: names = utils.resolve_names(z, 'facets') z.pop('creators') output = z.items() for name in names: for creator_type, creator_value in name.items(): output.append((creator_type, creator_value)) else: output = z.items() return output
Allow blank zotero url reference, but require zotero json data
Allow blank zotero url reference, but require zotero json data
Python
agpl-3.0
editorsnotes/editorsnotes,editorsnotes/editorsnotes
--- +++ @@ -5,8 +5,8 @@ class ZoteroLink(models.Model): doc = models.OneToOneField(Document, related_name='_zotero_link') - zotero_url = models.URLField() - zotero_data = models.TextField(blank=True) + zotero_url = models.URLField(blank=True) + zotero_data = models.TextField() date_information = models.TextField(blank=True) def __str__(self): return 'Zotero data: %s' % self.doc.__str__()
9fda3df6ae1f31af139c03eaf8b385746816f3b4
spec/helper.py
spec/helper.py
from pygametemplate import Game from example_view import ExampleView class TestGame(Game): """An altered Game class for testing purposes.""" def __init__(self, StartingView, resolution): super(TestGame, self).__init__(StartingView, resolution) def log(self, *error_message): """Altered log function which just raises errors.""" raise game = TestGame(ExampleView, (1280, 720))
from pygametemplate import Game from example_view import ExampleView class TestGame(Game): """An altered Game class for testing purposes.""" def __init__(self, StartingView, resolution): super(TestGame, self).__init__(StartingView, resolution) game = TestGame(ExampleView, (1280, 720))
Remove TestGame.log() method as log() isn't a method of Game anymore
Remove TestGame.log() method as log() isn't a method of Game anymore
Python
mit
AndyDeany/pygame-template
--- +++ @@ -7,9 +7,5 @@ def __init__(self, StartingView, resolution): super(TestGame, self).__init__(StartingView, resolution) - def log(self, *error_message): - """Altered log function which just raises errors.""" - raise - game = TestGame(ExampleView, (1280, 720))
36b8ec51dc6e1caca90db41d83d4dc21d70005a5
app/task.py
app/task.py
from mongoengine import Document, DateTimeField, EmailField, IntField, \ ReferenceField, StringField import datetime, enum class Priority(enum.IntEnum): LOW = 0, MIDDLE = 1, HIGH = 2 """ This defines the basic model for a Task as we want it to be stored in the MongoDB. """ class Task(Document): title = StringField(max_length=150, required=True) description = StringField(max_length=800, required=True) creator = EmailField(max_length=120, required=True) assigne = EmailField(max_length=120, required=True) created_at = DateTimeField(default=datetime.datetime.now, required=True) status = IntField(default=0, required=True) priority = IntField(default=Priority.LOW, required=True)
from mongoengine import Document, DateTimeField, EmailField, IntField, \ ReferenceField, StringField, ValidationError import datetime, enum, Exception from app import logger class Priority(enum.IntEnum): """ This defines the priority levels a Task can have. """ LOW = 0, MIDDLE = 1, HIGH = 2 class Status(enum.IntEnum): """ This defines statuses a Task can have. """ OPEN = 0 IN_PROGRESS = 1 CLOSED = 2 class Task(Document): """ This defines the basic model for a Task as we want it to be stored in the MongoDB. title (str): The title of the Task. description (str): A description of the Task. creator (str): The task creators email address. assigne (str): The email address of the person the Task is assigned to. created_at (datetime): The point in the time when the Task was created. status (Status): The current status of the Task. priority(Priority): The priority level of the Task. """ title = StringField(max_length=150, required=True) description = StringField(max_length=800, required=True) creator = EmailField(max_length=120, required=True) assigne = EmailField(max_length=120, required=True) created_at = DateTimeField(default=datetime.datetime.now, required=True) status = IntField(default=Status.OPEN, required=True) priority = IntField(default=Priority.LOW, required=True)
Add a Status enum and documentation
Add a Status enum and documentation
Python
mit
Zillolo/lazy-todo
--- +++ @@ -1,17 +1,38 @@ from mongoengine import Document, DateTimeField, EmailField, IntField, \ - ReferenceField, StringField -import datetime, enum + ReferenceField, StringField, ValidationError +import datetime, enum, Exception + +from app import logger class Priority(enum.IntEnum): + """ + This defines the priority levels a Task can have. + """ LOW = 0, MIDDLE = 1, HIGH = 2 -""" -This defines the basic model for a Task as we want it to be stored in the - MongoDB. -""" +class Status(enum.IntEnum): + """ + This defines statuses a Task can have. + """ + OPEN = 0 + IN_PROGRESS = 1 + CLOSED = 2 + class Task(Document): + """ + This defines the basic model for a Task as we want it to be stored in the + MongoDB. + + title (str): The title of the Task. + description (str): A description of the Task. + creator (str): The task creators email address. + assigne (str): The email address of the person the Task is assigned to. + created_at (datetime): The point in the time when the Task was created. + status (Status): The current status of the Task. + priority(Priority): The priority level of the Task. + """ title = StringField(max_length=150, required=True) description = StringField(max_length=800, required=True) @@ -20,5 +41,5 @@ created_at = DateTimeField(default=datetime.datetime.now, required=True) - status = IntField(default=0, required=True) + status = IntField(default=Status.OPEN, required=True) priority = IntField(default=Priority.LOW, required=True)
acf3819d433f3ebc3d3eed17c61f2542f7429f8e
trimesh/resources/__init__.py
trimesh/resources/__init__.py
import os import inspect # find the current absolute path using inspect _pwd = os.path.dirname( os.path.abspath( inspect.getfile( inspect.currentframe()))) def get_resource(name, decode=True): """ Get a resource from the trimesh/resources folder. Parameters ------------- name : str File path relative to `trimesh/resources` decode : bool Whether or not to decode result as UTF-8 Returns ------------- resource : str or bytes File data """ # get the resource using relative names with open(os.path.join(_pwd, name), 'rb') as f: resource = f.read() # make sure we return it as a string if asked if decode and hasattr(resource, 'decode'): return resource.decode('utf-8') return resource
import os # find the current absolute path to this directory _pwd = os.path.dirname(__file__) def get_resource(name, decode=True): """ Get a resource from the trimesh/resources folder. Parameters ------------- name : str File path relative to `trimesh/resources` decode : bool Whether or not to decode result as UTF-8 Returns ------------- resource : str or bytes File data """ # get the resource using relative names with open(os.path.join(_pwd, name), 'rb') as f: resource = f.read() # make sure we return it as a string if asked if decode and hasattr(resource, 'decode'): return resource.decode('utf-8') return resource
Use __file__ instead of inspect, for compatibility with frozen environments
RF: Use __file__ instead of inspect, for compatibility with frozen environments
Python
mit
mikedh/trimesh,mikedh/trimesh,dajusc/trimesh,mikedh/trimesh,mikedh/trimesh,dajusc/trimesh
--- +++ @@ -1,11 +1,8 @@ import os -import inspect -# find the current absolute path using inspect -_pwd = os.path.dirname( - os.path.abspath( - inspect.getfile( - inspect.currentframe()))) + +# find the current absolute path to this directory +_pwd = os.path.dirname(__file__) def get_resource(name, decode=True):
83dabc9fc1142e1575843d3a68c6241185543936
fabtastic/db/__init__.py
fabtastic/db/__init__.py
from django.conf import settings from fabtastic.db import util db_engine = util.get_db_setting('ENGINE') if 'postgresql_psycopg2' in db_engine: from fabtastic.db.postgres import * else: raise NotImplementedError("Fabtastic: DB engine '%s' is not supported" % db_engine)
from django.conf import settings from fabtastic.db import util db_engine = util.get_db_setting('ENGINE') if 'postgresql_psycopg2' in db_engine: from fabtastic.db.postgres import * else: print("Fabtastic WARNING: DB engine '%s' is not supported" % db_engine)
Make the warning for SQLite not being supported a print instead of an exception.
Make the warning for SQLite not being supported a print instead of an exception.
Python
bsd-3-clause
duointeractive/django-fabtastic
--- +++ @@ -6,4 +6,4 @@ if 'postgresql_psycopg2' in db_engine: from fabtastic.db.postgres import * else: - raise NotImplementedError("Fabtastic: DB engine '%s' is not supported" % db_engine) + print("Fabtastic WARNING: DB engine '%s' is not supported" % db_engine)
208f90497c7a6867f9aeece84b1161926ca1627b
nethud/nh_client.py
nethud/nh_client.py
""" An example client. Run simpleserv.py first before running this. """ import json from twisted.internet import reactor, protocol # a client protocol class EchoClient(protocol.Protocol): """Once connected, send a message, then print the result.""" def connectionMade(self): data = '{"register": {"email": "[email protected]", ' + \ '"username": "Qalthos",' + \ '"password": "password"}}' #~ data = '{"auth": {"username": "Qalthos", "password": "password"}}' print data self.transport.write(data) def dataReceived(self, data): "As soon as any data is received, write it back." print "Server said:", data def connectionLost(self, reason): print "Connection lost" class EchoFactory(protocol.ClientFactory): protocol = EchoClient def clientConnectionFailed(self, connector, reason): print "Connection failed - goodbye!" reactor.stop() def clientConnectionLost(self, connector, reason): print "Connection lost - goodbye!" reactor.stop() # this connects the protocol to a server runing on port 8000 def main(): f = EchoFactory() reactor.connectTCP("games-ng.csh.rit.edu", 53421, f) reactor.run() # this only runs if the module was *not* imported if __name__ == '__main__': main()
""" An example client. Run simpleserv.py first before running this. """ import json from twisted.internet import reactor, protocol # a client protocol class EchoClient(protocol.Protocol): """Once connected, send a message, then print the result.""" def connectionMade(self): self.send_message('auth', username='Qalthos', password='password') def dataReceived(self, data): "As soon as any data is received, write it back." print "Server said:", data def connectionLost(self, reason): print "Connection lost" # Nethack Protocol Wrapper def send_message(self, command, **kw): data = json.dumps(dict(command=kw)) self.transport.write(data) class EchoFactory(protocol.ClientFactory): protocol = EchoClient def clientConnectionFailed(self, connector, reason): print "Connection failed - goodbye!" reactor.stop() def clientConnectionLost(self, connector, reason): print "Connection lost - goodbye!" reactor.stop() # this connects the protocol to a server runing on port 8000 def main(): f = EchoFactory() reactor.connectTCP("games-ng.csh.rit.edu", 53421, f) reactor.run() # this only runs if the module was *not* imported if __name__ == '__main__': main()
Simplify nethack protocol to a single method.
Simplify nethack protocol to a single method.
Python
mit
ryansb/netHUD
--- +++ @@ -13,12 +13,7 @@ """Once connected, send a message, then print the result.""" def connectionMade(self): - data = '{"register": {"email": "[email protected]", ' + \ - '"username": "Qalthos",' + \ - '"password": "password"}}' - #~ data = '{"auth": {"username": "Qalthos", "password": "password"}}' - print data - self.transport.write(data) + self.send_message('auth', username='Qalthos', password='password') def dataReceived(self, data): "As soon as any data is received, write it back." @@ -26,6 +21,12 @@ def connectionLost(self, reason): print "Connection lost" + + # Nethack Protocol Wrapper + def send_message(self, command, **kw): + data = json.dumps(dict(command=kw)) + self.transport.write(data) + class EchoFactory(protocol.ClientFactory): protocol = EchoClient
881e693d16d12109c3ececffda61336b020c172a
portable_mds/tests/conftest.py
portable_mds/tests/conftest.py
import os import tempfile import shutil import tzlocal import pytest from ..mongoquery.mds import MDS @pytest.fixture(params=[1], scope='function') def mds_all(request): '''Provide a function level scoped FileStore instance talking to temporary database on localhost:27017 with both v0 and v1. ''' ver = request.param tempdirname = tempfile.mkdtemp() mds = MDS({'directory': tempdirname, 'timezone': tzlocal.get_localzone().zone}, version=ver) filenames = ['run_starts.json', 'run_stops.json', 'event_descriptors.json', 'events.json'] for fn in filenames: with open(os.path.join(tempdirname, fn), 'w') as f: f.write('[]') def delete_dm(): shutil.rmtree(tempdirname) request.addfinalizer(delete_dm) return mds
import os import tempfile import shutil import tzlocal import pytest import portable_mds.mongoquery.mds import portable_mds.sqlite.mds variations = [portable_mds.mongoquery.mds, portable_mds.sqlite.mds] @pytest.fixture(params=variations, scope='function') def mds_all(request): '''Provide a function level scoped FileStore instance talking to temporary database on localhost:27017 with both v0 and v1. ''' tempdirname = tempfile.mkdtemp() mds = request.param.MDS({'directory': tempdirname, 'timezone': tzlocal.get_localzone().zone}, version=1) filenames = ['run_starts.json', 'run_stops.json', 'event_descriptors.json', 'events.json'] for fn in filenames: with open(os.path.join(tempdirname, fn), 'w') as f: f.write('[]') def delete_dm(): shutil.rmtree(tempdirname) request.addfinalizer(delete_dm) return mds
Test sqlite and mongoquery variations.
TST: Test sqlite and mongoquery variations.
Python
bsd-3-clause
ericdill/databroker,ericdill/databroker
--- +++ @@ -3,19 +3,21 @@ import shutil import tzlocal import pytest -from ..mongoquery.mds import MDS +import portable_mds.mongoquery.mds +import portable_mds.sqlite.mds +variations = [portable_mds.mongoquery.mds, + portable_mds.sqlite.mds] [email protected](params=[1], scope='function') [email protected](params=variations, scope='function') def mds_all(request): '''Provide a function level scoped FileStore instance talking to temporary database on localhost:27017 with both v0 and v1. ''' - ver = request.param tempdirname = tempfile.mkdtemp() - mds = MDS({'directory': tempdirname, - 'timezone': tzlocal.get_localzone().zone}, version=ver) + mds = request.param.MDS({'directory': tempdirname, + 'timezone': tzlocal.get_localzone().zone}, version=1) filenames = ['run_starts.json', 'run_stops.json', 'event_descriptors.json', 'events.json'] for fn in filenames:
bd5c215c1c481f3811753412bca6b509bb00591a
me_api/app.py
me_api/app.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from flask import Flask from .middleware.me import me from .cache import cache def _register_module(app, module): if module == 'douban': from .middleware import douban app.register_blueprint(douban.douban_api) elif module == 'github': from .middleware import github app.register_blueprint(github.github_api) elif module == 'instagram': from .middleware import instagram app.register_blueprint(instagram.instagram_api) elif module == 'keybase': from .middleware import keybase app.register_blueprint(keybase.keybase_api) elif module == 'medium': from .middleware import medium app.register_blueprint(medium.medium_api) elif module == 'stackoverflow': from .middleware import stackoverflow app.register_blueprint(stackoverflow.stackoverflow_api) def create_app(config): app = Flask(__name__) app.config.from_object(config) cache.init_app(app) modules = config.modules['modules'] app.register_blueprint(me) for module in modules.keys(): _register_module(app, module) return app
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from flask import Flask from werkzeug.utils import import_string from me_api.middleware.me import me from me_api.cache import cache middlewares = { 'douban': 'me_api.middleware.douban:douban_api', 'github': 'me_api.middleware.github:github_api', 'instagram': 'me_api.middleware.instagram:instagram_api', 'keybase': 'me_api.middleware.keybase:keybase_api', 'medium': 'me_api.middleware.medium:medium_api', 'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api', } def create_app(config): app = Flask(__name__) app.config.from_object(config) cache.init_app(app) modules = config.modules['modules'] app.register_blueprint(me) for module in modules.keys(): blueprint = import_string(middlewares[module]) app.register_blueprint(blueprint) return app
Improve the way that import middlewares
Improve the way that import middlewares
Python
mit
lord63/me-api
--- +++ @@ -5,30 +5,20 @@ from flask import Flask +from werkzeug.utils import import_string -from .middleware.me import me -from .cache import cache +from me_api.middleware.me import me +from me_api.cache import cache -def _register_module(app, module): - if module == 'douban': - from .middleware import douban - app.register_blueprint(douban.douban_api) - elif module == 'github': - from .middleware import github - app.register_blueprint(github.github_api) - elif module == 'instagram': - from .middleware import instagram - app.register_blueprint(instagram.instagram_api) - elif module == 'keybase': - from .middleware import keybase - app.register_blueprint(keybase.keybase_api) - elif module == 'medium': - from .middleware import medium - app.register_blueprint(medium.medium_api) - elif module == 'stackoverflow': - from .middleware import stackoverflow - app.register_blueprint(stackoverflow.stackoverflow_api) +middlewares = { + 'douban': 'me_api.middleware.douban:douban_api', + 'github': 'me_api.middleware.github:github_api', + 'instagram': 'me_api.middleware.instagram:instagram_api', + 'keybase': 'me_api.middleware.keybase:keybase_api', + 'medium': 'me_api.middleware.medium:medium_api', + 'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api', +} def create_app(config): @@ -39,6 +29,7 @@ modules = config.modules['modules'] app.register_blueprint(me) for module in modules.keys(): - _register_module(app, module) + blueprint = import_string(middlewares[module]) + app.register_blueprint(blueprint) return app
af6f4868f4329fec75e43fe0cdcd1a7665c5238a
contentcuration/manage.py
contentcuration/manage.py
#!/usr/bin/env python import os import sys # Attach Python Cloud Debugger if __name__ == "__main__": #import warnings #warnings.filterwarnings('ignore', message=r'Module .*? is being added to sys\.path', append=True) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contentcuration.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys if __name__ == "__main__": #import warnings #warnings.filterwarnings('ignore', message=r'Module .*? is being added to sys\.path', append=True) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contentcuration.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Remove comment on attaching cloud debugger
Remove comment on attaching cloud debugger
Python
mit
DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation
--- +++ @@ -3,7 +3,6 @@ import sys -# Attach Python Cloud Debugger if __name__ == "__main__": #import warnings #warnings.filterwarnings('ignore', message=r'Module .*? is being added to sys\.path', append=True)
948b9987afa95d7a69bd61f3d8f9fea822323b01
wagtaildraftail/draft_text.py
wagtaildraftail/draft_text.py
from __future__ import absolute_import, unicode_literals import json from draftjs_exporter.html import HTML from wagtail.wagtailcore.rich_text import RichText from wagtaildraftail.settings import get_exporter_config class DraftText(RichText): def __init__(self, value, **kwargs): super(DraftText, self).__init__(value or '{}', **kwargs) self.exporter = HTML(get_exporter_config()) def get_json(self): return self.source def __html__(self): return self.exporter.render(json.loads(self.source))
from __future__ import absolute_import, unicode_literals import json from django.utils.functional import cached_property from draftjs_exporter.html import HTML from wagtail.wagtailcore.rich_text import RichText from wagtaildraftail.settings import get_exporter_config class DraftText(RichText): def __init__(self, value, **kwargs): super(DraftText, self).__init__(value or '{}', **kwargs) self.exporter = HTML(get_exporter_config()) def get_json(self): return self.source @cached_property def _html(self): return self.exporter.render(json.loads(self.source)) def __html__(self): return self._html def __eq__(self, other): return self.__html__() == other.__html__()
Implement equality check for DraftText nodes
Implement equality check for DraftText nodes Compare the (cached) rendered html of a node
Python
mit
gasman/wagtaildraftail,gasman/wagtaildraftail,gasman/wagtaildraftail,springload/wagtaildraftail,gasman/wagtaildraftail,springload/wagtaildraftail,springload/wagtaildraftail,springload/wagtaildraftail
--- +++ @@ -1,6 +1,8 @@ from __future__ import absolute_import, unicode_literals import json + +from django.utils.functional import cached_property from draftjs_exporter.html import HTML @@ -16,5 +18,12 @@ def get_json(self): return self.source + @cached_property + def _html(self): + return self.exporter.render(json.loads(self.source)) + def __html__(self): - return self.exporter.render(json.loads(self.source)) + return self._html + + def __eq__(self, other): + return self.__html__() == other.__html__()
8312ac22c444b895bab9f2a3707e4d4a7ccc40b2
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='synapse', version='0.1.0a1', description='Synapse Distributed Key-Value Hypergraph Analysis Framework', author='Invisigoth Kenshoto', author_email='[email protected]', url='https://github.com/vertexproject/synapse', license='Apache License 2.0', packages=find_packages(exclude=['scripts', ]), include_package_data=True, install_requires=[ 'pyOpenSSL>=16.2.0,<18.0.0', 'msgpack==0.5.1', 'xxhash>=1.0.1,<2.0.0', 'lmdb>=0.94,<1.0.0', 'tornado>=5.1,<6.0.0', 'regex>=2017.9.23', 'PyYAML>=3.13,<4.0', 'sphinx==1.7.0', ], classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Topic :: System :: Clustering', 'Topic :: System :: Distributed Computing', 'Topic :: System :: Software Distribution', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='synapse', version='0.1.0a1', description='Synapse Distributed Key-Value Hypergraph Analysis Framework', author='Invisigoth Kenshoto', author_email='[email protected]', url='https://github.com/vertexproject/synapse', license='Apache License 2.0', packages=find_packages(exclude=['scripts', ]), include_package_data=True, install_requires=[ 'pyOpenSSL>=16.2.0,<18.0.0', 'msgpack==0.5.1', 'xxhash>=1.0.1,<2.0.0', 'lmdb>=0.94,<1.0.0', 'tornado>=5.1,<6.0.0', 'regex>=2017.9.23', 'PyYAML>=3.13,<4.0', ], classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Topic :: System :: Clustering', 'Topic :: System :: Distributed Computing', 'Topic :: System :: Software Distribution', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], )
Remove sphinx pinning since 1.7.6 has been released.
Remove sphinx pinning since 1.7.6 has been released.
Python
apache-2.0
vertexproject/synapse,vertexproject/synapse,vertexproject/synapse
--- +++ @@ -24,7 +24,6 @@ 'tornado>=5.1,<6.0.0', 'regex>=2017.9.23', 'PyYAML>=3.13,<4.0', - 'sphinx==1.7.0', ], classifiers=[
c75749922c8be3b70bacd66a6b25b8e50faf7b76
setup.py
setup.py
# -*- coding: utf-8 -*- from setuptools import setup setup( name="myapp", version='0.0.1-dev', description='My Awesome Application', author='**INSERT_AUTHOR_NAME**', author_email='**INSERT_AUTHOR_EMAIL**', packages=[ 'myapp', 'myapp.blueprints' ], url='https://www.github.com/codehugger/myapp', include_package_data=True, zip_safe=False, install_requires=[ 'Flask==0.10.1', 'Flask-Migrate==1.2.0', 'Flask-SQLAlchemy==1.0', 'Flask-Script==0.6.7', 'Flask-Testing==0.4.1', 'Jinja2==2.7.2', 'Mako==0.9.1', 'MarkupSafe==0.19', 'SQLAlchemy==0.9.4', 'Werkzeug==0.9.4', 'alembic==0.6.4', 'itsdangerous==0.24', 'wsgiref==0.1.2', ] )
# -*- coding: utf-8 -*- from setuptools import setup setup( name="myapp", version='0.0.1-dev', description='My Awesome Application', author='**INSERT_AUTHOR_NAME**', author_email='**INSERT_AUTHOR_EMAIL**', packages=[ 'myapp', 'myapp.blueprints' ], url='https://www.github.com/codehugger/myapp', include_package_data=True, zip_safe=False, install_requires=[ 'Flask==1.0', 'Flask-Migrate==1.2.0', 'Flask-SQLAlchemy==1.0', 'Flask-Script==0.6.7', 'Flask-Testing==0.4.1', 'Jinja2==2.7.2', 'Mako==0.9.1', 'MarkupSafe==0.19', 'SQLAlchemy==0.9.4', 'Werkzeug==0.9.4', 'alembic==0.6.4', 'itsdangerous==0.24', 'wsgiref==0.1.2', ] )
Bump flask from 0.10.1 to 1.0
Bump flask from 0.10.1 to 1.0 Bumps [flask](https://github.com/pallets/flask) from 0.10.1 to 1.0. - [Release notes](https://github.com/pallets/flask/releases) - [Changelog](https://github.com/pallets/flask/blob/main/CHANGES.rst) - [Commits](https://github.com/pallets/flask/compare/0.10.1...1.0) --- updated-dependencies: - dependency-name: flask dependency-type: direct:production ... Signed-off-by: dependabot[bot] <[email protected]>
Python
bsd-3-clause
codehugger/Flask-Starter,codehugger/Flask-Starter
--- +++ @@ -17,7 +17,7 @@ include_package_data=True, zip_safe=False, install_requires=[ - 'Flask==0.10.1', + 'Flask==1.0', 'Flask-Migrate==1.2.0', 'Flask-SQLAlchemy==1.0', 'Flask-Script==0.6.7',
d2f7fce3cac7b2d742ab553325b3394092a0c8f8
setup.py
setup.py
from setuptools import setup setup( name='libgen', version='0.1', license='MIT', author='Adolfo Silva', author_email='[email protected]', url='https://github.com/adolfosilva/libgen.py', description='A script to download books from gen.lib.rus.ec', tests_requires=['pytest'], py_modules=['libgen'], entry_points={ 'console_scripts': ['libgen=libgen:main'], }, install_requires=['beautifulsoup4', 'tabulate', 'requests'] )
from setuptools import setup setup( name='libgen.py', version='0.1.0', license='MIT', author='Adolfo Silva', author_email='[email protected]', url='https://github.com/adolfosilva/libgen.py', description='A script to download books from gen.lib.rus.ec', classifiers=[ 'License :: OSI Approved :: MIT License', ], keywords='libgen', include_package_data=True, # include files listed in MANIFEST.in tests_requires=['pytest'], py_modules=['libgen'], entry_points={ 'console_scripts': ['libgen=libgen:main'], }, install_requires=['beautifulsoup4', 'tabulate', 'requests'] )
Change the name of the package
Change the name of the package Full length 'version'. Add 'classifiers' and 'keywords'. Include files in MANIFEST.in in the dist.
Python
mit
adolfosilva/libgen.py
--- +++ @@ -1,13 +1,18 @@ from setuptools import setup setup( - name='libgen', - version='0.1', + name='libgen.py', + version='0.1.0', license='MIT', author='Adolfo Silva', author_email='[email protected]', url='https://github.com/adolfosilva/libgen.py', description='A script to download books from gen.lib.rus.ec', + classifiers=[ + 'License :: OSI Approved :: MIT License', + ], + keywords='libgen', + include_package_data=True, # include files listed in MANIFEST.in tests_requires=['pytest'], py_modules=['libgen'], entry_points={
5c851ee3d333518829ce26bfc06fd1038e70651c
corehq/util/decorators.py
corehq/util/decorators.py
from functools import wraps import logging from corehq.util.global_request import get_request from dimagi.utils.logging import notify_exception def handle_uncaught_exceptions(mail_admins=True): """Decorator to log uncaught exceptions and prevent them from bubbling up the call chain. """ def _outer(fn): @wraps(fn) def _handle_exceptions(*args, **kwargs): try: return fn(*args, **kwargs) except Exception as e: msg = "Uncaught exception from {}.{}".format(fn.__module__, fn.__name__) if mail_admins: notify_exception(get_request(), msg) else: logging.exception(msg) return _handle_exceptions return _outer
from functools import wraps import logging from corehq.util.global_request import get_request from dimagi.utils.logging import notify_exception class ContextDecorator(object): """ A base class that enables a context manager to also be used as a decorator. https://docs.python.org/3/library/contextlib.html#contextlib.ContextDecorator """ def __call__(self, fn): @wraps(fn) def decorated(*args, **kwds): with self: return fn(*args, **kwds) return decorated def handle_uncaught_exceptions(mail_admins=True): """Decorator to log uncaught exceptions and prevent them from bubbling up the call chain. """ def _outer(fn): @wraps(fn) def _handle_exceptions(*args, **kwargs): try: return fn(*args, **kwargs) except Exception as e: msg = "Uncaught exception from {}.{}".format(fn.__module__, fn.__name__) if mail_admins: notify_exception(get_request(), msg) else: logging.exception(msg) return _handle_exceptions return _outer class change_log_level(ContextDecorator): """ Temporarily change the log level of a specific logger. Can be used as either a context manager or decorator. """ def __init__(self, logger, level): self.logger = logging.getLogger(logger) self.new_level = level self.original_level = self.logger.level def __enter__(self): self.logger.setLevel(self.new_level) def __exit__(self, exc_type, exc_val, exc_tb): self.logger.setLevel(self.original_level)
Add util to temporarily alter log levels
Add util to temporarily alter log levels Also backport ContextDecorator from python 3. I saw this just the other day and it looks like an awesome pattern, and a much clearer way to write decorators.
Python
bsd-3-clause
qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq
--- +++ @@ -2,6 +2,19 @@ import logging from corehq.util.global_request import get_request from dimagi.utils.logging import notify_exception + + +class ContextDecorator(object): + """ + A base class that enables a context manager to also be used as a decorator. + https://docs.python.org/3/library/contextlib.html#contextlib.ContextDecorator + """ + def __call__(self, fn): + @wraps(fn) + def decorated(*args, **kwds): + with self: + return fn(*args, **kwds) + return decorated def handle_uncaught_exceptions(mail_admins=True): @@ -22,3 +35,20 @@ return _handle_exceptions return _outer + + +class change_log_level(ContextDecorator): + """ + Temporarily change the log level of a specific logger. + Can be used as either a context manager or decorator. + """ + def __init__(self, logger, level): + self.logger = logging.getLogger(logger) + self.new_level = level + self.original_level = self.logger.level + + def __enter__(self): + self.logger.setLevel(self.new_level) + + def __exit__(self, exc_type, exc_val, exc_tb): + self.logger.setLevel(self.original_level)
a35d6f59d214741f554dde1363d2eac7addb04cb
crypto_enigma/__init__.py
crypto_enigma/__init__.py
#!/usr/bin/env python # encoding: utf8 """An Enigma machine simulator with rich textual display functionality.""" from ._version import __version__, __author__ #__all__ = ['machine', 'components'] from .components import * from .machine import *
#!/usr/bin/env python # encoding: utf8 """An Enigma machine simulator with rich textual display functionality. Limitations ~~~~~~~~~~~ Note that the correct display of some characters used to represent components (thin Naval rotors) assumes support for Unicode, while some aspects of the display of machine state depend on support for combining Unicode. This is a `known limitation <https://github.com/orome/crypto-enigma-py/issues/1>`__ that will be addressed in a future release. Note also that at the start of any scripts that use this package, you should .. parsed-literal:: from __future__ import unicode_literals before any code that uses the API, or confiure IPython (in `ipython_config.py`) with .. parsed-literal:: c.InteractiveShellApp.exec_lines += ["from __future__ import unicode_literals"] or explicitly suppply Unicode strings (e.g., as in many of the examples here with :code:`u'TESTING'`). """ from ._version import __version__, __author__ #__all__ = ['machine', 'components'] from .components import * from .machine import *
Add limitations to package documentation
Add limitations to package documentation
Python
bsd-3-clause
orome/crypto-enigma-py
--- +++ @@ -1,7 +1,33 @@ #!/usr/bin/env python # encoding: utf8 -"""An Enigma machine simulator with rich textual display functionality.""" +"""An Enigma machine simulator with rich textual display functionality. + +Limitations +~~~~~~~~~~~ + +Note that the correct display of some characters used to represent +components (thin Naval rotors) assumes support for Unicode, while some +aspects of the display of machine state depend on support for combining +Unicode. This is a `known +limitation <https://github.com/orome/crypto-enigma-py/issues/1>`__ that +will be addressed in a future release. + +Note also that at the start of any scripts that use this package, you should + +.. parsed-literal:: + + from __future__ import unicode_literals + +before any code that uses the API, or confiure IPython (in `ipython_config.py`) with + +.. parsed-literal:: + + c.InteractiveShellApp.exec_lines += ["from __future__ import unicode_literals"] + +or explicitly suppply Unicode strings (e.g., as in many of the examples here with :code:`u'TESTING'`). + +""" from ._version import __version__, __author__ #__all__ = ['machine', 'components']
08291f3948108da15b9832c495fade04cf2e22c4
tests/tests.py
tests/tests.py
#!/usr/bin/env python3 from selenium import webdriver import unittest class AdminPageTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_visit_admin_page(self): # Visit admin page self.browser.get('http://localhost:8000/admin') # Check page title self.assertIn('Django site admin', self.browser.title) class API_fetch_tests(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_fetch_Ingredient_JSON(self): pass def test_fetch_Drink_JSON(self): pass if __name__ == '__main__': print('test') unittest.main()
#!/usr/bin/env python3 from selenium import webdriver import unittest class AdminPageTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_visit_admin_page(self): # Visit admin page self.browser.get('http://localhost:8000/admin') # Check page title self.assertIn('Django site admin', self.browser.title) class API_fetch_tests(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_fetch_Ingredient_JSON(self): pass def test_fetch_Drink_JSON(self): pass class ReactAppTests(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_fetch_index(self): self.browser.get('http://localhost:8000/index') self.assertIn('Cocktails', self.browser.title) if __name__ == '__main__': print('test') unittest.main()
Add test to check title of index
Add test to check title of index
Python
mit
jake-jake-jake/cocktails,jake-jake-jake/cocktails,jake-jake-jake/cocktails,jake-jake-jake/cocktails
--- +++ @@ -19,6 +19,7 @@ # Check page title self.assertIn('Django site admin', self.browser.title) + class API_fetch_tests(unittest.TestCase): def setUp(self): @@ -34,6 +35,18 @@ pass +class ReactAppTests(unittest.TestCase): + + def setUp(self): + self.browser = webdriver.Firefox() + + def tearDown(self): + self.browser.quit() + + def test_fetch_index(self): + self.browser.get('http://localhost:8000/index') + self.assertIn('Cocktails', self.browser.title) + if __name__ == '__main__': print('test') unittest.main()
44520918dc0fad40f3afcfc2cdfde6f3208543cd
garden_lighting/MCP23017/raspberry.py
garden_lighting/MCP23017/raspberry.py
import time import os import wiringpi from garden_lighting.MCP23017.MCP23017 import MCP23017 class RaspberryMCP23017(MCP23017): def __init__(self, dev_addr, rst_pin=0xFF, i2cport=1): super().__init__(dev_addr, rst_pin, i2cport) def initDevice(self): ''' Does a reset to put all registers in initial state ''' os.system("gpio export " + str(self.RstPin) + " out") # Set pin numbering mode # We don't need performance, don't want root and don't want to interfere with # other wiringpi instances -> sysfspy wiringpi.wiringPiSetupSys() # Define the reset pin as output wiringpi.pinMode(self.RstPin, wiringpi.GPIO.OUTPUT) # Create a reset impulse wiringpi.digitalWrite(self.RstPin, wiringpi.GPIO.LOW) # wait for 50 ms time.sleep(.050) wiringpi.digitalWrite(self.RstPin, wiringpi.GPIO.HIGH)
import time import wiringpi from garden_lighting.MCP23017.MCP23017 import MCP23017 class RaspberryMCP23017(MCP23017): def __init__(self, dev_addr, rst_pin=0xFF, i2cport=1): super().__init__(dev_addr, rst_pin, i2cport) def initDevice(self): ''' Does a reset to put all registers in initial state ''' # Set pin numbering mode # wiringPiSetupSys() did not work because pins were low after booting and running the write commands # This requires root! wiringpi.wiringPiSetupGpio() # Define the reset pin as output wiringpi.pinMode(self.RstPin, wiringpi.GPIO.OUTPUT) # Create a reset impulse wiringpi.digitalWrite(self.RstPin, wiringpi.GPIO.LOW) # wait for 50 ms time.sleep(.050) wiringpi.digitalWrite(self.RstPin, wiringpi.GPIO.HIGH)
Use wiringPiSetupGpio, which required root. With wiringPiSetupSys some gpios stayed on low after boot.
Use wiringPiSetupGpio, which required root. With wiringPiSetupSys some gpios stayed on low after boot.
Python
mit
ammannbros/garden-lighting,ammannbros/garden-lighting,ammannbros/garden-lighting,ammannbros/garden-lighting
--- +++ @@ -1,5 +1,4 @@ import time -import os import wiringpi from garden_lighting.MCP23017.MCP23017 import MCP23017 @@ -13,11 +12,10 @@ Does a reset to put all registers in initial state ''' - os.system("gpio export " + str(self.RstPin) + " out") # Set pin numbering mode - # We don't need performance, don't want root and don't want to interfere with - # other wiringpi instances -> sysfspy - wiringpi.wiringPiSetupSys() + # wiringPiSetupSys() did not work because pins were low after booting and running the write commands + # This requires root! + wiringpi.wiringPiSetupGpio() # Define the reset pin as output wiringpi.pinMode(self.RstPin, wiringpi.GPIO.OUTPUT)
f30a923b881e908fa607e276de1d152d803248f1
pgpdump/__main__.py
pgpdump/__main__.py
import sys from . import BinaryData for filename in sys.argv[1:]: with open(filename) as infile: data = BinaryData(infile.read()) for packet in data.packets(): print hex(packet.key_id), packet.creation_date
import sys import cProfile from . import AsciiData, BinaryData def parsefile(name): with open(name) as infile: if name.endswith('.asc'): data = AsciiData(infile.read()) else: data = BinaryData(infile.read()) counter = 0 for packet in data.packets(): counter += 1 print counter def main(): for filename in sys.argv[1:]: parsefile(filename) if __name__ == '__main__': cProfile.run('main()', 'main.profile')
Update main to run a profiler
Update main to run a profiler Signed-off-by: Dan McGee <[email protected]>
Python
bsd-3-clause
toofishes/python-pgpdump
--- +++ @@ -1,9 +1,22 @@ import sys +import cProfile -from . import BinaryData +from . import AsciiData, BinaryData -for filename in sys.argv[1:]: - with open(filename) as infile: - data = BinaryData(infile.read()) - for packet in data.packets(): - print hex(packet.key_id), packet.creation_date +def parsefile(name): + with open(name) as infile: + if name.endswith('.asc'): + data = AsciiData(infile.read()) + else: + data = BinaryData(infile.read()) + counter = 0 + for packet in data.packets(): + counter += 1 + print counter + +def main(): + for filename in sys.argv[1:]: + parsefile(filename) + +if __name__ == '__main__': + cProfile.run('main()', 'main.profile')
fddc7e09bcebf9b4875906ad03e58699237b13be
src/nodeconductor_assembly_waldur/packages/filters.py
src/nodeconductor_assembly_waldur/packages/filters.py
import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.PackageTemplate fields = ('name', 'settings_uuid',) class OpenStackPackageFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') customer = UUIDFilter(name='tenant__service_project_link__project__customer') project = UUIDFilter(name='tenant__service_project_link__project') class Meta(object): model = models.OpenStackPackage fields = ('name', 'customer', 'project')
import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.PackageTemplate fields = ('name', 'settings_uuid',) class OpenStackPackageFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') customer = UUIDFilter(name='tenant__service_project_link__project__customer__uuid') project = UUIDFilter(name='tenant__service_project_link__project__uuid') tenant = UUIDFilter(name='tenant__uuid') class Meta(object): model = models.OpenStackPackage fields = ('name', 'customer', 'project', 'tenant')
Enable filtering OpenStack package by tenant.
Enable filtering OpenStack package by tenant.
Python
mit
opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind
--- +++ @@ -16,9 +16,10 @@ class OpenStackPackageFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') - customer = UUIDFilter(name='tenant__service_project_link__project__customer') - project = UUIDFilter(name='tenant__service_project_link__project') + customer = UUIDFilter(name='tenant__service_project_link__project__customer__uuid') + project = UUIDFilter(name='tenant__service_project_link__project__uuid') + tenant = UUIDFilter(name='tenant__uuid') class Meta(object): model = models.OpenStackPackage - fields = ('name', 'customer', 'project') + fields = ('name', 'customer', 'project', 'tenant')
f5d4f543cc7265433bf6040335b2f6d592b52b91
lmod/__init__.py
lmod/__init__.py
from functools import partial from os import environ from subprocess import Popen, PIPE LMOD_SYSTEM_NAME = environ.get('LMOD_SYSTEM_NAME', '') def module(command, *args): cmd = (environ['LMOD_CMD'], 'python', '--terse', command) result = Popen(cmd + args, stdout=PIPE, stderr=PIPE) if command in ('load', 'unload', 'restore', 'save'): exec(result.stdout.read()) return result.stderr.read().decode() def avail(): string = module('avail') modules = [] for entry in string.split(): if not (entry.startswith('/') or entry.endswith('/')): modules.append(entry) return modules def list(): string = module('list').strip() if string != "No modules loaded": return string.split() return [] def savelist(system=LMOD_SYSTEM_NAME): names = module('savelist').split() if system: suffix = '.{}'.format(system) n = len(suffix) names = [name[:-n] for name in names if name.endswith(suffix)] return names show = partial(module, 'show') load = partial(module, 'load') unload = partial(module, 'unload') restore = partial(module, 'restore') save = partial(module, 'save')
import os # require by lmod output evaluated by exec() from functools import partial from os import environ from subprocess import Popen, PIPE LMOD_SYSTEM_NAME = environ.get('LMOD_SYSTEM_NAME', '') def module(command, *args): cmd = (environ['LMOD_CMD'], 'python', '--terse', command) result = Popen(cmd + args, stdout=PIPE, stderr=PIPE) if command in ('load', 'unload', 'restore', 'save'): exec(result.stdout.read()) return result.stderr.read().decode() def avail(): string = module('avail') modules = [] for entry in string.split(): if not (entry.startswith('/') or entry.endswith('/')): modules.append(entry) return modules def list(): string = module('list').strip() if string != "No modules loaded": return string.split() return [] def savelist(system=LMOD_SYSTEM_NAME): names = module('savelist').split() if system: suffix = '.{}'.format(system) n = len(suffix) names = [name[:-n] for name in names if name.endswith(suffix)] return names show = partial(module, 'show') load = partial(module, 'load') unload = partial(module, 'unload') restore = partial(module, 'restore') save = partial(module, 'save')
Add import os in lmod to fix regression
Add import os in lmod to fix regression
Python
mit
cmd-ntrf/jupyter-lmod,cmd-ntrf/jupyter-lmod,cmd-ntrf/jupyter-lmod
--- +++ @@ -1,3 +1,5 @@ +import os # require by lmod output evaluated by exec() + from functools import partial from os import environ from subprocess import Popen, PIPE
5d7f2f84600abcede94a0aaee087ef299cf740a6
farmers_api/farmers/views.py
farmers_api/farmers/views.py
from rest_framework import viewsets from .models import Farmer from .serializers import FarmerSerializer class FarmerViewSet(viewsets.ReadOnlyModelViewSet): queryset = Farmer.objects.all() serializer_class = FarmerSerializer
from rest_framework import viewsets from .models import Farmer from .serializers import FarmerSerializer class FarmerViewSet(viewsets.ReadOnlyModelViewSet): queryset = Farmer.objects.all() serializer_class = FarmerSerializer filter_fields = ('town',)
Add filter on the town field on the Farmer model
Add filter on the town field on the Farmer model
Python
bsd-2-clause
tm-kn/farmers-api
--- +++ @@ -7,3 +7,4 @@ class FarmerViewSet(viewsets.ReadOnlyModelViewSet): queryset = Farmer.objects.all() serializer_class = FarmerSerializer + filter_fields = ('town',)
833ed3352c2e40923c167ddb41edba17db292bb7
salt/returners/mongo_return.py
salt/returners/mongo_return.py
''' Return data to a mongodb server This is the default interface for returning data for the butter statd subsytem ''' import logging import pymongo log = logging.getLogger(__name__) __opts__ = { 'mongo.host': 'salt', 'mongo.port': 27017, 'mongo.db': 'salt', } def returner(ret): ''' Return data to a mongodb server ''' conn = pymongo.Connection( __opts__['mongo.host'], __opts__['mongo.port'], ) db = conn[__opts__['mongo.db']] col = db[ret['id']] back = {} if type(ret['return']) == type(dict()): for key in ret['return']: back[key.replace('.', '-')] = ret['return'][key] else: back = ret['return'] log.debug( back ) col.insert({ret['jid']: back})
''' Return data to a mongodb server This is the default interface for returning data for the butter statd subsytem ''' import logging import pymongo log = logging.getLogger(__name__) __opts__ = { 'mongo.host': 'salt', 'mongo.port': 27017, 'mongo.db': 'salt', 'mongo.user': '', 'mongo.password': '', } def returner(ret): ''' Return data to a mongodb server ''' conn = pymongo.Connection( __opts__['mongo.host'], __opts__['mongo.port'], ) db = conn[__opts__['mongo.db']] user = __opts__.get('mongo.user') password = __opts__.get('mongo.password') if user and password: db.authenticate(user, password) col = db[ret['id']] back = {} if type(ret['return']) == type(dict()): for key in ret['return']: back[key.replace('.', '-')] = ret['return'][key] else: back = ret['return'] log.debug( back ) col.insert({ret['jid']: back})
Allow mongo returner to update a password protected mongo database.
Allow mongo returner to update a password protected mongo database.
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -13,6 +13,8 @@ 'mongo.host': 'salt', 'mongo.port': 27017, 'mongo.db': 'salt', + 'mongo.user': '', + 'mongo.password': '', } def returner(ret): @@ -24,6 +26,12 @@ __opts__['mongo.port'], ) db = conn[__opts__['mongo.db']] + + user = __opts__.get('mongo.user') + password = __opts__.get('mongo.password') + if user and password: + db.authenticate(user, password) + col = db[ret['id']] back = {} if type(ret['return']) == type(dict()):
d4e03bfcbc6292d3a50237f95c9d67ba5d89a475
swampdragon/pubsub_providers/redis_sub_provider.py
swampdragon/pubsub_providers/redis_sub_provider.py
import json import tornadoredis.pubsub import tornadoredis from .base_provider import BaseProvider class RedisSubProvider(BaseProvider): def __init__(self): self._subscriber = tornadoredis.pubsub.SockJSSubscriber(tornadoredis.Client()) def close(self, broadcaster): for channel in self._subscriber.subscribers: if broadcaster in self._subscriber.subscribers[channel]: self._subscriber.subscribers[channel].pop(broadcaster) def get_channel(self, base_channel, **channel_filter): return self._construct_channel(base_channel, **channel_filter) def subscribe(self, channels, broadcaster): self._subscriber.subscribe(channels, broadcaster) def unsubscribe(self, channels, broadcaster): for channel in channels: if broadcaster in self._subscriber.subscribers[channel]: self._subscriber.subscribers[channel].pop(broadcaster) def publish(self, channel, data): if isinstance(data, dict): data = json.dumps(data) broadcasters = list(self._subscriber.subscribers[channel].keys()) if broadcasters: for bc in broadcasters: if not bc.session.is_closed: bc.broadcast(broadcasters, data) break
import json import tornadoredis.pubsub import tornadoredis from .base_provider import BaseProvider class RedisSubProvider(BaseProvider): def __init__(self): self._subscriber = tornadoredis.pubsub.SockJSSubscriber(tornadoredis.Client()) def close(self, broadcaster): for channel in self._subscriber.subscribers: if broadcaster in self._subscriber.subscribers[channel]: self._subscriber.unsubscribe(channel, broadcaster) def get_channel(self, base_channel, **channel_filter): return self._construct_channel(base_channel, **channel_filter) def subscribe(self, channels, broadcaster): self._subscriber.subscribe(channels, broadcaster) def unsubscribe(self, channels, broadcaster): for channel in channels: if broadcaster in self._subscriber.subscribers[channel]: self._subscriber.subscribers[channel].pop(broadcaster) def publish(self, channel, data): if isinstance(data, dict): data = json.dumps(data) broadcasters = list(self._subscriber.subscribers[channel].keys()) if broadcasters: for bc in broadcasters: if not bc.session.is_closed: bc.broadcast(broadcasters, data) break
Use usubscribe rather than popping the broadcaster
Use usubscribe rather than popping the broadcaster
Python
bsd-3-clause
sahlinet/swampdragon,boris-savic/swampdragon,michael-k/swampdragon,denizs/swampdragon,aexeagmbh/swampdragon,jonashagstedt/swampdragon,jonashagstedt/swampdragon,d9pouces/swampdragon,boris-savic/swampdragon,sahlinet/swampdragon,aexeagmbh/swampdragon,jonashagstedt/swampdragon,bastianh/swampdragon,boris-savic/swampdragon,michael-k/swampdragon,faulkner/swampdragon,bastianh/swampdragon,seclinch/swampdragon,Manuel4131/swampdragon,michael-k/swampdragon,faulkner/swampdragon,seclinch/swampdragon,Manuel4131/swampdragon,Manuel4131/swampdragon,seclinch/swampdragon,sahlinet/swampdragon,denizs/swampdragon,d9pouces/swampdragon,aexeagmbh/swampdragon,denizs/swampdragon,bastianh/swampdragon,faulkner/swampdragon,d9pouces/swampdragon,h-hirokawa/swampdragon,h-hirokawa/swampdragon
--- +++ @@ -11,7 +11,7 @@ def close(self, broadcaster): for channel in self._subscriber.subscribers: if broadcaster in self._subscriber.subscribers[channel]: - self._subscriber.subscribers[channel].pop(broadcaster) + self._subscriber.unsubscribe(channel, broadcaster) def get_channel(self, base_channel, **channel_filter): return self._construct_channel(base_channel, **channel_filter)
e30e5e9780cfe674a70856609ad6010056936263
picdump/webadapter.py
picdump/webadapter.py
import urllib.request class WebAdapter: def get(self, urllike): url = self.mk_url(urllike) try: res = urllib.request.urlopen(url) return res.read() except Exception as e: raise e def open(self, urllike): url = self.mk_url(urllike) try: return urllib.request.urlopen(url) except Exception as e: raise e def mk_url(self, urllike): return str(urllike)
import requests class WebAdapter: def __init__(self): self.cookies = {} def get(self, urllike): res = requests.get(str(urllike), cookies=self.cookies) self.cookies = res.cookies return res.text
Use requests instead of urllib.request
Use requests instead of urllib.request
Python
mit
kanosaki/PicDump,kanosaki/PicDump
--- +++ @@ -1,22 +1,12 @@ -import urllib.request +import requests class WebAdapter: + def __init__(self): + self.cookies = {} + def get(self, urllike): - url = self.mk_url(urllike) - try: - res = urllib.request.urlopen(url) - return res.read() - except Exception as e: - raise e - - def open(self, urllike): - url = self.mk_url(urllike) - try: - return urllib.request.urlopen(url) - except Exception as e: - raise e - - def mk_url(self, urllike): - return str(urllike) + res = requests.get(str(urllike), cookies=self.cookies) + self.cookies = res.cookies + return res.text
a35abfda8af01f3c5bab4f4122060b630c118cac
bitbots_head_behavior/src/bitbots_head_behavior/actions/pattern_search.py
bitbots_head_behavior/src/bitbots_head_behavior/actions/pattern_search.py
import math from dynamic_stack_decider.abstract_action_element import AbstractActionElement class PatternSearch(AbstractActionElement): def __init__(self, blackboard, dsd, parameters=None): super(PatternSearch, self).__init__(blackboard, dsd, parameters) self.index = 0 self.pattern = self.blackboard.config['search_pattern'] def perform(self, reevaluate=False): head_pan, head_tilt = self.pattern[int(self.index)] # Convert to radians head_pan = head_pan / 180.0 * math.pi head_tilt = head_tilt / 180.0 * math.pi print("Searching at {}, {}".format(head_pan, head_tilt)) self.blackboard.head_capsule.send_motor_goals(head_pan, head_tilt, 1.5, 1.5) # Increment index self.index = (self.index + 0.2) % len(self.pattern)
import math from dynamic_stack_decider.abstract_action_element import AbstractActionElement class PatternSearch(AbstractActionElement): def __init__(self, blackboard, dsd, parameters=None): super(PatternSearch, self).__init__(blackboard, dsd, parameters) self.index = 0 self.pattern = self.blackboard.config['search_pattern'] def perform(self, reevaluate=False): head_pan, head_tilt = self.pattern[int(self.index)] # Convert to radians head_pan = head_pan / 180.0 * math.pi head_tilt = head_tilt / 180.0 * math.pi rospy.logdebug_throttle_identical(1, f"Searching at {head_pan}, {head_tilt}") self.blackboard.head_capsule.send_motor_goals(head_pan, head_tilt, 1.5, 1.5) # Increment index self.index = (self.index + 0.2) % len(self.pattern)
Use ros-logging instead of print
Use ros-logging instead of print
Python
bsd-3-clause
bit-bots/bitbots_behaviour
--- +++ @@ -14,7 +14,8 @@ # Convert to radians head_pan = head_pan / 180.0 * math.pi head_tilt = head_tilt / 180.0 * math.pi - print("Searching at {}, {}".format(head_pan, head_tilt)) + + rospy.logdebug_throttle_identical(1, f"Searching at {head_pan}, {head_tilt}") self.blackboard.head_capsule.send_motor_goals(head_pan, head_tilt, 1.5, 1.5) # Increment index self.index = (self.index + 0.2) % len(self.pattern)
86ff28441a23762d30cbab9843a7abeb67bfd028
src/mist/bucky_extras/clients/debug_client.py
src/mist/bucky_extras/clients/debug_client.py
import sys from bucky.client import Client class DebugClient(Client): out_path = None def __init__(self, cfg, pipe): super(DebugClient, self).__init__(pipe) if self.out_path: self.stdout = open(self.out_path, 'w') else: self.stdout = sys.stdout def send(self, host, name, value, time): if self.filter(host, name, value, time): self.write(host, name, value, time) def filter(self, host, name, value, time): return True def write(self, host, name, value, time): self.stdout.write('%s %s %s %s\n' % (host, name, value, time)) self.stdout.flush()
import sys import time import datetime from bucky.client import Client from bucky.names import statname class DebugClient(Client): out_path = None def __init__(self, cfg, pipe): super(DebugClient, self).__init__(pipe) if self.out_path: self.stdout = open(self.out_path, 'w') else: self.stdout = sys.stdout def send(self, host, name, value, tstamp): if self.filter(host, name, value, tstamp): self.write(host, name, value, tstamp) def filter(self, host, name, value, tstamp): return True def write(self, host, name, value, tstamp): target = statname(host, name) dtime = datetime.datetime.fromtimestamp(tstamp) time_lbl = dtime.strftime('%y%m%d %H:%M:%S') self.stdout.write('%s (%.1fs) %s %r\n' % (time_lbl, tstamp - time.time(), target, value)) self.stdout.flush()
Improve printing in bucky's DebugClient
Improve printing in bucky's DebugClient
Python
apache-2.0
mistio/mist.monitor,mistio/mist.monitor
--- +++ @@ -1,6 +1,9 @@ import sys +import time +import datetime from bucky.client import Client +from bucky.names import statname class DebugClient(Client): @@ -13,13 +16,18 @@ else: self.stdout = sys.stdout - def send(self, host, name, value, time): - if self.filter(host, name, value, time): - self.write(host, name, value, time) + def send(self, host, name, value, tstamp): + if self.filter(host, name, value, tstamp): + self.write(host, name, value, tstamp) - def filter(self, host, name, value, time): + def filter(self, host, name, value, tstamp): return True - def write(self, host, name, value, time): - self.stdout.write('%s %s %s %s\n' % (host, name, value, time)) + def write(self, host, name, value, tstamp): + target = statname(host, name) + dtime = datetime.datetime.fromtimestamp(tstamp) + time_lbl = dtime.strftime('%y%m%d %H:%M:%S') + self.stdout.write('%s (%.1fs) %s %r\n' % (time_lbl, + tstamp - time.time(), + target, value)) self.stdout.flush()
b38f465e512f9b7e79935c156c60ef56d6122387
aiohttp_middlewares/constants.py
aiohttp_middlewares/constants.py
""" ============================= aiohttp_middlewares.constants ============================= Collection of constants for ``aiohttp_middlewares`` project. """ #: Set of idempotent HTTP methods IDEMPOTENT_METHODS = frozenset({'GET', 'HEAD', 'OPTIONS', 'TRACE'}) #: Set of non-idempotent HTTP methods NON_IDEMPOTENT_METHODS = frozenset({'POST', 'PUT', 'PATCH', 'DELETE'})
""" ============================= aiohttp_middlewares.constants ============================= Collection of constants for ``aiohttp_middlewares`` project. """ #: Set of idempotent HTTP methods IDEMPOTENT_METHODS = frozenset({'GET', 'HEAD', 'OPTIONS', 'TRACE'}) #: Set of non-idempotent HTTP methods NON_IDEMPOTENT_METHODS = frozenset({'DELETE', 'PATCH', 'POST', 'PUT'})
Order HTTP methods in constant.
chore: Order HTTP methods in constant.
Python
bsd-3-clause
playpauseandstop/aiohttp-middlewares,playpauseandstop/aiohttp-middlewares
--- +++ @@ -11,4 +11,4 @@ IDEMPOTENT_METHODS = frozenset({'GET', 'HEAD', 'OPTIONS', 'TRACE'}) #: Set of non-idempotent HTTP methods -NON_IDEMPOTENT_METHODS = frozenset({'POST', 'PUT', 'PATCH', 'DELETE'}) +NON_IDEMPOTENT_METHODS = frozenset({'DELETE', 'PATCH', 'POST', 'PUT'})
fbb2c05aef76c02094c13f5edeaecd9b7428ff11
alignak_backend/models/uipref.py
alignak_backend/models/uipref.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Resource information of host """ def get_name(): """ Get name of this resource :return: name of this resource :rtype: str """ return 'uipref' def get_schema(): """ Schema structure of this resource :return: schema dictionnary :rtype: dict """ return { 'allow_unknown': True, 'schema': { 'type': { 'type': 'string', 'ui': { 'title': "Preference's type", 'visible': True, 'orderable': True, 'searchable': True, "format": None }, 'default': '' }, 'user': { 'type': 'string', 'ui': { 'title': "User name", 'visible': True, 'orderable': True, 'searchable': True, "format": None }, 'default': '' }, 'data': { 'type': 'list', 'ui': { 'title': "User name", 'visible': True, 'orderable': True, 'searchable': True, "format": None }, 'default': [] }, } }
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Resource information of host """ def get_name(): """ Get name of this resource :return: name of this resource :rtype: str """ return 'uipref' def get_schema(): """ Schema structure of this resource :return: schema dictionnary :rtype: dict """ return { 'allow_unknown': True, 'schema': { 'type': { 'type': 'string', 'ui': { 'title': "Preference's type", 'visible': True, 'orderable': True, 'searchable': True, "format": None }, 'default': '' }, 'user': { 'type': 'string', 'ui': { 'title': "User name", 'visible': True, 'orderable': True, 'searchable': True, "format": None }, 'default': '' }, 'data': { 'type': 'dict', 'ui': { 'title': "Preference's dictionary", 'visible': True, 'orderable': True, 'searchable': True, "format": None }, 'default': [] }, } }
Update UI preferences model (dict)
Update UI preferences model (dict)
Python
agpl-3.0
Alignak-monitoring-contrib/alignak-backend,Alignak-monitoring-contrib/alignak-backend,Alignak-monitoring-contrib/alignak-backend,Alignak-monitoring-contrib/alignak-backend
--- +++ @@ -48,9 +48,9 @@ 'default': '' }, 'data': { - 'type': 'list', + 'type': 'dict', 'ui': { - 'title': "User name", + 'title': "Preference's dictionary", 'visible': True, 'orderable': True, 'searchable': True,
53b9eff3ffc1768d3503021e7248351e24d59af7
tests/httpd.py
tests/httpd.py
import SimpleHTTPServer import BaseHTTPServer class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_POST(s): s.send_response(200) s.end_headers() if __name__ == '__main__': server_class = BaseHTTPServer.HTTPServer httpd = server_class(('0.0.0.0', 8328), Handler) try: httpd.serve_forever() except KeyboardInterrupt: httpd.server_close()
import BaseHTTPServer class Handler(BaseHTTPServer.BaseHTTPRequestHandler): def do_POST(self): content_type = self.headers.getheader('content-type') content_length = int(self.headers.getheader('content-length')) self.send_response(200) self.send_header('Content-Type', content_type) self.send_header('Content-Length', str(content_length)) self.end_headers() self.wfile.write(self.rfile.read(content_length)) if __name__ == '__main__': server_class = BaseHTTPServer.HTTPServer httpd = server_class(('0.0.0.0', 8328), Handler) try: httpd.serve_forever() except KeyboardInterrupt: httpd.server_close()
Fix test http server, change to echo back request body
Fix test http server, change to echo back request body
Python
bsd-2-clause
chop-dbhi/django-webhooks,pombredanne/django-webhooks,pombredanne/django-webhooks,chop-dbhi/django-webhooks
--- +++ @@ -1,10 +1,14 @@ -import SimpleHTTPServer import BaseHTTPServer -class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler): - def do_POST(s): - s.send_response(200) - s.end_headers() +class Handler(BaseHTTPServer.BaseHTTPRequestHandler): + def do_POST(self): + content_type = self.headers.getheader('content-type') + content_length = int(self.headers.getheader('content-length')) + self.send_response(200) + self.send_header('Content-Type', content_type) + self.send_header('Content-Length', str(content_length)) + self.end_headers() + self.wfile.write(self.rfile.read(content_length)) if __name__ == '__main__': server_class = BaseHTTPServer.HTTPServer
b9143462c004af7d18a66fa92ad94585468751b9
IndexedRedis/fields/classic.py
IndexedRedis/fields/classic.py
# Copyright (c) 2017 Timothy Savannah under LGPL version 2.1. See LICENSE for more information. # # fields.classic - The IRField type which behaves like the "classic" IndexedRedis string-named fields. # # vim: set ts=8 shiftwidth=8 softtabstop=8 noexpandtab : from . import IRField, IR_NULL_STRINGS, irNull from ..compat_str import tobytes class IRClassicField(IRField): ''' IRClassicField - The IRField type which behaves like the "classic" IndexedRedis string-named fields. This will store and retrieve data encoding into the default encoding (@see IndexedRedis.compat_str.setDefaultIREncoding) and have a default value of empty string. ''' CAN_INDEX = True def __init__(self, name='', hashIndex=False): IRField.__init__(self, name=name, hashIndex=hashIndex, defaultValue='') def __new__(self, name='', hashIndex=False): return IRField.__new__(self, name) # vim: set ts=8 shiftwidth=8 softtabstop=8 noexpandtab :
# Copyright (c) 2017 Timothy Savannah under LGPL version 2.1. See LICENSE for more information. # # fields.classic - The IRField type which behaves like the "classic" IndexedRedis string-named fields. # # vim: set ts=8 shiftwidth=8 softtabstop=8 noexpandtab : from . import IRField, IR_NULL_STRINGS, irNull from ..compat_str import tobytes, encoded_str_type class IRClassicField(IRField): ''' IRClassicField - The IRField type which behaves like the "classic" IndexedRedis string-named fields. This will store and retrieve data encoding into the default encoding (@see IndexedRedis.compat_str.setDefaultIREncoding) and have a default value of empty string. ''' CAN_INDEX = True def __init__(self, name='', hashIndex=False): IRField.__init__(self, name=name, valueType=encoded_str_type, hashIndex=hashIndex, defaultValue='') def __new__(self, name='', hashIndex=False): return IRField.__new__(self, name) # vim: set ts=8 shiftwidth=8 softtabstop=8 noexpandtab :
Change IRFieldClassic to use 'encoded_str_type'
Change IRFieldClassic to use 'encoded_str_type'
Python
lgpl-2.1
kata198/indexedredis,kata198/indexedredis
--- +++ @@ -8,7 +8,7 @@ from . import IRField, IR_NULL_STRINGS, irNull -from ..compat_str import tobytes +from ..compat_str import tobytes, encoded_str_type class IRClassicField(IRField): ''' @@ -23,7 +23,7 @@ CAN_INDEX = True def __init__(self, name='', hashIndex=False): - IRField.__init__(self, name=name, hashIndex=hashIndex, defaultValue='') + IRField.__init__(self, name=name, valueType=encoded_str_type, hashIndex=hashIndex, defaultValue='') def __new__(self, name='', hashIndex=False): return IRField.__new__(self, name)
effa5f84fc93ced38ad9e5d3b0a16bea2d3914ef
caminae/common/templatetags/field_verbose_name.py
caminae/common/templatetags/field_verbose_name.py
from django import template register = template.Library() def field_verbose_name(obj, field): """Usage: {{ object|get_object_field }}""" return obj._meta.get_field(field).verbose_name register.filter(field_verbose_name) register.filter('verbose', field_verbose_name)
from django import template from django.db.models.fields.related import FieldDoesNotExist register = template.Library() def field_verbose_name(obj, field): """Usage: {{ object|get_object_field }}""" try: return obj._meta.get_field(field).verbose_name except FieldDoesNotExist: a = getattr(obj, '%s_verbose_name' % field) if a is None: raise return unicode(a) register.filter(field_verbose_name) register.filter('verbose', field_verbose_name)
Allow column to be a property
Allow column to be a property
Python
bsd-2-clause
makinacorpus/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,camillemonchicourt/Geotrek,Anaethelion/Geotrek,johan--/Geotrek,johan--/Geotrek,johan--/Geotrek,makinacorpus/Geotrek,camillemonchicourt/Geotrek,GeotrekCE/Geotrek-admin,mabhub/Geotrek,makinacorpus/Geotrek,Anaethelion/Geotrek,Anaethelion/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,mabhub/Geotrek,makinacorpus/Geotrek,mabhub/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,camillemonchicourt/Geotrek
--- +++ @@ -1,11 +1,17 @@ from django import template +from django.db.models.fields.related import FieldDoesNotExist register = template.Library() def field_verbose_name(obj, field): """Usage: {{ object|get_object_field }}""" - - return obj._meta.get_field(field).verbose_name + try: + return obj._meta.get_field(field).verbose_name + except FieldDoesNotExist: + a = getattr(obj, '%s_verbose_name' % field) + if a is None: + raise + return unicode(a) register.filter(field_verbose_name) register.filter('verbose', field_verbose_name)
bdb78cd1bb13981a20ecb0cf9eb981d784c95b0e
fellowms/forms.py
fellowms/forms.py
from django.forms import ModelForm, widgets from .models import Fellow, Event, Expense, Blog class FellowForm(ModelForm): class Meta: model = Fellow exclude = [ "inauguration_year", "mentor", ] class EventForm(ModelForm): class Meta: model = Event exclude = [ "status", "budget_approve", ] # We don't want to expose fellows' data # so we will request the email # and match on the database. labels = { 'fellow': 'Fellow', 'url': "Event's homepage url", 'name': "Event's name", } class ExpenseForm(ModelForm): class Meta: model = Expense exclude = [ 'id', 'status', ] class BlogForm(ModelForm): class Meta: model = Blog fields = '__all__'
from django.forms import ModelForm, widgets from .models import Fellow, Event, Expense, Blog class FellowForm(ModelForm): class Meta: model = Fellow exclude = [ "home_lon", "home_lat", "inauguration_year", "mentor", ] class EventForm(ModelForm): class Meta: model = Event exclude = [ "status", "budget_approve", ] # We don't want to expose fellows' data # so we will request the email # and match on the database. labels = { 'fellow': 'Fellow', 'url': "Event's homepage url", 'name': "Event's name", } class ExpenseForm(ModelForm): class Meta: model = Expense exclude = [ 'id', 'status', ] class BlogForm(ModelForm): class Meta: model = Blog fields = '__all__'
Update form to handle home_lon and home_lat
Update form to handle home_lon and home_lat
Python
bsd-3-clause
softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat
--- +++ @@ -6,6 +6,8 @@ class Meta: model = Fellow exclude = [ + "home_lon", + "home_lat", "inauguration_year", "mentor", ]
ca2b02d551e9bb4c8625ae79f7878892673fa731
corehq/apps/es/domains.py
corehq/apps/es/domains.py
from .es_query import HQESQuery from . import filters class DomainES(HQESQuery): index = 'domains' @property def builtin_filters(self): return [ real_domains, commconnect_domains, created, ] + super(DomainES, self).builtin_filters def real_domains(): return filters.term("is_test", False) def commconnect_domains(): return filters.term("commconnect_enabled", True) def created(gt=None, gte=None, lt=None, lte=None): return filters.date_range('date_created', gt, gte, lt, lte)
from .es_query import HQESQuery from . import filters class DomainES(HQESQuery): index = 'domains' @property def builtin_filters(self): return [ real_domains, commcare_domains, commconnect_domains, commtrack_domains, created, ] + super(DomainES, self).builtin_filters def real_domains(): return filters.term("is_test", False) def commcare_domains(): return filters.AND(filters.term("commconnect_enabled", False), filters.term("commtrack_enabled", False)) def commconnect_domains(): return filters.term("commconnect_enabled", True) def commtrack_domains(): return filters.term("commtrack_enabled", True) def created(gt=None, gte=None, lt=None, lte=None): return filters.date_range('date_created', gt, gte, lt, lte)
Add CommCare, CommTrack filters for DomainES
Add CommCare, CommTrack filters for DomainES
Python
bsd-3-clause
qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq
--- +++ @@ -9,7 +9,9 @@ def builtin_filters(self): return [ real_domains, + commcare_domains, commconnect_domains, + commtrack_domains, created, ] + super(DomainES, self).builtin_filters @@ -18,9 +20,18 @@ return filters.term("is_test", False) +def commcare_domains(): + return filters.AND(filters.term("commconnect_enabled", False), + filters.term("commtrack_enabled", False)) + + def commconnect_domains(): return filters.term("commconnect_enabled", True) +def commtrack_domains(): + return filters.term("commtrack_enabled", True) + + def created(gt=None, gte=None, lt=None, lte=None): return filters.date_range('date_created', gt, gte, lt, lte)
11f933e986dd9e2c62b852ca38a37f959c10145e
tools/utils.py
tools/utils.py
#!/usr/bin/env python ''' This script provides utils for python scripts in cameo. ''' import os import sys import subprocess def TryAddDepotToolsToPythonPath(): depot_tools = FindDepotToolsInPath() if depot_tools: sys.path.append(depot_tools) def FindDepotToolsInPath(): paths = os.getenv('PATH').split(os.path.pathsep) for path in paths: if os.path.basename(path) == 'depot_tools': return path return None def IsWindows(): return sys.platform == 'cygwin' or sys.platform.startswith('win') def IsLinux(): return sys.platform.startswith('linux') def IsMac(): return sys.platform.startswith('darwin') def GitExe(): if IsWindows(): return 'git.bat' else: return 'git' def GetCommandOutput(command, cwd=None): proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, cwd=cwd) output = proc.communicate()[0] result = proc.returncode if result: raise Exception('%s: %s' % (subprocess.list2cmdline(command), output)) return output
#!/usr/bin/env python ''' This script provides utils for python scripts in cameo. ''' import os import sys import subprocess def TryAddDepotToolsToPythonPath(): depot_tools = FindDepotToolsInPath() if depot_tools: sys.path.append(depot_tools) def FindDepotToolsInPath(): paths = os.getenv('PATH').split(os.path.pathsep) for path in paths: if os.path.basename(path) == '': # path is end with os.path.pathsep path = os.path.dirname(path) if os.path.basename(path) == 'depot_tools': return path return None def IsWindows(): return sys.platform == 'cygwin' or sys.platform.startswith('win') def IsLinux(): return sys.platform.startswith('linux') def IsMac(): return sys.platform.startswith('darwin') def GitExe(): if IsWindows(): return 'git.bat' else: return 'git' def GetCommandOutput(command, cwd=None): proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, cwd=cwd) output = proc.communicate()[0] result = proc.returncode if result: raise Exception('%s: %s' % (subprocess.list2cmdline(command), output)) return output
Fix FindDepotToolsInPath not working in some cases
Fix FindDepotToolsInPath not working in some cases When depot tools' path in PATH is like '/home/project/depot_tools/', FindDepotToolsInPath will not detect it because os.path.basename will get empty string. Fix this by getting its parent if its basename is empty. BUG=https://github.com/otcshare/cameo/issues/29
Python
bsd-3-clause
shaochangbin/crosswalk,rakuco/crosswalk,RafuCater/crosswalk,DonnaWuDongxia/crosswalk,tomatell/crosswalk,mrunalk/crosswalk,jpike88/crosswalk,dreamsxin/crosswalk,stonegithubs/crosswalk,weiyirong/crosswalk-1,siovene/crosswalk,baleboy/crosswalk,crosswalk-project/crosswalk,fujunwei/crosswalk,ZhengXinCN/crosswalk,minggangw/crosswalk,axinging/crosswalk,RafuCater/crosswalk,darktears/crosswalk,qjia7/crosswalk,Shouqun/crosswalk,heke123/crosswalk,axinging/crosswalk,marcuspridham/crosswalk,marcuspridham/crosswalk,axinging/crosswalk,baleboy/crosswalk,marcuspridham/crosswalk,XiaosongWei/crosswalk,PeterWangIntel/crosswalk,dreamsxin/crosswalk,rakuco/crosswalk,xzhan96/crosswalk,baleboy/crosswalk,ZhengXinCN/crosswalk,baleboy/crosswalk,mrunalk/crosswalk,jondong/crosswalk,pozdnyakov/crosswalk,bestwpw/crosswalk,seanlong/crosswalk,huningxin/crosswalk,marcuspridham/crosswalk,minggangw/crosswalk,Pluto-tv/crosswalk,mrunalk/crosswalk,seanlong/crosswalk,amaniak/crosswalk,bestwpw/crosswalk,lincsoon/crosswalk,mrunalk/crosswalk,Shouqun/crosswalk,minggangw/crosswalk,fujunwei/crosswalk,lincsoon/crosswalk,lincsoon/crosswalk,seanlong/crosswalk,fujunwei/crosswalk,zeropool/crosswalk,seanlong/crosswalk,XiaosongWei/crosswalk,heke123/crosswalk,jpike88/crosswalk,stonegithubs/crosswalk,kurli/crosswalk,baleboy/crosswalk,amaniak/crosswalk,weiyirong/crosswalk-1,rakuco/crosswalk,siovene/crosswalk,jondwillis/crosswalk,xzhan96/crosswalk,lincsoon/crosswalk,Bysmyyr/crosswalk,rakuco/crosswalk,hgl888/crosswalk-efl,chinakids/crosswalk,jpike88/crosswalk,DonnaWuDongxia/crosswalk,PeterWangIntel/crosswalk,darktears/crosswalk,qjia7/crosswalk,jondwillis/crosswalk,Bysmyyr/crosswalk,shaochangbin/crosswalk,PeterWangIntel/crosswalk,tedshroyer/crosswalk,chinakids/crosswalk,chuan9/crosswalk,alex-zhang/crosswalk,crosswalk-project/crosswalk-efl,dreamsxin/crosswalk,fujunwei/crosswalk,zliang7/crosswalk,crosswalk-project/crosswalk,fujunwei/crosswalk,wuhengzhi/crosswalk,hgl888/crosswalk-efl,baleboy/crosswalk,weiyirong/crosswalk-1,chuan9/crosswalk,Bysmyyr/crosswalk,qjia7/crosswalk,pk-sam/crosswalk,axinging/crosswalk,huningxin/crosswalk,stonegithubs/crosswalk,tedshroyer/crosswalk,darktears/crosswalk,amaniak/crosswalk,myroot/crosswalk,tomatell/crosswalk,myroot/crosswalk,heke123/crosswalk,Pluto-tv/crosswalk,leonhsl/crosswalk,TheDirtyCalvinist/spacewalk,minggangw/crosswalk,zliang7/crosswalk,jpike88/crosswalk,hgl888/crosswalk-efl,PeterWangIntel/crosswalk,mrunalk/crosswalk,zeropool/crosswalk,heke123/crosswalk,Shouqun/crosswalk,pk-sam/crosswalk,weiyirong/crosswalk-1,baleboy/crosswalk,rakuco/crosswalk,crosswalk-project/crosswalk,zeropool/crosswalk,stonegithubs/crosswalk,jondong/crosswalk,seanlong/crosswalk,chuan9/crosswalk,dreamsxin/crosswalk,kurli/crosswalk,PeterWangIntel/crosswalk,pk-sam/crosswalk,tomatell/crosswalk,pk-sam/crosswalk,pozdnyakov/crosswalk,pk-sam/crosswalk,myroot/crosswalk,xzhan96/crosswalk,shaochangbin/crosswalk,Shouqun/crosswalk,jondwillis/crosswalk,RafuCater/crosswalk,huningxin/crosswalk,hgl888/crosswalk,kurli/crosswalk,XiaosongWei/crosswalk,hgl888/crosswalk,rakuco/crosswalk,shaochangbin/crosswalk,tedshroyer/crosswalk,dreamsxin/crosswalk,amaniak/crosswalk,crosswalk-project/crosswalk,DonnaWuDongxia/crosswalk,zeropool/crosswalk,kurli/crosswalk,siovene/crosswalk,darktears/crosswalk,zliang7/crosswalk,xzhan96/crosswalk,alex-zhang/crosswalk,tomatell/crosswalk,huningxin/crosswalk,TheDirtyCalvinist/spacewalk,xzhan96/crosswalk,XiaosongWei/crosswalk,marcuspridham/crosswalk,lincsoon/crosswalk,Bysmyyr/crosswalk,bestwpw/crosswalk,weiyirong/crosswalk-1,alex-zhang/crosswalk,Bysmyyr/crosswalk,zeropool/crosswalk,chinakids/crosswalk,RafuCater/crosswalk,siovene/crosswalk,XiaosongWei/crosswalk,Pluto-tv/crosswalk,wuhengzhi/crosswalk,wuhengzhi/crosswalk,weiyirong/crosswalk-1,dreamsxin/crosswalk,huningxin/crosswalk,bestwpw/crosswalk,RafuCater/crosswalk,wuhengzhi/crosswalk,Bysmyyr/crosswalk,wuhengzhi/crosswalk,fujunwei/crosswalk,chuan9/crosswalk,baleboy/crosswalk,Bysmyyr/crosswalk,TheDirtyCalvinist/spacewalk,tomatell/crosswalk,pk-sam/crosswalk,weiyirong/crosswalk-1,zliang7/crosswalk,stonegithubs/crosswalk,hgl888/crosswalk,pozdnyakov/crosswalk,xzhan96/crosswalk,minggangw/crosswalk,amaniak/crosswalk,siovene/crosswalk,xzhan96/crosswalk,tomatell/crosswalk,minggangw/crosswalk,lincsoon/crosswalk,Bysmyyr/crosswalk,leonhsl/crosswalk,zliang7/crosswalk,chuan9/crosswalk,heke123/crosswalk,Pluto-tv/crosswalk,fujunwei/crosswalk,lincsoon/crosswalk,RafuCater/crosswalk,tedshroyer/crosswalk,jpike88/crosswalk,bestwpw/crosswalk,leonhsl/crosswalk,qjia7/crosswalk,Pluto-tv/crosswalk,amaniak/crosswalk,hgl888/crosswalk,siovene/crosswalk,ZhengXinCN/crosswalk,ZhengXinCN/crosswalk,ZhengXinCN/crosswalk,stonegithubs/crosswalk,bestwpw/crosswalk,crosswalk-project/crosswalk,tomatell/crosswalk,Shouqun/crosswalk,jondong/crosswalk,rakuco/crosswalk,leonhsl/crosswalk,zeropool/crosswalk,marcuspridham/crosswalk,minggangw/crosswalk,jondwillis/crosswalk,axinging/crosswalk,qjia7/crosswalk,crosswalk-project/crosswalk,alex-zhang/crosswalk,jondwillis/crosswalk,chinakids/crosswalk,kurli/crosswalk,tedshroyer/crosswalk,marcuspridham/crosswalk,TheDirtyCalvinist/spacewalk,hgl888/crosswalk-efl,Pluto-tv/crosswalk,seanlong/crosswalk,crosswalk-project/crosswalk-efl,dreamsxin/crosswalk,jondong/crosswalk,alex-zhang/crosswalk,darktears/crosswalk,DonnaWuDongxia/crosswalk,PeterWangIntel/crosswalk,TheDirtyCalvinist/spacewalk,zeropool/crosswalk,Pluto-tv/crosswalk,zliang7/crosswalk,ZhengXinCN/crosswalk,DonnaWuDongxia/crosswalk,myroot/crosswalk,bestwpw/crosswalk,zliang7/crosswalk,hgl888/crosswalk,jondong/crosswalk,heke123/crosswalk,crosswalk-project/crosswalk,jpike88/crosswalk,DonnaWuDongxia/crosswalk,marcuspridham/crosswalk,heke123/crosswalk,shaochangbin/crosswalk,hgl888/crosswalk,axinging/crosswalk,ZhengXinCN/crosswalk,crosswalk-project/crosswalk,tedshroyer/crosswalk,mrunalk/crosswalk,siovene/crosswalk,amaniak/crosswalk,xzhan96/crosswalk,kurli/crosswalk,crosswalk-project/crosswalk-efl,jondong/crosswalk,hgl888/crosswalk-efl,pozdnyakov/crosswalk,crosswalk-project/crosswalk-efl,huningxin/crosswalk,crosswalk-project/crosswalk-efl,darktears/crosswalk,chinakids/crosswalk,crosswalk-project/crosswalk-efl,qjia7/crosswalk,rakuco/crosswalk,heke123/crosswalk,axinging/crosswalk,leonhsl/crosswalk,alex-zhang/crosswalk,jondong/crosswalk,hgl888/crosswalk,tedshroyer/crosswalk,XiaosongWei/crosswalk,lincsoon/crosswalk,wuhengzhi/crosswalk,alex-zhang/crosswalk,PeterWangIntel/crosswalk,pozdnyakov/crosswalk,pozdnyakov/crosswalk,minggangw/crosswalk,leonhsl/crosswalk,hgl888/crosswalk,DonnaWuDongxia/crosswalk,crosswalk-project/crosswalk-efl,myroot/crosswalk,chuan9/crosswalk,stonegithubs/crosswalk,shaochangbin/crosswalk,chuan9/crosswalk,XiaosongWei/crosswalk,zliang7/crosswalk,hgl888/crosswalk-efl,RafuCater/crosswalk,hgl888/crosswalk-efl,darktears/crosswalk,jpike88/crosswalk,TheDirtyCalvinist/spacewalk,myroot/crosswalk,Shouqun/crosswalk,chinakids/crosswalk,darktears/crosswalk,jondong/crosswalk,jondwillis/crosswalk,pk-sam/crosswalk,leonhsl/crosswalk,jondwillis/crosswalk
--- +++ @@ -15,6 +15,9 @@ def FindDepotToolsInPath(): paths = os.getenv('PATH').split(os.path.pathsep) for path in paths: + if os.path.basename(path) == '': + # path is end with os.path.pathsep + path = os.path.dirname(path) if os.path.basename(path) == 'depot_tools': return path return None
91ff0fcb40d5d5318b71f0eb4b0873fb470265a0
migrations/versions/f0c9c797c230_populate_application_settings_with_.py
migrations/versions/f0c9c797c230_populate_application_settings_with_.py
"""populate application_settings with started apps Revision ID: f0c9c797c230 Revises: 31850461ed3 Create Date: 2017-02-16 01:02:02.951573 """ # revision identifiers, used by Alembic. revision = 'f0c9c797c230' down_revision = '31850461ed3' from alembic import op import sqlalchemy as sa from puffin.core import docker, applications def upgrade(): running_applications = docker.get_all_running_applications() for running_application in running_applications: user = running_application[0] application = running_application[1] applications.set_application_started(user, application, True) def downgrade(): pass
"""populate application_settings with started apps Revision ID: f0c9c797c230 Revises: 31850461ed3 Create Date: 2017-02-16 01:02:02.951573 """ # revision identifiers, used by Alembic. revision = 'f0c9c797c230' down_revision = '31850461ed3' from alembic import op import sqlalchemy as sa from puffin.core import docker, applications def upgrade(): running_applications = docker.get_all_running_applications() for a in running_applications: user = a[0] application = a[1] applications.set_application_started(user, application, True) def downgrade(): started_applications = applications.get_all_started_applications() for a in started_applications: user = a[0] application = a[1] applications.set_application_started(user, application, False)
Add downgrade started applications migration
Add downgrade started applications migration
Python
agpl-3.0
loomchild/puffin,loomchild/puffin,loomchild/puffin,puffinrocks/puffin,puffinrocks/puffin,loomchild/jenca-puffin,loomchild/puffin,loomchild/jenca-puffin,loomchild/puffin
--- +++ @@ -17,10 +17,14 @@ def upgrade(): running_applications = docker.get_all_running_applications() - for running_application in running_applications: - user = running_application[0] - application = running_application[1] + for a in running_applications: + user = a[0] + application = a[1] applications.set_application_started(user, application, True) def downgrade(): - pass + started_applications = applications.get_all_started_applications() + for a in started_applications: + user = a[0] + application = a[1] + applications.set_application_started(user, application, False)
50ead4fe13eec7ad9760f0f577212beb8e8a51be
pombola/info/views.py
pombola/info/views.py
from django.views.generic import DetailView from models import InfoPage class InfoPageView(DetailView): """Show the page, or 'index' if no slug""" model = InfoPage
from django.views.generic import DetailView from models import InfoPage class InfoPageView(DetailView): """Show the page for the given slug""" model = InfoPage queryset = InfoPage.objects.filter(kind=InfoPage.KIND_PAGE)
Use a queryset to display only kind=page
Use a queryset to display only kind=page
Python
agpl-3.0
mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,hzj123/56th,ken-muturi/pombola,mysociety/pombola,patricmutwiri/pombola,patricmutwiri/pombola,ken-muturi/pombola,ken-muturi/pombola,hzj123/56th,ken-muturi/pombola,ken-muturi/pombola,hzj123/56th,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,geoffkilpin/pombola,hzj123/56th,ken-muturi/pombola,patricmutwiri/pombola,mysociety/pombola,geoffkilpin/pombola,patricmutwiri/pombola,patricmutwiri/pombola,mysociety/pombola,geoffkilpin/pombola,hzj123/56th,patricmutwiri/pombola,geoffkilpin/pombola
--- +++ @@ -2,5 +2,6 @@ from models import InfoPage class InfoPageView(DetailView): - """Show the page, or 'index' if no slug""" + """Show the page for the given slug""" model = InfoPage + queryset = InfoPage.objects.filter(kind=InfoPage.KIND_PAGE)