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
fc50467212347502792a54397ae6f5477136a32f
pombola/south_africa/urls.py
pombola/south_africa/urls.py
from django.conf.urls import patterns, include, url from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, \ SAOrganisationDetailView, SAPersonDetail, SANewsletterPage from pombola.core.urls import organisation_patterns, person_patterns # Override the organisation url so we can vary it depending on the organisation type. for index, pattern in enumerate(organisation_patterns): if pattern.name == 'organisation': organisation_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation') # Override the person url so we can add some extra data for index, pattern in enumerate(person_patterns): if pattern.name == 'person': person_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAPersonDetail.as_view(), name='person') urlpatterns = patterns('pombola.south_africa.views', url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'), url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'), url(r'^info/newsletter', SANewsletterPage.as_view(), {'slug': 'newsletter'}, name='info_page_newsletter'), )
from django.conf.urls import patterns, include, url from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, \ SAOrganisationDetailView, SAPersonDetail, SANewsletterPage from pombola.core.urls import organisation_patterns, person_patterns # Override the organisation url so we can vary it depending on the organisation type. for index, pattern in enumerate(organisation_patterns): if pattern.name == 'organisation': organisation_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation') # Override the person url so we can add some extra data for index, pattern in enumerate(person_patterns): if pattern.name == 'person': person_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAPersonDetail.as_view(), name='person') urlpatterns = patterns('pombola.south_africa.views', url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'), url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'), # Catch the newsletter info page to change the template used so that the signup form is injected. # NOTE - you still need to create an InfoPage with the slug 'newsletter' for this not to 404. url(r'^info/newsletter', SANewsletterPage.as_view(), {'slug': 'newsletter'}, name='info_page_newsletter'), )
Add note about needing to create the infopage
Add note about needing to create the infopage
Python
agpl-3.0
hzj123/56th,ken-muturi/pombola,hzj123/56th,geoffkilpin/pombola,patricmutwiri/pombola,patricmutwiri/pombola,hzj123/56th,ken-muturi/pombola,patricmutwiri/pombola,ken-muturi/pombola,ken-muturi/pombola,patricmutwiri/pombola,patricmutwiri/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,ken-muturi/pombola,mysociety/pombola,hzj123/56th,patricmutwiri/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,ken-muturi/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola
--- +++ @@ -17,5 +17,8 @@ urlpatterns = patterns('pombola.south_africa.views', url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'), url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'), + + # Catch the newsletter info page to change the template used so that the signup form is injected. + # NOTE - you still need to create an InfoPage with the slug 'newsletter' for this not to 404. url(r'^info/newsletter', SANewsletterPage.as_view(), {'slug': 'newsletter'}, name='info_page_newsletter'), )
775e0b819e3eac2f84d41900de7bdc2058156389
backend/blog/types.py
backend/blog/types.py
from typing import Optional import strawberry from api.scalars import DateTime from users.types import UserType @strawberry.type class Post: id: strawberry.ID author: UserType title: str slug: str excerpt: Optional[str] content: Optional[str] published: DateTime image: Optional[str]
from typing import Optional import strawberry from api.scalars import DateTime from users.types import UserType @strawberry.type class Post: id: strawberry.ID author: UserType title: str slug: str excerpt: Optional[str] content: Optional[str] published: DateTime @strawberry.field def image(self, info) -> Optional[str]: if not self.image: return None return info.context.build_absolute_uri(self.image.url)
Return absolute url for blog image
Return absolute url for blog image
Python
mit
patrick91/pycon,patrick91/pycon
--- +++ @@ -14,4 +14,10 @@ excerpt: Optional[str] content: Optional[str] published: DateTime - image: Optional[str] + + @strawberry.field + def image(self, info) -> Optional[str]: + if not self.image: + return None + + return info.context.build_absolute_uri(self.image.url)
7387d77a094b7368cf80a1e8c1db41356d92fc38
calaccess_website/templatetags/calaccess_website_tags.py
calaccess_website/templatetags/calaccess_website_tags.py
import os from django import template from django.conf import settings from django.template.defaultfilters import stringfilter register = template.Library() @register.simple_tag def archive_url(file_path, is_latest=False): """ Accepts the relative path to a CAL-ACCESS file in our achive. Returns a fully-qualified absolute URL where it can be downloaded. """ # If this is the 'latest' version of the file the path will need to be hacked if is_latest: # Split off the file name filepath = os.path.basename(file_path) # Special hack for the clean biggie zip if filepath.startswith("clean_"): filepath = "clean.zip" # Concoct the latest URL path = os.path.join( settings.AWS_STORAGE_BUCKET_NAME, 'latest', filepath ) # If not we can just join it to the subject name else: path = os.path.join(settings.AWS_STORAGE_BUCKET_NAME, file_path) # Either way, join it to the base and pass it back return "http://{}".format(path) @register.filter @stringfilter def format_page_anchor(value): return value.lower().replace('_', '-') @register.filter @stringfilter def first_line(text): return text.split('\n')[0]
import os from django import template from django.conf import settings from django.template.defaultfilters import stringfilter register = template.Library() @register.simple_tag def archive_url(file_path, is_latest=False): """ Accepts the relative path to a CAL-ACCESS file in our achive. Returns a fully-qualified absolute URL where it can be downloaded. """ # If this is the 'latest' version of the file the path will need to be hacked if is_latest: # Split off the file name filepath = os.path.basename(file_path) # Special hack for the clean biggie zip if filepath.startswith("clean_"): filepath = "clean.zip" # Concoct the latest URL path = os.path.join( "calaccess.download", 'latest', filepath ) # If not we can just join it to the subject name else: path = os.path.join("calaccess.download", file_path) # Either way, join it to the base and pass it back return "http://{}".format(path) @register.filter @stringfilter def format_page_anchor(value): return value.lower().replace('_', '-') @register.filter @stringfilter def first_line(text): return text.split('\n')[0]
Substitute in our download bucket in that template tag now that the two things are separated
Substitute in our download bucket in that template tag now that the two things are separated
Python
mit
california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website
--- +++ @@ -21,13 +21,13 @@ filepath = "clean.zip" # Concoct the latest URL path = os.path.join( - settings.AWS_STORAGE_BUCKET_NAME, + "calaccess.download", 'latest', filepath ) # If not we can just join it to the subject name else: - path = os.path.join(settings.AWS_STORAGE_BUCKET_NAME, file_path) + path = os.path.join("calaccess.download", file_path) # Either way, join it to the base and pass it back return "http://{}".format(path)
2b4b71246646db8e28b999d2ff249c3a36aa0c33
uitools/qt.py
uitools/qt.py
"""Convenience to import Qt if it is availible, otherwise provide stubs. Normally I wouldn't bother with something like this, but due to the testing contexts that we often run we may import stuff from uitools that does not have Qt avilaible. """ __all__ = ['Qt', 'QtCore', 'QtGui'] try: from PyQt4 import QtCore, QtGui except ImportError: try: from PySide import QtCore, QtGui except ImportError: for name in __all__: globals().setdefault(name, None) Qt = QtCore.Qt if QtCore else None
"""Wrapping the differences between PyQt4 and PySide.""" import sys __all__ = ['Qt', 'QtCore', 'QtGui'] try: import PySide from PySide import QtCore, QtGui sys.modules.setdefault('PyQt4', PySide) except ImportError: try: import PyQt4 from PyQt4 import QtCore, QtGui sys.modules.setdefault('PySide', PySide) except ImportError: for name in __all__: globals().setdefault(name, None) Qt = QtCore.Qt if QtCore else None
Check for PySide first, and proxy PyQt4 to it
Check for PySide first, and proxy PyQt4 to it This allows our other tools, which are rather dumb, to import the wrong one and generally continue to work.
Python
bsd-3-clause
westernx/uitools
--- +++ @@ -1,18 +1,18 @@ -"""Convenience to import Qt if it is availible, otherwise provide stubs. +"""Wrapping the differences between PyQt4 and PySide.""" -Normally I wouldn't bother with something like this, but due to the -testing contexts that we often run we may import stuff from uitools that -does not have Qt avilaible. - -""" +import sys __all__ = ['Qt', 'QtCore', 'QtGui'] try: - from PyQt4 import QtCore, QtGui + import PySide + from PySide import QtCore, QtGui + sys.modules.setdefault('PyQt4', PySide) except ImportError: try: - from PySide import QtCore, QtGui + import PyQt4 + from PyQt4 import QtCore, QtGui + sys.modules.setdefault('PySide', PySide) except ImportError: for name in __all__: globals().setdefault(name, None)
a1746483da4e84c004e55ea4d33693a764ac5807
githubsetupircnotifications.py
githubsetupircnotifications.py
""" github-setup-irc-notifications - Configure all repositories in an organization with irc notifications """ import github3
""" github-setup-irc-notifications - Configure all repositories in an organization with irc notifications """ import argparse import github3 def main(): parser = argparse.ArgumentParser() parser.add_argument('--username'), parser.add_argument('--password'), args = parser.parse_args()
Add username and password args
Add username and password args
Python
mit
kragniz/github-setup-irc-notifications
--- +++ @@ -3,4 +3,13 @@ with irc notifications """ +import argparse + import github3 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--username'), + parser.add_argument('--password'), + args = parser.parse_args()
d384781d77521f6e4b97b783737be09a7a99423e
glance_registry_local_check.py
glance_registry_local_check.py
#!/usr/bin/env python from maas_common import (status_ok, status_err, metric, get_keystone_client, get_auth_ref) from requests import Session from requests import exceptions as exc def check(auth_ref): keystone = get_keystone_client(auth_ref) tenant_id = keystone.tenant_id auth_token = keystone.auth_token registry_endpoint = 'http://127.0.0.1:9191' api_status = 1 milliseconds = 0 s = Session() s.headers.update( {'Content-type': 'application/json', 'x-auth-token': auth_token}) try: # /images returns a list of public, non-deleted images r = s.get('%s/images' % registry_endpoint, verify=False, timeout=10) except (exc.ConnectionError, exc.HTTPError, exc.Timeout): api_status = 0 milliseconds = -1 except Exception as e: status_err(str(e)) else: milliseconds = r.elapsed.total_seconds() * 1000 if not r.ok: api_status = 0 status_ok() metric('glance_registry_local_status', 'uint32', api_status) metric('glance_registry_local_response_time', 'uint32', milliseconds) def main(): auth_ref = get_auth_ref() check(auth_ref) if __name__ == "__main__": main()
#!/usr/bin/env python from maas_common import (status_ok, status_err, metric, get_keystone_client, get_auth_ref) from requests import Session from requests import exceptions as exc def check(auth_ref): keystone = get_keystone_client(auth_ref) tenant_id = keystone.tenant_id auth_token = keystone.auth_token registry_endpoint = 'http://127.0.0.1:9191' api_status = 1 milliseconds = 0 s = Session() s.headers.update( {'Content-type': 'application/json', 'x-auth-token': auth_token}) try: # /images returns a list of public, non-deleted images r = s.get('%s/images' % registry_endpoint, verify=False, timeout=10) except (exc.ConnectionError, exc.HTTPError, exc.Timeout): api_status = 0 milliseconds = -1 except Exception as e: status_err(str(e)) else: milliseconds = r.elapsed.total_seconds() * 1000 if not r.ok: api_status = 0 status_ok() metric('glance_registry_local_status', 'uint32', api_status) metric('glance_registry_local_response_time', 'int32', milliseconds) def main(): auth_ref = get_auth_ref() check(auth_ref) if __name__ == "__main__": main()
Change metric type to int32
Change metric type to int32 This was done as we may now send a -1 to indicate that we could not obtain response timing from request.
Python
apache-2.0
mattt416/rpc-openstack,xeregin/rpc-openstack,darrenchan/rpc-openstack,major/rpc-openstack,byronmccollum/rpc-openstack,shannonmitchell/rpc-openstack,cloudnull/rpc-maas,npawelek/rpc-maas,miguelgrinberg/rpc-openstack,robb-romans/rpc-openstack,rcbops/rpc-openstack,BjoernT/rpc-openstack,nrb/rpc-openstack,git-harry/rpc-openstack,sigmavirus24/rpc-openstack,claco/rpc-openstack,cloudnull/rpc-maas,stevelle/rpc-openstack,mancdaz/rpc-openstack,npawelek/rpc-maas,briancurtin/rpc-maas,jacobwagner/rpc-openstack,mancdaz/rpc-openstack,busterswt/rpc-openstack,cfarquhar/rpc-openstack,xeregin/rpc-openstack,miguelgrinberg/rpc-openstack,cfarquhar/rpc-maas,xeregin/rpc-openstack,prometheanfire/rpc-openstack,cloudnull/rpc-maas,jacobwagner/rpc-openstack,miguelgrinberg/rpc-openstack,galstrom21/rpc-openstack,robb-romans/rpc-openstack,cloudnull/rpc-openstack,stevelle/rpc-openstack,claco/rpc-openstack,cfarquhar/rpc-maas,shannonmitchell/rpc-openstack,nrb/rpc-openstack,andymcc/rpc-openstack,BjoernT/rpc-openstack,mattt416/rpc-openstack,nrb/rpc-openstack,git-harry/rpc-openstack,andymcc/rpc-openstack,byronmccollum/rpc-openstack,jpmontez/rpc-openstack,byronmccollum/rpc-openstack,galstrom21/rpc-openstack,hughsaunders/rpc-openstack,prometheanfire/rpc-openstack,darrenchan/rpc-openstack,xeregin/rpc-openstack,sigmavirus24/rpc-openstack,rcbops/rpc-openstack,darrenchan/rpc-openstack,stevelle/rpc-openstack,briancurtin/rpc-maas,cfarquhar/rpc-maas,mattt416/rpc-openstack,claco/rpc-openstack,npawelek/rpc-maas,hughsaunders/rpc-openstack,cloudnull/rpc-openstack,jpmontez/rpc-openstack,sigmavirus24/rpc-openstack,sigmavirus24/rpc-openstack,busterswt/rpc-openstack,briancurtin/rpc-maas,darrenchan/rpc-openstack,andymcc/rpc-openstack,busterswt/rpc-openstack,cfarquhar/rpc-openstack,jpmontez/rpc-openstack,major/rpc-openstack
--- +++ @@ -37,7 +37,7 @@ status_ok() metric('glance_registry_local_status', 'uint32', api_status) - metric('glance_registry_local_response_time', 'uint32', milliseconds) + metric('glance_registry_local_response_time', 'int32', milliseconds) def main():
582c445e6ceb781cfb913a4d6a200d8887f66e16
filters/filters.py
filters/filters.py
import re import os def get_emoji_content(filename): full_filename = os.path.join(os.path.dirname(__file__), 'emojis', filename) with open(full_filename, 'r') as fp: return fp.read() def fix_emoji(value): """ Replace some text emojis with pictures """ emojis = { '(+)': get_emoji_content('plus.html'), '(-)': get_emoji_content('minus.html'), '(?)': get_emoji_content('question.html'), '(!)': get_emoji_content('alarm.html'), '(/)': get_emoji_content('check.html'), } for e in emojis: value = value.replace(e, emojis[e]) return value def cleanup(value): value = re.sub('\{code.*?\}.*?\{code\}', ' ', value, 0, re.S) return re.sub('\{noformat.*?\}.*?\{noformat\}', ' ', value, 0, re.S)
import re import os def get_emoji_content(filename): full_filename = os.path.join(os.path.dirname(__file__), 'emojis', filename) with open(full_filename, 'r') as fp: return fp.read() def fix_emoji(value): """ Replace some text emojis with pictures """ emojis = { '(+)': get_emoji_content('plus.html'), '(-)': get_emoji_content('minus.html'), '(?)': get_emoji_content('question.html'), '(!)': get_emoji_content('alarm.html'), '(/)': get_emoji_content('check.html'), } for e in emojis: value = value.replace(e, emojis[e]) return value def cleanup(value): """ Remove {code}...{/code} and {noformat}...{noformat} fragments from worklog comment :param value: worklog comment text :return: cleaned worklog comment text """ value = re.sub('\{code.*?\}.*?\{.*?code\}', ' ', value, 0, re.S) return re.sub('\{noformat.*?\}.*?\{noformat\}', ' ', value, 0, re.S)
Fix small issue in the cleanup filter. It now supports {/code} closing tag (was only {code})
Fix small issue in the cleanup filter. It now supports {/code} closing tag (was only {code})
Python
mit
vv-p/jira-reports,vv-p/jira-reports
--- +++ @@ -25,5 +25,10 @@ def cleanup(value): - value = re.sub('\{code.*?\}.*?\{code\}', ' ', value, 0, re.S) + """ + Remove {code}...{/code} and {noformat}...{noformat} fragments from worklog comment + :param value: worklog comment text + :return: cleaned worklog comment text + """ + value = re.sub('\{code.*?\}.*?\{.*?code\}', ' ', value, 0, re.S) return re.sub('\{noformat.*?\}.*?\{noformat\}', ' ', value, 0, re.S)
764f7d422da005fd84d9f24c36709442c1b2d51e
blanc_events/admin.py
blanc_events/admin.py
# -*- coding: utf-8 -*- from django.contrib import admin from blanc_pages.admin import BlancPageAdminMixin from .models import Category, Event @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): search_fields = ('title',) prepopulated_fields = { 'slug': ('title',) } @admin.register(Event) class EventAdmin(BlancPageAdminMixin, admin.ModelAdmin): pass fieldsets = ( ('Event', { 'fields': ( 'title', 'category', 'location', 'image', 'summary', 'start', 'end' ) }), ('Advanced options', { 'fields': ('slug',) }), ) date_hierarchy = 'start' list_display = ('title', 'start', 'end', 'category',) list_filter = ('published', 'start', 'category__title',) prepopulated_fields = { 'slug': ('title',) }
# -*- coding: utf-8 -*- from django.contrib import admin from blanc_pages.admin import BlancPageAdminMixin from .models import Category, Event @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): search_fields = ('title',) prepopulated_fields = { 'slug': ('title',) } @admin.register(Event) class EventAdmin(BlancPageAdminMixin, admin.ModelAdmin): fieldsets = ( ('Event', { 'fields': ( 'title', 'category', 'location', 'image', 'summary', 'start', 'end' ) }), ('Advanced options', { 'fields': ('slug',) }), ) date_hierarchy = 'start' list_display = ('title', 'start', 'end', 'category',) list_filter = ('published', 'start', 'category',) prepopulated_fields = { 'slug': ('title',) }
Use category, not category title for list_filter
Use category, not category title for list_filter
Python
bsd-3-clause
blancltd/django-glitter-events,blancltd/django-glitter-events
--- +++ @@ -17,7 +17,6 @@ @admin.register(Event) class EventAdmin(BlancPageAdminMixin, admin.ModelAdmin): - pass fieldsets = ( ('Event', { 'fields': ( @@ -30,7 +29,7 @@ ) date_hierarchy = 'start' list_display = ('title', 'start', 'end', 'category',) - list_filter = ('published', 'start', 'category__title',) + list_filter = ('published', 'start', 'category',) prepopulated_fields = { 'slug': ('title',) }
e710c6be61f94ff2b82a84339c95a77611b291e8
fmn/api/distgit.py
fmn/api/distgit.py
import logging from fastapi import Depends from httpx import AsyncClient from ..core.config import Settings, get_settings log = logging.getLogger(__name__) class DistGitClient: def __init__(self, settings): self.client = AsyncClient(base_url=settings.services.distgit_url, timeout=None) async def get_projects(self, pattern): response = await self.client.get( "/api/0/projects", params={ "pattern": f"*{pattern}*", "short": "true", "fork": "false", }, ) response.raise_for_status() result = response.json() return [project["name"] for project in result["projects"]] def get_distgit_client(settings: Settings = Depends(get_settings)): return DistGitClient(settings)
import logging from fastapi import Depends from httpx import AsyncClient from ..core.config import Settings, get_settings log = logging.getLogger(__name__) class DistGitClient: def __init__(self, settings): self.client = AsyncClient(base_url=settings.services.distgit_url, timeout=None) async def get_projects(self, pattern): response = await self.client.get( "/api/0/projects", params={ "pattern": f"*{pattern}*", "short": "true", "fork": "false", }, ) response.raise_for_status() result = response.json() return result["projects"] def get_distgit_client(settings: Settings = Depends(get_settings)): return DistGitClient(settings)
Fix retrieval of artifact names
Fix retrieval of artifact names Signed-off-by: Aurélien Bompard <bceb368e7f2cb351af47298f32034f0587bbe4a6@bompard.org>
Python
lgpl-2.1
fedora-infra/fmn,fedora-infra/fmn,fedora-infra/fmn,fedora-infra/fmn,fedora-infra/fmn
--- +++ @@ -23,8 +23,7 @@ ) response.raise_for_status() result = response.json() - - return [project["name"] for project in result["projects"]] + return result["projects"] def get_distgit_client(settings: Settings = Depends(get_settings)):
6e76c9af0a4bdd6696b918913af73559c6dcd3c3
main.py
main.py
#!/usr/bin/env python3 from flask import Flask from flask import request from flask import jsonify from utils import download_file, is_video_json_valid from annotations import sort_annotations_by_time, is_annotation_json_valid from videoeditor import bake_annotations app = Flask(__name__) @app.route("/", methods=["POST"]) def index(): request_json = request.get_json() # Allow both plain JSON objects and arrays if type(request_json) is dict: request_json = [request_json] for video_json in request_json: if not is_video_json_valid(video_json) or not is_annotation_json_valid(video_json["annotations"]): return jsonify({"message": "Annotation json was malformed"}), 400 else : video_uri = video_json["videoUri"] video_filename = video_uri.rsplit("/")[-1] video_location = download_file(video_uri, video_filename) sorted_annotations = sort_annotations_by_time(video_json["annotations"]) bake_annotations(video_location, video_filename, sorted_annotations) return jsonify({"message": "Annotated video created succesfully"}) if __name__ == "__main__": app.run(debug=True)
#!/usr/bin/env python3 from flask import Flask from flask import request from flask import jsonify from utils import download_file, is_video_json_valid from annotations import sort_annotations_by_time, is_annotation_json_valid from videoeditor import bake_annotations app = Flask(__name__) @app.route("/", methods=["POST"]) def index(): request_json = request.get_json() # Allow both plain JSON objects and arrays if type(request_json) is dict: request_json = [request_json] for video_json in request_json: if not is_video_json_valid(video_json): return jsonify({"message": "A video json was malformed"}), 400 if not video_json["annotations"]: # TODO: Handle video with no annotations break if not is_annotation_json_valid(video_json["annotations"]): return jsonify({"message": "An annotation json was malformed"}), 400 else : video_uri = video_json["videoUri"] video_filename = video_uri.rsplit("/")[-1] video_location = download_file(video_uri, video_filename) sorted_annotations = sort_annotations_by_time(video_json["annotations"]) bake_annotations(video_location, video_filename, sorted_annotations) return jsonify({"message": "Annotated video created succesfully"}) if __name__ == "__main__": app.run(debug=True)
Add a bunch more JSON payload validation related funcionality
Add a bunch more JSON payload validation related funcionality
Python
mit
melonmanchan/achso-video-exporter,melonmanchan/achso-video-exporter
--- +++ @@ -19,8 +19,13 @@ request_json = [request_json] for video_json in request_json: - if not is_video_json_valid(video_json) or not is_annotation_json_valid(video_json["annotations"]): - return jsonify({"message": "Annotation json was malformed"}), 400 + if not is_video_json_valid(video_json): + return jsonify({"message": "A video json was malformed"}), 400 + if not video_json["annotations"]: + # TODO: Handle video with no annotations + break + if not is_annotation_json_valid(video_json["annotations"]): + return jsonify({"message": "An annotation json was malformed"}), 400 else : video_uri = video_json["videoUri"] video_filename = video_uri.rsplit("/")[-1]
221ff606f1c834141dd19d9101ab750733437b95
make.py
make.py
#!/usr/bin/env python """ make.py A drop-in or mostly drop-in replacement for GNU make. """ import sys, os import pymake.command, pymake.process pymake.command.main(sys.argv[1:], os.environ, os.getcwd(), cb=sys.exit) pymake.process.ParallelContext.spin() assert False, "Not reached"
#!/usr/bin/env python """ make.py A drop-in or mostly drop-in replacement for GNU make. """ import sys, os import pymake.command, pymake.process import gc gc.disable() pymake.command.main(sys.argv[1:], os.environ, os.getcwd(), cb=sys.exit) pymake.process.ParallelContext.spin() assert False, "Not reached"
Disable GC, since we no longer create cycles anywhere.
Disable GC, since we no longer create cycles anywhere.
Python
mit
indygreg/pymake,mozilla/pymake,mozilla/pymake,mozilla/pymake
--- +++ @@ -9,6 +9,9 @@ import sys, os import pymake.command, pymake.process +import gc +gc.disable() + pymake.command.main(sys.argv[1:], os.environ, os.getcwd(), cb=sys.exit) pymake.process.ParallelContext.spin() assert False, "Not reached"
6466e0fb7c5f7da0048a9ed9e1dd8023ddc5f59a
members/views.py
members/views.py
from django.shortcuts import render from django.http import HttpResponse from hackfmi.utils import json_view from .models import User def homepage(request): return render(request, "index.html", {}) @json_view def search(request, name): members = User.objects.filter(first_name__icontains=name) or \ User.objects.filter(last_name__icontains=name) or \ User.objects.filter(username__icontains=name) json_data = [dict( id=member.id, full_name=' '.join([member.first_name, member.last_name])) for member in members] return json_data
# -*- coding: utf-8 -*- from django.shortcuts import render from django.http import HttpResponse from hackfmi.utils import json_view from .models import User def homepage(request): return render(request, "index.html", {}) @json_view def search(request, name): members = User.objects.filter(first_name__icontains=name) or \ User.objects.filter(last_name__icontains=name) or \ User.objects.filter(username__icontains=name) json_data = [dict( id=member.id, faculty_number=member.faculty_number, full_name=' '.join([member.first_name, member.last_name])) for member in members] return json_data
Add faculty_number to search's json
Add faculty_number to search's json
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
--- +++ @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from django.shortcuts import render from django.http import HttpResponse @@ -17,6 +18,7 @@ json_data = [dict( id=member.id, + faculty_number=member.faculty_number, full_name=' '.join([member.first_name, member.last_name])) for member in members]
87ce10a94bdbedd97dae19989a7382b2bfa8ecde
snactor/utils/__init__.py
snactor/utils/__init__.py
def get_chan(channels, chan): channels.setdefault(chan['name'], {'producers': [], 'consumers': [], 'data': chan})
def get_chan(channels, chan): return channels.setdefault(chan['name'], {'producers': [], 'consumers': [], 'data': chan})
Fix get_chan (which should return the channel)
Fix get_chan (which should return the channel)
Python
apache-2.0
leapp-to/snactor
--- +++ @@ -1,3 +1,3 @@ def get_chan(channels, chan): - channels.setdefault(chan['name'], {'producers': [], 'consumers': [], 'data': chan}) + return channels.setdefault(chan['name'], {'producers': [], 'consumers': [], 'data': chan})
fdb1931b7cac6f0c7968829efb81ea677d2b5390
linux/user/srwrapper.py
linux/user/srwrapper.py
#!/usr/bin/env python import subprocess import sys import time SRHOME = '/home/stoneridge' SRPYTHON = '%s/stoneridge' % (SRHOME,) SRRUN = '%s/srrun.py' % (SRPYTHON,) SRWORKER = '%s/srworker.py' % (SRPYTHON,) SRINI = '%s/stoneridge.ini' % (SRHOME,) LOG = '%s/srworker.log' % (SRHOME,) cli = [sys.executable, SRRUN, SRWORKER, '--config', SRINI, '--log', LOG] p = subprocess.Popen(cli) p.wait() while True: # Sleep indefinitely in case of failure, so we choose when to kill the # terminal. This isn't particularly useful on the actual infrastructure, # but it works great for debugging errors during testing. time.sleep(60)
#!/usr/bin/env python import subprocess import sys import time SRHOME = '/home/stoneridge' SRPYTHON = '%s/stoneridge' % (SRHOME,) SRRUN = '%s/srrun.py' % (SRPYTHON,) SRWORKER = '%s/srworker.py' % (SRPYTHON,) SRINI = '%s/stoneridge.ini' % (SRHOME,) LOG = '%s/logs/srworker.log' % (SRHOME,) cli = [sys.executable, SRRUN, SRWORKER, '--config', SRINI, '--log', LOG] p = subprocess.Popen(cli) p.wait() while True: # Sleep indefinitely in case of failure, so we choose when to kill the # terminal. This isn't particularly useful on the actual infrastructure, # but it works great for debugging errors during testing. time.sleep(60)
Fix path to worker log on linux
Fix path to worker log on linux
Python
mpl-2.0
mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge
--- +++ @@ -9,7 +9,7 @@ SRRUN = '%s/srrun.py' % (SRPYTHON,) SRWORKER = '%s/srworker.py' % (SRPYTHON,) SRINI = '%s/stoneridge.ini' % (SRHOME,) -LOG = '%s/srworker.log' % (SRHOME,) +LOG = '%s/logs/srworker.log' % (SRHOME,) cli = [sys.executable, SRRUN, SRWORKER, '--config', SRINI, '--log', LOG]
957513329838474ba8f54c4571ea87c92600caf1
pyli.py
pyli.py
import parser import token import symbol import sys from pprint import pprint tree = parser.st2tuple(parser.suite(sys.argv[1])) def convert_readable(tree): return tuple(((token.tok_name[i] if token.tok_name.get(i) else symbol.sym_name[i]) if isinstance(i, int) else (i if isinstance(i, str) else convert_readable(i))) for i in tree) read_tree = convert_readable(tree) pprint(read_tree)
import parser import token import symbol import sys from pprint import pprint tree = parser.st2tuple(parser.suite(sys.argv[1])) def convert_readable(tree): return tuple(((token.tok_name[i] if token.tok_name.get(i) else symbol.sym_name[i]) if isinstance(i, int) else (i if isinstance(i, str) else convert_readable(i))) for i in tree) def find_tokens(tree): if isinstance(tree, str): return tuple(), tuple() if tree[0] == 'NAME': return (tree[1],), tuple() if tree[0] == 'import_name': return tuple(), find_tokens(tree[2])[0] if tree[0] == 'expr_stmt' and any(t[0] == 'EQUAL' for t in tree[1:]): i = (i for i,t in enumerate(tree[1:]) if t[0] == 'EQUAL').next() return (tuple(token for t in tree[i+1:] for token in find_tokens(t)[0]), tuple(token for t in tree[:i] for token in find_tokens(t)[0])) if all(isinstance(t, str) for t in tree): return tuple(), tuple() fb = tuple(find_tokens(t) for t in (p for p in tree if isinstance(p, tuple))) print fb free, bound = zip(*fb) free = tuple(x for f in free for x in f) bound = tuple(x for f in bound for x in f) return tuple(free), tuple(bound) read_tree = convert_readable(tree) pprint(read_tree) pprint(find_tokens(read_tree))
Write a free/bound token finder
Write a free/bound token finder
Python
mit
thenoviceoof/pyli
--- +++ @@ -15,5 +15,26 @@ (i if isinstance(i, str) else convert_readable(i))) for i in tree) +def find_tokens(tree): + if isinstance(tree, str): + return tuple(), tuple() + if tree[0] == 'NAME': + return (tree[1],), tuple() + if tree[0] == 'import_name': + return tuple(), find_tokens(tree[2])[0] + if tree[0] == 'expr_stmt' and any(t[0] == 'EQUAL' for t in tree[1:]): + i = (i for i,t in enumerate(tree[1:]) if t[0] == 'EQUAL').next() + return (tuple(token for t in tree[i+1:] for token in find_tokens(t)[0]), + tuple(token for t in tree[:i] for token in find_tokens(t)[0])) + if all(isinstance(t, str) for t in tree): + return tuple(), tuple() + fb = tuple(find_tokens(t) for t in (p for p in tree if isinstance(p, tuple))) + print fb + free, bound = zip(*fb) + free = tuple(x for f in free for x in f) + bound = tuple(x for f in bound for x in f) + return tuple(free), tuple(bound) + read_tree = convert_readable(tree) pprint(read_tree) +pprint(find_tokens(read_tree))
a65d86ea92d6b3de2d8585650595677efc18d3c2
test.py
test.py
import time import urllib import RPi.GPIO as GPIO # GPIO input pin to use LPR_PIN = 3 # URL to get image from SOURCE = 'http://192.168.0.13:8080/photoaf.jpg' # Path to save image locally FILE = 'img.jpg' # Use GPIO pin numbers GPIO.setmode(GPIO.BCM) # Disable "Ports already in use" warning GPIO.setwarnings(False) # Set the pin to be an input GPIO.setup(LPR_PIN, GPIO.IN) # Only save the image once per gate openning captured = False # Main loop while True: # Capture the image if not captured yet and switch is closed (open gate) if not captured and GPIO.input(LPR_PIN) == True: urllib.urlretrieve(SOURCE, FILE) print "Gate has been opened!" captured = True # If there was a capture and the switch is now open (closed gate) then # ready the loop to capture again. if captured and GPIO.input(LPR_PIN) == False: print "The gate has now closed!" captured = False time.sleep(0.1)
import time import urllib import RPi.GPIO as GPIO # GPIO input pin to use LPR_PIN = 3 # URL to get image from SOURCE = 'http://192.168.0.13:8080/photoaf.jpg' # Path to save image locally FILE = 'img.jpg' # Use GPIO pin numbers GPIO.setmode(GPIO.BCM) # Disable "Ports already in use" warning GPIO.setwarnings(False) # Set the pin to be an input GPIO.setup(LPR_PIN, GPIO.IN) # Only save the image once per gate openning captured = False # Main loop while True: # Capture the image if not captured yet and switch is closed (open gate) if not captured and GPIO.input(LPR_PIN) == True: urllib.urlretrieve(SOURCE, FILE) print "Gate has been opened!" captured = True # If there was a capture and the switch is now open (closed gate) then # ready the loop to capture again. if captured and GPIO.input(LPR_PIN) == False: print "The gate has now closed!" captured = False time.sleep(1)
Adjust loop delay to take into account switch undecidedness (Step one in presentation)
Adjust loop delay to take into account switch undecidedness (Step one in presentation)
Python
mit
adampiskorski/lpr_poc
--- +++ @@ -34,4 +34,4 @@ print "The gate has now closed!" captured = False - time.sleep(0.1) + time.sleep(1)
5841f314636ee534342aa3e4530cc3ee933a052b
src/ezweb/compressor_filters.py
src/ezweb/compressor_filters.py
# -*- coding: utf-8 -*- from compressor.filters import FilterBase class JSUseStrictFilter(FilterBase): def output(self, **kwargs): return self.remove_use_strict(self.content) def remove_use_strict(js): js = js.replace("'use strict';", '') js = js.replace('"use strict";', '') return js
# -*- coding: utf-8 -*- from compressor.filters import FilterBase class JSUseStrictFilter(FilterBase): def output(self, **kwargs): return self.remove_use_strict(self.content) def remove_use_strict(self, js): # Replacing by a ';' is safer than replacing by '' js = js.replace("'use strict';", ';') js = js.replace('"use strict";', ';') return js
Fix a bug while replacing "use strict" JS pragmas
Fix a bug while replacing "use strict" JS pragmas
Python
agpl-3.0
jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud
--- +++ @@ -8,7 +8,8 @@ def output(self, **kwargs): return self.remove_use_strict(self.content) - def remove_use_strict(js): - js = js.replace("'use strict';", '') - js = js.replace('"use strict";', '') + def remove_use_strict(self, js): + # Replacing by a ';' is safer than replacing by '' + js = js.replace("'use strict';", ';') + js = js.replace('"use strict";', ';') return js
ff67e435ea31680698166e4ae3296ff4211e2b51
kremlin/__init__.py
kremlin/__init__.py
""" # # #### ##### # # ##### # # # # # # # # # ## ## # # # ## # # ### #### #### # # # # # # # # ##### # # # # # # # # ## # # # # # # ##### # # # # # # # # Kremlin Magical Everything System Glasnost Image Board and Boredom Inhibitor """ from flask import Flask from flaskext.sqlalchemy import SQLAlchemy from flaskext.uploads import configure_uploads, UploadSet, IMAGES app = Flask(__name__) # Load default configuration values, override with whatever is specified # in configuration file. This is, I think, the sanest approach. app.config.from_object('kremlin.config_defaults') app.config.from_envvar('KREMLIN_CONFIGURATION') # Set database from configuration values app.config['SQLALCHEMY_DATABASE_URI'] = app.config['DATABASE_URI'] db = SQLAlchemy(app) uploaded_images = UploadSet("images", IMAGES) # Create upload set # and configure like a motherfucker. uploaded_images = UploadSet("images", IMAGES) configure_uploads(app, uploaded_images) # Import relevant modules # this is done last to avoid touchy situations import kremlin.dbmodel import kremlin.core import kremlin.forms # Create all database tables db.create_all()
""" # # #### ##### # # ##### # # # # # # # # # ## ## # # # ## # # ### #### #### # # # # # # # # ##### # # # # # # # # ## # # # # # # ##### # # # # # # # # Kremlin Magical Everything System Glasnost Image Board and Boredom Inhibitor """ from flask import Flask from flaskext.uploads import configure_uploads, UploadSet, IMAGES from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) # Load default configuration values, override with whatever is specified # in configuration file. This is, I think, the sanest approach. app.config.from_object('kremlin.config_defaults') app.config.from_envvar('KREMLIN_CONFIGURATION') # Set database from configuration values app.config['SQLALCHEMY_DATABASE_URI'] = app.config['DATABASE_URI'] db = SQLAlchemy(app) uploaded_images = UploadSet("images", IMAGES) # Create upload set # and configure like a motherfucker. uploaded_images = UploadSet("images", IMAGES) configure_uploads(app, uploaded_images) # Import relevant modules # this is done last to avoid touchy situations import kremlin.dbmodel import kremlin.core import kremlin.forms # Create all database tables db.create_all()
Fix import for new Flask-SQlAlchemy (no longer in flaskext)
Fix import for new Flask-SQlAlchemy (no longer in flaskext)
Python
bsd-2-clause
glasnost/kremlin,glasnost/kremlin,glasnost/kremlin
--- +++ @@ -11,8 +11,8 @@ """ from flask import Flask -from flaskext.sqlalchemy import SQLAlchemy from flaskext.uploads import configure_uploads, UploadSet, IMAGES +from flask_sqlalchemy import SQLAlchemy app = Flask(__name__)
b09424edf37989c3868eb63badfc65897d41f410
kremlin/__init__.py
kremlin/__init__.py
""" # # #### ##### # # ##### # # # # # # # # # ## ## # # # ## # # ### #### #### # # # # # # # # ##### # # # # # # # # ## # # # # # # ##### # # # # # # # # Kremlin Magical Everything System Glasnost Image Board and Boredom Inhibitor """ from flask import Flask from flaskext.uploads import configure_uploads, UploadSet, IMAGES from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) # Load default configuration values, override with whatever is specified # in configuration file. This is, I think, the sanest approach. app.config.from_object('kremlin.config_defaults') app.config.from_envvar('KREMLIN_CONFIGURATION') # Set database from configuration values app.config['SQLALCHEMY_DATABASE_URI'] = app.config['DATABASE_URI'] db = SQLAlchemy(app) # Create upload set # and configure like a motherfucker. uploaded_images = UploadSet("images", IMAGES) configure_uploads(app, uploaded_images) # Import relevant modules # this is done last to avoid touchy situations import kremlin.dbmodel import kremlin.core import kremlin.forms def db_init(): """ Initialize database for use """ db.create_all()
""" # # #### ##### # # ##### # # # # # # # # # ## ## # # # ## # # ### #### #### # # # # # # # # ##### # # # # # # # # ## # # # # # # ##### # # # # # # # # Kremlin Magical Everything System Glasnost Image Board and Boredom Inhibitor """ from flask import Flask from flask_uploads import configure_uploads, UploadSet, IMAGES from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) # Load default configuration values, override with whatever is specified # in configuration file. This is, I think, the sanest approach. app.config.from_object('kremlin.config_defaults') app.config.from_envvar('KREMLIN_CONFIGURATION') # Set database from configuration values app.config['SQLALCHEMY_DATABASE_URI'] = app.config['DATABASE_URI'] db = SQLAlchemy(app) # Create upload set # and configure like a motherfucker. uploaded_images = UploadSet("images", IMAGES) configure_uploads(app, uploaded_images) # Import relevant modules # this is done last to avoid touchy situations import kremlin.dbmodel import kremlin.core import kremlin.forms def db_init(): """ Initialize database for use """ db.create_all()
Fix legacy import for Flask-Uploads
Fix legacy import for Flask-Uploads
Python
bsd-2-clause
glasnost/kremlin,glasnost/kremlin,glasnost/kremlin
--- +++ @@ -11,7 +11,7 @@ """ from flask import Flask -from flaskext.uploads import configure_uploads, UploadSet, IMAGES +from flask_uploads import configure_uploads, UploadSet, IMAGES from flask_sqlalchemy import SQLAlchemy app = Flask(__name__)
3d51452d466fc733ee782d8e82463588bb9d2418
handler/base_handler.py
handler/base_handler.py
import os from serf_master import SerfHandler from utils import with_payload, truncated_stdout class BaseHandler(SerfHandler): def __init__(self, *args, **kwargs): super(BaseHandler, self).__init__(*args, **kwargs) self.setup() def setup(self): pass @truncated_stdout @with_payload def where(self, role=None): my_role = os.environ.get('ROLE', 'no_role') if my_role == role: print(self.my_info()) def my_info(self): return { 'ip': os.environ.get('ADVERTISE', None) }
import os import socket from serf_master import SerfHandler from utils import with_payload, truncated_stdout class BaseHandler(SerfHandler): def __init__(self, *args, **kwargs): super(BaseHandler, self).__init__(*args, **kwargs) self.setup() def setup(self): pass @truncated_stdout @with_payload def where(self, role=None): my_role = os.environ.get('ROLE', 'no_role') if my_role == role: print(self.my_info()) def my_info(self): ip = (os.environ.get('ADVERTISE') or socket.gethostbyname(socket.gethostname())) return {'ip': ip}
Improve default for ip in 'where' event
Improve default for ip in 'where' event
Python
mit
waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode
--- +++ @@ -1,4 +1,5 @@ import os +import socket from serf_master import SerfHandler from utils import with_payload, truncated_stdout @@ -21,6 +22,6 @@ print(self.my_info()) def my_info(self): - return { - 'ip': os.environ.get('ADVERTISE', None) - } + ip = (os.environ.get('ADVERTISE') or + socket.gethostbyname(socket.gethostname())) + return {'ip': ip}
85b3a68ef93aa18dd176d8804f7f5089d7cf7be9
helpers/file_helpers.py
helpers/file_helpers.py
import os def expand_directory(directory_path): ret = [] for file_path in os.listdir(directory_path): if os.path.isfile(os.path.join(directory_path, file_path)): # Append instead of extend or += because those separate the string into its individual characters # This has to do with the way strings act like lists in python ret.append(os.path.join(directory_path, file_path)) return ret def find_file_id_in_commit(file_name, revision_number): with open(".pvcs/revisions/" + str(revision_number) + "/change_map") as change_map: for line in change_map.readlines(): if line.find(file_name) != -1: return int(line.split(",")[0])
import os def expand_directory(directory_path): """Recursively create a list of all the files in a directory and its subdirectories """ ret = [] for file_path in os.listdir(directory_path): if os.path.isfile(os.path.join(directory_path, file_path)): # Append instead of extend or += because those separate the string into its individual characters # This has to do with the way strings act like lists in python ret.append(os.path.join(directory_path, file_path)) else: ret.extend(expand_directory(os.path.join(directory_path, file_path))) return ret def find_file_id_in_commit(file_name, revision_number): """Find the file id of a specified file in the change map of a specified commit """ with open(".pvcs/revisions/" + str(revision_number) + "/change_map") as change_map: # Loop through every line, find the one containing the file, return the id for line in change_map.readlines(): if line.find(file_name) != -1: return int(line.split(",")[0])
Add more documentation. Fix the expand_directory function
Add more documentation. Fix the expand_directory function
Python
mit
PaulOlteanu/PVCS
--- +++ @@ -1,6 +1,8 @@ import os def expand_directory(directory_path): + """Recursively create a list of all the files in a directory and its subdirectories + """ ret = [] for file_path in os.listdir(directory_path): @@ -8,11 +10,18 @@ # Append instead of extend or += because those separate the string into its individual characters # This has to do with the way strings act like lists in python ret.append(os.path.join(directory_path, file_path)) + else: + ret.extend(expand_directory(os.path.join(directory_path, file_path))) return ret def find_file_id_in_commit(file_name, revision_number): + """Find the file id of a specified file in the change map of a specified commit + """ + + with open(".pvcs/revisions/" + str(revision_number) + "/change_map") as change_map: + # Loop through every line, find the one containing the file, return the id for line in change_map.readlines(): if line.find(file_name) != -1: return int(line.split(",")[0])
1f4bd95d758db4e2388b180f637963e26a033790
InvenTree/part/migrations/0034_auto_20200404_1238.py
InvenTree/part/migrations/0034_auto_20200404_1238.py
# Generated by Django 2.2.10 on 2020-04-04 12:38 from django.db import migrations from django.db.utils import OperationalError, ProgrammingError from part.models import Part from stdimage.utils import render_variations def create_thumbnails(apps, schema_editor): """ Create thumbnails for all existing Part images. """ try: for part in Part.objects.all(): # Render thumbnail for each existing Part if part.image: try: part.image.render_variations() except FileNotFoundError: print("Missing image:", part.image()) # The image is missing, so clear the field part.image = None part.save() except (OperationalError, ProgrammingError): # Migrations have not yet been applied - table does not exist print("Could not generate Part thumbnails") class Migration(migrations.Migration): dependencies = [ ('part', '0033_auto_20200404_0445'), ] operations = [ migrations.RunPython(create_thumbnails), ]
# Generated by Django 2.2.10 on 2020-04-04 12:38 from django.db import migrations def create_thumbnails(apps, schema_editor): """ Create thumbnails for all existing Part images. Note: This functionality is now performed in apps.py, as running the thumbnail script here caused too many database level errors. This migration is left here to maintain the database migration history """ pass class Migration(migrations.Migration): dependencies = [ ('part', '0033_auto_20200404_0445'), ] operations = [ migrations.RunPython(create_thumbnails, reverse_code=create_thumbnails), ]
Remove the problematic migration entirely
Remove the problematic migration entirely - The thumbnail check code is run every time the server is started anyway!
Python
mit
inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree
--- +++ @@ -1,32 +1,20 @@ # Generated by Django 2.2.10 on 2020-04-04 12:38 from django.db import migrations -from django.db.utils import OperationalError, ProgrammingError - -from part.models import Part -from stdimage.utils import render_variations def create_thumbnails(apps, schema_editor): """ Create thumbnails for all existing Part images. + + Note: This functionality is now performed in apps.py, + as running the thumbnail script here caused too many database level errors. + + This migration is left here to maintain the database migration history + """ + pass - try: - for part in Part.objects.all(): - # Render thumbnail for each existing Part - if part.image: - try: - part.image.render_variations() - except FileNotFoundError: - print("Missing image:", part.image()) - # The image is missing, so clear the field - part.image = None - part.save() - - except (OperationalError, ProgrammingError): - # Migrations have not yet been applied - table does not exist - print("Could not generate Part thumbnails") class Migration(migrations.Migration): @@ -35,5 +23,5 @@ ] operations = [ - migrations.RunPython(create_thumbnails), + migrations.RunPython(create_thumbnails, reverse_code=create_thumbnails), ]
1f598e3752d18ecf4f022588531093d711ac6c01
lemur/authorizations/models.py
lemur/authorizations/models.py
""" .. module: lemur.authorizations.models :platform: unix :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Netflix Secops <secops@netflix.com> """ from sqlalchemy import Column, Integer, String from sqlalchemy_utils import JSONType from lemur.database import db from lemur.plugins.base import plugins class Authorization(db.Model): __tablename__ = "pending_dns_authorizations" id = Column(Integer, primary_key=True, autoincrement=True) account_number = Column(String(128)) domains = Column(JSONType) dns_provider_type = Column(String(128)) options = Column(JSONType) @property def plugin(self): return plugins.get(self.plugin_name) def __repr__(self): return "Authorization(id={id})".format(label=self.id) def __init__(self, account_number, domains, dns_provider_type, options=None): self.account_number = account_number self.domains = domains self.dns_provider_type = dns_provider_type self.options = options
""" .. module: lemur.authorizations.models :platform: unix :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Netflix Secops <secops@netflix.com> """ from sqlalchemy import Column, Integer, String from sqlalchemy_utils import JSONType from lemur.database import db from lemur.plugins.base import plugins class Authorization(db.Model): __tablename__ = "pending_dns_authorizations" id = Column(Integer, primary_key=True, autoincrement=True) account_number = Column(String(128)) domains = Column(JSONType) dns_provider_type = Column(String(128)) options = Column(JSONType) @property def plugin(self): return plugins.get(self.plugin_name) def __repr__(self): return "Authorization(id={id})".format(id=self.id) def __init__(self, account_number, domains, dns_provider_type, options=None): self.account_number = account_number self.domains = domains self.dns_provider_type = dns_provider_type self.options = options
Fix unmatched field in Authorization
Fix unmatched field in Authorization The field in the formatted string was not matching the args
Python
apache-2.0
Netflix/lemur,Netflix/lemur,Netflix/lemur,Netflix/lemur
--- +++ @@ -25,7 +25,7 @@ return plugins.get(self.plugin_name) def __repr__(self): - return "Authorization(id={id})".format(label=self.id) + return "Authorization(id={id})".format(id=self.id) def __init__(self, account_number, domains, dns_provider_type, options=None): self.account_number = account_number
0e7487948fe875d5d077f230b804983b28ca72cb
utils.py
utils.py
from score import score_funcs from db import conn curr = conn.cursor() def process_diff(diffiduser): try: diffid, user = diffiduser except: return diff = get_diff_for_diffid(diffid) zum = 0 for f in score_funcs: zum += f(diff) print zum, diffid def get_diff_for_diffid(diffid): return "This is a test diff" def get_is_spam_score(diff): return 0 def is_spam(diff): return get_is_spam_score(diff) > 0.6
from score import score_funcs from db import conn curr = conn.cursor() def process_diff(diffiduser): try: diffid, user = diffiduser except: return diff = get_diff_for_diffid(diffid) zum = 0 for f in score_funcs: zum += f(diff) print zum, diffid def get_diff_for_diffid(diffid): rev = urlopen("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&format=json&rvdiffto=prev&revids=%s" % diffid).read() rev = json.loads(rev) pages = rev["query"]["pages"] diff = pages.values()[0]["revisions"][0]["diff"]["*"] diff = lxml.html.document_fromstring(diff) addedlines = diff.xpath("//td[@class='diff-addedline']") deledlines = diff.xpath("//td[@class='diff-deletedline']") addedstring = "" deledstring = "" for i in addedlines: diffchanges = i.xpath("./span[@class='diffchange diffchange-inline']/text()") if not diffchanges: addedstring = addedstring + " " + i.text_content() else: addedstring = addedstring + " " + " ".join(diffchanges) for i in deledlines: diffchanges = i.xpath("./span[@class='diffchange diffchange-inline']/text()") if not diffchanges: deledstring = deledstring + " " + i.text_content() else: deledstring = deledstring + " " + " ".join(diffchanges) return addedstring, deledstring def get_is_spam_score(diff): return 0 def is_spam(diff): return get_is_spam_score(diff) > 0.6
Add util function for getting diff content
Add util function for getting diff content
Python
mit
tjcsl/wedge,tjcsl/wedge
--- +++ @@ -16,7 +16,28 @@ def get_diff_for_diffid(diffid): - return "This is a test diff" + rev = urlopen("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&format=json&rvdiffto=prev&revids=%s" % diffid).read() + rev = json.loads(rev) + pages = rev["query"]["pages"] + diff = pages.values()[0]["revisions"][0]["diff"]["*"] + diff = lxml.html.document_fromstring(diff) + addedlines = diff.xpath("//td[@class='diff-addedline']") + deledlines = diff.xpath("//td[@class='diff-deletedline']") + addedstring = "" + deledstring = "" + for i in addedlines: + diffchanges = i.xpath("./span[@class='diffchange diffchange-inline']/text()") + if not diffchanges: + addedstring = addedstring + " " + i.text_content() + else: + addedstring = addedstring + " " + " ".join(diffchanges) + for i in deledlines: + diffchanges = i.xpath("./span[@class='diffchange diffchange-inline']/text()") + if not diffchanges: + deledstring = deledstring + " " + i.text_content() + else: + deledstring = deledstring + " " + " ".join(diffchanges) + return addedstring, deledstring def get_is_spam_score(diff):
4ca1fdddfa7b76ecd515473d102867868f8d7204
pywikibot/families/wikidata_family.py
pywikibot/families/wikidata_family.py
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The wikidata family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikidata' self.langs = { 'wikidata': 'wikidata.org', 'repo': 'wikidata-test-repo.wikimedia.de', 'client': 'wikidata-test-client.wikimedia.de', } def shared_data_repository(self, code, transcluded=False): """Always return a repository tupe. This enables testing whether the site opject is the repository itself, see Site.is_data_repository() """ if transcluded: return(None, None) else: return ('wikidata', 'wikidata') if code == 'wikidata' else ('repo', 'wikidata')
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The wikidata family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikidata' self.langs = { 'wikidata': 'www.wikidata.org', 'repo': 'wikidata-test-repo.wikimedia.de', 'client': 'wikidata-test-client.wikimedia.de', } def shared_data_repository(self, code, transcluded=False): """Always return a repository tupe. This enables testing whether the site opject is the repository itself, see Site.is_data_repository() """ if transcluded: return(None, None) else: return ('wikidata', 'wikidata') if code == 'wikidata' else ('repo', 'wikidata')
Use www.wikidata.org instead of wikidata.org Rewrite-followup to r11105
Use www.wikidata.org instead of wikidata.org Rewrite-followup to r11105 Patch #3605769 by Legoktm Because of various issues [1], using wikidata.org may cause random problems. Using www.wikidata.org will fix these. [1] https://bugzilla.wikimedia.org/show_bug.cgi?id=45005
Python
mit
pywikibot/core-migration-example
--- +++ @@ -11,7 +11,7 @@ super(Family, self).__init__() self.name = 'wikidata' self.langs = { - 'wikidata': 'wikidata.org', + 'wikidata': 'www.wikidata.org', 'repo': 'wikidata-test-repo.wikimedia.de', 'client': 'wikidata-test-client.wikimedia.de', }
cd4d67ae0796e45ef699e1bab60ee5aeeac91dbb
native_qwebview_example/run.py
native_qwebview_example/run.py
import sys from browser import BrowserDialog from PyQt4 import QtGui from PyQt4.QtCore import QUrl from PyQt4.QtWebKit import QWebView class MyBrowser(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) QWebView.__init__(self) self.ui = BrowserDialog() self.ui.setupUi(self) self.ui.lineEdit.returnPressed.connect(self.loadURL) def loadURL(self): url = self.ui.lineEdit.text() self.ui.qwebview.load(QUrl(url)) self.show() # self.ui.lineEdit.setText("") if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = MyBrowser() myapp.ui.qwebview.load(QUrl('http://localhost:8800/taxtweb')) myapp.show() sys.exit(app.exec_())
# Basic example for testing purposes, taken from # https://pythonspot.com/creating-a-webbrowser-with-python-and-pyqt-tutorial/ import sys from browser import BrowserDialog from PyQt4 import QtGui from PyQt4.QtCore import QUrl from PyQt4.QtWebKit import QWebView class MyBrowser(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) QWebView.__init__(self) self.ui = BrowserDialog() self.ui.setupUi(self) self.ui.lineEdit.returnPressed.connect(self.loadURL) def loadURL(self): url = self.ui.lineEdit.text() self.ui.qwebview.load(QUrl(url)) self.show() # self.ui.lineEdit.setText("") if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = MyBrowser() myapp.ui.qwebview.load(QUrl('http://localhost:8800/taxtweb')) myapp.show() sys.exit(app.exec_())
Add a comment about where the basic example was taken [skip CI]
Add a comment about where the basic example was taken [skip CI]
Python
agpl-3.0
gem/oq-svir-qgis,gem/oq-svir-qgis,gem/oq-svir-qgis,gem/oq-svir-qgis
--- +++ @@ -1,3 +1,6 @@ +# Basic example for testing purposes, taken from +# https://pythonspot.com/creating-a-webbrowser-with-python-and-pyqt-tutorial/ + import sys from browser import BrowserDialog from PyQt4 import QtGui
5a2ff00b3574c8fb187fd87fcda3f79f7dd43b3c
tests/data_test.py
tests/data_test.py
from pork.data import Data from mock import Mock, patch, mock_open from StringIO import StringIO patch.TEST_PREFIX = 'it' class TestData: def it_loads_json_data_from_file(self): with patch("__builtin__.open", mock_open(read_data='{"foo":"bar"}'), create=True) as m: data = Data() assert data.get('foo') == 'bar' def it_sets_and_gets_keys(self): data = Data() data.set('foo', 'bar') assert data.get('foo') == 'bar' def it_deletes_existing_keys(self): data = Data() data.set('foo', 'bar') data.delete('foo') assert data.get('foo') is None def it_is_empty_if_there_are_no_keys(self): data = Data() assert data.is_empty() def it_returns_the_data_dict(self): data = Data() data.set('foo', 'bar') assert data.list() == { 'foo': 'bar' } def it_fails_silently_if_it_cannot_save(self): data = Data() with patch("__builtin__.open", side_effect=ValueError): data.set('foo', 'bar') assert True
from pork.data import Data from mock import Mock, patch, mock_open from StringIO import StringIO patch.TEST_PREFIX = 'it' @patch.object(Data, '_data_path', '/tmp/doesnt_exist') class TestData: def it_loads_json_data_from_file(self): with patch("__builtin__.open", mock_open(read_data='{"foo":"bar"}'), create=True) as m: data = Data() assert data.get('foo') == 'bar' def it_sets_and_gets_keys(self): data = Data() data.set('foo', 'bar') assert data.get('foo') == 'bar' def it_deletes_existing_keys(self): data = Data() data.set('foo', 'bar') data.delete('foo') assert data.get('foo') is None def it_is_empty_if_there_are_no_keys(self): data = Data() assert data.is_empty() def it_returns_the_data_dict(self): data = Data() data.set('foo', 'bar') assert data.list() == { 'foo': 'bar' } def it_fails_silently_if_it_cannot_save(self): data = Data() with patch("__builtin__.open", side_effect=ValueError): data.set('foo', 'bar') assert True
Patch Data._data_path so it doesn't find the real data file.
Patch Data._data_path so it doesn't find the real data file.
Python
mit
jimmycuadra/pork,jimmycuadra/pork
--- +++ @@ -5,6 +5,7 @@ patch.TEST_PREFIX = 'it' +@patch.object(Data, '_data_path', '/tmp/doesnt_exist') class TestData: def it_loads_json_data_from_file(self): with patch("__builtin__.open", mock_open(read_data='{"foo":"bar"}'),
c4e1f1c147783a4a735dd943d5d7491302de300e
csunplugged/config/urls.py
csunplugged/config/urls.py
"""csunplugged URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = i18n_patterns( url(r'', include('general.urls', namespace='general')), url(r'^topics/', include('topics.urls', namespace='topics')), url(r'^resources/', include('resources.urls', namespace='resources')), url(r'^admin/', include(admin.site.urls)), ) # ] + static(settings.STATIC_URL, documnet_root=settings.STATIC_ROOT)
"""csunplugged URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin urlpatterns = i18n_patterns( url(r'', include('general.urls', namespace='general')), url(r'^topics/', include('topics.urls', namespace='topics')), url(r'^resources/', include('resources.urls', namespace='resources')), url(r'^admin/', include(admin.site.urls)), )
Remove unused static URL pathing
Remove unused static URL pathing
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
--- +++ @@ -16,8 +16,6 @@ from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin -from django.conf import settings -from django.conf.urls.static import static urlpatterns = i18n_patterns( url(r'', include('general.urls', namespace='general')), @@ -25,4 +23,3 @@ url(r'^resources/', include('resources.urls', namespace='resources')), url(r'^admin/', include(admin.site.urls)), ) -# ] + static(settings.STATIC_URL, documnet_root=settings.STATIC_ROOT)
96c20164b3221321f71e12fd7054766a92722e08
test.py
test.py
from coils import user_input from sqlalchemy import create_engine username = user_input('Username', default='root') password = user_input('Password', password=True) dbname = user_input('Database name') engine = create_engine( 'mysql://{:}:{:}@localhost'.format(username, password), isolation_level='READ UNCOMMITTED' ) conn = engine.connect() conn.execute('drop database {:}'.format(dbname)) conn.close()
"""Add a timestamp.""" from coils import user_input, Config from sqlalchemy import create_engine, Column, DateTime, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker config = Config('wabbit.cfg') # Connect to database engine and start a session. dbname = user_input('Database name', default=config['db_name']) user1 = user_input('Username', default=config['username']) pass1 = user_input('Password', default=config['password']) host = user_input('Host', default=config['host']) engine = create_engine('mysql://{:}:{:}@{:}/{:}'.format(user1, pass1, host, dbname)) conn = engine.connect() Session = sessionmaker(bind=engine) session = Session() # Declare a mapping. Base = declarative_base() class Image(Base): __tablename__ = 'images' id = Column(Integer, primary_key=True) tstamp = Column(DateTime()) def __init__(self, tstamp): self.tstamp = tstamp def __repr__(self): return "<Image('{:}')>".format(self.tstamp) # Create the table. Base.metadata.create_all(engine) # Create the object. import datetime image1 = Image(datetime.datetime.now()) # Persist the object. session.add(image1) # Commit the transaction. session.commit() # Close the session. conn.close()
Add timestamp upon each run.
Add timestamp upon each run.
Python
mit
vmlaker/wabbit,vmlaker/wabbit,vmlaker/wabbit,vmlaker/wabbit
--- +++ @@ -1,14 +1,48 @@ -from coils import user_input -from sqlalchemy import create_engine +"""Add a timestamp.""" -username = user_input('Username', default='root') -password = user_input('Password', password=True) -dbname = user_input('Database name') +from coils import user_input, Config +from sqlalchemy import create_engine, Column, DateTime, Integer +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker -engine = create_engine( - 'mysql://{:}:{:}@localhost'.format(username, password), - isolation_level='READ UNCOMMITTED' - ) +config = Config('wabbit.cfg') + +# Connect to database engine and start a session. +dbname = user_input('Database name', default=config['db_name']) +user1 = user_input('Username', default=config['username']) +pass1 = user_input('Password', default=config['password']) +host = user_input('Host', default=config['host']) +engine = create_engine('mysql://{:}:{:}@{:}/{:}'.format(user1, pass1, host, dbname)) conn = engine.connect() -conn.execute('drop database {:}'.format(dbname)) +Session = sessionmaker(bind=engine) +session = Session() + +# Declare a mapping. +Base = declarative_base() +class Image(Base): + __tablename__ = 'images' + + id = Column(Integer, primary_key=True) + tstamp = Column(DateTime()) + + def __init__(self, tstamp): + self.tstamp = tstamp + + def __repr__(self): + return "<Image('{:}')>".format(self.tstamp) + +# Create the table. +Base.metadata.create_all(engine) + +# Create the object. +import datetime +image1 = Image(datetime.datetime.now()) + +# Persist the object. +session.add(image1) + +# Commit the transaction. +session.commit() + +# Close the session. conn.close()
7cd716635eb0db5f36e8267c312fc462aa16e210
prerequisites.py
prerequisites.py
#!/usr/bin/env python import sys # Check that we are in an activated virtual environment try: import os virtual_env = os.environ['VIRTUAL_ENV'] except KeyError: print("It doesn't look like you are in an activated virtual environment.") print("Did you make one?") print("Did you activate it?") sys.exit(1) # Check that we have installed Django try: import django except ImportError: print("It doesn't look like Django is installed.") print("Are you in an activated virtual environment?") print("Did you pip install from requirements.txt?") sys.exit(1) # Check that we have the expected version of Django expected_version = (1, 7, 1) try: assert django.VERSION[:3] == expected_version except AssertionError: print("It doesn't look like you have the expected version " "of Django installed.") print("You have {0}".format('.'.join([str(i) for i in django.VERSION][:3]))) sys.exit(1) # All good, have fun! print("Everything looks okay to me... Have fun!")
#!/usr/bin/env python import sys # Check that we are in an activated virtual environment try: import os virtual_env = os.environ['VIRTUAL_ENV'] except KeyError: print("It doesn't look like you are in an activated virtual environment.") print("Did you make one?") print("Did you activate it?") sys.exit(1) # Check that we have installed Django try: import django except ImportError: print("It doesn't look like Django is installed.") print("Are you in an activated virtual environment?") print("Did you pip install from requirements.txt?") sys.exit(1) # Check that we have the expected version of Django expected_version = '1.7.1' installed_version = django.get_version() try: assert installed_version == expected_version except AssertionError: print("It doesn't look like you have the expected version " "of Django installed.") print("You have {0}.".format(installed_version)) sys.exit(1) # All good, have fun! print("Everything looks okay to me... Have fun!")
Use django.get_version in prerequisite checker
Use django.get_version in prerequisite checker
Python
mit
mpirnat/django-tutorial-v2
--- +++ @@ -25,13 +25,14 @@ # Check that we have the expected version of Django -expected_version = (1, 7, 1) +expected_version = '1.7.1' +installed_version = django.get_version() try: - assert django.VERSION[:3] == expected_version + assert installed_version == expected_version except AssertionError: print("It doesn't look like you have the expected version " "of Django installed.") - print("You have {0}".format('.'.join([str(i) for i in django.VERSION][:3]))) + print("You have {0}.".format(installed_version)) sys.exit(1)
d53152aedff7777be771124a91ba325f75398739
test.py
test.py
#! /usr/bin/env python from theora import Ogg from numpy import concatenate, zeros_like from scipy.misc import toimage f = open("video.ogv") o = Ogg(f) Y, Cb, Cr = o.test() Cb2 = zeros_like(Y) for i in range(Cb2.shape[0]): for j in range(Cb2.shape[1]): Cb2[i, j] = Cb[i/2, j/2] Cr2 = zeros_like(Y) for i in range(Cr2.shape[0]): for j in range(Cr2.shape[1]): Cr2[i, j] = Cr[i/2, j/2] w, h = Y.shape Y = Y.reshape((1, w, h)) Cb = Cb2.reshape((1, w, h)) Cr = Cr2.reshape((1, w, h)) A = concatenate((Y, Cb, Cr)) img = toimage(A, mode="YCbCr", channel_axis=0) print img from pylab import imshow, show from matplotlib import cm imshow(img, origin="lower") show()
#! /usr/bin/env python from theora import Ogg from numpy import concatenate, zeros_like from scipy.misc import toimage f = open("video.ogv") o = Ogg(f) Y, Cb, Cr = o.test() Cb2 = zeros_like(Y) for i in range(Cb2.shape[0]): for j in range(Cb2.shape[1]): Cb2[i, j] = Cb[i/2, j/2] Cr2 = zeros_like(Y) for i in range(Cr2.shape[0]): for j in range(Cr2.shape[1]): Cr2[i, j] = Cr[i/2, j/2] w, h = Y.shape Y = Y.reshape((1, w, h)) Cb = Cb2.reshape((1, w, h)) Cr = Cr2.reshape((1, w, h)) A = concatenate((Y, Cb, Cr)) img = toimage(A, mode="YCbCr", channel_axis=0) img.convert("RGB").save("frame.png") from pylab import imshow, show from matplotlib import cm imshow(img, origin="lower") show()
Save the image to png
Save the image to png
Python
bsd-3-clause
certik/python-theora,certik/python-theora
--- +++ @@ -22,7 +22,7 @@ Cr = Cr2.reshape((1, w, h)) A = concatenate((Y, Cb, Cr)) img = toimage(A, mode="YCbCr", channel_axis=0) -print img +img.convert("RGB").save("frame.png") from pylab import imshow, show from matplotlib import cm
c244f074615765ba26874c2dba820a95984686bb
os_tasklib/neutron/__init__.py
os_tasklib/neutron/__init__.py
# -*- coding: utf-8 -*- # Copyright 2015 Hewlett-Packard Development Company, L.P. # # 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 create_port import CreatePort # noqa from delete_ports import DeletePorts # noqa from show_network import ShowNetwork # noqa
# -*- coding: utf-8 -*- # Copyright 2015 Hewlett-Packard Development Company, L.P. # # 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 os_tasklib.neutron.create_port import CreatePort # noqa from os_tasklib.neutron.delete_ports import DeletePorts # noqa from os_tasklib.neutron.show_network import ShowNetwork # noqa
Fix imports on Python 3
Fix imports on Python 3 On Python 3, imports are absolute by default. Because of these invalid imports, tests don't run anymore on Python 3, since tests cannot be loaded. Change-Id: Ib11a09432939df959568de400f60dfe981d0a403
Python
apache-2.0
stackforge/cue,stackforge/cue,openstack/cue,stackforge/cue,openstack/cue,openstack/cue
--- +++ @@ -14,6 +14,6 @@ # under the License. -from create_port import CreatePort # noqa -from delete_ports import DeletePorts # noqa -from show_network import ShowNetwork # noqa +from os_tasklib.neutron.create_port import CreatePort # noqa +from os_tasklib.neutron.delete_ports import DeletePorts # noqa +from os_tasklib.neutron.show_network import ShowNetwork # noqa
664c0924ca3a5ba58d0205c2fd733e6ad2e4f5dd
spanky/commands/cmd_users.py
spanky/commands/cmd_users.py
import click from spanky.cli import pass_context @click.command('users', short_help='creates users base on /etc/spanky/users') @pass_context def cli(ctx): config = ctx.config.load('users.yml')
import click from spanky.cli import pass_context from spanky.lib.users import UserInit @click.command('users', short_help='creates users base on /etc/spanky/users') @pass_context def cli(ctx): config = ctx.config.load('users.yml')() user_init = UserInit(config) user_init.build()
Use the config when creating users.
Use the config when creating users.
Python
bsd-3-clause
pglbutt/spanky,pglbutt/spanky,pglbutt/spanky
--- +++ @@ -1,8 +1,11 @@ import click from spanky.cli import pass_context +from spanky.lib.users import UserInit @click.command('users', short_help='creates users base on /etc/spanky/users') @pass_context def cli(ctx): - config = ctx.config.load('users.yml') + config = ctx.config.load('users.yml')() + user_init = UserInit(config) + user_init.build()
253ea73b37b9295ef0e31c2f1b1bdc7922cb6da5
spitfire/runtime/repeater.py
spitfire/runtime/repeater.py
class RepeatTracker(object): def __init__(self): self.repeater_map = {} def __setitem__(self, key, value): try: self.repeater_map[key].index = value except KeyError, e: self.repeater_map[key] = Repeater(value) def __getitem__(self, key): return self.repeater_map[key] class Repeater(object): def __init__(self, index=0, length=None): self.index = index self.length = length @property def number(self): return self.index + 1 @property def even(self): return not (self.index % 2) @property def odd(self): return (self.index % 2) @property def first(self): return (self.index == 0) @property def last(self): return (self.index == (self.length - 1)) def reiterate(iterable): try: length = len(iterable) except TypeError: # if the iterable is a generator, then we have no length length = None for index, item in enumerate(iterable): yield (Repeater(index, length), item)
class RepeatTracker(object): def __init__(self): self.repeater_map = {} def __setitem__(self, key, value): try: self.repeater_map[key].index = value except KeyError, e: self.repeater_map[key] = Repeater(value) def __getitem__(self, key): return self.repeater_map[key] class Repeater(object): def __init__(self, index=0, item=None, length=None): self.index = index self.item = item self.length = length @property def number(self): return self.index + 1 @property def even(self): return not (self.index % 2) @property def odd(self): return (self.index % 2) @property def first(self): return (self.index == 0) @property def last(self): return (self.index == (self.length - 1)) class RepeatIterator(object): def __init__(self, iterable): self.src_iterable = iterable self.src_iterator = enumerate(iterable) try: self.length = len(iterable) except TypeError: # if the iterable is a generator, then we have no length self.length = None def __iter__(self): return self def next(self): index, item = self.src_iterator.next() return Repeater(index, item, self.length)
Revert last change (breaks XSPT)
Revert last change (breaks XSPT)
Python
bsd-3-clause
nicksay/spitfire,spt/spitfire,spt/spitfire,spt/spitfire,nicksay/spitfire,nicksay/spitfire,youtube/spitfire,spt/spitfire,youtube/spitfire,youtube/spitfire,nicksay/spitfire,youtube/spitfire
--- +++ @@ -12,8 +12,9 @@ return self.repeater_map[key] class Repeater(object): - def __init__(self, index=0, length=None): + def __init__(self, index=0, item=None, length=None): self.index = index + self.item = item self.length = length @property @@ -36,14 +37,22 @@ def last(self): return (self.index == (self.length - 1)) -def reiterate(iterable): - try: - length = len(iterable) - except TypeError: - # if the iterable is a generator, then we have no length - length = None - for index, item in enumerate(iterable): - yield (Repeater(index, length), item) +class RepeatIterator(object): + def __init__(self, iterable): + self.src_iterable = iterable + self.src_iterator = enumerate(iterable) + try: + self.length = len(iterable) + except TypeError: + # if the iterable is a generator, then we have no length + self.length = None + + def __iter__(self): + return self + + def next(self): + index, item = self.src_iterator.next() + return Repeater(index, item, self.length)
abce02dc1a30b869300eee36b29d5e61320d64c5
test.py
test.py
#!/usr/bin/env python import os import subprocess import time import glob import unittest class ZxSpecTestCase(unittest.TestCase): def setUp(self): clean() def tearDown(self): clean() def test_zx_spec_header_displayed(self): ZX_SPEC_OUTPUT_FILE = "printout.txt" proc = subprocess.Popen([ "fuse", "--tape", "bin/zx-spec-test.tap", "--auto-load", "--no-autosave-settings"]) while not os.path.exists(ZX_SPEC_OUTPUT_FILE): time.sleep(0.1) time.sleep(1) proc.kill() with open(ZX_SPEC_OUTPUT_FILE, 'r') as f: zx_spec_output = f.read() self.assertRegexpMatches(zx_spec_output, 'ZX Spec - The TDD Framework') def clean(): for f in glob.glob("printout.*"): os.remove(f) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python import os import subprocess import time import glob import unittest class ZxSpecTestCase(unittest.TestCase): @classmethod def setUpClass(self): clean() self.output = run_zx_spec() def test_zx_spec_header_displayed(self): self.assertRegexpMatches(self.output, 'ZX Spec - The TDD Framework') def test_all_tests_pass(self): self.assertRegexpMatches(self.output, 'Pass: 0, Fail: 0') @classmethod def tearDownClass(self): clean() def clean(): for f in glob.glob("printout.*"): os.remove(f) def run_zx_spec(): ZX_SPEC_OUTPUT_FILE = "printout.txt" proc = subprocess.Popen([ "fuse", "--tape", "bin/zx-spec-test.tap", "--auto-load", "--no-autosave-settings"]) wait_count = 0 while not os.path.exists(ZX_SPEC_OUTPUT_FILE): time.sleep(0.1) wait_count += 1 if wait_count == 20: raise 'Output file not produced in time' time.sleep(1) proc.kill() with open(ZX_SPEC_OUTPUT_FILE, 'r') as f: return f.read() if __name__ == '__main__': unittest.main()
Add timeout for printout production
Add timeout for printout production
Python
mit
rhargreaves/zx-spec
--- +++ @@ -6,35 +6,46 @@ import unittest class ZxSpecTestCase(unittest.TestCase): - def setUp(self): + + @classmethod + def setUpClass(self): clean() - - def tearDown(self): - clean() + self.output = run_zx_spec() def test_zx_spec_header_displayed(self): - ZX_SPEC_OUTPUT_FILE = "printout.txt" + self.assertRegexpMatches(self.output, 'ZX Spec - The TDD Framework') - proc = subprocess.Popen([ - "fuse", - "--tape", "bin/zx-spec-test.tap", - "--auto-load", - "--no-autosave-settings"]) + def test_all_tests_pass(self): + self.assertRegexpMatches(self.output, 'Pass: 0, Fail: 0') - while not os.path.exists(ZX_SPEC_OUTPUT_FILE): - time.sleep(0.1) - - time.sleep(1) - proc.kill() - - with open(ZX_SPEC_OUTPUT_FILE, 'r') as f: - zx_spec_output = f.read() - - self.assertRegexpMatches(zx_spec_output, 'ZX Spec - The TDD Framework') + @classmethod + def tearDownClass(self): + clean() def clean(): for f in glob.glob("printout.*"): os.remove(f) +def run_zx_spec(): + ZX_SPEC_OUTPUT_FILE = "printout.txt" + proc = subprocess.Popen([ + "fuse", + "--tape", "bin/zx-spec-test.tap", + "--auto-load", + "--no-autosave-settings"]) + + wait_count = 0 + while not os.path.exists(ZX_SPEC_OUTPUT_FILE): + time.sleep(0.1) + wait_count += 1 + if wait_count == 20: + raise 'Output file not produced in time' + + time.sleep(1) + proc.kill() + + with open(ZX_SPEC_OUTPUT_FILE, 'r') as f: + return f.read() + if __name__ == '__main__': unittest.main()
e8775f0f64bcae6b0789df6d4a2a5aca9f5cf4ac
telemetry/telemetry/internal/platform/power_monitor/msr_power_monitor_unittest.py
telemetry/telemetry/internal/platform/power_monitor/msr_power_monitor_unittest.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import time import unittest from telemetry import decorators from telemetry.internal.platform.power_monitor import msr_power_monitor from telemetry.internal.platform import win_platform_backend class MsrPowerMonitorTest(unittest.TestCase): @decorators.Enabled('xp', 'win7', 'win8') # http://crbug.com/479337 def testMsrRuns(self): platform_backend = win_platform_backend.WinPlatformBackend() power_monitor = msr_power_monitor.MsrPowerMonitorWin(platform_backend) if not power_monitor.CanMonitorPower(): logging.warning('Test not supported on this platform.') return power_monitor.StartMonitoringPower(None) time.sleep(0.01) statistics = power_monitor.StopMonitoringPower() self.assertEqual(statistics['identifier'], 'msr') self.assertIn('energy_consumption_mwh', statistics) self.assertGreater(statistics['energy_consumption_mwh'], 0)
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import time import unittest from telemetry import decorators from telemetry.internal.platform.power_monitor import msr_power_monitor from telemetry.internal.platform import win_platform_backend class MsrPowerMonitorTest(unittest.TestCase): @decorators.Disabled('all') # http://crbug.com/712486 #@decorators.Enabled('xp', 'win7', 'win8') # http://crbug.com/479337 def testMsrRuns(self): platform_backend = win_platform_backend.WinPlatformBackend() power_monitor = msr_power_monitor.MsrPowerMonitorWin(platform_backend) if not power_monitor.CanMonitorPower(): logging.warning('Test not supported on this platform.') return power_monitor.StartMonitoringPower(None) time.sleep(0.01) statistics = power_monitor.StopMonitoringPower() self.assertEqual(statistics['identifier'], 'msr') self.assertIn('energy_consumption_mwh', statistics) self.assertGreater(statistics['energy_consumption_mwh'], 0)
Disable flaky MSR power monitor unit test.
[Telemetry] Disable flaky MSR power monitor unit test. BUG=chromium:712486 Review-Url: https://codereview.chromium.org/2827723002
Python
bsd-3-clause
catapult-project/catapult-csm,benschmaus/catapult,benschmaus/catapult,catapult-project/catapult,catapult-project/catapult,benschmaus/catapult,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult,catapult-project/catapult,benschmaus/catapult,benschmaus/catapult,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult
--- +++ @@ -12,7 +12,8 @@ class MsrPowerMonitorTest(unittest.TestCase): - @decorators.Enabled('xp', 'win7', 'win8') # http://crbug.com/479337 + @decorators.Disabled('all') # http://crbug.com/712486 + #@decorators.Enabled('xp', 'win7', 'win8') # http://crbug.com/479337 def testMsrRuns(self): platform_backend = win_platform_backend.WinPlatformBackend() power_monitor = msr_power_monitor.MsrPowerMonitorWin(platform_backend)
262cdf05ae4f53e1eab184e23791daa4d6422c51
orges/optimizer/base.py
orges/optimizer/base.py
""" Abstract optimizer defining the API of optimizer implementations. """ from __future__ import division, print_function, with_statement from abc import abstractmethod, ABCMeta # Abstract Base Class class BaseOptimizer(object): """ Abstract optimizer, a systematic way to call a function with arguments. """ __metaclass__ = ABCMeta @abstractmethod def optimize(self, function, param_spec, return_spec): """ :param function: :param param_spec: Parameter specification for the given function. :param return_spec: Return value specification for the given function. """ class BaseCaller(object): """Abstract caller handling calls to a given invoker.""" __metaclass__ = ABCMeta @abstractmethod def __init__(self): self._invoker = None @property @abstractmethod def invoker(self): return self._invoker @invoker.setter @abstractmethod def invoker(self, invoker): self._invoker = invoker @abstractmethod def on_result(self, result, fargs, *vargs, **kwargs): ''' Handles a result. :param return_value: Return value of the given arguments. :param fargs: The arguments given to a function. ''' pass @abstractmethod def on_error(self, error, fargs, *vargs, **kwargs): ''' Handles an error. :param fargs: The arguments given to a function. ''' pass
""" This module provides an abstract base class for implementing optimizer """ from __future__ import division, print_function, with_statement from abc import abstractmethod, ABCMeta # Abstract Base Class class BaseOptimizer(object): """ Abstract base class for objects optimizing objective functions. """ __metaclass__ = ABCMeta @abstractmethod def optimize(self, function, param_spec, return_spec): """ :param function: Objective function :param param_spec: Parameters specification for `function` :param return_spec: Return value specification for `function` """ # TODO: Include invoker property class BaseCaller(object): """Abstract base class for objects calling :meth:`orges.invoker.base.BaseInvoker.invoke` (and being called back by it). """ __metaclass__ = ABCMeta @abstractmethod def __init__(self): self._invoker = None @property @abstractmethod def invoker(self): "The invoker that is used by this caller." return self._invoker @invoker.setter @abstractmethod def invoker(self, invoker): self._invoker = invoker @abstractmethod def on_result(self, result, fargs, *vargs, **kwargs): """ Called when :meth:`orges.invoker.base.BaseInvoker.invoke` was successful. :param result: Return value of the objective function :param fargs: Arguments the objective function was applied to """ pass @abstractmethod def on_error(self, error, fargs, *vargs, **kwargs): """ Called when :meth:`orges.invoker.base.BaseInvoker.invoke` was *not* successful. :param error: Error that occured :param fargs: Arguments the objective function was applied to """ pass
Add documentation to BaseCaller and BaseOptimizer class
Add documentation to BaseCaller and BaseOptimizer class
Python
bsd-3-clause
cigroup-ol/metaopt,cigroup-ol/metaopt,cigroup-ol/metaopt
--- +++ @@ -1,6 +1,7 @@ """ -Abstract optimizer defining the API of optimizer implementations. +This module provides an abstract base class for implementing optimizer """ + from __future__ import division, print_function, with_statement from abc import abstractmethod, ABCMeta # Abstract Base Class @@ -8,7 +9,7 @@ class BaseOptimizer(object): """ - Abstract optimizer, a systematic way to call a function with arguments. + Abstract base class for objects optimizing objective functions. """ __metaclass__ = ABCMeta @@ -16,14 +17,17 @@ @abstractmethod def optimize(self, function, param_spec, return_spec): """ - :param function: - :param param_spec: Parameter specification for the given function. - :param return_spec: Return value specification for the given function. + :param function: Objective function + :param param_spec: Parameters specification for `function` + :param return_spec: Return value specification for `function` """ + # TODO: Include invoker property class BaseCaller(object): - """Abstract caller handling calls to a given invoker.""" + """Abstract base class for objects calling + :meth:`orges.invoker.base.BaseInvoker.invoke` (and being called back by it). + """ __metaclass__ = ABCMeta @@ -34,6 +38,7 @@ @property @abstractmethod def invoker(self): + "The invoker that is used by this caller." return self._invoker @invoker.setter @@ -43,19 +48,22 @@ @abstractmethod def on_result(self, result, fargs, *vargs, **kwargs): - ''' - Handles a result. + """ + Called when :meth:`orges.invoker.base.BaseInvoker.invoke` was + successful. - :param return_value: Return value of the given arguments. - :param fargs: The arguments given to a function. - ''' + :param result: Return value of the objective function + :param fargs: Arguments the objective function was applied to + """ pass @abstractmethod def on_error(self, error, fargs, *vargs, **kwargs): - ''' - Handles an error. + """ + Called when :meth:`orges.invoker.base.BaseInvoker.invoke` was *not* + successful. - :param fargs: The arguments given to a function. - ''' + :param error: Error that occured + :param fargs: Arguments the objective function was applied to + """ pass
7e98ecd888dba1f5e19b4e1a2f3f9aebd7756c5c
panoptes_client/user.py
panoptes_client/user.py
from panoptes_client.panoptes import PanoptesObject, LinkResolver class User(PanoptesObject): _api_slug = 'users' _link_slug = 'users' _edit_attributes = () LinkResolver.register(User) LinkResolver.register(User, 'owner')
from panoptes_client.panoptes import PanoptesObject, LinkResolver class User(PanoptesObject): _api_slug = 'users' _link_slug = 'users' _edit_attributes = () def avatar(self): return User.http_get('{}/avatar'.format(self.id))[0] LinkResolver.register(User) LinkResolver.register(User, 'owner')
Add method to get User's avatar
Add method to get User's avatar
Python
apache-2.0
zooniverse/panoptes-python-client
--- +++ @@ -6,5 +6,8 @@ _link_slug = 'users' _edit_attributes = () + def avatar(self): + return User.http_get('{}/avatar'.format(self.id))[0] + LinkResolver.register(User) LinkResolver.register(User, 'owner')
bdedbef5a8326705523cd3a7113cadb15d4a59ec
ckanext/wirecloudview/tests/test_plugin.py
ckanext/wirecloudview/tests/test_plugin.py
"""Tests for plugin.py.""" import ckanext.wirecloudview.plugin as plugin from mock import MagicMock, patch class DataRequestPluginTest(unittest.TestCase): def test_process_dashboardid_should_strip(self): self.assertEqual(plugin.process_dashboardid(self, " owner/name ", context), "onwer/name") def test_process_dashboardid_should_leave_untouched_valid_dashboard_ids(self): self.assertEqual(plugin.process_dashboardid(self, "owner/name", context), "onwer/name")
# -*- coding: utf-8 -*- # Copyright (c) 2017 Future Internet Consulting and Development Solutions S.L. # This file is part of CKAN WireCloud View Extension. # CKAN WireCloud View Extension 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. # CKAN WireCloud View Extension 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 CKAN WireCloud View Extension. If not, see <http://www.gnu.org/licenses/>. # This file is part of CKAN Data Requests Extension. import unittest from mock import MagicMock, patch import ckanext.wirecloudview.plugin as plugin class DataRequestPluginTest(unittest.TestCase): def test_process_dashboardid_should_strip(self): self.assertEqual(plugin.process_dashboardid(self, " owner/name ", context), "onwer/name") def test_process_dashboardid_should_leave_untouched_valid_dashboard_ids(self): self.assertEqual(plugin.process_dashboardid(self, "owner/name", context), "onwer/name")
Fix unittest import and add copyright headers
Fix unittest import and add copyright headers
Python
agpl-3.0
conwetlab/ckanext-wirecloud_view,conwetlab/ckanext-wirecloud_view,conwetlab/ckanext-wirecloud_view,conwetlab/ckanext-wirecloud_view
--- +++ @@ -1,7 +1,28 @@ -"""Tests for plugin.py.""" -import ckanext.wirecloudview.plugin as plugin +# -*- coding: utf-8 -*- + +# Copyright (c) 2017 Future Internet Consulting and Development Solutions S.L. + +# This file is part of CKAN WireCloud View Extension. + +# CKAN WireCloud View Extension 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. + +# CKAN WireCloud View Extension 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 CKAN WireCloud View Extension. If not, see <http://www.gnu.org/licenses/>. +# This file is part of CKAN Data Requests Extension. + +import unittest from mock import MagicMock, patch + +import ckanext.wirecloudview.plugin as plugin class DataRequestPluginTest(unittest.TestCase):
982557f5ad850fb4126bea4adb65aef16291fbd6
core/forms.py
core/forms.py
from django import forms from django.utils.translation import ugettext_lazy as _ from .models import Contact class ContactForm(forms.ModelForm): class Meta: exclude = ("created_on",) model = Contact class DonateForm(forms.Form): name = forms.CharField( max_length=100, widget=forms.TextInput(attrs={"class": "form-control"}) ) email = forms.EmailField( widget=forms.EmailInput(attrs={"class": "form-control"}) ) phone = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control"}) ) address = forms.CharField( widget=forms.Textarea(attrs={"class": "form-control"}) ) pan = forms.CharField( label=_("PAN"), max_length=10, widget=forms.TextInput(attrs={"class": "form-control"}), help_text=_("PAN is required as per government regulations.") ) is_indian = forms.BooleanField( initial = False, label=_("I hereby declare that I am an Indian"), widget=forms.CheckboxInput(), help_text=_("At this moment, we can accept donations from Indians only") ) def clean_is_indian(self): data = self.cleaned_data["is_indian"] if data != True: raise forms.ValidationError(_("Sorry, we can accept donations " "from Indians only.")) return data
from django import forms from django.utils.translation import ugettext_lazy as _ from .models import Contact class ContactForm(forms.ModelForm): class Meta: exclude = ("created_on",) model = Contact class DonateForm(forms.Form): name = forms.CharField( max_length=100, widget=forms.TextInput(attrs={"class": "form-control"}) ) email = forms.EmailField( widget=forms.EmailInput(attrs={"class": "form-control"}) ) phone = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control"}) ) address = forms.CharField( widget=forms.Textarea(attrs={"class": "form-control"}) ) pan = forms.CharField( label=_("PAN"), max_length=10, widget=forms.TextInput(attrs={"class": "form-control"}), help_text=_("PAN is required as per government regulations.") ) is_indian = forms.BooleanField( initial = False, label=_("I declare that I am an Indian citizen"), widget=forms.CheckboxInput(), help_text=_("At this moment, we can accept donations from Indians only") ) def clean_is_indian(self): data = self.cleaned_data["is_indian"] if data != True: raise forms.ValidationError(_("Sorry, we can accept donations " "from Indians only.")) return data
Change to the label name for resident status.
Change to the label name for resident status.
Python
bsd-3-clause
PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari
--- +++ @@ -32,7 +32,7 @@ ) is_indian = forms.BooleanField( initial = False, - label=_("I hereby declare that I am an Indian"), + label=_("I declare that I am an Indian citizen"), widget=forms.CheckboxInput(), help_text=_("At this moment, we can accept donations from Indians only") )
192ba8b2bfa138662cd25f3502fd376187ca3e73
pagarme/__init__.py
pagarme/__init__.py
# encoding: utf-8 from .pagarme import Pagarme from .exceptions import *
# -*- coding: utf-8 -*- __version__ = '2.0.0-dev' __description__ = 'Pagar.me Python library' __long_description__ = '' from .pagarme import Pagarme from .exceptions import *
Set global stats for pagarme-python
Set global stats for pagarme-python
Python
mit
pbassut/pagarme-python,mbodock/pagarme-python,pagarme/pagarme-python,aroncds/pagarme-python,reginaldojunior/pagarme-python
--- +++ @@ -1,4 +1,8 @@ -# encoding: utf-8 +# -*- coding: utf-8 -*- + +__version__ = '2.0.0-dev' +__description__ = 'Pagar.me Python library' +__long_description__ = '' from .pagarme import Pagarme from .exceptions import *
a8053bb36cf9cfe292274b79c435ab6eb6fc6633
urls.py
urls.py
from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'gnome_developer_network.views.home', name='home'), # url(r'^gnome_developer_network/', include('gnome_developer_network.foo.urls')), url(r'^api/', include('gnome_developer_network.api.home')) # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), )
# vim: tabstop=4 noexpandtab shiftwidth=4 softtabstop=4 from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'gnome_developer_network.views.home', name='home'), # url(r'^gnome_developer_network/', include('gnome_developer_network.foo.urls')), url(r'^api/', include('gnome_developer_network.api.urls')) # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), )
Fix url include for api app
Fix url include for api app
Python
agpl-3.0
aruiz/GDN
--- +++ @@ -1,3 +1,4 @@ +# vim: tabstop=4 noexpandtab shiftwidth=4 softtabstop=4 from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: @@ -8,7 +9,7 @@ # Examples: # url(r'^$', 'gnome_developer_network.views.home', name='home'), # url(r'^gnome_developer_network/', include('gnome_developer_network.foo.urls')), - url(r'^api/', include('gnome_developer_network.api.home')) + url(r'^api/', include('gnome_developer_network.api.urls')) # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
4ec22f8a0fdd549967e3a30096867b87bc458dde
tensorflow_cloud/python/tests/integration/call_run_on_script_with_keras_ctl_test.py
tensorflow_cloud/python/tests/integration/call_run_on_script_with_keras_ctl_test.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. import tensorflow_cloud as tfc # MultiWorkerMirroredStrategy tfc.run( entry_point="tensorflow_cloud/python/tests/testdata/mnist_example_using_ctl.py", distribution_strategy=None, worker_count=1, requirements_txt="tensorflow_cloud/python/tests/testdata/requirements.txt", stream_logs=True, )
# 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. """Integration tests for calling tfc.run on script with keras.""" import os import sys from unittest import mock import tensorflow as tf import tensorflow_cloud as tfc class TensorflowCloudOnScriptTest(tf.test.TestCase): def setUp(self): super(TensorflowCloudOnScriptTest, self).setUp() self.test_data_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "../testdata/" ) @mock.patch.object(sys, "exit", autospec=True) def test_MWMS_on_script(self, mock_exit): mock_exit.side_effect = RuntimeError("exit called") with self.assertRaises(RuntimeError): tfc.run( entry_point=os.path.join( self.test_data_path, "mnist_example_using_ctl.py" ), distribution_strategy=None, worker_count=1, requirements_txt=os.path.join( self.test_data_path, "requirements.txt"), ) mock_exit.assert_called_once_with(0) if __name__ == "__main__": tf.test.main()
Add test harness to call_run_on_script_with_keras
Add test harness to call_run_on_script_with_keras
Python
apache-2.0
tensorflow/cloud,tensorflow/cloud
--- +++ @@ -11,14 +11,37 @@ # 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. +"""Integration tests for calling tfc.run on script with keras.""" +import os +import sys +from unittest import mock +import tensorflow as tf import tensorflow_cloud as tfc -# MultiWorkerMirroredStrategy -tfc.run( - entry_point="tensorflow_cloud/python/tests/testdata/mnist_example_using_ctl.py", - distribution_strategy=None, - worker_count=1, - requirements_txt="tensorflow_cloud/python/tests/testdata/requirements.txt", - stream_logs=True, -) + +class TensorflowCloudOnScriptTest(tf.test.TestCase): + def setUp(self): + super(TensorflowCloudOnScriptTest, self).setUp() + self.test_data_path = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "../testdata/" + ) + + @mock.patch.object(sys, "exit", autospec=True) + def test_MWMS_on_script(self, mock_exit): + mock_exit.side_effect = RuntimeError("exit called") + with self.assertRaises(RuntimeError): + tfc.run( + entry_point=os.path.join( + self.test_data_path, "mnist_example_using_ctl.py" + ), + distribution_strategy=None, + worker_count=1, + requirements_txt=os.path.join( + self.test_data_path, "requirements.txt"), + ) + mock_exit.assert_called_once_with(0) + + +if __name__ == "__main__": + tf.test.main()
ec0bcd5981cb9349b3cdaa570f843f49650bedd1
profile_collection/startup/99-bluesky.py
profile_collection/startup/99-bluesky.py
def detselect(detector_object, suffix="_stats_total1"): """Switch the active detector and set some internal state""" gs.DETS =[detector_object] gs.PLOT_Y = detector_object.name + suffix gs.TABLE_COLS = [gs.PLOT_Y] def chx_plot_motor(scan): fig = None if gs.PLOTMODE == 1: fig = plt.gcf() elif gs.PLOTMODE == 2: fig = plt.gcf() fig.clear() elif gs.PLOTMODE == 3: fig = plt.figure() return LivePlot(gs.PLOT_Y, scan.motor._name, fig=fig) dscan.default_sub_factories['all'][1] = chx_plot_motor gs.PLOTMODE = 1 from bluesky.global_state import resume, abort, stop, panic, all_is_well, state
def detselect(detector_object, suffix="_stats_total1"): """Switch the active detector and set some internal state""" gs.DETS =[detector_object] gs.PLOT_Y = detector_object.name + suffix gs.TABLE_COLS = [gs.PLOT_Y] def chx_plot_motor(scan): fig = None if gs.PLOTMODE == 1: fig = plt.gcf() elif gs.PLOTMODE == 2: fig = plt.gcf() fig.clear() elif gs.PLOTMODE == 3: fig = plt.figure() return LivePlot(gs.PLOT_Y, scan.motor._name, fig=fig) # this changes the default plotter for *all* classes that # inherit from bluesky.simple_scans._StepScan dscan.default_sub_factories['all'][1] = chx_plot_motor gs.PLOTMODE = 1 from bluesky.global_state import (resume, abort, stop, panic, all_is_well, state) # hacking on the logbook! from pyOlog import SimpleOlogClient client = SimpleOlogClient() from pprint import pformat, pprint from bluesky.callbacks import CallbackBase from IPython import get_ipython class OlogCallback(CallbackBase): def start(self, doc): session = get_ipython() commands = list(session.history_manager.get_range()) print("Received a start document") print('scan_id = %s' % doc['scan_id']) print('last command = %s ' % commands[-1][2]) print('start document = %s' % pformat(doc)) document_content = ('%s: %s\n\n' 'RunStart Document\n' '-----------------\n' '%s' % (doc['scan_id'], commands[-1][2], pformat(doc))) print('document_content = %s' % document_content) client.log(document_content, logbooks='Data Acquisition') #dscan.default_sub_factories['all'].append(OlogCallback()) gs.RE.subscribe('start', OlogCallback()) gs.RE.logbook = None
Customize programmatic Olog entries from bluesky
ENH: Customize programmatic Olog entries from bluesky
Python
bsd-2-clause
NSLS-II-CHX/ipython_ophyd,NSLS-II-CHX/ipython_ophyd
--- +++ @@ -16,8 +16,41 @@ fig = plt.figure() return LivePlot(gs.PLOT_Y, scan.motor._name, fig=fig) +# this changes the default plotter for *all* classes that +# inherit from bluesky.simple_scans._StepScan dscan.default_sub_factories['all'][1] = chx_plot_motor gs.PLOTMODE = 1 -from bluesky.global_state import resume, abort, stop, panic, all_is_well, state +from bluesky.global_state import (resume, abort, stop, panic, + all_is_well, state) + + +# hacking on the logbook! + +from pyOlog import SimpleOlogClient +client = SimpleOlogClient() +from pprint import pformat, pprint +from bluesky.callbacks import CallbackBase +from IPython import get_ipython +class OlogCallback(CallbackBase): + def start(self, doc): + session = get_ipython() + commands = list(session.history_manager.get_range()) + print("Received a start document") + print('scan_id = %s' % doc['scan_id']) + print('last command = %s ' % commands[-1][2]) + print('start document = %s' % pformat(doc)) + document_content = ('%s: %s\n\n' + 'RunStart Document\n' + '-----------------\n' + '%s' % (doc['scan_id'], + commands[-1][2], + pformat(doc))) + print('document_content = %s' % document_content) + client.log(document_content, logbooks='Data Acquisition') + +#dscan.default_sub_factories['all'].append(OlogCallback()) +gs.RE.subscribe('start', OlogCallback()) +gs.RE.logbook = None +
2abe71aaf9357bed719dc5e1118ee4fe49c4101e
jjvm.py
jjvm.py
#!/usr/bin/python import argparse import struct import sys ############### ### CLASSES ### ############### class MyParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2) ################### ### SUBROUTINES ### ################### def lenCpItem(tag): if tag == 0xa: return 3 else: return -1 ############ ### MAIN ### ############ parser = MyParser('Run bytecode in jjvm') parser.add_argument('path', help='path to class') args = parser.parse_args() with open(args.path, "rb") as c: c.seek(8) cpcount = struct.unpack(">H", c.read(2))[0] - 1 print "Constant pool count: %d" % cpcount; cpTag = ord(c.read(1)) print "Got tag: %d" % cpTag print "Size: %d" % lenCpItem(cpTag)
#!/usr/bin/python import argparse import os import struct import sys ############### ### CLASSES ### ############### class MyParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2) ################### ### SUBROUTINES ### ################### def lenCpStruct(tag): if tag == 0xa: return 3 else: return -1 ############ ### MAIN ### ############ parser = MyParser('Run bytecode in jjvm') parser.add_argument('path', help='path to class') args = parser.parse_args() with open(args.path, "rb") as c: c.seek(8) cpCount = struct.unpack(">H", c.read(2))[0] - 1 print "Constant pool count: %d" % cpCount; while cpCount >= 0: cpTag = ord(c.read(1)) print "Got tag: %d" % cpTag cpStructSize = lenCpStruct(cpTag) if cpStructSize < 0: print "ERROR: cpStructSize %d for tag %d" % (cpStructSize, cpTag) sys.exit(1) print "Size: %d" % cpStructSize cpCount -= 1 c.seek(cpStructSize, os.SEEK_CUR)
Halt on unrecognized constant pool tag
Halt on unrecognized constant pool tag
Python
apache-2.0
justinccdev/jjvm
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/python import argparse +import os import struct import sys @@ -16,7 +17,7 @@ ################### ### SUBROUTINES ### ################### -def lenCpItem(tag): +def lenCpStruct(tag): if tag == 0xa: return 3 else: @@ -31,11 +32,21 @@ with open(args.path, "rb") as c: c.seek(8) - cpcount = struct.unpack(">H", c.read(2))[0] - 1 + cpCount = struct.unpack(">H", c.read(2))[0] - 1 - print "Constant pool count: %d" % cpcount; + print "Constant pool count: %d" % cpCount; - cpTag = ord(c.read(1)) + while cpCount >= 0: + cpTag = ord(c.read(1)) - print "Got tag: %d" % cpTag - print "Size: %d" % lenCpItem(cpTag) + print "Got tag: %d" % cpTag + cpStructSize = lenCpStruct(cpTag) + + if cpStructSize < 0: + print "ERROR: cpStructSize %d for tag %d" % (cpStructSize, cpTag) + sys.exit(1) + + print "Size: %d" % cpStructSize + + cpCount -= 1 + c.seek(cpStructSize, os.SEEK_CUR)
a7e0d9633f23e25841298d8406dafdfdb664857a
opps/articles/forms.py
opps/articles/forms.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from .models import Post, Album, Link from opps.core.widgets import OppsEditor class PostAdminForm(forms.ModelForm): class Meta: model = Post widgets = {'content': OppsEditor()} class AlbumAdminForm(forms.ModelForm): class Meta: model = Album widgets = { 'headline': OppsEditor() } class LinkAdminForm(forms.ModelForm): class Meta: model = Link
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from .models import Post, Album, Link from opps.core.widgets import OppsEditor class PostAdminForm(forms.ModelForm): multiupload_link = '/fileupload/image/' class Meta: model = Post widgets = {'content': OppsEditor()} class AlbumAdminForm(forms.ModelForm): multiupload_link = '/fileupload/image/' class Meta: model = Album widgets = { 'headline': OppsEditor() } class LinkAdminForm(forms.ModelForm): class Meta: model = Link
Add multiupload_link in post/album form
Add multiupload_link in post/album form
Python
mit
YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,opps/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,opps/opps
--- +++ @@ -8,12 +8,14 @@ class PostAdminForm(forms.ModelForm): + multiupload_link = '/fileupload/image/' class Meta: model = Post widgets = {'content': OppsEditor()} class AlbumAdminForm(forms.ModelForm): + multiupload_link = '/fileupload/image/' class Meta: model = Album widgets = {
16bf1a3b096159604928cdcc99cab671347bb244
contentstore/urls.py
contentstore/urls.py
from django.conf.urls import url, include from rest_framework import routers import views router = routers.DefaultRouter() router.register(r'schedule', views.ScheduleViewSet) router.register(r'messageset', views.MessageSetViewSet) router.register(r'message', views.MessageViewSet) router.register(r'binarycontent', views.BinaryContentViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browseable API. urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token'), url('^message/(?P<pk>.+)/content$', views.MessagesContentView.as_view({'get': 'retrieve'})), url('^messageset/(?P<pk>.+)/messages$', views.MessagesetMessagesContentView.as_view({'get': 'retrieve'})), ]
from django.conf.urls import url, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'schedule', views.ScheduleViewSet) router.register(r'messageset', views.MessageSetViewSet) router.register(r'message', views.MessageViewSet) router.register(r'binarycontent', views.BinaryContentViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browseable API. urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token'), url('^message/(?P<pk>.+)/content$', views.MessagesContentView.as_view({'get': 'retrieve'})), url('^messageset/(?P<pk>.+)/messages$', views.MessagesetMessagesContentView.as_view({'get': 'retrieve'})), ]
Fix imports for py 3
Fix imports for py 3
Python
bsd-3-clause
praekelt/django-messaging-contentstore,praekelt/django-messaging-contentstore
--- +++ @@ -1,6 +1,6 @@ from django.conf.urls import url, include from rest_framework import routers -import views +from . import views router = routers.DefaultRouter() router.register(r'schedule', views.ScheduleViewSet)
c74fc42de3f052ac83342ed33afb2865080c8d67
threema/gateway/__init__.py
threema/gateway/__init__.py
""" This API can be used to send text messages to any Threema user, and to receive incoming messages and delivery receipts. There are two main modes of operation: * Basic mode (server-based encryption) - The server handles all encryption for you. - The server needs to know the private key associated with your Threema API identity. - Incoming messages and delivery receipts are not supported. * End-to-end encrypted mode - The server doesn't know your private key. - Incoming messages and delivery receipts are supported. - You need to run software on your side to encrypt each message before it can be sent, and to decrypt any incoming messages or delivery receipts. The mode that you can use depends on the way your account was set up. .. moduleauthor:: Lennart Grahl <lennart.grahl@threema.ch> """ import itertools # noinspection PyUnresolvedReferences from ._gateway import * # noqa # noinspection PyUnresolvedReferences from .exception import * # noqa # noinspection PyUnresolvedReferences from . import bin, simple, e2e, key, util # noqa __author__ = 'Lennart Grahl <lennart.grahl@threema.ch>' __status__ = 'Production' __version__ = '3.0.0' feature_level = 3 __all__ = tuple(itertools.chain( ('feature_level',), _gateway.__all__, # noqa exception.__all__, # noqa ('bin', 'simple', 'e2e', 'key', 'util') ))
""" This API can be used to send text messages to any Threema user, and to receive incoming messages and delivery receipts. There are two main modes of operation: * Basic mode (server-based encryption) - The server handles all encryption for you. - The server needs to know the private key associated with your Threema API identity. - Incoming messages and delivery receipts are not supported. * End-to-end encrypted mode - The server doesn't know your private key. - Incoming messages and delivery receipts are supported. - You need to run software on your side to encrypt each message before it can be sent, and to decrypt any incoming messages or delivery receipts. The mode that you can use depends on the way your account was set up. .. moduleauthor:: Lennart Grahl <lennart.grahl@threema.ch> """ import itertools # noinspection PyUnresolvedReferences from ._gateway import * # noqa # noinspection PyUnresolvedReferences from .exception import * # noqa __author__ = 'Lennart Grahl <lennart.grahl@threema.ch>' __status__ = 'Production' __version__ = '3.0.0' feature_level = 3 __all__ = tuple(itertools.chain( ('feature_level',), ('bin', 'simple', 'e2e', 'key', 'util'), _gateway.__all__, # noqa exception.__all__, # noqa ))
Remove unneeded imports leading to failures
Remove unneeded imports leading to failures
Python
mit
threema-ch/threema-msgapi-sdk-python,lgrahl/threema-msgapi-sdk-python
--- +++ @@ -27,8 +27,6 @@ from ._gateway import * # noqa # noinspection PyUnresolvedReferences from .exception import * # noqa -# noinspection PyUnresolvedReferences -from . import bin, simple, e2e, key, util # noqa __author__ = 'Lennart Grahl <lennart.grahl@threema.ch>' __status__ = 'Production' @@ -37,7 +35,7 @@ __all__ = tuple(itertools.chain( ('feature_level',), + ('bin', 'simple', 'e2e', 'key', 'util'), _gateway.__all__, # noqa exception.__all__, # noqa - ('bin', 'simple', 'e2e', 'key', 'util') ))
b738e428838e038e88fe78db9680e37c72a88497
scheduler.py
scheduler.py
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("DESTALINATOR_TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logging.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logging.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logging.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() if not os.getenv('DESTALINATOR_SENTRY_DSN'): raise e logging.info("END: destalinate_job") if __name__ == "__main__": sched.start()
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger from config import Config raven_client = RavenClient() # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("DESTALINATOR_TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logging.info("Destalinating") config = Config() if not config.sb_token or not config.api_token: logging.error( "Missing at least one required Slack environment variable.\n" "Make sure to set DESTALINATOR_SB_TOKEN and DESTALINATOR_API_TOKEN." ) else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logging.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() if not os.getenv('DESTALINATOR_SENTRY_DSN'): raise e logging.info("END: destalinate_job") if __name__ == "__main__": sched.start()
Support old environement variable names
Support old environement variable names
Python
apache-2.0
royrapoport/destalinator,randsleadershipslack/destalinator,randsleadershipslack/destalinator,TheConnMan/destalinator,royrapoport/destalinator,TheConnMan/destalinator
--- +++ @@ -8,6 +8,7 @@ import archiver import announcer import flagger +from config import Config raven_client = RavenClient() @@ -24,8 +25,12 @@ @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logging.info("Destalinating") - if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: - logging.error("Missing at least one Slack environment variable.") + config = Config() + if not config.sb_token or not config.api_token: + logging.error( + "Missing at least one required Slack environment variable.\n" + "Make sure to set DESTALINATOR_SB_TOKEN and DESTALINATOR_API_TOKEN." + ) else: try: warner.Warner().warn()
397e185ae225613969ecff11e1cfed1e642daca0
troposphere/codeartifact.py
troposphere/codeartifact.py
# Copyright (c) 2012-2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 18.7.0 from . import AWSObject class Domain(AWSObject): resource_type = "AWS::CodeArtifact::Domain" props = { 'DomainName': (basestring, True), 'PermissionsPolicyDocument': (dict, False), } class Repository(AWSObject): resource_type = "AWS::CodeArtifact::Repository" props = { 'Description': (basestring, False), 'DomainName': (basestring, True), 'DomainOwner': (basestring, False), 'ExternalConnections': ([basestring], False), 'PermissionsPolicyDocument': (dict, False), 'RepositoryName': (basestring, True), 'Upstreams': ([basestring], False), }
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 25.0.0 from . import AWSObject from troposphere import Tags class Domain(AWSObject): resource_type = "AWS::CodeArtifact::Domain" props = { 'DomainName': (basestring, True), 'EncryptionKey': (basestring, False), 'PermissionsPolicyDocument': (dict, False), 'Tags': (Tags, False), } class Repository(AWSObject): resource_type = "AWS::CodeArtifact::Repository" props = { 'Description': (basestring, False), 'DomainName': (basestring, True), 'DomainOwner': (basestring, False), 'ExternalConnections': ([basestring], False), 'PermissionsPolicyDocument': (dict, False), 'RepositoryName': (basestring, True), 'Tags': (Tags, False), 'Upstreams': ([basestring], False), }
Update CodeArtifact per 2020-11-05 changes
Update CodeArtifact per 2020-11-05 changes
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
--- +++ @@ -1,13 +1,14 @@ -# Copyright (c) 2012-2020, Mark Peek <mark@peek.org> +# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** -# Resource specification version: 18.7.0 +# Resource specification version: 25.0.0 from . import AWSObject +from troposphere import Tags class Domain(AWSObject): @@ -15,7 +16,9 @@ props = { 'DomainName': (basestring, True), + 'EncryptionKey': (basestring, False), 'PermissionsPolicyDocument': (dict, False), + 'Tags': (Tags, False), } @@ -29,5 +32,6 @@ 'ExternalConnections': ([basestring], False), 'PermissionsPolicyDocument': (dict, False), 'RepositoryName': (basestring, True), + 'Tags': (Tags, False), 'Upstreams': ([basestring], False), }
e767d25a5e6c088cac6465ce95706e77149f39ef
tests/integration/states/cmd.py
tests/integration/states/cmd.py
''' Tests for the file state ''' # Import python libs import os # # Import salt libs from saltunittest import TestLoader, TextTestRunner import integration from integration import TestDaemon class CMDTest(integration.ModuleCase): ''' Validate the cmd state ''' def test_run(self): ''' cmd.run ''' ret = self.run_state('cmd.run', name='ls', cwd='/') result = ret[next(iter(ret))]['result'] self.assertTrue(result) def test_test_run(self): ''' cmd.run test interface ''' ret = self.run_state('cmd.run', name='ls', test=True) result = ret[next(iter(ret))]['result'] self.assertIsNone(result)
''' Tests for the file state ''' # Import python libs # Import salt libs import integration import tempfile class CMDTest(integration.ModuleCase): ''' Validate the cmd state ''' def test_run(self): ''' cmd.run ''' ret = self.run_state('cmd.run', name='ls', cwd=tempfile.gettempdir()) result = ret[next(iter(ret))]['result'] self.assertTrue(result) def test_test_run(self): ''' cmd.run test interface ''' ret = self.run_state('cmd.run', name='ls', cwd=tempfile.gettempdir(), test=True) result = ret[next(iter(ret))]['result'] self.assertIsNone(result)
Use tempdir to ensure there will always be a directory which can be accessed.
Use tempdir to ensure there will always be a directory which can be accessed.
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -2,12 +2,10 @@ Tests for the file state ''' # Import python libs -import os -# + # Import salt libs -from saltunittest import TestLoader, TextTestRunner import integration -from integration import TestDaemon +import tempfile class CMDTest(integration.ModuleCase): @@ -18,7 +16,8 @@ ''' cmd.run ''' - ret = self.run_state('cmd.run', name='ls', cwd='/') + + ret = self.run_state('cmd.run', name='ls', cwd=tempfile.gettempdir()) result = ret[next(iter(ret))]['result'] self.assertTrue(result) @@ -26,6 +25,7 @@ ''' cmd.run test interface ''' - ret = self.run_state('cmd.run', name='ls', test=True) + ret = self.run_state('cmd.run', name='ls', + cwd=tempfile.gettempdir(), test=True) result = ret[next(iter(ret))]['result'] self.assertIsNone(result)
6b971de14fbd987286b02bf6e469a1fbb7ad8695
graph.py
graph.py
from __future__ import unicode_literals class Graph(object): """A class for a simple graph data structure.""" def __init__(self): self.nodes = {} def __repr__(self): pass def nodes(self): """Return a list of all nodes in the graph.""" return [node for node in self.nodes] def edges(self): """Return a list of all edges in the graph.""" return "edge list" def add_node(self, n): """Add a new node to the graph.""" self.nodes[n] = set() def add_edge(self, n1, n2): """Add a new edge connecting n1 to n2.""" self.nodes[n1].add(n2) def del_node(self, n): """Delete a node from the graph.""" del self.nodes[n] for edgeset in self.nodes.values: edgeset.discard(n) def del_edge(self, n1, n2): """Delete the edge connecting two nodes from graph.""" self.nodes[n1].remove(n2) def has_node(self, n): """Check if a given node is in the graph.""" return n in self.nodes def neighbors(self, n): """Return a list of all nodes connected to 'n' by edges.""" neighbors = [] for node in self.nodes: if n in self.node: neighbors.append(node) return neighbors
from __future__ import unicode_literals class Graph(object): """A class for a simple graph data structure.""" def __init__(self): self.graph = {} def __repr__(self): return repr(self.graph) def nodes(self): """Return a list of all nodes in the graph.""" return [node for node in self.graph] def edges(self): """Return a list of all edges in the graph.""" return "edge list" def add_node(self, n): """Add a new node to the graph.""" self.graph[n] = set() def add_edge(self, n1, n2): """Add a new edge connecting n1 to n2.""" self.graph[n1].add(n2) def del_node(self, n): """Delete a node from the graph.""" del self.graph[n] for edgeset in self.graph.values(): edgeset.discard(n) def del_edge(self, n1, n2): """Delete the edge connecting two nodes from graph.""" self.graph[n1].remove(n2) def has_node(self, n): """Check if a given node is in the graph.""" return n in self.graph def neighbors(self, n): """Return a list of all nodes connected to 'n' by edges.""" neighbors = [] for node in self.graph: if n in self.node: neighbors.append(node) return neighbors
Change dictionary name to avoid collision; fix dict.values() call
Change dictionary name to avoid collision; fix dict.values() call
Python
mit
jay-tyler/data-structures,jonathanstallings/data-structures
--- +++ @@ -4,14 +4,14 @@ class Graph(object): """A class for a simple graph data structure.""" def __init__(self): - self.nodes = {} + self.graph = {} def __repr__(self): - pass + return repr(self.graph) def nodes(self): """Return a list of all nodes in the graph.""" - return [node for node in self.nodes] + return [node for node in self.graph] def edges(self): """Return a list of all edges in the graph.""" @@ -19,30 +19,30 @@ def add_node(self, n): """Add a new node to the graph.""" - self.nodes[n] = set() + self.graph[n] = set() def add_edge(self, n1, n2): """Add a new edge connecting n1 to n2.""" - self.nodes[n1].add(n2) + self.graph[n1].add(n2) def del_node(self, n): """Delete a node from the graph.""" - del self.nodes[n] - for edgeset in self.nodes.values: + del self.graph[n] + for edgeset in self.graph.values(): edgeset.discard(n) def del_edge(self, n1, n2): """Delete the edge connecting two nodes from graph.""" - self.nodes[n1].remove(n2) + self.graph[n1].remove(n2) def has_node(self, n): """Check if a given node is in the graph.""" - return n in self.nodes + return n in self.graph def neighbors(self, n): """Return a list of all nodes connected to 'n' by edges.""" neighbors = [] - for node in self.nodes: + for node in self.graph: if n in self.node: neighbors.append(node) return neighbors
3365064f885230020fa7671af2d158d5d46e2e80
modloader/modconfig.py
modloader/modconfig.py
"""This file is free software under the GPLv3 license""" import sys import os import shutil import renpy from modloader.modinfo import get_mods def remove_mod(mod_name): """Remove a mod from the game and reload. Args: mod_name (str): The internal name of the mod to be removed """ mod_class = get_mods()[mod_name] mod_folder = mod_class.__module__ shutil.rmtree(os.path.join(renpy.config.gamedir, "mods", mod_folder)) print "Sucessfully removed {}, reloading".format(mod_name) sys.stdout.flush() renpy.exports.reload_script()
"""This file is free software under the GPLv3 license""" import sys import os import shutil from renpy.display.core import Displayable from renpy.display.render import Render, render import renpy from renpy.audio.music import stop as _stop_music import renpy.game from renpy.text.text import Text from renpy.display.imagelike import Solid from modloader.modinfo import get_mods class MessageDisplayable(Displayable): def __init__(self, message, bg, fg, *args, **kwargs): super(MessageDisplayable, self).__init__(*args, **kwargs) self.message = message self.bg = bg self.fg = fg def render(self, width, height, st, at): rv = Render(width, height) sr = render(Solid(self.bg), width, height, st, at) rv.blit(sr, (0, 0)) td = Text(self.message, size=32, xalign=0.5, yalign=0.5, color=self.fg, style="_text") tr = render(td, width, height, st, at) rv.blit(tr, (width/2 - tr.width/2, height/2 - tr.height/2)) return rv def show_message(message, bg="#3485e7", fg="#fff", stop_music=True): if stop_music: _stop_music() renpy.game.interface.draw_screen(MessageDisplayable(message, bg, fg), False, True) def remove_mod(mod_name): """Remove a mod from the game and reload. Args: mod_name (str): The internal name of the mod to be removed """ show_message("Removing mod...") mod_class = get_mods()[mod_name] mod_folder = mod_class.__module__ shutil.rmtree(os.path.join(renpy.config.gamedir, "mods", mod_folder)) print "Sucessfully removed {}, reloading".format(mod_name) sys.stdout.flush() renpy.exports.reload_script()
Add message shown when removing mods. Add function to show some text to the screen - `show_message`
Add message shown when removing mods. Add function to show some text to the screen - `show_message`
Python
mit
AWSW-Modding/AWSW-Modtools
--- +++ @@ -3,9 +3,41 @@ import os import shutil +from renpy.display.core import Displayable +from renpy.display.render import Render, render import renpy +from renpy.audio.music import stop as _stop_music +import renpy.game +from renpy.text.text import Text +from renpy.display.imagelike import Solid from modloader.modinfo import get_mods + + +class MessageDisplayable(Displayable): + def __init__(self, message, bg, fg, *args, **kwargs): + super(MessageDisplayable, self).__init__(*args, **kwargs) + self.message = message + self.bg = bg + self.fg = fg + + def render(self, width, height, st, at): + rv = Render(width, height) + + sr = render(Solid(self.bg), width, height, st, at) + rv.blit(sr, (0, 0)) + + td = Text(self.message, size=32, xalign=0.5, yalign=0.5, color=self.fg, style="_text") + tr = render(td, width, height, st, at) + + rv.blit(tr, (width/2 - tr.width/2, height/2 - tr.height/2)) + return rv + + +def show_message(message, bg="#3485e7", fg="#fff", stop_music=True): + if stop_music: + _stop_music() + renpy.game.interface.draw_screen(MessageDisplayable(message, bg, fg), False, True) def remove_mod(mod_name): @@ -14,9 +46,11 @@ Args: mod_name (str): The internal name of the mod to be removed """ + show_message("Removing mod...") mod_class = get_mods()[mod_name] mod_folder = mod_class.__module__ shutil.rmtree(os.path.join(renpy.config.gamedir, "mods", mod_folder)) print "Sucessfully removed {}, reloading".format(mod_name) sys.stdout.flush() + renpy.exports.reload_script()
a26a57e44bbca6bbb5c7078c724552aaf5a6dda4
takeyourmeds/utils/checks.py
takeyourmeds/utils/checks.py
import re import os from django.core import checks from django.conf import settings re_url = re.compile(r'\shref="(?P<url>/[^"]*)"') @checks.register() def hardcoded_urls(app_configs, **kwargs): for x in settings.TEMPLATES: for y in x['DIRS']: for root, _, filenames in os.walk(y): for z in filenames: fullpath = os.path.join(root, z) with open(fullpath) as f: html = f.read() for m in re_url.finditer(html): yield checks.Error("%s contains hardcoded URL %s" % ( fullpath, m.group('url'), ), id='takeyourmeds.utils.E001')
import re import os from django.core import checks from django.conf import settings re_url = re.compile(r'\shref="(?P<url>/[^"]*)"') @checks.register() def hardcoded_urls(app_configs, **kwargs): for x in settings.TEMPLATES: for y in x['DIRS']: for root, _, filenames in os.walk(y): for z in filenames: fullpath = os.path.join(root, z) with open(fullpath) as f: html = f.read() for m in re_url.finditer(html): yield checks.Error("%s contains hardcoded URL %r" % ( fullpath, m.group('url'), ), id='takeyourmeds.utils.E001')
Use repr so it's more obvious what the problem is
Use repr so it's more obvious what the problem is
Python
mit
takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web
--- +++ @@ -18,7 +18,7 @@ html = f.read() for m in re_url.finditer(html): - yield checks.Error("%s contains hardcoded URL %s" % ( + yield checks.Error("%s contains hardcoded URL %r" % ( fullpath, m.group('url'), ), id='takeyourmeds.utils.E001')
4d1a50b1765cd5da46ac9633b3c91eb5e0a72f3d
tests/toolchains/test_atmel_studio.py
tests/toolchains/test_atmel_studio.py
import sys import unittest from asninja.parser import AtmelStudioProject from asninja.toolchains.atmel_studio import * class TestAtmelStudioGccToolchain(unittest.TestCase): def test_constructor(self): tc = AtmelStudioGccToolchain('arm-') self.assertEqual('arm-', tc.path) self.assertEqual('arm', tc.tool_type) @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_from_project(self): asp = AtmelStudioProject('Korsar3.cproj', 'Korsar3') tc = AtmelStudioGccToolchain.from_project(asp) self.assertEqual('C:\\Program Files (x86)\\Atmel\\Atmel Studio 6.2\\..\\Atmel Toolchain\\ARM GCC\\Native\\' '4.8.1437\\arm-gnu-toolchain\\bin', tc.path) self.assertEqual('arm', tc.tool_type) @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_read_reg(self): pass if __name__ == '__main__': unittest.main()
import sys import unittest from unittest.mock import patch from asninja.parser import AtmelStudioProject from asninja.toolchains.atmel_studio import * class TestAtmelStudioGccToolchain(unittest.TestCase): def test_constructor(self): tc = AtmelStudioGccToolchain('arm-') self.assertEqual('arm-', tc.path) self.assertEqual('arm', tc.tool_type) @patch.object(AtmelStudioGccToolchain, 'read_reg', return_value = 'DUMMY_PATH') def test_from_project(self, mock_method): asp = AtmelStudioProject('Korsar3.cproj', 'Korsar3') tc = AtmelStudioGccToolchain.from_project(asp) self.assertEqual('DUMMY_PATH\\..\\Atmel Toolchain\\ARM GCC\\Native\\4.8.1437\\arm-gnu-toolchain\\bin', tc.path) self.assertEqual('arm', tc.tool_type) @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_read_reg(self): pass if __name__ == '__main__': unittest.main()
Use unittest.mock to mock Windows Registry read.
tests: Use unittest.mock to mock Windows Registry read.
Python
mit
alunegov/AtmelStudioToNinja
--- +++ @@ -1,5 +1,6 @@ import sys import unittest +from unittest.mock import patch from asninja.parser import AtmelStudioProject from asninja.toolchains.atmel_studio import * @@ -11,13 +12,12 @@ self.assertEqual('arm-', tc.path) self.assertEqual('arm', tc.tool_type) - @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") - def test_from_project(self): + @patch.object(AtmelStudioGccToolchain, 'read_reg', return_value = 'DUMMY_PATH') + def test_from_project(self, mock_method): asp = AtmelStudioProject('Korsar3.cproj', 'Korsar3') tc = AtmelStudioGccToolchain.from_project(asp) - self.assertEqual('C:\\Program Files (x86)\\Atmel\\Atmel Studio 6.2\\..\\Atmel Toolchain\\ARM GCC\\Native\\' - '4.8.1437\\arm-gnu-toolchain\\bin', tc.path) + self.assertEqual('DUMMY_PATH\\..\\Atmel Toolchain\\ARM GCC\\Native\\4.8.1437\\arm-gnu-toolchain\\bin', tc.path) self.assertEqual('arm', tc.tool_type) @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
35d80ac6af0a546f138f6db31511e9dade7aae8e
feder/es_search/queries.py
feder/es_search/queries.py
from elasticsearch_dsl import Search, Index from elasticsearch_dsl.query import MultiMatch, Match, Q, MoreLikeThis from elasticsearch_dsl.connections import get_connection, connections from .documents import LetterDocument def serialize_document(doc): return { "_id": doc.__dict__["meta"]["id"], "_index": doc.__dict__["meta"]["index"], } def search_keywords(query): q = MultiMatch(query=query, fields=["title", "body", "content"]) return LetterDocument.search().query(q).execute() def more_like_this(doc): like = serialize_document(doc) q = MoreLikeThis(like=like, fields=["title", "body"],) query = LetterDocument.search().query(q) print(query.to_dict()) x = query.execute() print(x) return x
from elasticsearch_dsl import Search, Index from elasticsearch_dsl.query import MultiMatch, Match, Q, MoreLikeThis from elasticsearch_dsl.connections import get_connection, connections from .documents import LetterDocument def serialize_document(doc): return { "_id": doc.__dict__["meta"]["id"], "_index": doc.__dict__["meta"]["index"], } def search_keywords(query): q = MultiMatch(query=query, fields=["title", "body", "content"]) return LetterDocument.search().query(q).execute() def more_like_this(doc): like = serialize_document(doc) q = MoreLikeThis(like=like, fields=["title", "body"],) query = LetterDocument.search().query(q) # print(query.to_dict()) return query.execute()
Reduce debug logging in more_like_this
Reduce debug logging in more_like_this
Python
mit
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
--- +++ @@ -20,7 +20,5 @@ like = serialize_document(doc) q = MoreLikeThis(like=like, fields=["title", "body"],) query = LetterDocument.search().query(q) - print(query.to_dict()) - x = query.execute() - print(x) - return x + # print(query.to_dict()) + return query.execute()
0ac9f362906e6d55d10d4c6ee1e0ce1f288821ee
rst2pdf/sectnumlinks.py
rst2pdf/sectnumlinks.py
import docutils class SectNumFolder(docutils.nodes.SparseNodeVisitor): def __init__(self, document): docutils.nodes.SparseNodeVisitor.__init__(self, document) self.sectnums = {} def visit_generated(self, node): for i in node.parent.parent['ids']: self.sectnums[i]=node.parent.astext().replace(u'\xa0\xa0\xa0',' ') class SectRefExpander(docutils.nodes.SparseNodeVisitor): def __init__(self, document, sectnums): docutils.nodes.SparseNodeVisitor.__init__(self, document) self.sectnums = sectnums def visit_reference(self, node): if node.get('refid', None) in self.sectnums: node.children=[docutils.nodes.Text('%s '%self.sectnums[node.get('refid')])]
import docutils class SectNumFolder(docutils.nodes.SparseNodeVisitor): def __init__(self, document): docutils.nodes.SparseNodeVisitor.__init__(self, document) self.sectnums = {} def visit_generated(self, node): for i in node.parent.parent['ids']: self.sectnums[i]=node.parent.astext().replace(u'\xa0\xa0\xa0',' ') def unknown_visit(self, node): pass class SectRefExpander(docutils.nodes.SparseNodeVisitor): def __init__(self, document, sectnums): docutils.nodes.SparseNodeVisitor.__init__(self, document) self.sectnums = sectnums def visit_reference(self, node): if node.get('refid', None) in self.sectnums: node.children=[docutils.nodes.Text('%s '%self.sectnums[node.get('refid')])] def unknown_visit(self, node): pass
Support visiting unknown nodes in SectNumFolder and SectRefExpander
Support visiting unknown nodes in SectNumFolder and SectRefExpander
Python
mit
rst2pdf/rst2pdf,rst2pdf/rst2pdf
--- +++ @@ -9,6 +9,9 @@ for i in node.parent.parent['ids']: self.sectnums[i]=node.parent.astext().replace(u'\xa0\xa0\xa0',' ') + def unknown_visit(self, node): + pass + class SectRefExpander(docutils.nodes.SparseNodeVisitor): def __init__(self, document, sectnums): docutils.nodes.SparseNodeVisitor.__init__(self, document) @@ -17,3 +20,6 @@ def visit_reference(self, node): if node.get('refid', None) in self.sectnums: node.children=[docutils.nodes.Text('%s '%self.sectnums[node.get('refid')])] + + def unknown_visit(self, node): + pass
f350de4b748c8a6e8368a8d4500be92ad14b78c3
pip/vendor/__init__.py
pip/vendor/__init__.py
""" pip.vendor is for vendoring dependencies of pip to prevent needing pip to depend on something external. Files inside of pip.vendor should be considered immutable and should only be updated to versions from upstream. """ from __future__ import absolute_import # Monkeypatch pip.vendor.six into just six try: import six except ImportError: import sys from . import six sys.modules["six"] = six
""" pip.vendor is for vendoring dependencies of pip to prevent needing pip to depend on something external. Files inside of pip.vendor should be considered immutable and should only be updated to versions from upstream. """ from __future__ import absolute_import # Monkeypatch pip.vendor.six into just six # This is kind of terrible, however it is the least bad of 3 bad options # #1 Ship pip with ``six`` such that it gets installed as a regular module # #2 Modify pip.vendor.html5lib so that instead of ``import six`` it uses # ``from pip.vendor import six``. # #3 This monkeypatch which adds six to the top level modules only when # pip.vendor.* is being used. # # #1 involves pollutiong the globally installed packages and possibly # preventing people from using older or newer versions of the six library # #2 Means we've modified upstream which makes it more dificult to upgrade # in the future and paves the way for us to be in charge of maintaining it. # #3 Allows us to not modify upstream while only pollutiong the global # namespace when ``pip.vendor`` has been imported, which in typical usage # is isolated to command line evocations. try: import six except ImportError: import sys from . import six sys.modules["six"] = six
Document the reasons why we are monkeypatching six into sys.modules
Document the reasons why we are monkeypatching six into sys.modules
Python
mit
minrk/pip,harrisonfeng/pip,tdsmith/pip,xavfernandez/pip,caosmo/pip,zenlambda/pip,haridsv/pip,Carreau/pip,pjdelport/pip,habnabit/pip,alex/pip,davidovich/pip,luzfcb/pip,alex/pip,jamezpolley/pip,pradyunsg/pip,mujiansu/pip,natefoo/pip,sigmavirus24/pip,luzfcb/pip,patricklaw/pip,h4ck3rm1k3/pip,James-Firth/pip,ChristopherHogan/pip,atdaemon/pip,sigmavirus24/pip,James-Firth/pip,zenlambda/pip,qwcode/pip,prasaianooz/pip,RonnyPfannschmidt/pip,nthall/pip,RonnyPfannschmidt/pip,nthall/pip,pypa/pip,ncoghlan/pip,mujiansu/pip,chaoallsome/pip,atdaemon/pip,yati-sagade/pip,squidsoup/pip,caosmo/pip,zorosteven/pip,msabramo/pip,pjdelport/pip,wkeyword/pip,yati-sagade/pip,zorosteven/pip,squidsoup/pip,jasonkying/pip,mattrobenolt/pip,willingc/pip,KarelJakubec/pip,jamezpolley/pip,willingc/pip,ChristopherHogan/pip,ianw/pip,natefoo/pip,pradyunsg/pip,blarghmatey/pip,sbidoul/pip,fiber-space/pip,alex/pip,techtonik/pip,minrk/pip,prasaianooz/pip,davidovich/pip,luzfcb/pip,xavfernandez/pip,zenlambda/pip,pfmoore/pip,rouge8/pip,zvezdan/pip,atdaemon/pip,dstufft/pip,mindw/pip,techtonik/pip,h4ck3rm1k3/pip,natefoo/pip,jamezpolley/pip,dstufft/pip,nthall/pip,benesch/pip,qbdsoft/pip,rouge8/pip,supriyantomaftuh/pip,haridsv/pip,mindw/pip,qbdsoft/pip,erikrose/pip,davidovich/pip,Gabriel439/pip,ChristopherHogan/pip,graingert/pip,harrisonfeng/pip,Ivoz/pip,dstufft/pip,jasonkying/pip,wkeyword/pip,sigmavirus24/pip,cjerdonek/pip,graingert/pip,prasaianooz/pip,yati-sagade/pip,rbtcollins/pip,mujiansu/pip,benesch/pip,rbtcollins/pip,esc/pip,jythontools/pip,chaoallsome/pip,zvezdan/pip,esc/pip,rouge8/pip,tdsmith/pip,jmagnusson/pip,blarghmatey/pip,zvezdan/pip,alquerci/pip,zorosteven/pip,erikrose/pip,KarelJakubec/pip,habnabit/pip,RonnyPfannschmidt/pip,Ivoz/pip,pjdelport/pip,msabramo/pip,ncoghlan/pip,esc/pip,techtonik/pip,jmagnusson/pip,alquerci/pip,supriyantomaftuh/pip,wkeyword/pip,Carreau/pip,haridsv/pip,mindw/pip,xavfernandez/pip,benesch/pip,ianw/pip,blarghmatey/pip,patricklaw/pip,fiber-space/pip,pypa/pip,rbtcollins/pip,qbdsoft/pip,pfmoore/pip,Gabriel439/pip,fiber-space/pip,jythontools/pip,qwcode/pip,jmagnusson/pip,supriyantomaftuh/pip,erikrose/pip,willingc/pip,graingert/pip,squidsoup/pip,habnabit/pip,Gabriel439/pip,KarelJakubec/pip,jasonkying/pip,James-Firth/pip,harrisonfeng/pip,jythontools/pip,ncoghlan/pip,h4ck3rm1k3/pip,cjerdonek/pip,mattrobenolt/pip,chaoallsome/pip,sbidoul/pip,tdsmith/pip,caosmo/pip
--- +++ @@ -8,6 +8,20 @@ from __future__ import absolute_import # Monkeypatch pip.vendor.six into just six +# This is kind of terrible, however it is the least bad of 3 bad options +# #1 Ship pip with ``six`` such that it gets installed as a regular module +# #2 Modify pip.vendor.html5lib so that instead of ``import six`` it uses +# ``from pip.vendor import six``. +# #3 This monkeypatch which adds six to the top level modules only when +# pip.vendor.* is being used. +# +# #1 involves pollutiong the globally installed packages and possibly +# preventing people from using older or newer versions of the six library +# #2 Means we've modified upstream which makes it more dificult to upgrade +# in the future and paves the way for us to be in charge of maintaining it. +# #3 Allows us to not modify upstream while only pollutiong the global +# namespace when ``pip.vendor`` has been imported, which in typical usage +# is isolated to command line evocations. try: import six except ImportError:
29da3abba1a8ddb37bce77d1226faa371f3650b3
docs/moosedocs.py
docs/moosedocs.py
#!/usr/bin/env python import sys import os # Locate MOOSE directory MOOSE_DIR = os.getenv('MOOSE_DIR', os.path.join(os.getcwd(), 'moose')) if not os.path.exists(MOOSE_DIR): MOOSE_DIR = os.path.join(os.getenv('HOME'), 'projects', 'moose') if not os.path.exists(MOOSE_DIR): raise Exception('Failed to locate MOOSE, specify the MOOSE_DIR environment variable.') # Append MOOSE python directory MOOSE_PYTHON_DIR = os.path.join(MOOSE_DIR, 'python') if MOOSE_PYTHON_DIR not in sys.path: sys.path.append(MOOSE_PYTHON_DIR) import MooseDocs MooseDocs.MOOSE_DIR = MOOSE_DIR if __name__ == '__main__': sys.exit(MooseDocs.moosedocs())
#!/usr/bin/env python import sys import os # Locate MOOSE directory MOOSE_DIR = os.getenv('MOOSE_DIR', os.path.join(os.getcwd(), 'moose')) if not os.path.exists(MOOSE_DIR): MOOSE_DIR = os.path.join(os.getenv('HOME'), 'projects', 'moose') if not os.path.exists(MOOSE_DIR): raise Exception('Failed to locate MOOSE, specify the MOOSE_DIR environment variable.') # Append MOOSE python directory MOOSE_PYTHON_DIR = os.path.join(MOOSE_DIR, 'python') if MOOSE_PYTHON_DIR not in sys.path: sys.path.append(MOOSE_PYTHON_DIR) import MooseDocs MooseDocs.MOOSE_DIR = MOOSE_DIR if __name__ == '__main__': sys.exit(MooseDocs.moosedocs())
Correct spacing in docs python
Correct spacing in docs python (refs #6699)
Python
lgpl-2.1
jessecarterMOOSE/moose,liuwenf/moose,yipenggao/moose,lindsayad/moose,idaholab/moose,yipenggao/moose,bwspenc/moose,YaqiWang/moose,joshua-cogliati-inl/moose,Chuban/moose,yipenggao/moose,bwspenc/moose,sapitts/moose,SudiptaBiswas/moose,SudiptaBiswas/moose,friedmud/moose,stimpsonsg/moose,Chuban/moose,lindsayad/moose,idaholab/moose,bwspenc/moose,milljm/moose,joshua-cogliati-inl/moose,sapitts/moose,stimpsonsg/moose,permcody/moose,backmari/moose,sapitts/moose,andrsd/moose,idaholab/moose,andrsd/moose,liuwenf/moose,idaholab/moose,harterj/moose,harterj/moose,backmari/moose,laagesen/moose,dschwen/moose,permcody/moose,backmari/moose,lindsayad/moose,nuclear-wizard/moose,lindsayad/moose,stimpsonsg/moose,Chuban/moose,idaholab/moose,nuclear-wizard/moose,YaqiWang/moose,dschwen/moose,andrsd/moose,joshua-cogliati-inl/moose,YaqiWang/moose,liuwenf/moose,dschwen/moose,jessecarterMOOSE/moose,milljm/moose,nuclear-wizard/moose,laagesen/moose,joshua-cogliati-inl/moose,friedmud/moose,dschwen/moose,friedmud/moose,liuwenf/moose,sapitts/moose,yipenggao/moose,liuwenf/moose,milljm/moose,laagesen/moose,permcody/moose,laagesen/moose,YaqiWang/moose,bwspenc/moose,jessecarterMOOSE/moose,SudiptaBiswas/moose,permcody/moose,laagesen/moose,harterj/moose,nuclear-wizard/moose,sapitts/moose,andrsd/moose,backmari/moose,friedmud/moose,milljm/moose,jessecarterMOOSE/moose,harterj/moose,SudiptaBiswas/moose,stimpsonsg/moose,jessecarterMOOSE/moose,SudiptaBiswas/moose,harterj/moose,bwspenc/moose,liuwenf/moose,andrsd/moose,Chuban/moose,dschwen/moose,milljm/moose,lindsayad/moose
--- +++ @@ -5,16 +5,16 @@ # Locate MOOSE directory MOOSE_DIR = os.getenv('MOOSE_DIR', os.path.join(os.getcwd(), 'moose')) if not os.path.exists(MOOSE_DIR): - MOOSE_DIR = os.path.join(os.getenv('HOME'), 'projects', 'moose') + MOOSE_DIR = os.path.join(os.getenv('HOME'), 'projects', 'moose') if not os.path.exists(MOOSE_DIR): - raise Exception('Failed to locate MOOSE, specify the MOOSE_DIR environment variable.') + raise Exception('Failed to locate MOOSE, specify the MOOSE_DIR environment variable.') # Append MOOSE python directory MOOSE_PYTHON_DIR = os.path.join(MOOSE_DIR, 'python') if MOOSE_PYTHON_DIR not in sys.path: - sys.path.append(MOOSE_PYTHON_DIR) + sys.path.append(MOOSE_PYTHON_DIR) import MooseDocs MooseDocs.MOOSE_DIR = MOOSE_DIR if __name__ == '__main__': - sys.exit(MooseDocs.moosedocs()) + sys.exit(MooseDocs.moosedocs())
348cff3fef4c1bcbbb091ddae9ac407179e08011
build.py
build.py
#!/usr/bin/python import sys import os from Scripts.common import get_ini_conf, write_ini_conf if __name__ == "__main__": # Python 2 compatibility if sys.version_info.major > 2: raw_input = input config = get_ini_conf("config.ini") # Find cached module name if "module_name" not in config or not config["module_name"]: module_name = str(raw_input("Enter a module name: ")) config["module_name"] = module_name.strip() # Write back config write_ini_conf(config, "config.ini") # Just execute the build script from Scripts.setup import make_output_dir, run_cmake, run_cmake_build make_output_dir() run_cmake(config) run_cmake_build(config) print("Success!") sys.exit(0)
#!/usr/bin/python import sys import os from os.path import join, realpath, dirname from Scripts.common import get_ini_conf, write_ini_conf if __name__ == "__main__": # Python 2 compatibility if sys.version_info.major > 2: raw_input = input config_file = join(dirname(realpath(__file__)), "config.ini") config = get_ini_conf(config_file) # Find cached module name if "module_name" not in config or not config["module_name"]: module_name = str(raw_input("Enter a module name: ")) config["module_name"] = module_name.strip() # Write back config write_ini_conf(config, config_file) # Just execute the build script from Scripts.setup import make_output_dir, run_cmake, run_cmake_build make_output_dir() run_cmake(config) run_cmake_build(config) print("Success!") sys.exit(0)
Fix issue when the cwd is not in the config directory
Fix issue when the cwd is not in the config directory
Python
mit
tobspr/P3DModuleBuilder,tobspr/P3DModuleBuilder,tobspr/P3DModuleBuilder
--- +++ @@ -2,6 +2,7 @@ import sys import os +from os.path import join, realpath, dirname from Scripts.common import get_ini_conf, write_ini_conf @@ -11,7 +12,8 @@ if sys.version_info.major > 2: raw_input = input - config = get_ini_conf("config.ini") + config_file = join(dirname(realpath(__file__)), "config.ini") + config = get_ini_conf(config_file) # Find cached module name if "module_name" not in config or not config["module_name"]: @@ -19,7 +21,7 @@ config["module_name"] = module_name.strip() # Write back config - write_ini_conf(config, "config.ini") + write_ini_conf(config, config_file) # Just execute the build script from Scripts.setup import make_output_dir, run_cmake, run_cmake_build
20288a2e41c43cde37b14c63d4d0733bffe2dd69
application.py
application.py
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) if __name__ == '__main__': manager.run()
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) manager.add_command("runserver", Server(port=5004)) if __name__ == '__main__': manager.run()
Update to run on port 5004
Update to run on port 5004 For development we will want to run multiple apps, so they should each bind to a different port number.
Python
mit
mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend
--- +++ @@ -2,10 +2,11 @@ import os from app import create_app -from flask.ext.script import Manager +from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) +manager.add_command("runserver", Server(port=5004)) if __name__ == '__main__': manager.run()
5f6c55d8399c63893b8e5b4a432349e14cd5331d
thefuck/specific/archlinux.py
thefuck/specific/archlinux.py
""" This file provide some utility functions for Arch Linux specific rules.""" import subprocess from .. import utils @utils.memoize def get_pkgfile(command): """ Gets the packages that provide the given command using `pkgfile`. If the command is of the form `sudo foo`, searches for the `foo` command instead. """ try: command = command.strip() if command.startswith('sudo '): command = command[5:] command = command.split(" ")[0] packages = subprocess.check_output( ['pkgfile', '-b', '-v', command], universal_newlines=True, stderr=utils.DEVNULL ).splitlines() return [package.split()[0] for package in packages] except subprocess.CalledProcessError: return None def archlinux_env(): if utils.which('yaourt'): pacman = 'yaourt' elif utils.which('pacman'): pacman = 'sudo pacman' else: return False, None enabled_by_default = utils.which('pkgfile') return enabled_by_default, pacman
""" This file provide some utility functions for Arch Linux specific rules.""" import subprocess from .. import utils @utils.memoize def get_pkgfile(command): """ Gets the packages that provide the given command using `pkgfile`. If the command is of the form `sudo foo`, searches for the `foo` command instead. """ try: command = command.strip() if command.startswith('sudo '): command = command[5:] command = command.split(" ")[0] packages = subprocess.check_output( ['pkgfile', '-b', '-v', command], universal_newlines=True, stderr=utils.DEVNULL ).splitlines() return [package.split()[0] for package in packages] except subprocess.CalledProcessError: return [] def archlinux_env(): if utils.which('yaourt'): pacman = 'yaourt' elif utils.which('pacman'): pacman = 'sudo pacman' else: return False, None enabled_by_default = utils.which('pkgfile') return enabled_by_default, pacman
Fix issue with attempting to scroll through options when not-found package has no packages with matching names causing crash.
Fix issue with attempting to scroll through options when not-found package has no packages with matching names causing crash.
Python
mit
nvbn/thefuck,mlk/thefuck,SimenB/thefuck,Clpsplug/thefuck,scorphus/thefuck,nvbn/thefuck,scorphus/thefuck,Clpsplug/thefuck,mlk/thefuck,SimenB/thefuck
--- +++ @@ -25,7 +25,7 @@ return [package.split()[0] for package in packages] except subprocess.CalledProcessError: - return None + return [] def archlinux_env():
aa12f94327060fb0a34a050e0811a5adbd1c0b2a
wsgiproxy/requests_client.py
wsgiproxy/requests_client.py
# -*- coding: utf-8 -*- import requests class HttpClient(object): """A HTTP client using requests""" default_options = dict(verify=False, allow_redirects=False) def __init__(self, chunk_size=1024 * 24, session=None, **requests_options): options = self.default_options.copy() options.update(requests_options) self.options = options self.chunk_size = chunk_size self.session = session def __call__(self, uri, method, body, headers): kwargs = self.options.copy() kwargs['headers'] = headers if 'Transfer-Encoding' in headers: del headers['Transfer-Encoding'] if headers.get('Content-Length'): kwargs['data'] = body.read(int(headers['Content-Length'])) if self.session is None: session = requests.sessions.Session() else: session = self.session response = session.request(method, uri, **kwargs) location = response.headers.get('location') or None status = '%s %s' % (response.status_code, response.reason) headers = [(k.title(), v) for k, v in response.headers.items()] return (status, location, headers, response.iter_content(chunk_size=self.chunk_size))
# -*- coding: utf-8 -*- import requests from functools import partial class HttpClient(object): """A HTTP client using requests""" default_options = dict(verify=False, allow_redirects=False) def __init__(self, chunk_size=1024 * 24, session=None, **requests_options): options = self.default_options.copy() options.update(requests_options) self.options = options self.chunk_size = chunk_size self.session = session def __call__(self, uri, method, body, headers): kwargs = self.options.copy() kwargs['headers'] = headers if 'Transfer-Encoding' in headers: del headers['Transfer-Encoding'] if headers.get('Content-Length'): kwargs['data'] = body.read(int(headers['Content-Length'])) kwargs['stream'] = True if self.session is None: session = requests.sessions.Session() else: session = self.session response = session.request(method, uri, **kwargs) location = response.headers.get('location') or None status = '%s %s' % (response.status_code, response.reason) headers = [(k.title(), v) for k, v in response.headers.items()] return (status, location, headers, iter(partial(response.raw.read, self.chunk_size), ''))
Return the data not gzip decoded
Return the data not gzip decoded Requests does that by default so you need to use the underlying raw data and let webtest decode it itself instead.
Python
mit
gawel/WSGIProxy2
--- +++ @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- import requests +from functools import partial class HttpClient(object): @@ -21,6 +22,7 @@ del headers['Transfer-Encoding'] if headers.get('Content-Length'): kwargs['data'] = body.read(int(headers['Content-Length'])) + kwargs['stream'] = True if self.session is None: session = requests.sessions.Session() @@ -30,6 +32,8 @@ location = response.headers.get('location') or None status = '%s %s' % (response.status_code, response.reason) + headers = [(k.title(), v) for k, v in response.headers.items()] + return (status, location, headers, - response.iter_content(chunk_size=self.chunk_size)) + iter(partial(response.raw.read, self.chunk_size), ''))
71513ce192b62f36e1d19e8e90188b79153d5e7c
hodor/models/challenges.py
hodor/models/challenges.py
# -*- coding: utf-8 -*- from hodor import db from sqlalchemy import inspect class Challenges(db.Model): __tablename__= 'challenges' #Data variables for each Challenges chalid=db.Column(db.String(32), primary_key=True,unique=True,nullable=False) name = db.Column(db.String(32), nullable=False) points = db.Column(db.Integer, nullable=False) description = db.Column(db.String(2048), nullable=False) @staticmethod def save(self): db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def get_all(): return Challenges.query.all()
# -*- coding: utf-8 -*- from hodor import db from sqlalchemy import inspect class Challenges(db.Model): __tablename__= 'challenges' #Data variables for each challenge chall_id=db.Column(db.String(32), primary_key=True,unique=True,nullable=False) name = db.Column(db.String(32), nullable=False) points = db.Column(db.Integer, nullable=False) description = db.Column(db.String(2048), nullable=False) hints=db.Column(db.String(512), nullable=False) @staticmethod def save(self): db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def get_all(): return Challenges.query.all()
Add hints column in challenge model
Add hints column in challenge model
Python
mit
hodorsec/hodor-backend
--- +++ @@ -7,11 +7,12 @@ class Challenges(db.Model): __tablename__= 'challenges' - #Data variables for each Challenges - chalid=db.Column(db.String(32), primary_key=True,unique=True,nullable=False) + #Data variables for each challenge + chall_id=db.Column(db.String(32), primary_key=True,unique=True,nullable=False) name = db.Column(db.String(32), nullable=False) points = db.Column(db.Integer, nullable=False) description = db.Column(db.String(2048), nullable=False) + hints=db.Column(db.String(512), nullable=False) @staticmethod def save(self):
79d78e477e8cf64e7d4cd86470df3c251f6d8376
prequ/locations.py
prequ/locations.py
import os from shutil import rmtree from .click import secho from pip.utils.appdirs import user_cache_dir # The user_cache_dir helper comes straight from pip itself CACHE_DIR = user_cache_dir('prequ') # NOTE # We used to store the cache dir under ~/.pip-tools, which is not the # preferred place to store caches for any platform. This has been addressed # in pip-tools==1.0.5, but to be good citizens, we point this out explicitly # to the user when this directory is still found. LEGACY_CACHE_DIR = os.path.expanduser('~/.pip-tools') if os.path.exists(LEGACY_CACHE_DIR): secho('Removing old cache dir {} (new cache dir is {})'.format(LEGACY_CACHE_DIR, CACHE_DIR), fg='yellow') rmtree(LEGACY_CACHE_DIR)
from pip.utils.appdirs import user_cache_dir # The user_cache_dir helper comes straight from pip itself CACHE_DIR = user_cache_dir('prequ')
Remove migration code of pip-tools legacy cache
Remove migration code of pip-tools legacy cache It's not a responsibility of Prequ to remove legacy cache dir of pip-tools.
Python
bsd-2-clause
suutari-ai/prequ,suutari/prequ,suutari/prequ
--- +++ @@ -1,19 +1,4 @@ -import os -from shutil import rmtree - -from .click import secho from pip.utils.appdirs import user_cache_dir # The user_cache_dir helper comes straight from pip itself CACHE_DIR = user_cache_dir('prequ') - -# NOTE -# We used to store the cache dir under ~/.pip-tools, which is not the -# preferred place to store caches for any platform. This has been addressed -# in pip-tools==1.0.5, but to be good citizens, we point this out explicitly -# to the user when this directory is still found. -LEGACY_CACHE_DIR = os.path.expanduser('~/.pip-tools') - -if os.path.exists(LEGACY_CACHE_DIR): - secho('Removing old cache dir {} (new cache dir is {})'.format(LEGACY_CACHE_DIR, CACHE_DIR), fg='yellow') - rmtree(LEGACY_CACHE_DIR)
1474c74bc65576e1931ff603c63be0d5d1ca803a
dmoj/executors/RKT.py
dmoj/executors/RKT.py
from dmoj.executors.base_executor import CompiledExecutor from dmoj.executors.mixins import ScriptDirectoryMixin import os class Executor(ScriptDirectoryMixin, CompiledExecutor): ext = '.rkt' name = 'RKT' fs = ['/etc/nsswitch.conf$', '/etc/passwd$', os.path.expanduser('~/\.racket/.*?'), '/etc/racket/.*?'] command = 'racket' syscalls = ['epoll_create', 'epoll_wait', 'poll', 'select'] address_grace = 131072 test_program = '''\ #lang racket (displayln (read-line)) ''' def get_compile_args(self): return [self.runtime_dict['raco'], 'make', self._code] def get_cmdline(self): return [self.get_command(), self._code] def get_executable(self): return self.get_command() @classmethod def initialize(cls, sandbox=True): if 'raco' not in cls.runtime_dict: return False return super(Executor, cls).initialize(sandbox) @classmethod def get_versionable_commands(cls): return [('racket', cls.get_command())] @classmethod def get_find_first_mapping(cls): return { 'racket': ['racket'], 'raco': ['raco'] }
import os from dmoj.executors.base_executor import CompiledExecutor from dmoj.executors.mixins import ScriptDirectoryMixin class Executor(ScriptDirectoryMixin, CompiledExecutor): ext = '.rkt' name = 'RKT' fs = [os.path.expanduser('~/\.racket/.*?'), '/etc/racket/.*?'] command = 'racket' syscalls = ['epoll_create', 'epoll_wait', 'poll', 'select'] address_grace = 131072 test_program = '''\ #lang racket (displayln (read-line)) ''' def get_compile_args(self): return [self.runtime_dict['raco'], 'make', self._code] def get_cmdline(self): return [self.get_command(), self._code] def get_executable(self): return self.get_command() @classmethod def initialize(cls, sandbox=True): if 'raco' not in cls.runtime_dict: return False return super(Executor, cls).initialize(sandbox) @classmethod def get_versionable_commands(cls): return [('racket', cls.get_command())] @classmethod def get_find_first_mapping(cls): return { 'racket': ['racket'], 'raco': ['raco'] }
Remove some more paths from Racket
Remove some more paths from Racket
Python
agpl-3.0
DMOJ/judge,DMOJ/judge,DMOJ/judge
--- +++ @@ -1,13 +1,13 @@ +import os + from dmoj.executors.base_executor import CompiledExecutor from dmoj.executors.mixins import ScriptDirectoryMixin -import os class Executor(ScriptDirectoryMixin, CompiledExecutor): ext = '.rkt' name = 'RKT' - fs = ['/etc/nsswitch.conf$', '/etc/passwd$', os.path.expanduser('~/\.racket/.*?'), - '/etc/racket/.*?'] + fs = [os.path.expanduser('~/\.racket/.*?'), '/etc/racket/.*?'] command = 'racket'
bbc0bd975b78d88b8a3a9372f08c343bb1dd5d21
hours_slept_time_series.py
hours_slept_time_series.py
import plotly as py import plotly.graph_objs as go from sys import argv import names from csvparser import parse data_file = argv[1] raw_data = parse(data_file) sleep_durations = [] nap_durations = [] for date, rests in raw_data.items(): sleep_total = nap_total = 0 for r in rests: rest, wake, is_nap = r delta_h = (wake - rest).seconds / 3600 if is_nap: nap_total += delta_h else: sleep_total += delta_h sleep_durations.append(sleep_total) nap_durations.append(nap_total) dates = list(raw_data.keys()) sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration') nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration') data = go.Data([sleep_trace, nap_trace]) layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates), yaxis={'title': 'Hours Slept', 'dtick': 1}) figure = go.Figure(data=data, layout=layout) py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
import plotly as py import plotly.graph_objs as go from sys import argv import names from csvparser import parse data_file = argv[1] raw_data = parse(data_file) sleep_durations = [] nap_durations = [] for date, rests in raw_data.items(): sleep_total = nap_total = 0 for r in rests: rest, wake, is_nap = r delta_h = (wake - rest).seconds / 3600 if is_nap: nap_total += delta_h else: sleep_total += delta_h sleep_durations.append(sleep_total) nap_durations.append(nap_total) dates = list(raw_data.keys()) sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration', mode='lines+markers') nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration', mode='lines+markers') data = go.Data([sleep_trace, nap_trace]) layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates), yaxis={'title': 'Hours Slept', 'dtick': 1}) figure = go.Figure(data=data, layout=layout) py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
Add markers to time series
Add markers to time series
Python
mit
f-jiang/sleep-pattern-grapher
--- +++ @@ -25,8 +25,8 @@ dates = list(raw_data.keys()) -sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration') -nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration') +sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration', mode='lines+markers') +nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration', mode='lines+markers') data = go.Data([sleep_trace, nap_trace]) layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates), @@ -34,3 +34,4 @@ figure = go.Figure(data=data, layout=layout) py.offline.plot(figure, filename=names.output_file_name(__file__, dates)) +
b594c8fd213989e52b08f7bab7f4bf53b8772f3a
filer/__init__.py
filer/__init__.py
#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.23' # pragma: nocover
#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.24' # pragma: nocover
Bump version as instructed by bamboo.
Bump version as instructed by bamboo.
Python
bsd-3-clause
pbs/django-filer,pbs/django-filer,pbs/django-filer,pbs/django-filer,pbs/django-filer
--- +++ @@ -1,3 +1,3 @@ #-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 -__version__ = '0.9pbs.23' # pragma: nocover +__version__ = '0.9pbs.24' # pragma: nocover
7dd683be3df9d8e6ad9c67baa19dbaf5663bdd64
pwnableapp/__init__.py
pwnableapp/__init__.py
import logging import flask import sys class Flask(flask.Flask): def __init__(self, *args, **kwargs): super(Flask, self).__init__(*args, **kwargs) # Set error handlers self.register_error_handler(500, self.internal_error_handler) for error in (400, 403, 404): self.register_error_handler(error, self.make_error_handler(error)) def init_logging(self): """Must be called after config setup.""" if not self.debug: handler = logging.FileHandler( self.config.get('LOG_FILE', '/tmp/flask.log')) handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)8s [%(filename)s:%(lineno)d] %(message)s')) handler.setLevel(logging.INFO) self.logger.addHandler(handler) def internal_error_handler(self, message=None): return flask.make_response(flask.render_template( 'error.html', message=message, code=500, exc=sys.exc_info()[1]), 500) def make_error_handler(self, code): def _error_handler(message=None): return flask.make_response(flask.render_template( 'error.html', message=message, code=code)) return _error_handler
import logging import flask import os import sys class Flask(flask.Flask): def __init__(self, *args, **kwargs): super(Flask, self).__init__(*args, **kwargs) # Set error handlers self.register_error_handler(500, self.internal_error_handler) for error in (400, 403, 404): self.register_error_handler(error, self.make_error_handler(error)) def init_logging(self): """Must be called after config setup.""" if not self.debug: old_umask = os.umask(0077) handler = logging.FileHandler( self.config.get('LOG_FILE', '/tmp/flask.log')) handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)8s [%(filename)s:%(lineno)d] %(message)s')) handler.setLevel(logging.INFO) self.logger.addHandler(handler) self.logger.info('Logging started.') os.umask(old_umask) def internal_error_handler(self, message=None): return flask.make_response(flask.render_template( 'error.html', message=message, code=500, exc=sys.exc_info()[1]), 500) def make_error_handler(self, code): def _error_handler(message=None): return flask.make_response(flask.render_template( 'error.html', message=message, code=code)) return _error_handler
Set umask before starting logging.
Set umask before starting logging.
Python
apache-2.0
Matir/pwnableweb,Matir/pwnableweb,Matir/pwnableweb,Matir/pwnableweb
--- +++ @@ -1,5 +1,6 @@ import logging import flask +import os import sys class Flask(flask.Flask): @@ -14,12 +15,15 @@ def init_logging(self): """Must be called after config setup.""" if not self.debug: + old_umask = os.umask(0077) handler = logging.FileHandler( self.config.get('LOG_FILE', '/tmp/flask.log')) handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)8s [%(filename)s:%(lineno)d] %(message)s')) handler.setLevel(logging.INFO) self.logger.addHandler(handler) + self.logger.info('Logging started.') + os.umask(old_umask) def internal_error_handler(self, message=None): return flask.make_response(flask.render_template(
47c0feaf96969d65e8f3e3652903cc20b353103d
vtwt/util.py
vtwt/util.py
import re from htmlentitydefs import name2codepoint # From http://wiki.python.org/moin/EscapingHtml _HTMLENT_CODEPOINT_RE = re.compile('&({0}|#\d+);'.format( '|'.join(name2codepoint.keys()))) def recodeText(text): def _entToUnichr(match): ent = match.group(1) try: if ent.startswith("#"): char = unichr(int(ent[1:])) else: char = unichr(name2codepoint[ent]) except: char = match.group(0) return char return _HTMLENT_CODEPOINT_RE.sub(_entToUnichr, text)
import re from htmlentitydefs import name2codepoint # From http://wiki.python.org/moin/EscapingHtml _HTMLENT_CODEPOINT_RE = re.compile('&({0}|#\d+);'.format( '|'.join(name2codepoint.keys()))) def recodeText(text): """Parses things like &amp; and &#8020; into real characters.""" def _entToUnichr(match): ent = match.group(1) try: if ent.startswith("#"): char = unichr(int(ent[1:])) else: char = unichr(name2codepoint[ent]) except: char = match.group(0) return char return _HTMLENT_CODEPOINT_RE.sub(_entToUnichr, text)
Add a comment for robin
Add a comment for robin
Python
bsd-3-clause
olix0r/vtwt
--- +++ @@ -8,6 +8,7 @@ '|'.join(name2codepoint.keys()))) def recodeText(text): + """Parses things like &amp; and &#8020; into real characters.""" def _entToUnichr(match): ent = match.group(1) try:
bf2c3e8553c0cbf0ab863efe1459a1da11b99355
sigopt/exception.py
sigopt/exception.py
import copy class SigOptException(Exception): pass class ApiException(SigOptException): def __init__(self, body, status_code): self.message = body.get('message', None) if body is not None else None self._body = body if self.message is not None: super(ApiException, self).__init__(self.message) else: super(ApiException, self).__init__() self.status_code = status_code def to_json(self): return copy.deepcopy(self._body)
import copy class SigOptException(Exception): pass class ApiException(SigOptException): def __init__(self, body, status_code): self.message = body.get('message', None) if body is not None else None self._body = body if self.message is not None: super(ApiException, self).__init__(self.message) else: super(ApiException, self).__init__() self.status_code = status_code def __repr__(self): return u'{0}({1}, {2}, {3})'.format( self.__class__.__name__, self.message, self.status_code, self._body, ) def __str__(self): return 'ApiException ({0}): {1}'.format( self.status_code, self.message, ) def to_json(self): return copy.deepcopy(self._body)
Add str/repr methods to ApiException
Add str/repr methods to ApiException
Python
mit
sigopt/sigopt-python,sigopt/sigopt-python
--- +++ @@ -15,5 +15,19 @@ super(ApiException, self).__init__() self.status_code = status_code + def __repr__(self): + return u'{0}({1}, {2}, {3})'.format( + self.__class__.__name__, + self.message, + self.status_code, + self._body, + ) + + def __str__(self): + return 'ApiException ({0}): {1}'.format( + self.status_code, + self.message, + ) + def to_json(self): return copy.deepcopy(self._body)
e85e94d901560cd176883b3522cf0a961759732c
db/Db.py
db/Db.py
import abc import sqlite3 import Config class Db(object): __metaclass__ = abc.ABCMeta def __init__(self): self._connection = self.connect() @abc.abstractmethod def connect(self, config_file = None): raise NotImplementedError("Called method is not implemented") @abc.abstractmethod def execute(self, query, params = None): raise NotImplementedError("Called method is not implemented") @abc.abstractmethod def commit(self): raise NotImplementedError("Called method is not implemented") @abc.abstractmethod def close(self): raise NotImplementedError("Called method is not implemented") class SQLiteDb(Db): def connect(self, config_file): conf = Config(config_file) cfg = conf.sqlite_options() sqlite3.connect(cfg.db_file) def execute(self, query, params = None): self._connection.execute(query, params) def commit(self): self._connection.commit() def close(self): self._connection.close()
import abc import sqlite3 from ebroker.Config import Config def getDb(config_file = None): return SQLiteDb(config_file) class Db(object): __metaclass__ = abc.ABCMeta def __init__(self, config_file = None): self._config_file = config_file self._connection = None # make sure attribute _connection exists @abc.abstractmethod def connect(self): raise NotImplementedError("Called method is not implemented") @abc.abstractmethod def execute(self, query, params = None): raise NotImplementedError("Called method is not implemented") @abc.abstractmethod def commit(self): raise NotImplementedError("Called method is not implemented") @abc.abstractmethod def close(self): raise NotImplementedError("Called method is not implemented") class SQLiteDb(Db): def __init__(self, config_file = None): super(SQLiteDb, self).__init__(config_file) conf = Config(config_file) cfg = conf.sqlite_options() self._db_file = cfg.db_file def connect(self): self._connection = sqlite3.connect(self._db_file) def execute(self, query, params = None): if self._connection is None: self.connect() if params is None: self._connection.execute(query) else: self._connection.execute(query, params) def commit(self): self._connection.commit() def close(self): self._connection.close() def prepare(db = None): _db = db if _db is None: _db = getDb() _db.execute(''' CREATE TABLE requests(ticker int, price double, amount int, symbol varchar(10), amount_satisfied int) ''')
Fix various small issues in DB support
Fix various small issues in DB support
Python
mit
vjuranek/e-broker-client
--- +++ @@ -2,17 +2,23 @@ import sqlite3 -import Config +from ebroker.Config import Config + + +def getDb(config_file = None): + return SQLiteDb(config_file) + class Db(object): __metaclass__ = abc.ABCMeta - def __init__(self): - self._connection = self.connect() + def __init__(self, config_file = None): + self._config_file = config_file + self._connection = None # make sure attribute _connection exists @abc.abstractmethod - def connect(self, config_file = None): + def connect(self): raise NotImplementedError("Called method is not implemented") @abc.abstractmethod @@ -30,16 +36,37 @@ class SQLiteDb(Db): - def connect(self, config_file): + + def __init__(self, config_file = None): + super(SQLiteDb, self).__init__(config_file) conf = Config(config_file) cfg = conf.sqlite_options() - sqlite3.connect(cfg.db_file) + self._db_file = cfg.db_file + + def connect(self): + self._connection = sqlite3.connect(self._db_file) def execute(self, query, params = None): - self._connection.execute(query, params) + if self._connection is None: + self.connect() + if params is None: + self._connection.execute(query) + else: + self._connection.execute(query, params) def commit(self): self._connection.commit() def close(self): self._connection.close() + + +def prepare(db = None): + _db = db + if _db is None: + _db = getDb() + _db.execute(''' + CREATE TABLE requests(ticker int, price double, amount int, symbol varchar(10), amount_satisfied int) + ''') + +
b175b8a68cd98aa00326747aa66038f9692d8704
ginga/qtw/Plot.py
ginga/qtw/Plot.py
# # Plot.py -- Plotting function for Ginga FITS viewer. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # # GUI imports from ginga.qtw.QtHelp import QtGui, QtCore from ginga.qtw import QtHelp import matplotlib from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from ginga.base.PlotBase import PlotBase, HistogramMixin, CutsMixin class Plot(PlotBase): def __init__(self, logger, width=300, height=300, dpi=100): PlotBase.__init__(self, logger, FigureCanvas, width=width, height=height, dpi=dpi) class Histogram(Plot, HistogramMixin): pass class Cuts(Plot, CutsMixin): pass #END
# # Plot.py -- Plotting function for Ginga FITS viewer. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # # GUI imports from ginga.qtw.QtHelp import QtGui, QtCore from ginga.qtw import QtHelp from ginga.toolkit import toolkit import matplotlib if toolkit == 'qt4': from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg \ as FigureCanvas elif toolkit == 'qt5': # qt5 backend is not yet released in matplotlib stable from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg \ as FigureCanvas from ginga.base.PlotBase import PlotBase, HistogramMixin, CutsMixin class Plot(PlotBase): def __init__(self, logger, width=300, height=300, dpi=100): PlotBase.__init__(self, logger, FigureCanvas, width=width, height=height, dpi=dpi) class Histogram(Plot, HistogramMixin): pass class Cuts(Plot, CutsMixin): pass #END
Fix for Qt5 in plugins that use matplotlib
Fix for Qt5 in plugins that use matplotlib
Python
bsd-3-clause
rupak0577/ginga,eteq/ginga,eteq/ginga,naojsoft/ginga,stscieisenhamer/ginga,eteq/ginga,Cadair/ginga,sosey/ginga,rajul/ginga,ejeschke/ginga,naojsoft/ginga,pllim/ginga,rajul/ginga,Cadair/ginga,rajul/ginga,Cadair/ginga,sosey/ginga,sosey/ginga,stscieisenhamer/ginga,pllim/ginga,rupak0577/ginga,pllim/ginga,rupak0577/ginga,ejeschke/ginga,naojsoft/ginga,ejeschke/ginga,stscieisenhamer/ginga
--- +++ @@ -10,9 +10,16 @@ # GUI imports from ginga.qtw.QtHelp import QtGui, QtCore from ginga.qtw import QtHelp +from ginga.toolkit import toolkit import matplotlib -from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas +if toolkit == 'qt4': + from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg \ + as FigureCanvas +elif toolkit == 'qt5': + # qt5 backend is not yet released in matplotlib stable + from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg \ + as FigureCanvas from ginga.base.PlotBase import PlotBase, HistogramMixin, CutsMixin
b35b8935b8f7f429e93c2989add837cc3a1bf1ef
releases/models.py
releases/models.py
from docutils import nodes # Issue type list (keys) + color values ISSUE_TYPES = { 'bug': 'A04040', 'feature': '40A056', 'support': '4070A0', } class Issue(nodes.Element): @property def type(self): return self['type_'] @property def backported(self): return self.get('backported', False) @property def major(self): return self.get('major', False) @property def number(self): return self.get('number', None) @property def line(self): return self.get('line', None) def __repr__(self): flag = '' if self.backported: flag = 'backported' elif self.major: flag = 'major' elif self.line: flag = self.line + '+' if flag: flag = ' ({})'.format(flag) return '<{issue.type} #{issue.number}{flag}>'.format(issue=self, flag=flag) class Release(nodes.Element): @property def number(self): return self['number'] def __repr__(self): return '<release {}>'.format(self.number)
from docutils import nodes # Issue type list (keys) + color values ISSUE_TYPES = { 'bug': 'A04040', 'feature': '40A056', 'support': '4070A0', } class Issue(nodes.Element): @property def type(self): return self['type_'] @property def backported(self): return self.get('backported', False) @property def major(self): return self.get('major', False) @property def number(self): return self.get('number', None) @property def line(self): return self.get('line', None) def __repr__(self): flag = '' if self.backported: flag = 'backported' elif self.major: flag = 'major' elif self.line: flag = self.line + '+' if flag: flag = ' ({0})'.format(flag) return '<{issue.type} #{issue.number}{flag}>'.format(issue=self, flag=flag) class Release(nodes.Element): @property def number(self): return self['number'] def __repr__(self): return '<release {0}>'.format(self.number)
Add Python 2.6 fix for model reprs.
Add Python 2.6 fix for model reprs.
Python
bsd-2-clause
bitprophet/releases
--- +++ @@ -39,8 +39,9 @@ elif self.line: flag = self.line + '+' if flag: - flag = ' ({})'.format(flag) - return '<{issue.type} #{issue.number}{flag}>'.format(issue=self, flag=flag) + flag = ' ({0})'.format(flag) + return '<{issue.type} #{issue.number}{flag}>'.format(issue=self, + flag=flag) class Release(nodes.Element): @@ -49,4 +50,4 @@ return self['number'] def __repr__(self): - return '<release {}>'.format(self.number) + return '<release {0}>'.format(self.number)
72115876305387bcbc79f5bd6dff69e7ad0cbf8e
Models/LogNormal.py
Models/LogNormal.py
from __future__ import division import sys import numpy as np from random import randrange, choice import matplotlib.pyplot as plt from matplotlib import patches, path import scipy.stats '''This script codes the LogNormal Models''' # To code the LogNormal...each division is 75:25 # Still working on this...numbers are not properly summing to N yet # Getting proper number of divisions but whole thing is yet to come together def SimLogNorm(N, S, sample_size): for i in range(sample_size): sample = [] RAC = [N*.75,N*.25] while len(RAC) < S: x = choice(RAC) new1 = x * .75 new2 = x * .25 RAC.append(x) RAC.append(new1) RAC.append(new2) print RAC sample.append(RAC) sample = SimLogNorm(20, 5, 10) print sample
from __future__ import division import sys import numpy as np from random import randrange, choice import matplotlib.pyplot as plt from matplotlib import patches, path import scipy.stats '''This script codes the LogNormal Models''' # To code the LogNormal...each division is 75:25 # Still working on this...numbers are not properly summing to N yet # Getting proper number of divisions but whole thing is yet to come together def SimLogNorm(N, S, sample_size): for i in range(sample_size): sample = [] RAC = [] while len(RAC) < S: sp1 = N * .75 RAC.append(sp1) sp2 = N * .25 RAC.append(sp2) sp3 = choice(RAC) * .75 RAC.append(sp3) sp4 = sp3 * 1/3 RAC.append(sp4) #print RAC sample.append(RAC) print sample samples = SimLogNorm(8, 4, 5)
Work on Log Normal. Not ready yet.
Work on Log Normal. Not ready yet.
Python
mit
nhhillis/SADModels
--- +++ @@ -11,24 +11,30 @@ # Still working on this...numbers are not properly summing to N yet # Getting proper number of divisions but whole thing is yet to come together + def SimLogNorm(N, S, sample_size): for i in range(sample_size): sample = [] - RAC = [N*.75,N*.25] + RAC = [] while len(RAC) < S: - x = choice(RAC) - new1 = x * .75 - new2 = x * .25 - RAC.append(x) - RAC.append(new1) - RAC.append(new2) - print RAC + + sp1 = N * .75 + RAC.append(sp1) + sp2 = N * .25 + RAC.append(sp2) + sp3 = choice(RAC) * .75 + RAC.append(sp3) + sp4 = sp3 * 1/3 + RAC.append(sp4) + #print RAC + sample.append(RAC) - -sample = SimLogNorm(20, 5, 10) -print sample + + print sample + +samples = SimLogNorm(8, 4, 5)
40bb2b8aaff899f847211273f6631547b6bac978
pyhessian/data_types.py
pyhessian/data_types.py
__all__ = ['long'] if hasattr(__builtins__, 'long'): long = long else: class long(int): pass
__all__ = ['long'] if 'long' in __builtins__: long = __builtins__['long'] else: class long(int): pass
Fix bug encoding long type in python 2.x
Fix bug encoding long type in python 2.x
Python
bsd-3-clause
cyrusmg/python-hessian,cyrusmg/python-hessian,cyrusmg/python-hessian
--- +++ @@ -1,8 +1,8 @@ __all__ = ['long'] -if hasattr(__builtins__, 'long'): - long = long +if 'long' in __builtins__: + long = __builtins__['long'] else: class long(int): pass
2aa19e8b039b202ea3cf59e4ce95d8f16f4bc284
generate-key.py
generate-key.py
#!/usr/bin/python import os import sqlite3 import sys import time db = sqlite3.connect('/var/lib/zon-api/data.db') if len(sys.argv) < 3: print('Usage: %s "Firstname Lastname" email@example.com' % sys.argv[0]) print('\nLast keys:') query = 'SELECT * FROM client ORDER by reset DESC' for client in db.execute(query): print(u'{0}: "{2}" {3}'.format(*client).encode('utf8')) sys.exit(1) api_key = str(os.urandom(26).encode('hex')) tier = 'free' name = sys.argv[1] email = sys.argv[2] requests = 0 reset = int(time.time()) query = 'INSERT INTO client VALUES (?, ?, ?, ?, ?, ?)' db.execute(query, (api_key, tier, name, email, requests, reset)) db.commit() db.close() print api_key
#!/usr/bin/python from datetime import datetime import os import sqlite3 import sys import time db = sqlite3.connect('/var/lib/zon-api/data.db') if len(sys.argv) < 3: print('Usage: %s "Firstname Lastname" email@example.com' % sys.argv[0]) print('\nLast keys:') query = 'SELECT * FROM client ORDER by reset DESC' for client in db.execute(query): reset = datetime.fromtimestamp(client[5]) print(u'{0}: "{2}" {3} ({reset})'.format(*client, reset=reset).encode('utf8')) sys.exit(1) api_key = str(os.urandom(26).encode('hex')) tier = 'free' name = sys.argv[1] email = sys.argv[2] requests = 0 reset = int(time.time()) query = 'INSERT INTO client VALUES (?, ?, ?, ?, ?, ?)' db.execute(query, (api_key, tier, name, email, requests, reset)) db.commit() db.close() print api_key
Include 'reset' date when listing keys
MAINT: Include 'reset' date when listing keys Note that this has been changed long ago and only committed now to catch up with the currently deployed state.
Python
bsd-3-clause
ZeitOnline/content-api,ZeitOnline/content-api
--- +++ @@ -1,5 +1,6 @@ #!/usr/bin/python +from datetime import datetime import os import sqlite3 import sys @@ -12,7 +13,8 @@ print('\nLast keys:') query = 'SELECT * FROM client ORDER by reset DESC' for client in db.execute(query): - print(u'{0}: "{2}" {3}'.format(*client).encode('utf8')) + reset = datetime.fromtimestamp(client[5]) + print(u'{0}: "{2}" {3} ({reset})'.format(*client, reset=reset).encode('utf8')) sys.exit(1) api_key = str(os.urandom(26).encode('hex'))
b172c997ef6b295b0367afb381ab818a254ce59b
geodj/models.py
geodj/models.py
from django.db import models class Country(models.Model): name = models.TextField() iso_code = models.CharField(max_length=2, unique=True) def __unicode__(self): return self.name class Artist(models.Model): name = models.TextField() mbid = models.TextField(unique=True) country = models.ForeignKey(Country)
from django.db import models class Country(models.Model): name = models.TextField() iso_code = models.CharField(max_length=2, unique=True) def __unicode__(self): return self.name @staticmethod def with_artists(): return Country.objects.annotate(number_of_artists=models.Count('artist')).filter(number_of_artists__gte=1) class Artist(models.Model): name = models.TextField() mbid = models.TextField(unique=True) country = models.ForeignKey(Country)
Add Country.with_artists() to filter out countries without artists
Add Country.with_artists() to filter out countries without artists
Python
mit
6/GeoDJ,6/GeoDJ
--- +++ @@ -7,6 +7,10 @@ def __unicode__(self): return self.name + @staticmethod + def with_artists(): + return Country.objects.annotate(number_of_artists=models.Count('artist')).filter(number_of_artists__gte=1) + class Artist(models.Model): name = models.TextField() mbid = models.TextField(unique=True)
211091ed92e8bafcac1e9b1c523d392b609fca73
saleor/core/tracing.py
saleor/core/tracing.py
from functools import partial from graphene.types.resolver import default_resolver from graphql import ResolveInfo def should_trace(info: ResolveInfo) -> bool: if info.field_name not in info.parent_type.fields: return False resolver = info.parent_type.fields[info.field_name].resolver return not ( resolver is None or is_default_resolver(resolver) or is_introspection_field(info) ) def is_introspection_field(info: ResolveInfo): for path in info.path: if isinstance(path, str) and path.startswith("__"): return True return False def is_default_resolver(resolver): while isinstance(resolver, partial): resolver = resolver.func if resolver is default_resolver: return True return resolver is default_resolver
from functools import partial from graphene.types.resolver import default_resolver from graphql import ResolveInfo def should_trace(info: ResolveInfo) -> bool: if info.field_name not in info.parent_type.fields: return False resolver = info.parent_type.fields[info.field_name].resolver return not ( resolver is None or is_default_resolver(resolver) or is_introspection_field(info) ) def is_introspection_field(info: ResolveInfo): if info.path is not None: for path in info.path: if isinstance(path, str) and path.startswith("__"): return True return False def is_default_resolver(resolver): while isinstance(resolver, partial): resolver = resolver.func if resolver is default_resolver: return True return resolver is default_resolver
Fix mypy error in introspection check
Fix mypy error in introspection check
Python
bsd-3-clause
mociepka/saleor,mociepka/saleor,mociepka/saleor
--- +++ @@ -17,9 +17,10 @@ def is_introspection_field(info: ResolveInfo): - for path in info.path: - if isinstance(path, str) and path.startswith("__"): - return True + if info.path is not None: + for path in info.path: + if isinstance(path, str) and path.startswith("__"): + return True return False
657b9cd09b3d4c7c07f53bc8f2d995d3b08b63c5
wsgi.py
wsgi.py
#!/usr/bin/python import os virtenv = os.path.join(os.environ.get('OPENSHIFT_PYTHON_DIR', '.'), 'virtenv') virtualenv = os.path.join(virtenv, 'bin/activate_this.py') try: exec_namespace = dict(__file__=virtualenv) with open(virtualenv, 'rb') as exec_file: file_contents = exec_file.read() compiled_code = compile(file_contents, virtualenv, 'exec') exec(compiled_code, exec_namespace) except IOError: pass from main import app as application application.config['SLACK_TEAM_ID'] = os.environ['SLACK_TEAM_ID'] application.config['SLACK_API_TOKEN'] = os.environ['SLACK_API_TOKEN'] application.config['SECRET_KEY'] = os.environ['FLASK_SECRET_KEY'] # Below for testing locally only if __name__ == '__main__': from wsgiref.simple_server import make_server httpd = make_server('localhost', 8051, application) # Wait for a single request, serve it and quit. httpd.serve_forever()
#!/usr/bin/python import os virtenv = os.path.join(os.environ.get('OPENSHIFT_PYTHON_DIR', '.'), 'virtenv') virtualenv = os.path.join(virtenv, 'bin/activate_this.py') try: exec_namespace = dict(__file__=virtualenv) with open(virtualenv, 'rb') as exec_file: file_contents = exec_file.read() compiled_code = compile(file_contents, virtualenv, 'exec') exec(compiled_code, exec_namespace) except IOError: pass from main import app as application application.config['SLACK_TEAM_ID'] = os.environ['SLACK_TEAM_ID'] application.config['SLACK_API_TOKEN'] = os.environ['SLACK_API_TOKEN'] application.config['SECRET_KEY'] = os.environ['FLASK_SECRET_KEY'] # Below for testing locally only if __name__ == '__main__': from wsgiref.simple_server import make_server httpd = make_server('0.0.0.0', 8051, application) httpd.serve_forever()
Use `0.0.0.0` instead of `localhost`
Use `0.0.0.0` instead of `localhost`
Python
mit
avinassh/slackipy,avinassh/slackipy,avinassh/slackipy
--- +++ @@ -25,6 +25,5 @@ # Below for testing locally only if __name__ == '__main__': from wsgiref.simple_server import make_server - httpd = make_server('localhost', 8051, application) - # Wait for a single request, serve it and quit. + httpd = make_server('0.0.0.0', 8051, application) httpd.serve_forever()
62a20e28a5f0bc9b6a9eab67891c875562337c94
rwt/tests/test_deps.py
rwt/tests/test_deps.py
import pkg_resources from rwt import deps def test_entry_points(): """ Ensure entry points are visible after making packages visible """ with deps.on_sys_path('jaraco.mongodb'): eps = pkg_resources.iter_entry_points('pytest11') assert list(eps), "Entry points not found" class TestInstallCheck: def test_installed(self): assert deps.pkg_installed('rwt') def test_not_installed(self): assert not deps.pkg_installed('not_a_package') def test_installed_version(self): assert not deps.pkg_installed('rwt==0.0') def test_not_installed_args(self): args = [ '-i', 'https://devpi.net', '-r', 'requirements.txt', 'rwt', 'not_a_package', 'rwt==0.0', ] expected = args.copy() expected.remove('rwt') filtered = deps.not_installed(args) assert list(filtered) == expected
import copy import pkg_resources from rwt import deps def test_entry_points(): """ Ensure entry points are visible after making packages visible """ with deps.on_sys_path('jaraco.mongodb'): eps = pkg_resources.iter_entry_points('pytest11') assert list(eps), "Entry points not found" class TestInstallCheck: def test_installed(self): assert deps.pkg_installed('rwt') def test_not_installed(self): assert not deps.pkg_installed('not_a_package') def test_installed_version(self): assert not deps.pkg_installed('rwt==0.0') def test_not_installed_args(self): args = [ '-i', 'https://devpi.net', '-r', 'requirements.txt', 'rwt', 'not_a_package', 'rwt==0.0', ] expected = copy.copy(args) expected.remove('rwt') filtered = deps.not_installed(args) assert list(filtered) == expected
Fix test failure on Python 2
Fix test failure on Python 2
Python
mit
jaraco/rwt
--- +++ @@ -1,3 +1,5 @@ +import copy + import pkg_resources from rwt import deps @@ -30,7 +32,7 @@ 'not_a_package', 'rwt==0.0', ] - expected = args.copy() + expected = copy.copy(args) expected.remove('rwt') filtered = deps.not_installed(args) assert list(filtered) == expected
0e26572466bbee071adb62cdb716e5d377774166
src/zeit/content/volume/browser/admin.py
src/zeit/content/volume/browser/admin.py
# -*- coding: utf-8 -*- from zeit.solr import query import zeit.content.article.article import zeit.content.infobox.infobox import zeit.cms.admin.browser.admin class VolumeAdminForm(zeit.cms.admin.browser.admin.EditFormCI): """ Admin View with the publish button. Check out the normal Admin View. /zeit.cms/src/zeit/cms/admin/browser/admin.py. """ def _get_result_from_solr(self): # TODO: Think about infoboxes. They should be published as well, # if they never got checked out they wont be in SOLR. # One Dirty Way would be to checkout all infoboxes after they got # imported. additional_queries = [ query.field('published', 'not-published'), query.or_(query.field_raw( 'type', zeit.content.article.article.ArticleType.type), query.field_raw( 'type', zeit.content.infobox.infobox.InfoboxType.type), ), query.bool_field('urgent', True) ] return self.context.all_content_via_solr( additional_query_contstraints=additional_queries)
# -*- coding: utf-8 -*- from zeit.solr import query import zeit.content.article.article import zeit.content.infobox.infobox import zeit.cms.admin.browser.admin import zope.formlib.form as form class VolumeAdminForm(zeit.cms.admin.browser.admin.EditFormCI): """ Admin View with the publish button. Check out the normal Admin View. /zeit.cms/src/zeit/cms/admin/browser/admin.py. """ extra_actions = form.Actions() @property def actions(self): return list(super(VolumeAdminForm, self).actions) + \ list(self.extra_actions) @form.action("Publish content of this volume", extra_actions) def publish_all(self, action, data): to_publish = self._get_result_from_solr(self) def _get_result_from_solr(self): # TODO: Think about infoboxes. They should be published as well. # Check if they are in Solr additional_queries = [ query.field('published', 'not-published'), query.or_( query.and_( query.bool_field('urgent', True), query.field_raw( 'type', zeit.content.article.article.ArticleType.type)), query.field_raw('type', zeit.content.infobox.infobox.InfoboxType.type), ), ] return self.context.all_content_via_solr( additional_query_contstraints=additional_queries)
Add additional Form action for publish
Add additional Form action for publish
Python
bsd-3-clause
ZeitOnline/zeit.content.volume,ZeitOnline/zeit.content.volume
--- +++ @@ -3,6 +3,7 @@ import zeit.content.article.article import zeit.content.infobox.infobox import zeit.cms.admin.browser.admin +import zope.formlib.form as form class VolumeAdminForm(zeit.cms.admin.browser.admin.EditFormCI): @@ -13,19 +14,33 @@ /zeit.cms/src/zeit/cms/admin/browser/admin.py. """ + extra_actions = form.Actions() + + @property + def actions(self): + return list(super(VolumeAdminForm, self).actions) + \ + list(self.extra_actions) + + @form.action("Publish content of this volume", extra_actions) + def publish_all(self, action, data): + to_publish = self._get_result_from_solr(self) + + def _get_result_from_solr(self): - # TODO: Think about infoboxes. They should be published as well, - # if they never got checked out they wont be in SOLR. - # One Dirty Way would be to checkout all infoboxes after they got - # imported. + # TODO: Think about infoboxes. They should be published as well. + # Check if they are in Solr additional_queries = [ query.field('published', 'not-published'), - query.or_(query.field_raw( - 'type', zeit.content.article.article.ArticleType.type), - query.field_raw( - 'type', zeit.content.infobox.infobox.InfoboxType.type), + query.or_( + query.and_( + query.bool_field('urgent', True), + query.field_raw( + 'type', + zeit.content.article.article.ArticleType.type)), + query.field_raw('type', + zeit.content.infobox.infobox.InfoboxType.type), ), - query.bool_field('urgent', True) + ] return self.context.all_content_via_solr( additional_query_contstraints=additional_queries)
507be5c8923b05304b223785cdba79ae7513f48a
openedx/stanford/djangoapps/register_cme/admin.py
openedx/stanford/djangoapps/register_cme/admin.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ExtraInfo class ExtraInfoAdmin(admin.ModelAdmin): """ Admin interface for ExtraInfo model. """ list_display = ('user', 'get_email', 'last_name', 'first_name',) search_fields = ('user__username', 'user__email', 'last_name', 'first_name',) def get_email(self, obj): return obj.user.email get_email.short_description = 'Email address' class Meta(object): model = ExtraInfo admin.site.register(ExtraInfo, ExtraInfoAdmin)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ExtraInfo admin.site.register(ExtraInfo)
Revert "Change `ExtraInfo` to user fields, add search"
Revert "Change `ExtraInfo` to user fields, add search" This reverts commit f5984fbd4187f4af65fb39b070f91870203d869b.
Python
agpl-3.0
caesar2164/edx-platform,caesar2164/edx-platform,caesar2164/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,caesar2164/edx-platform,Stanford-Online/edx-platform
--- +++ @@ -5,16 +5,4 @@ from .models import ExtraInfo -class ExtraInfoAdmin(admin.ModelAdmin): - """ Admin interface for ExtraInfo model. """ - list_display = ('user', 'get_email', 'last_name', 'first_name',) - search_fields = ('user__username', 'user__email', 'last_name', 'first_name',) - - def get_email(self, obj): - return obj.user.email - get_email.short_description = 'Email address' - - class Meta(object): - model = ExtraInfo - -admin.site.register(ExtraInfo, ExtraInfoAdmin) +admin.site.register(ExtraInfo)
febd9213aaa5cc65dbe724cf12f93cda9444f163
mysite/search/tasks/__init__.py
mysite/search/tasks/__init__.py
from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj from mysite.search import controllers import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): name = "search.GrabLaunchpadBugs" run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) for lp_project in lpproj2ohproj: openhatch_proj = lpproj2ohproj[lp_project] logger.info("Started to grab lp.net bugs for %s into %s" % ( lp_project, openhatch_project)) grab_lp_bugs(lp_project=lp_project, openhatch_project=openhatch_project) class GrabMiroBugs(PeriodicTask): name = "search.GrabMiroBugs" run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab Miro bitesized bugs") mysite.customs.miro.grab_miro_bugs()
from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj from mysite.search import controllers import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) for lp_project in lpproj2ohproj: openhatch_proj = lpproj2ohproj[lp_project] logger.info("Started to grab lp.net bugs for %s into %s" % ( lp_project, openhatch_project)) grab_lp_bugs(lp_project=lp_project, openhatch_project=openhatch_project) class GrabMiroBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab Miro bitesized bugs") mysite.customs.miro.grab_miro_bugs()
Stop manually specifying name of task.
Stop manually specifying name of task.
Python
agpl-3.0
vipul-sharma20/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,ojengwa/oh-mainline,jledbetter/openhatch,mzdaniel/oh-mainline,eeshangarg/oh-mainline,openhatch/oh-mainline,openhatch/oh-mainline,campbe13/openhatch,ehashman/oh-mainline,heeraj123/oh-mainline,nirmeshk/oh-mainline,campbe13/openhatch,SnappleCap/oh-mainline,ojengwa/oh-mainline,vipul-sharma20/oh-mainline,SnappleCap/oh-mainline,vipul-sharma20/oh-mainline,eeshangarg/oh-mainline,nirmeshk/oh-mainline,Changaco/oh-mainline,nirmeshk/oh-mainline,sudheesh001/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,sudheesh001/oh-mainline,openhatch/oh-mainline,ehashman/oh-mainline,ehashman/oh-mainline,heeraj123/oh-mainline,ehashman/oh-mainline,moijes12/oh-mainline,heeraj123/oh-mainline,campbe13/openhatch,mzdaniel/oh-mainline,willingc/oh-mainline,jledbetter/openhatch,heeraj123/oh-mainline,eeshangarg/oh-mainline,jledbetter/openhatch,moijes12/oh-mainline,Changaco/oh-mainline,jledbetter/openhatch,waseem18/oh-mainline,moijes12/oh-mainline,willingc/oh-mainline,sudheesh001/oh-mainline,vipul-sharma20/oh-mainline,eeshangarg/oh-mainline,waseem18/oh-mainline,jledbetter/openhatch,sudheesh001/oh-mainline,willingc/oh-mainline,SnappleCap/oh-mainline,openhatch/oh-mainline,heeraj123/oh-mainline,mzdaniel/oh-mainline,eeshangarg/oh-mainline,campbe13/openhatch,willingc/oh-mainline,onceuponatimeforever/oh-mainline,ojengwa/oh-mainline,sudheesh001/oh-mainline,waseem18/oh-mainline,onceuponatimeforever/oh-mainline,onceuponatimeforever/oh-mainline,nirmeshk/oh-mainline,ojengwa/oh-mainline,moijes12/oh-mainline,SnappleCap/oh-mainline,campbe13/openhatch,waseem18/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,SnappleCap/oh-mainline,nirmeshk/oh-mainline,moijes12/oh-mainline,openhatch/oh-mainline,onceuponatimeforever/oh-mainline,onceuponatimeforever/oh-mainline,willingc/oh-mainline,ehashman/oh-mainline,waseem18/oh-mainline,mzdaniel/oh-mainline,ojengwa/oh-mainline,vipul-sharma20/oh-mainline
--- +++ @@ -7,7 +7,6 @@ import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): - name = "search.GrabLaunchpadBugs" run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) @@ -20,7 +19,6 @@ class GrabMiroBugs(PeriodicTask): - name = "search.GrabMiroBugs" run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs)
83c0e33db27bc2b9aa7e06e125230e6c159439bb
address_book/address_book.py
address_book/address_book.py
__all__ = ['AddressBook'] class AddressBook(object): pass
__all__ = ['AddressBook'] class AddressBook(object): def __init__(self): self.persons = [] def add_person(self, person): self.persons.append(person)
Add persons storage and `add_person` method to `AddressBook` class
Add persons storage and `add_person` method to `AddressBook` class
Python
mit
dizpers/python-address-book-assignment
--- +++ @@ -2,4 +2,9 @@ class AddressBook(object): - pass + + def __init__(self): + self.persons = [] + + def add_person(self, person): + self.persons.append(person)
d27b2d71a0e5f834d4758c67fa6e8ed342001a88
salt/output/__init__.py
salt/output/__init__.py
''' Used to manage the outputter system. This package is the modular system used for managing outputters. ''' import salt.loader def display_output(data, out, opts=None): ''' Print the passed data using the desired output ''' if opts is None: opts = {} outputters = salt.loader.outputters(opts) if not out in outputters: outputters['pprint'](data) outputters[out](data)
''' Used to manage the outputter system. This package is the modular system used for managing outputters. ''' # Import salt utils import salt.loader def display_output(data, out, opts=None): ''' Print the passed data using the desired output ''' if opts is None: opts = {} outputters = salt.loader.outputters(opts) if not out in outputters: outputters['pprint'](data) outputters[out](data)
Add some checks to output module
Add some checks to output module
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -3,6 +3,7 @@ for managing outputters. ''' +# Import salt utils import salt.loader def display_output(data, out, opts=None):
f1afc32efaf0df2a2f8a0b474dc367c1eba8681d
salt/renderers/jinja.py
salt/renderers/jinja.py
from __future__ import absolute_import # Import python libs from StringIO import StringIO # Import salt libs from salt.exceptions import SaltRenderError import salt.utils.templates def render(template_file, env='', sls='', argline='', context=None, tmplpath=None, **kws): ''' Render the template_file, passing the functions and grains into the Jinja rendering system. :rtype: string ''' from_str = argline=='-s' if not from_str and argline: raise SaltRenderError( 'Unknown renderer option: {opt}'.format(opt=argline) ) tmp_data = salt.utils.templates.JINJA(template_file, to_str=True, salt=__salt__, grains=__grains__, opts=__opts__, pillar=__pillar__, env=env, sls=sls, context=context, tmplpath=tmplpath, **kws) if not tmp_data.get('result', False): raise SaltRenderError(tmp_data.get('data', 'Unknown render error in jinja renderer')) return StringIO(tmp_data['data'])
from __future__ import absolute_import # Import python libs from StringIO import StringIO # Import salt libs from salt.exceptions import SaltRenderError import salt.utils.templates def render(template_file, env='', sls='', argline='', context=None, tmplpath=None, **kws): ''' Render the template_file, passing the functions and grains into the Jinja rendering system. :rtype: string ''' from_str = argline == '-s' if not from_str and argline: raise SaltRenderError( 'Unknown renderer option: {opt}'.format(opt=argline) ) tmp_data = salt.utils.templates.JINJA(template_file, to_str=True, salt=__salt__, grains=__grains__, opts=__opts__, pillar=__pillar__, env=env, sls=sls, context=context, tmplpath=tmplpath, **kws) if not tmp_data.get('result', False): raise SaltRenderError( tmp_data.get('data', 'Unknown render error in jinja renderer') ) return StringIO(tmp_data['data'])
Clean up some PEP8 stuff
Clean up some PEP8 stuff
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -16,23 +16,24 @@ :rtype: string ''' - from_str = argline=='-s' + from_str = argline == '-s' if not from_str and argline: raise SaltRenderError( - 'Unknown renderer option: {opt}'.format(opt=argline) - ) - tmp_data = salt.utils.templates.JINJA(template_file, to_str=True, - salt=__salt__, - grains=__grains__, - opts=__opts__, - pillar=__pillar__, - env=env, - sls=sls, - context=context, - tmplpath=tmplpath, - **kws) + 'Unknown renderer option: {opt}'.format(opt=argline) + ) + tmp_data = salt.utils.templates.JINJA(template_file, + to_str=True, + salt=__salt__, + grains=__grains__, + opts=__opts__, + pillar=__pillar__, + env=env, + sls=sls, + context=context, + tmplpath=tmplpath, + **kws) if not tmp_data.get('result', False): - raise SaltRenderError(tmp_data.get('data', - 'Unknown render error in jinja renderer')) + raise SaltRenderError( + tmp_data.get('data', 'Unknown render error in jinja renderer') + ) return StringIO(tmp_data['data']) -
3706700e4725d23752269c2e833adfa736d0ce96
worker/jobs/session/__init__.py
worker/jobs/session/__init__.py
import os from typing import Optional, List from jobs.base.job import Job # If on a K8s cluster then use the K8s-based sessions # otherwise use the subsprocess-based session if "KUBERNETES_SERVICE_HOST" in os.environ: from .kubernetes_session import KubernetesSession Session = KubernetesSession # type: ignore else: from .subprocess_session import SubprocessSession Session = SubprocessSession # type: ignore Session.name = "session"
from typing import Type, Union from .kubernetes_session import api_instance, KubernetesSession from .subprocess_session import SubprocessSession # If on a K8s is available then use that # otherwise use the subsprocess-based session Session: Type[Union[KubernetesSession, SubprocessSession]] if api_instance is not None: Session = KubernetesSession else: Session = SubprocessSession Session.name = "session"
Improve switching between session types
fix(Worker): Improve switching between session types
Python
apache-2.0
stencila/hub,stencila/hub,stencila/hub,stencila/hub,stencila/hub
--- +++ @@ -1,17 +1,14 @@ -import os -from typing import Optional, List +from typing import Type, Union -from jobs.base.job import Job +from .kubernetes_session import api_instance, KubernetesSession +from .subprocess_session import SubprocessSession -# If on a K8s cluster then use the K8s-based sessions +# If on a K8s is available then use that # otherwise use the subsprocess-based session -if "KUBERNETES_SERVICE_HOST" in os.environ: - from .kubernetes_session import KubernetesSession - - Session = KubernetesSession # type: ignore +Session: Type[Union[KubernetesSession, SubprocessSession]] +if api_instance is not None: + Session = KubernetesSession else: - from .subprocess_session import SubprocessSession - - Session = SubprocessSession # type: ignore + Session = SubprocessSession Session.name = "session"
2acca2ea2ae2dc86d4b09ce21c88d578bbea6ea3
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages __about__ = {} with open("warehouse/__about__.py") as fp: exec(fp, None, __about__) setup( name=__about__["__title__"], version=__about__["__version__"], description=__about__["__summary__"], long_description=open("README.rst").read(), url=__about__["__uri__"], license=__about__["__license__"], author=__about__["__author__"], author_email=__about__["__email__"], install_requires=[ "Flask", "Flask-SQLAlchemy", "Flask-Script", "boto", "eventlet", "progress", "psycopg2", "python-s3file>=1.1", "requests", "schema", "xmlrpc2", ], extras_require={ "tests": [ "pylint", ], }, packages=find_packages(exclude=["tests"]), package_data={ "": ["LICENSE"], "warehouse": [ "simple/templates/*.html", "synchronize/*.crt", ], }, include_package_data=True, entry_points={ "console_scripts": [ "warehouse = warehouse.__main__:main", ], }, classifiers=[ "License :: OSI Approved :: BSD License", "Operating System :: POSIX", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ], zip_safe=False, )
#!/usr/bin/env python from setuptools import setup, find_packages __about__ = {} with open("warehouse/__about__.py") as fp: exec(fp, None, __about__) setup( name=__about__["__title__"], version=__about__["__version__"], description=__about__["__summary__"], long_description=open("README.rst").read(), url=__about__["__uri__"], license=__about__["__license__"], author=__about__["__author__"], author_email=__about__["__email__"], install_requires=[ "Flask", "Flask-SQLAlchemy", "Flask-Script", "boto", "eventlet", "progress", "psycopg2", "python-s3file>=1.1", "requests", "schema", "xmlrpc2", ], extras_require={ "tests": [ "pylint", ], }, packages=find_packages(exclude=["tests"]), package_data={ "warehouse": [ "simple/templates/*.html", "synchronize/*.crt", ], }, include_package_data=True, entry_points={ "console_scripts": [ "warehouse = warehouse.__main__:main", ], }, classifiers=[ "License :: OSI Approved :: BSD License", "Operating System :: POSIX", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ], zip_safe=False, )
Remove no longer needed package_data
Remove no longer needed package_data
Python
bsd-2-clause
davidfischer/warehouse
--- +++ @@ -39,7 +39,6 @@ packages=find_packages(exclude=["tests"]), package_data={ - "": ["LICENSE"], "warehouse": [ "simple/templates/*.html", "synchronize/*.crt",
e0883db2bfe5b32bdd73f44a9288fa8483bca08c
setup.py
setup.py
import versioneer from setuptools import setup, find_packages setup( name='domain-event-broker', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Send and receive domain events via RabbitMQ', author='Ableton AG', author_email='webteam@ableton.com', url='https://github.com/AbletonAG/domain-event-broker', license='MIT', packages=find_packages(), install_requires=["pika >= 1.0.0"], tests_require=["pytest >= 3.6.0"], zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], )
import versioneer from setuptools import setup, find_packages # Add README as description from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='domain-event-broker', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Send and receive domain events via RabbitMQ', long_description=long_description, long_description_content_type='text/markdown', author='Ableton AG', author_email='webteam@ableton.com', url='https://github.com/AbletonAG/domain-event-broker', license='MIT', packages=find_packages(), install_requires=["pika >= 1.0.0"], tests_require=["pytest >= 3.6.0"], zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], )
Add project description for PyPI
Add project description for PyPI
Python
mit
AbletonAG/domain-events
--- +++ @@ -1,12 +1,20 @@ import versioneer from setuptools import setup, find_packages + +# Add README as description +from os import path +this_directory = path.abspath(path.dirname(__file__)) +with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: + long_description = f.read() setup( name='domain-event-broker', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Send and receive domain events via RabbitMQ', + long_description=long_description, + long_description_content_type='text/markdown', author='Ableton AG', author_email='webteam@ableton.com', url='https://github.com/AbletonAG/domain-event-broker',
316a17402aca8ca99a90f151de7535a1033b3e24
tests/network/__init__.py
tests/network/__init__.py
from . file_transfer import * # NOQA #from . node import * # NOQA from . message import * # NOQA from . file_handshake import * # NOQA from . queued_file_transfer import * # NOQA from . process_transfers import * # NOQA from . bandwidth_test import * # NOQA if __name__ == "__main__": unittest.main()
from . file_transfer import * # NOQA from . node import * # NOQA from . message import * # NOQA from . file_handshake import * # NOQA from . queued_file_transfer import * # NOQA from . process_transfers import * # NOQA from . bandwidth_test import * # NOQA if __name__ == "__main__": unittest.main()
Fix pep8. Renable all tests.
Fix pep8. Renable all tests.
Python
mit
Storj/storjnode
--- +++ @@ -1,5 +1,5 @@ from . file_transfer import * # NOQA -#from . node import * # NOQA +from . node import * # NOQA from . message import * # NOQA from . file_handshake import * # NOQA from . queued_file_transfer import * # NOQA
713b1292019fef93e5ff2d11a22e775a59f3b3a8
south/signals.py
south/signals.py
""" South-specific signals """ from django.dispatch import Signal from django.conf import settings # Sent at the start of the migration of an app pre_migrate = Signal(providing_args=["app"]) # Sent after each successful migration of an app post_migrate = Signal(providing_args=["app"]) # Sent after each run of a particular migration in a direction ran_migration = Signal(providing_args=["app","migration","method"]) # Compatibility code for django.contrib.auth if 'django.contrib.auth' in settings.INSTALLED_APPS: def create_permissions_compat(app, **kwargs): from django.db.models import get_app from django.contrib.auth.management import create_permissions create_permissions(get_app(app), (), 0) post_migrate.connect(create_permissions_compat)
""" South-specific signals """ from django.dispatch import Signal from django.conf import settings # Sent at the start of the migration of an app pre_migrate = Signal(providing_args=["app"]) # Sent after each successful migration of an app post_migrate = Signal(providing_args=["app"]) # Sent after each run of a particular migration in a direction ran_migration = Signal(providing_args=["app","migration","method"]) # Compatibility code for django.contrib.auth # Is causing strange errors, removing for now (we might need to fix up orm first) #if 'django.contrib.auth' in settings.INSTALLED_APPS: #def create_permissions_compat(app, **kwargs): #from django.db.models import get_app #from django.contrib.auth.management import create_permissions #create_permissions(get_app(app), (), 0) #post_migrate.connect(create_permissions_compat)
Remove the auth contenttypes thing for now, needs improvement
Remove the auth contenttypes thing for now, needs improvement
Python
apache-2.0
theatlantic/django-south,theatlantic/django-south
--- +++ @@ -15,9 +15,10 @@ ran_migration = Signal(providing_args=["app","migration","method"]) # Compatibility code for django.contrib.auth -if 'django.contrib.auth' in settings.INSTALLED_APPS: - def create_permissions_compat(app, **kwargs): - from django.db.models import get_app - from django.contrib.auth.management import create_permissions - create_permissions(get_app(app), (), 0) - post_migrate.connect(create_permissions_compat) +# Is causing strange errors, removing for now (we might need to fix up orm first) +#if 'django.contrib.auth' in settings.INSTALLED_APPS: + #def create_permissions_compat(app, **kwargs): + #from django.db.models import get_app + #from django.contrib.auth.management import create_permissions + #create_permissions(get_app(app), (), 0) + #post_migrate.connect(create_permissions_compat)
c39faa36f2f81198ed9aaaf7e43096a454feaa0e
molly/molly/wurfl/views.py
molly/molly/wurfl/views.py
from pywurfl.algorithms import DeviceNotFound from django.http import Http404 from molly.utils.views import BaseView from molly.utils.breadcrumbs import NullBreadcrumb from molly.wurfl.vsm import vsa from molly.wurfl import device_parents from molly.wurfl.wurfl_data import devices class IndexView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(cls, request, context): if not getattr(cls.conf, 'expose_view', False): raise Http404 ua = request.GET.get('ua', request.META.get('HTTP_USER_AGENT', '')) ua = ua.decode('ascii', 'ignore') try: device = devices.select_ua( ua, search=vsa ) except (KeyError, DeviceNotFound): device = devices.select_id('generic_xhtml') context = { 'id': device.devid, 'is_mobile': not 'generic_web_browser' in device_parents[device.devid], 'brand_name': device.brand_name, 'model_name': device.model_name, } if request.GET.get('capabilities') == 'true': context['capabilities'] = dict((k, getattr(device, k)) for k in dir(device) if (not k.startswith('_') and not k.startswith('dev') and not k=='groups')) return cls.render(request, context, None)
from pywurfl.algorithms import DeviceNotFound from django.http import Http404 from molly.utils.views import BaseView from molly.utils.breadcrumbs import NullBreadcrumb from molly.wurfl.vsm import vsa from molly.wurfl import device_parents from molly.wurfl.wurfl_data import devices class IndexView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(cls, request, context): if not getattr(cls.conf, 'expose_view', False): raise Http404 ua = request.GET.get('ua', request.META.get('HTTP_USER_AGENT', '')) ua = ua.decode('ascii', 'ignore') try: device = devices.select_ua( ua, search=vsa ) except (KeyError, DeviceNotFound): device = devices.select_id('generic_xhtml') context = { 'id': device.devid, 'is_mobile': not 'generic_web_browser' in device_parents[device.devid], 'brand_name': device.brand_name, 'model_name': device.model_name, 'ua': ua, 'matched_ua': device.devua, } if request.GET.get('capabilities') == 'true': context['capabilities'] = dict((k, getattr(device, k)) for k in dir(device) if (not k.startswith('_') and not k.startswith('dev') and not k=='groups')) return cls.render(request, context, None)
Add UA and matched UA to device-detection view output.
Add UA and matched UA to device-detection view output.
Python
apache-2.0
mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject
--- +++ @@ -31,6 +31,8 @@ 'is_mobile': not 'generic_web_browser' in device_parents[device.devid], 'brand_name': device.brand_name, 'model_name': device.model_name, + 'ua': ua, + 'matched_ua': device.devua, } if request.GET.get('capabilities') == 'true':
57eaefa2f85522b7b9e596779df3d5dc2763e295
backend/rbac.py
backend/rbac.py
import urllib from flask import request, redirect, abort from flask.ext.security import current_user class RBACMixin(object): """ Role-based access control for views. """ # if False, we don't require authentication at all require_authentication = True # user must have all of these roles required_roles = [] def is_accessible(self): if not self.require_authentication: return True if not current_user.is_active() or not current_user.is_authenticated(): return False if all(current_user.has_role(r) for r in self.required_roles): return True return False def _handle_view(self, name, **kwargs): """ Override builtin _handle_view in order to redirect users when a view is not accessible. """ if not self.is_accessible(): if current_user.is_authenticated(): # permission denied abort(403) else: # login tmp = '/security/login?next=' + urllib.quote_plus(request.base_url) return redirect(tmp)
import urllib from flask import request, redirect, abort from flask.ext.security import current_user class RBACMixin(object): """ Role-based access control for views. """ # if False, we don't require authentication at all require_authentication = True # user must have all of these roles required_roles = [] def is_accessible(self): if not self.require_authentication: return True if not current_user.is_active() or not current_user.is_authenticated(): return False if all(current_user.has_role(r) for r in self.required_roles): return True return False def _handle_view(self, name, **kwargs): """ Override builtin _handle_view in order to redirect users when a view is not accessible. """ if not self.is_accessible(): if current_user.is_authenticated(): # permission denied abort(403) else: # login tmp = '/security/login?next=' + urllib.quote_plus(request.url) return redirect(tmp)
Include GET parameters in Admin login redirect.
Include GET parameters in Admin login redirect.
Python
apache-2.0
Code4SA/pmg-cms-2,Code4SA/pmg-cms-2,Code4SA/pmg-cms-2
--- +++ @@ -33,5 +33,5 @@ abort(403) else: # login - tmp = '/security/login?next=' + urllib.quote_plus(request.base_url) + tmp = '/security/login?next=' + urllib.quote_plus(request.url) return redirect(tmp)
fbbc42fd0c023f6f5f603f9dfcc961d87ca6d645
zou/app/blueprints/crud/custom_action.py
zou/app/blueprints/crud/custom_action.py
from zou.app.models.custom_action import CustomAction from .base import BaseModelsResource, BaseModelResource class CustomActionsResource(BaseModelsResource): def __init__(self): BaseModelsResource.__init__(self, CustomAction) class CustomActionResource(BaseModelResource): def __init__(self): BaseModelResource.__init__(self, CustomAction)
from zou.app.models.custom_action import CustomAction from .base import BaseModelsResource, BaseModelResource class CustomActionsResource(BaseModelsResource): def __init__(self): BaseModelsResource.__init__(self, CustomAction) def check_permissions(self): return True class CustomActionResource(BaseModelResource): def __init__(self): BaseModelResource.__init__(self, CustomAction)
Allow anyone to read custom actions
Allow anyone to read custom actions
Python
agpl-3.0
cgwire/zou
--- +++ @@ -8,6 +8,9 @@ def __init__(self): BaseModelsResource.__init__(self, CustomAction) + def check_permissions(self): + return True + class CustomActionResource(BaseModelResource):
c677df5f5f39afbf3aef3ceb1e83f3a97fb53f6b
bonspy/utils.py
bonspy/utils.py
def compare_vectors(x, y): for x_i, y_i in zip(x, y): comparison = _compare(x_i, y_i) if comparison == 0: continue else: return comparison return 0 def _compare(x, y): if x is not None and y is not None: return int(x > y) - int(x < y) elif x is not None and y is None: return -1 elif x is None and y is not None: return 1 else: return 0 class ConstantDict(dict): def __init__(self, constant): super(ConstantDict, self).__init__() self.constant = constant def values(self): return [self.constant] def __delitem__(self, key): try: super(ConstantDict, self).__delitem__(key) except KeyError: pass def __eq__(self, other): if type(other) is not type(self): return False elif other.constant == self.constant: return True else: return False def __getitem__(self, item): try: return super(ConstantDict, self).__getitem__(item) except KeyError: return self.constant def __repr__(self): return 'ConstantDict({})'.format(self.constant)
def compare_vectors(x, y): for x_i, y_i in zip(x, y): comparison = _compare(x_i, y_i) if comparison == 0: continue else: return comparison return 0 def _compare(x, y): if x is not None and y is not None: return int(x > y) - int(x < y) elif x is not None and y is None: return -1 elif x is None and y is not None: return 1 else: return 0 class ConstantDict(dict): def __init__(self, constant): super(ConstantDict, self).__init__() self.constant = constant self.deleted_keys = set() def update(self, E=None, **F): super(ConstantDict, self).update(E, **F) if type(E) is type(self): self.constant = E.constant def values(self): return [self.constant] + list(super(ConstantDict, self).values()) def __delitem__(self, key): try: super(ConstantDict, self).__delitem__(key) except KeyError: self.deleted_keys.add(key) def __eq__(self, other): if type(other) is not type(self): return False elif other.constant == self.constant and super(ConstantDict, self).__eq__(other): return True else: return False def __getitem__(self, item): try: return super(ConstantDict, self).__getitem__(item) except KeyError: if item in self.deleted_keys: raise else: return self.constant def __repr__(self): return 'ConstantDict({}, {})'.format(self.constant, super(ConstantDict, self).__repr__())
Fix bugs in new class
Fix bugs in new class
Python
bsd-3-clause
markovianhq/bonspy
--- +++ @@ -23,20 +23,27 @@ def __init__(self, constant): super(ConstantDict, self).__init__() self.constant = constant + self.deleted_keys = set() + + def update(self, E=None, **F): + super(ConstantDict, self).update(E, **F) + + if type(E) is type(self): + self.constant = E.constant def values(self): - return [self.constant] + return [self.constant] + list(super(ConstantDict, self).values()) def __delitem__(self, key): try: super(ConstantDict, self).__delitem__(key) except KeyError: - pass + self.deleted_keys.add(key) def __eq__(self, other): if type(other) is not type(self): return False - elif other.constant == self.constant: + elif other.constant == self.constant and super(ConstantDict, self).__eq__(other): return True else: return False @@ -45,7 +52,10 @@ try: return super(ConstantDict, self).__getitem__(item) except KeyError: - return self.constant + if item in self.deleted_keys: + raise + else: + return self.constant def __repr__(self): - return 'ConstantDict({})'.format(self.constant) + return 'ConstantDict({}, {})'.format(self.constant, super(ConstantDict, self).__repr__())
8b399d6ede630b785b51fb9e32fda811328e163e
test.py
test.py
import unittest from enigma import Enigma, Umkehrwalze, Walzen class EnigmaTestCase(unittest.TestCase): def setUp(self): # Rotors go from right to left, so I reverse the tuple to make Rotor # I be the leftmost. I may change this behavior in the future. rotors = ( Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q'), Walzen(wiring='AJDKSIRUXBLHWTMCQGZNPYFVOE', notch='E'), Walzen(wiring='BDFHJLCPRTXVZNYEIWGAKMUSQO', notch='V'), )[::-1] reflector = Umkehrwalze(wiring='YRUHQSLDPXNGOKMIEBFZCWVJAT') self.machine = Enigma(rotors=rotors, reflector=reflector) def test_encode_message(self): # The expected result for the setup above and message AAAAA is BDZGO # Src: https://en.wikipedia.org/wiki/Enigma_rotor_details#Rotor_offset encoded = self.machine.cipher('AAAAA') self.assertEqual('BDZGO', encoded) def run_tests(): runner = unittest.TextTestRunner() suite = unittest.TestLoader().loadTestsFromTestCase(EnigmaTestCase) runner.run(suite) if __name__ == '__main__': # pragma: no cover run_tests()
import unittest from enigma import Enigma, Umkehrwalze, Walzen class EnigmaTestCase(unittest.TestCase): def setUp(self): # Rotors go from right to left, so I reverse the tuple to make Rotor # I be the leftmost. I may change this behavior in the future. rotors = ( Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q'), Walzen(wiring='AJDKSIRUXBLHWTMCQGZNPYFVOE', notch='E'), Walzen(wiring='BDFHJLCPRTXVZNYEIWGAKMUSQO', notch='V'), )[::-1] reflector = Umkehrwalze(wiring='YRUHQSLDPXNGOKMIEBFZCWVJAT') self.machine = Enigma(rotors=rotors, reflector=reflector) def test_encode_message(self): # The expected result for the setup above and message AAAAA is BDZGO # Src: https://en.wikipedia.org/wiki/Enigma_rotor_details#Rotor_offset encoded = self.machine.cipher('AAAAA') self.assertEqual('BDZGO', encoded) def test_decode_message(self): decoded = self.machine.cipher('BDZGO') self.assertEqual('AAAAA', decoded) def run_tests(): runner = unittest.TextTestRunner() suite = unittest.TestLoader().loadTestsFromTestCase(EnigmaTestCase) runner.run(suite) if __name__ == '__main__': # pragma: no cover run_tests()
Test if ciphering is bidirectional
Test if ciphering is bidirectional
Python
mit
ranisalt/enigma
--- +++ @@ -23,6 +23,10 @@ encoded = self.machine.cipher('AAAAA') self.assertEqual('BDZGO', encoded) + def test_decode_message(self): + decoded = self.machine.cipher('BDZGO') + self.assertEqual('AAAAA', decoded) + def run_tests(): runner = unittest.TextTestRunner()
fafedf1cfdcd6c6b06dd4093a44db7429bd553eb
issues/views.py
issues/views.py
# Create your views here.
# Python Imports import datetime import md5 import os # Django Imports from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings from django.core import serializers from django.contrib.auth.decorators import login_required from django.utils.translation import gettext as _ from django.core.paginator import Paginator, InvalidPage, EmptyPage from django.db.models import Q from django.forms.util import ErrorList # Project imports from iridium.utils.template import template_django as template from iridium.utils.template import render_template from iridium.project.models import Project from models import * from forms import * def getProject(pid): if pid.isdigit(): proj = Project.objects.get(id=int(pid)) else: proj = Project.objects.get(name=pid.lower()) return proj @login_required @template("issue_list.html") def listIssues(request, pid): proj = getProject(pid) issues = proj.issue_set.all() return dict(section="issues", pid=pid, title=proj.name, issues=issues) @login_required @template("issue_view.html") def viewIssue(request, pid, sid): proj = getProject(pid) try: issue = Issue.objects.get(id=int(sid)) except: HttpResponseRedirect('/i/%s' % pid) return dict(section="issues", pid=pid, sid=sid, issue=issue) @login_required @template("generic_form.html") def newIssue(request, pid): if request.method == "POST": form = NewIssueForm(request.POST) else: form = NewIssueForm() if form.is_valid(): proj = getProject(pid) data = form.clean() data['author'] = request.user data['published'] = datetime.datetime.now() data['priority'] = int(data['priority']) data['status'] = int(data['status']) data['project'] = proj issue = proj.issue_set.create(**data) issue.save() proj.save() return HttpResponseRedirect('/i/%s/%i' % (pid, issue.id)) return dict(section='issues', pid=pid, title="New issue", form=form)
Add basic issue view, list, create.
[ISSUES] Add basic issue view, list, create.
Python
bsd-3-clause
clsdaniel/iridium
--- +++ @@ -1 +1,73 @@ -# Create your views here. +# Python Imports +import datetime +import md5 +import os + +# Django Imports +from django.http import HttpResponse, HttpResponseRedirect +from django.conf import settings +from django.core import serializers +from django.contrib.auth.decorators import login_required +from django.utils.translation import gettext as _ +from django.core.paginator import Paginator, InvalidPage, EmptyPage +from django.db.models import Q +from django.forms.util import ErrorList + +# Project imports +from iridium.utils.template import template_django as template +from iridium.utils.template import render_template +from iridium.project.models import Project + +from models import * +from forms import * + +def getProject(pid): + if pid.isdigit(): + proj = Project.objects.get(id=int(pid)) + else: + proj = Project.objects.get(name=pid.lower()) + return proj + +@login_required +@template("issue_list.html") +def listIssues(request, pid): + proj = getProject(pid) + issues = proj.issue_set.all() + + return dict(section="issues", pid=pid, title=proj.name, issues=issues) + + +@login_required +@template("issue_view.html") +def viewIssue(request, pid, sid): + proj = getProject(pid) + try: + issue = Issue.objects.get(id=int(sid)) + except: + HttpResponseRedirect('/i/%s' % pid) + + return dict(section="issues", pid=pid, sid=sid, issue=issue) + + +@login_required +@template("generic_form.html") +def newIssue(request, pid): + if request.method == "POST": + form = NewIssueForm(request.POST) + else: + form = NewIssueForm() + + if form.is_valid(): + proj = getProject(pid) + data = form.clean() + data['author'] = request.user + data['published'] = datetime.datetime.now() + data['priority'] = int(data['priority']) + data['status'] = int(data['status']) + data['project'] = proj + issue = proj.issue_set.create(**data) + issue.save() + proj.save() + return HttpResponseRedirect('/i/%s/%i' % (pid, issue.id)) + + return dict(section='issues', pid=pid, title="New issue", form=form)
28baf3a2568f8e1b67a19740ecd7ccfc90d36514
swift/dedupe/killall.py
swift/dedupe/killall.py
#!/usr/bin/python __author__ = 'mjwtom' import os os.system('ps -aux | grep swift-proxy-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-account-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-container-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-object-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') # remove the database file os.system('rm ~/*.db -rf')
#!/usr/bin/python __author__ = 'mjwtom' import os os.system('ps -aux | grep swift-proxy-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-account-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-container-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-object-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') # remove the database file os.system('rm ~/*.db -rf') os.system('rm /etc/swift/*.db -rf')
Change the position. use proxy-server to do dedupe instead of object-server
Change the position. use proxy-server to do dedupe instead of object-server
Python
apache-2.0
mjwtom/swift,mjwtom/swift
--- +++ @@ -11,4 +11,5 @@ # remove the database file os.system('rm ~/*.db -rf') +os.system('rm /etc/swift/*.db -rf')
6dd04ed490c49c85bf91db2cb0bf2bed82b5967b
fasttsne/__init__.py
fasttsne/__init__.py
import scipy.linalg as la import numpy as np from py_bh_tsne import _TSNE as TSNE def fast_tsne(data, pca_d=50, d=2, perplexity=30., theta=0.5): """ Run Barnes-Hut T-SNE on _data_. @param data The data. @param pca_d The dimensionality of data is reduced via PCA to this dimensionality. @param d The embedding dimensionality. Must be fixed to 2. @param perplexity The perplexity controls the effective number of neighbors. @param theta If set to 0, exact t-SNE is run, which takes very long for dataset > 5000 samples. """ N, _ = data.shape # inplace!! data -= data.mean(axis=0) # working with covariance + (svd on cov.) is # much faster than svd on data directly. cov = np.dot(data.T, data)/N u, s, v = la.svd(cov, full_matrices=False) u = u[:,0:pca_d] X = np.dot(data, u) tsne = TSNE() Y = tsne.run(X, N, pca_d, d, perplexity, theta) return Y
import scipy.linalg as la import numpy as np from fasttsne import _TSNE as TSNE def fast_tsne(data, pca_d=None, d=2, perplexity=30., theta=0.5): """ Run Barnes-Hut T-SNE on _data_. @param data The data. @param pca_d The dimensionality of data is reduced via PCA to this dimensionality. @param d The embedding dimensionality. Must be fixed to 2. @param perplexity The perplexity controls the effective number of neighbors. @param theta If set to 0, exact t-SNE is run, which takes very long for dataset > 5000 samples. """ N, _ = data.shape # inplace!! if pca_d is None: X = data else: # do PCA data -= data.mean(axis=0) # working with covariance + (svd on cov.) is # much faster than svd on data directly. cov = np.dot(data.T, data)/N u, s, v = la.svd(cov, full_matrices=False) u = u[:,0:pca_d] X = np.dot(data, u) tsne = TSNE() Y = tsne.run(X, N, X.shape[1], d, perplexity, theta) return Y
FIX (from Justin Bayer): avoid memory segfault when pca_d is choosen too big.
FIX (from Justin Bayer): avoid memory segfault when pca_d is choosen too big.
Python
bsd-3-clause
pryvkin10x/tsne,douglasbagnall/py_bh_tsne,douglasbagnall/py_bh_tsne,pryvkin10x/tsne,pryvkin10x/tsne
--- +++ @@ -2,10 +2,10 @@ import numpy as np -from py_bh_tsne import _TSNE as TSNE +from fasttsne import _TSNE as TSNE -def fast_tsne(data, pca_d=50, d=2, perplexity=30., theta=0.5): +def fast_tsne(data, pca_d=None, d=2, perplexity=30., theta=0.5): """ Run Barnes-Hut T-SNE on _data_. @@ -26,15 +26,20 @@ N, _ = data.shape # inplace!! - data -= data.mean(axis=0) + + if pca_d is None: + X = data + else: + # do PCA + data -= data.mean(axis=0) - # working with covariance + (svd on cov.) is - # much faster than svd on data directly. - cov = np.dot(data.T, data)/N - u, s, v = la.svd(cov, full_matrices=False) - u = u[:,0:pca_d] - X = np.dot(data, u) + # working with covariance + (svd on cov.) is + # much faster than svd on data directly. + cov = np.dot(data.T, data)/N + u, s, v = la.svd(cov, full_matrices=False) + u = u[:,0:pca_d] + X = np.dot(data, u) tsne = TSNE() - Y = tsne.run(X, N, pca_d, d, perplexity, theta) + Y = tsne.run(X, N, X.shape[1], d, perplexity, theta) return Y