commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
61b96e4f925831e64e80d0253428dbd1b2c8a6a4
app/grandchallenge/annotations/validators.py
app/grandchallenge/annotations/validators.py
from rest_framework import serializers from django.conf import settings def validate_grader_is_current_retina_user(grader, context): """ This method checks if the passed grader equals the request.user that is passed in the context. Only applies to users that are in the retina_graders group. """ request = context.get("request") if ( request is not None and request.user is not None and request.user.is_authenticated ): user = request.user if user.groups.filter( name=settings.RETINA_GRADERS_GROUP_NAME ).exists(): if grader != user: raise serializers.ValidationError( "User is not allowed to create annotation for other grader" )
from rest_framework import serializers from django.conf import settings def validate_grader_is_current_retina_user(grader, context): """ This method checks if the passed grader equals the request.user that is passed in the context. Only applies to users that are in the retina_graders group. BEWARE! Validation will pass if user is not logged in or request or request.user is not defined """ request = context.get("request") if ( request is not None and request.user is not None and request.user.is_authenticated ): user = request.user if user.groups.filter( name=settings.RETINA_GRADERS_GROUP_NAME ).exists(): if grader != user: raise serializers.ValidationError( "User is not allowed to create annotation for other grader" )
Add comment to clarify validation method usage
Add comment to clarify validation method usage
Python
apache-2.0
comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django
8dc822cf3577663cf817cd5d1ab537df3605752c
art_archive_api/models.py
art_archive_api/models.py
from application import db class Artist(db.Model): __tablename__ = 'artists' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(45)) birth_year = db.Column(db.Integer) death_year = db.Column(db.Integer) country = db.Column(db.String(45)) genre = db.Column(db.String(45)) images = db.relationship( 'Image', backref='artist', ) class Image(db.Model): __tablename__ = 'images' id = db.Column(db.Integer, primary_key=True) image_url = db.Column(db.String(255)) title = db.Column(db.String(255)) year = db.Column(db.Integer) artist_id = db.Column( db.Integer, db.ForeignKey('artists.id') ) description = db.Column(db.String(255))
from application import db class Artist(db.Model): __tablename__ = 'artists' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(45)) birth_year = db.Column(db.Integer) death_year = db.Column(db.Integer) country = db.Column(db.String(45)) genre = db.Column(db.String(45)) images = db.relationship( 'Image', backref='artist', ) def serialize(self): return { 'id': self.id, 'name': self.name, 'birth_year': self.birth_year, 'death_year': self.death_year, 'country': self.country, 'genre': self.genre, } def serialize_with_images(self): return { 'id': self.id, 'name': self.name, 'birth_year': self.birth_year, 'death_year': self.death_year, 'country': self.country, 'genre': self.genre, "images" : [image.serialize() for image in self.images] } class Image(db.Model): __tablename__ = 'images' id = db.Column(db.Integer, primary_key=True) image_url = db.Column(db.String(255)) title = db.Column(db.String(255)) year = db.Column(db.Integer) artist_id = db.Column( db.Integer, db.ForeignKey('artists.id') ) description = db.Column(db.String(255)) def serialize(self): return { 'id': self.id, 'image_url': self.image_url, 'title': self.title, 'year': self.year, 'description': self.description, }
UPDATE serialize method for json data
UPDATE serialize method for json data
Python
mit
EunJung-Seo/art_archive
26672e83ab1bd1a932d275dfd244fe20749e3b1e
tripleo_common/utils/safe_import.py
tripleo_common/utils/safe_import.py
# Copyright 2019 Red Hat, Inc. # 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 eventlet from eventlet.green import subprocess # Due to an eventlet issue subprocess is not being correctly patched # on git module so it has to be done manually git = eventlet.import_patched('git', ('subprocess', subprocess)) Repo = git.Repo # git.refs is lazy loaded when there's a new commit, this needs to be # patched as well. eventlet.import_patched('git.refs')
# Copyright 2019 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from eventlet.green import subprocess import eventlet.patcher as patcher # Due to an eventlet issue subprocess is not being correctly patched # on git.refs patcher.inject('git.refs', None, ('subprocess', subprocess), ) # this has to be loaded after the inject. import git # noqa: E402 Repo = git.Repo
Make gitpython and eventlet work with eventlet 0.25.1
Make gitpython and eventlet work with eventlet 0.25.1 Version 0.25 is having a bad interaction with python git. that is due to the way that eventlet unloads some modules now. Changed to use the inject method that supports what we need intead of the imported_patched that was having the problem Change-Id: I79894d4f711c64f536593fffcb6959df97c38838 Closes-bug: #1845181
Python
apache-2.0
openstack/tripleo-common,openstack/tripleo-common
4ae3b77847eeefd07d83f863c6ec71d7fdf750cb
turbustat/tests/test_rfft_to_fft.py
turbustat/tests/test_rfft_to_fft.py
from turbustat.statistics.rfft_to_fft import rfft_to_fft from ._testing_data import dataset1 import numpy as np import numpy.testing as npt from unittest import TestCase class testRFFT(TestCase): """docstring for testRFFT""" def __init__(self): self.dataset1 = dataset1 self.comp_rfft = rfft_to_fft(self.dataset1) def rfft_to_rfft(self): test_rfft = np.abs(np.fft.rfftn(self.dataset1)) shape2 = test_rfft.shape[-1] npt.assert_allclose(test_rfft, self.comp_rfft[:, :, :shape2+1]) def fft_to_rfft(self): test_fft = np.abs(np.fft.fftn(self.dataset1)) npt.assert_allclose(test_fft, self.comp_rfft)
import pytest from ..statistics.rfft_to_fft import rfft_to_fft from ._testing_data import dataset1 import numpy as np import numpy.testing as npt def test_rfft_to_rfft(): comp_rfft = rfft_to_fft(dataset1['moment0'][0]) test_rfft = np.abs(np.fft.rfftn(dataset1['moment0'][0])) shape2 = test_rfft.shape[-1] npt.assert_allclose(test_rfft, comp_rfft[:, :shape2]) def test_fft_to_rfft(): comp_rfft = rfft_to_fft(dataset1['moment0'][0]) test_fft = np.abs(np.fft.fftn(dataset1['moment0'][0])) npt.assert_allclose(test_fft, comp_rfft)
Fix and update the rfft tests
Fix and update the rfft tests
Python
mit
e-koch/TurbuStat,Astroua/TurbuStat
2d36b6fee7905e32aded8da7ffba68a5ec3c5d34
dwitter/user/forms.py
dwitter/user/forms.py
from django.contrib.auth import get_user_model from django.forms import ModelForm class UserSettingsForm(ModelForm): class Meta: model = get_user_model() fields = ('first_name', 'last_name', 'email',)
from django.contrib.auth import get_user_model from django.forms import ModelForm class UserSettingsForm(ModelForm): class Meta: model = get_user_model() fields = ('email',)
Remove first_name and last_name from user settings
Remove first_name and last_name from user settings
Python
apache-2.0
lionleaf/dwitter,lionleaf/dwitter,lionleaf/dwitter
7d9265cd3cb29606e37b296dde5af07099098228
axes/tests/test_checks.py
axes/tests/test_checks.py
from django.core.checks import run_checks, Error from django.test import override_settings from axes.checks import Messages, Hints, Codes from axes.conf import settings from axes.tests.base import AxesTestCase @override_settings(AXES_HANDLER='axes.handlers.cache.AxesCacheHandler') class CacheCheckTestCase(AxesTestCase): @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}}) def test_cache_check(self): errors = run_checks() self.assertEqual([], errors) @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}) def test_cache_check_errors(self): errors = run_checks() error = Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, ) self.assertEqual([error], errors)
from django.core.checks import run_checks, Error from django.test import override_settings from axes.checks import Messages, Hints, Codes from axes.conf import settings from axes.tests.base import AxesTestCase class CacheCheckTestCase(AxesTestCase): @override_settings( AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}}, ) def test_cache_check(self): errors = run_checks() self.assertEqual([], errors) @override_settings( AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, ) def test_cache_check_errors(self): errors = run_checks() error = Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, ) self.assertEqual([error], errors) @override_settings( AXES_HANDLER='axes.handlers.database.AxesDatabaseHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, ) def test_cache_check_does_not_produce_check_errors_with_database_handler(self): errors = run_checks() self.assertEqual([], errors)
Add check test for missing case branch
Add check test for missing case branch Signed-off-by: Aleksi Häkli <44cb6a94c0d20644d531e2be44779b52833cdcd2@iki.fi>
Python
mit
jazzband/django-axes,django-pci/django-axes
41368a5d45aa9568d8495a98399cb92398eeaa32
eva/models/pixelcnn.py
eva/models/pixelcnn.py
from keras.models import Model from keras.layers import Input, Convolution2D, Activation, Flatten, Dense from keras.layers.advanced_activations import PReLU from keras.optimizers import Nadam from eva.layers.residual_block import ResidualBlockList from eva.layers.masked_convolution2d import MaskedConvolution2D def PixelCNN(input_shape, filters, blocks, softmax=False, build=True): input_map = Input(shape=input_shape) model = MaskedConvolution2D(filters, 7, 7, mask='A', border_mode='same')(input_map) model = PReLU()(model) model = ResidualBlockList(model, filters, blocks) model = Convolution2D(filters//2, 1, 1)(model) model = PReLU()(model) model = Convolution2D(filters//2, 1, 1)(model) model = PReLU()(model) model = Convolution2D(1, 1, 1)(model) if not softmax: model = Activation('sigmoid')(model) else: raise NotImplementedError() if build: model = Model(input=input_map, output=model) model.compile(loss='binary_crossentropy', optimizer=Nadam(), metrics=['accuracy', 'fbeta_score', 'matthews_correlation']) return model
from keras.models import Model from keras.layers import Input, Convolution2D, Activation, Flatten, Dense from keras.layers.advanced_activations import PReLU from keras.optimizers import Nadam from eva.layers.residual_block import ResidualBlockList from eva.layers.masked_convolution2d import MaskedConvolution2D def PixelCNN(input_shape, filters, blocks, softmax=False, build=True): input_map = Input(shape=input_shape) model = MaskedConvolution2D(filters, 7, 7, mask='A', border_mode='same')(input_map) model = PReLU()(model) model = ResidualBlockList(model, filters, blocks) model = Convolution2D(filters//2, 1, 1)(model) model = PReLU()(model) model = Convolution2D(filters//2, 1, 1)(model) model = PReLU()(model) model = Convolution2D(1, 1, 1)(model) if not softmax: model = Activation('sigmoid')(model) else: raise NotImplementedError() if build: model = Model(input=input_map, output=model) model.compile(loss='binary_crossentropy', optimizer=Nadam(clipnorm=1., clipvalue=1.), metrics=['accuracy', 'fbeta_score', 'matthews_correlation']) return model
Add gradient clipping value and norm
Add gradient clipping value and norm
Python
apache-2.0
israelg99/eva
85d1fa8a390e715f38ddf9f680acb4337a469a66
cura/Settings/QualityAndUserProfilesModel.py
cura/Settings/QualityAndUserProfilesModel.py
# Copyright (c) 2016 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from UM.Application import Application from UM.Settings.ContainerRegistry import ContainerRegistry from cura.QualityManager import QualityManager from cura.Settings.ProfilesModel import ProfilesModel ## QML Model for listing the current list of valid quality and quality changes profiles. # class QualityAndUserProfilesModel(ProfilesModel): def __init__(self, parent = None): super().__init__(parent) ## Fetch the list of containers to display. # # See UM.Settings.Models.InstanceContainersModel._fetchInstanceContainers(). def _fetchInstanceContainers(self): # Fetch the list of qualities quality_list = super()._fetchInstanceContainers() # Fetch the list of quality changes. quality_manager = QualityManager.getInstance() application = Application.getInstance() machine_definition = quality_manager.getParentMachineDefinition(application.getGlobalContainerStack().getBottom()) if machine_definition.getMetaDataEntry("has_machine_quality"): definition_id = machine_definition.getId() else: definition_id = "fdmprinter" filter_dict = { "type": "quality_changes", "extruder": None, "definition": definition_id } quality_changes_list = ContainerRegistry.getInstance().findInstanceContainers(**filter_dict) return quality_list + quality_changes_list
# Copyright (c) 2016 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from UM.Application import Application from UM.Settings.ContainerRegistry import ContainerRegistry from cura.QualityManager import QualityManager from cura.Settings.ProfilesModel import ProfilesModel ## QML Model for listing the current list of valid quality and quality changes profiles. # class QualityAndUserProfilesModel(ProfilesModel): def __init__(self, parent = None): super().__init__(parent) ## Fetch the list of containers to display. # # See UM.Settings.Models.InstanceContainersModel._fetchInstanceContainers(). def _fetchInstanceContainers(self): global_container_stack = Application.getInstance().getGlobalContainerStack() if not global_container_stack: return [] # Fetch the list of qualities quality_list = super()._fetchInstanceContainers() # Fetch the list of quality changes. quality_manager = QualityManager.getInstance() machine_definition = quality_manager.getParentMachineDefinition(global_container_stack.getBottom()) if machine_definition.getMetaDataEntry("has_machine_quality"): definition_id = machine_definition.getId() else: definition_id = "fdmprinter" filter_dict = { "type": "quality_changes", "extruder": None, "definition": definition_id } quality_changes_list = ContainerRegistry.getInstance().findInstanceContainers(**filter_dict) return quality_list + quality_changes_list
Fix error on profiles page when there is no active machine
Fix error on profiles page when there is no active machine
Python
agpl-3.0
hmflash/Cura,Curahelper/Cura,Curahelper/Cura,fieldOfView/Cura,ynotstartups/Wanhao,hmflash/Cura,ynotstartups/Wanhao,fieldOfView/Cura
5d7806179d455073e020bdc6e6d0e7492f4e1d9e
test/unit/Algorithms/OrdinaryPercolationTest.py
test/unit/Algorithms/OrdinaryPercolationTest.py
import OpenPNM as op import scipy as sp mgr = op.Base.Workspace() mgr.loglevel = 60 class OrdinaryPercolationTest: def setup_test(self): self.net = op.Network.Cubic(shape=[5, 5, 5]) self.geo = op.Geometry.Toray090(network=self.net, pores=self.net.Ps, throats=self.net.Ts) self.phase = op.Phases.Water(network=self.net) self.phys = op.Physics.Standard(network=self.net, pores=self.net.Ps, throats=self.net.Ts) self.OP = op.Algorithms.OrdinaryPercolation(network=self.net, invading_phase=self.phase) Ps = self.net.pores(labels=['bottom_boundary']) self.OP.run(inlets=Ps) self.OP.return_results(Pc=7000) lpf = self.OP.evaluate_late_pore_filling(Pc=8000) assert sp.size(lpf) == self.net.Np
import OpenPNM as op import scipy as sp mgr = op.Base.Workspace() mgr.loglevel = 60 class OrdinaryPercolationTest: def setup_class(self): self.net = op.Network.Cubic(shape=[5, 5, 5]) self.geo = op.Geometry.Toray090(network=self.net, pores=self.net.Ps, throats=self.net.Ts) self.phase = op.Phases.Water(network=self.net) self.phys = op.Physics.Standard(network=self.net, phase=self.phase, pores=self.net.Ps, throats=self.net.Ts) self.OP1 = op.Algorithms.OrdinaryPercolation(network=self.net, invading_phase=self.phase) Ps = self.net.pores(labels=['bottom']) self.OP1.run(inlets=Ps) self.OP1.return_results(Pc=7000) lpf = self.OP1.evaluate_late_pore_filling(Pc=8000) assert sp.size(lpf) == self.net.Np def test_site_percolation(self): self.OP2 = op.Algorithms.OrdinaryPercolation(network=self.net, invading_phase=self.phase, percolation_type='site') Ps = self.net.pores(labels=['bottom']) self.OP2.run(inlets=Ps) self.OP2.return_results(Pc=7000) lpf = self.OP2.evaluate_late_pore_filling(Pc=8000) assert sp.size(lpf) == self.net.Np
Put a test on site percolation - probably needs some better tests on percolation thresholds maybe
Put a test on site percolation - probably needs some better tests on percolation thresholds maybe
Python
mit
TomTranter/OpenPNM,PMEAL/OpenPNM
b722fe0d5b84eeb5c9e7279679826ff5097bfd91
contentdensity/textifai/urls.py
contentdensity/textifai/urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^textinput', views.textinput, name='textinput'), url(r'^featureoutput', views.featureoutput, name='featureoutput'), url(r'^account', views.account, name='account'), ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^textinput', views.textinput, name='textinput'), url(r'^featureoutput', views.featureoutput, name='featureoutput'), url(r'^account', views.account, name='account'), url(r'^general-insights$', views.general_insights, name='general-insights'), ]
Add URL mapping for general-insights page
Add URL mapping for general-insights page
Python
mit
CS326-important/space-deer,CS326-important/space-deer
a85beb35d7296b0a8bd5a385b44fa13fb9f178ed
imgur-clean.py
imgur-clean.py
#!/usr/bin/env python3 """ "imgur-album-downloader" is great, but it seems to download albums twice, and appends their stupid ID to the end. This script fixes both. """ import hashlib import re import os import sys IMGUR_FILENAME_REGEX = re.compile(r'([0-9]+)(?:-\w+)?\.([A-Za-z0-9]+)') def get_hash(fn): with open(fn, 'rb') as fh: hashsum = hashlib.md5(fh.read()).digest() return hashsum if __name__ == '__main__': if len(sys.argv) >= 2: os.chdir(sys.argv[1]) sums = {} for fn in os.listdir('.'): match = IMGUR_FILENAME_REGEX.match(fn) if match is None: continue new_fn = f'{match.group(1)}.{match.group(2)}' if fn == new_fn: continue print(f"Renaming '{fn}' to '{new_fn}'") os.rename(fn, new_fn) hashsum = get_hash(new_fn) files = sums.get(hashsum, []) files.append(new_fn) sums[hashsum] = files for hashsum, files in sums.items(): if len(files) > 1: files_quoted = [f"'{x}'" for x in files] print(f"Found duplicates: {', '.join(files_quoted)}") files.sort() for fn in files[1:]: os.remove(fn)
#!/usr/bin/env python3 """ "imgur-album-downloader" is great, but it seems to download albums twice, and appends their stupid ID to the end. This script fixes both. """ import re import os import sys IMGUR_FILENAME_REGEX = re.compile(r'([0-9]+)-(\w+)\.([A-Za-z0-9]+)') if __name__ == '__main__': if len(sys.argv) >= 2: os.chdir(sys.argv[1]) ids = {} for fn in os.listdir('.'): match = IMGUR_FILENAME_REGEX.match(fn) if match is None: continue new_fn = f'{match[1]}.{match[3]}' if fn == new_fn: continue print(f"Renaming '{fn}' to '{new_fn}'") os.rename(fn, new_fn) id = match[2] files = ids.get(id, []) files.append(new_fn) ids[id] = files for _, files in ids.items(): if len(files) > 1: files_quoted = ', '.join(f"'{fn}'" for fn in files) print(f"Found duplicates: {files_quoted}") files.sort() for fn in files[1:]: print(f"Removing {fn}") os.remove(fn)
Remove imgur duplicates based on ID.
Remove imgur duplicates based on ID.
Python
mit
ammongit/scripts,ammongit/scripts,ammongit/scripts,ammongit/scripts
6144ac22f7b07cb1bd322bb05391a530f128768f
tests/integration/fileserver/fileclient_test.py
tests/integration/fileserver/fileclient_test.py
# -*- coding: utf-8 -*- ''' :codauthor: :email:`Mike Place <mp@saltstack.com>` ''' # Import Salt Testing libs from salttesting.helpers import (ensure_in_syspath, destructiveTest) from salttesting.mock import MagicMock, patch ensure_in_syspath('../') # Import salt libs import integration from salt import fileclient # Import Python libs import os class FileClientTest(integration.ModuleCase): def setUp(self): self.file_client = fileclient.Client(self.master_opts) def test_file_list_emptydirs(self): ''' Ensure that the fileclient class won't allow a direct call to file_list_emptydirs() ''' with self.assertRaises(NotImplementedError): self.file_client.file_list_emptydirs() def test_get_file(self): ''' Ensure that the fileclient class won't allow a direct call to get_file() ''' with self.assertRaises(NotImplementedError): self.file_client.get_file(None) def test_get_file_client(self): with patch.dict(self.minion_opts, {'file_client': 'remote'}): with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')): ret = fileclient.get_file_client(self.minion_opts) self.assertEqual('remote_client', ret) if __name__ == '__main__': from integration import run_tests run_tests(FileClientTest)
# -*- coding: utf-8 -*- ''' :codauthor: :email:`Mike Place <mp@saltstack.com>` ''' # Import Salt Testing libs from salttesting.unit import skipIf from salttesting.helpers import ensure_in_syspath from salttesting.mock import MagicMock, patch, NO_MOCK, NO_MOCK_REASON ensure_in_syspath('../') # Import salt libs import integration from salt import fileclient @skipIf(NO_MOCK, NO_MOCK_REASON) class FileClientTest(integration.ModuleCase): def setUp(self): self.file_client = fileclient.Client(self.master_opts) def test_file_list_emptydirs(self): ''' Ensure that the fileclient class won't allow a direct call to file_list_emptydirs() ''' with self.assertRaises(NotImplementedError): self.file_client.file_list_emptydirs() def test_get_file(self): ''' Ensure that the fileclient class won't allow a direct call to get_file() ''' with self.assertRaises(NotImplementedError): self.file_client.get_file(None) def test_get_file_client(self): with patch.dict(self.minion_opts, {'file_client': 'remote'}): with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')): ret = fileclient.get_file_client(self.minion_opts) self.assertEqual('remote_client', ret) if __name__ == '__main__': from integration import run_tests run_tests(FileClientTest)
Remove unused imports & Skip if no mock available
Remove unused imports & Skip if no mock available
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
98bdb678a9092c5c19bc2b379cca74a2ed33c457
libqtile/layout/subverttile.py
libqtile/layout/subverttile.py
from base import SubLayout, Rect from sublayouts import HorizontalStack from subtile import SubTile class SubVertTile(SubTile): arrangements = ["top", "bottom"] def _init_sublayouts(self): ratio = self.ratio expand = self.expand master_windows = self.master_windows arrangement = self.arrangement class MasterWindows(HorizontalStack): def filter(self, client): return self.index_of(client) < master_windows def request_rectangle(self, r, windows): return (r, Rect()) class SlaveWindows(HorizontalStack): def filter(self, client): return self.index_of(client) >= master_windows def request_rectangle(self, r, windows): if self.autohide and not windows: return (Rect(), r) else: if arrangement == "top": rmaster, rslave = r.split_horizontal(ratio=ratio) else: rslave, rmaster = r.split_horizontal(ratio=(1-ratio)) return (rslave, rmaster) self.sublayouts.append(SlaveWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) ) self.sublayouts.append(MasterWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) )
from base import SubLayout, Rect from sublayouts import HorizontalStack from subtile import SubTile class SubVertTile(SubTile): arrangements = ["top", "bottom"] def _init_sublayouts(self): class MasterWindows(HorizontalStack): def filter(self, client): return self.index_of(client) < self.parent.master_windows def request_rectangle(self, r, windows): return (r, Rect()) class SlaveWindows(HorizontalStack): def filter(self, client): return self.index_of(client) >= self.parent.master_windows def request_rectangle(self, r, windows): if self.autohide and not windows: return (Rect(), r) else: if self.parent.arrangement == "top": rmaster, rslave = r.split_horizontal(ratio=self.parent.ratio) else: rslave, rmaster = r.split_horizontal(ratio=(1-self.parent.ratio)) return (rslave, rmaster) self.sublayouts.append(SlaveWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) ) self.sublayouts.append(MasterWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) )
Refactor SubVertTile - make sublayout use the parents' variables
Refactor SubVertTile - make sublayout use the parents' variables
Python
mit
rxcomm/qtile,de-vri-es/qtile,EndPointCorp/qtile,zordsdavini/qtile,bavardage/qtile,nxnfufunezn/qtile,encukou/qtile,andrewyoung1991/qtile,ramnes/qtile,himaaaatti/qtile,de-vri-es/qtile,frostidaho/qtile,encukou/qtile,andrewyoung1991/qtile,w1ndy/qtile,frostidaho/qtile,nxnfufunezn/qtile,StephenBarnes/qtile,farebord/qtile,kopchik/qtile,rxcomm/qtile,jdowner/qtile,flacjacket/qtile,w1ndy/qtile,cortesi/qtile,aniruddhkanojia/qtile,qtile/qtile,himaaaatti/qtile,ramnes/qtile,xplv/qtile,flacjacket/qtile,soulchainer/qtile,kynikos/qtile,dequis/qtile,cortesi/qtile,jdowner/qtile,kseistrup/qtile,kiniou/qtile,apinsard/qtile,kiniou/qtile,kynikos/qtile,qtile/qtile,kopchik/qtile,kseistrup/qtile,tych0/qtile,tych0/qtile,apinsard/qtile,xplv/qtile,zordsdavini/qtile,soulchainer/qtile,dequis/qtile,farebord/qtile,aniruddhkanojia/qtile,EndPointCorp/qtile,StephenBarnes/qtile
224abf5e0e8d5e7bad7a86c622b711e997e8ae10
pyconcz_2016/team/models.py
pyconcz_2016/team/models.py
from django.db import models class Organizer(models.Model): full_name = models.CharField(max_length=200) email = models.EmailField( default='', blank=True, help_text="This is private") twitter = models.CharField(max_length=255, blank=True) github = models.CharField(max_length=255, blank=True) photo = models.ImageField(upload_to='team/pyconcz2016/') published = models.BooleanField(default=False)
from django.db import models class Organizer(models.Model): full_name = models.CharField(max_length=200) email = models.EmailField( default='', blank=True, help_text="This is private") twitter = models.CharField(max_length=255, blank=True) github = models.CharField(max_length=255, blank=True) photo = models.ImageField(upload_to='team/pyconcz2016/') published = models.BooleanField(default=False) def __str__(self): return self.full_name
Add string representation of organizer object
Add string representation of organizer object
Python
mit
pyvec/cz.pycon.org-2017,pyvec/cz.pycon.org-2017,pyvec/cz.pycon.org-2016,pyvec/cz.pycon.org-2017,benabraham/cz.pycon.org-2017,benabraham/cz.pycon.org-2017,pyvec/cz.pycon.org-2016,benabraham/cz.pycon.org-2017,pyvec/cz.pycon.org-2016
9a6b06d4a69bf5a7fb59d93000dc2aba02035957
tests/test_helpers.py
tests/test_helpers.py
import unittest from contextlib import redirect_stdout from conllu import print_tree from conllu.tree_helpers import TreeNode from io import StringIO class TestPrintTree(unittest.TestCase): def test_print_empty_list(self): result = self._capture_print(print_tree, []) self.assertEqual(result, "") def test_print_simple_treenode(self): node = TreeNode(data={"id": "X", "deprel": "Y"}, children={}) result = self._capture_print(print_tree, node) self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n") def test_print_list_of_nodes(self): node = TreeNode(data={"id": "X", "deprel": "Y"}, children={}) nodes = [node, node] result = self._capture_print(print_tree, nodes) self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n" * 2) def _capture_print(self, func, args): f = StringIO() with redirect_stdout(f): func(args) return f.getvalue()
import unittest from conllu import print_tree from conllu.tree_helpers import TreeNode from io import StringIO try: from contextlib import redirect_stdout except ImportError: import sys import contextlib @contextlib.contextmanager def redirect_stdout(target): original = sys.stdout sys.stdout = target yield sys.stdout = original class TestPrintTree(unittest.TestCase): def test_print_empty_list(self): result = self._capture_print(print_tree, []) self.assertEqual(result, "") def test_print_simple_treenode(self): node = TreeNode(data={"id": "X", "deprel": "Y"}, children={}) result = self._capture_print(print_tree, node) self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n") def test_print_list_of_nodes(self): node = TreeNode(data={"id": "X", "deprel": "Y"}, children={}) nodes = [node, node] result = self._capture_print(print_tree, nodes) self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n" * 2) def _capture_print(self, func, args): f = StringIO() with redirect_stdout(f): func(args) return f.getvalue()
Fix redirect_stdout not available in python2.
Fix redirect_stdout not available in python2.
Python
mit
EmilStenstrom/conllu
8b0302544bfb09d8abf9630db9a1dcc7e47add39
massa/domain.py
massa/domain.py
# -*- coding: utf-8 -*- from sqlalchemy import ( Column, Date, Integer, MetaData, Numeric, String, Table, ) def define_tables(metadata): Table('measurement', metadata, Column('id', Integer, primary_key=True), Column('weight', Numeric(4, 1), nullable=False), Column('code', String(25), nullable=False), Column('note', String(140), nullable=True), Column('date_measured', Date(), nullable=False), ) class Db(object): def __init__(self, engine): self._meta = MetaData(engine) define_tables(self._meta) def make_tables(self): self._meta.create_all() def drop_tables(self): self._meta.drop_all() @property def measurement(self): return self._meta.tables['measurement'] class MeasurementService(object): def __init__(self, table): self._table = table def find_all(self): s = self._table.select() return s.execute() def create(self, **kwargs): i = self._table.insert() i.execute(**kwargs)
# -*- coding: utf-8 -*- from sqlalchemy import ( Column, Date, Integer, MetaData, Numeric, String, Table, ) def define_tables(metadata): Table('measurement', metadata, Column('id', Integer, primary_key=True), Column('weight', Numeric(4, 1), nullable=False), Column('code', String(25), nullable=False), Column('note', String(140), nullable=True), Column('date_measured', Date(), nullable=False), ) class Db(object): def __init__(self, engine): self._meta = MetaData(engine) define_tables(self._meta) def make_tables(self): self._meta.create_all() def drop_tables(self): self._meta.drop_all() @property def measurement(self): return self._meta.tables['measurement'] class MeasurementService(object): def __init__(self, table): self._table = table def find_all(self): s = self._table.select() items = [] for item in s.execute(): items.append(self.make_exposable(item)) return items def create(self, **kwargs): i = self._table.insert() i.execute(**kwargs) def make_exposable(self, measurement): return { 'id': measurement.id, 'weight': float(measurement.weight), 'code': measurement.code, }
Make measurements exposable before returning.
Make measurements exposable before returning.
Python
mit
jaapverloop/massa
43e8dc72304c7647dae9323cbce73e7bc78ecf7d
src/idea/tests/smoke_tests.py
src/idea/tests/smoke_tests.py
import os from django.utils import timezone from django_webtest import WebTest from exam.decorators import fixture from exam.cases import Exam from django.core.urlresolvers import reverse class SmokeTest(Exam, WebTest): csrf_checks = False fixtures = ['state'] @fixture def user(self): try: from collab.django_factories import UserF return UserF(username="test1@example.com", person__title='') except ImportError: from django.contrib.auth.models import User user = User() user.username = "test1@example.com" user.first_name = 'first' user.last_name = 'last' user.email = '"test1@example.com"' user.password = 'pbkdf2_sha256$10000$ggAKkiHobFL8$xQzwPeHNX1vWr9uNmZ/gKbd17uLGZVM8QNcgmaIEAUs=' user.is_staff = False user.is_active = True user.is_superuser = False user.last_login = timezone.now() user.date_joined = timezone.now() user.save() return user def get(self, url): return self.app.get(url, user=self.user) def test_idea_home(self): page = self.get(reverse('idea:idea_list')) self.assertEquals(200, page.status_code)
import os from django.utils import timezone from django_webtest import WebTest from exam.decorators import fixture from exam.cases import Exam from django.core.urlresolvers import reverse from django.contrib.auth.models import User class SmokeTest(Exam, WebTest): csrf_checks = False fixtures = ['state', 'core-test-fixtures'] @fixture def user(self): user = User.objects.get(username="test1@example.com") return user def get(self, url): return self.app.get(url, user=self.user) def test_idea_home(self): page = self.get(reverse('idea:idea_list')) self.assertEquals(200, page.status_code)
Use fixtures for smoke tests
Use fixtures for smoke tests
Python
cc0-1.0
cfpb/idea-box,cfpb/idea-box,cfpb/idea-box
76fa14f61811cd38f2c91851a648fa88f6142b15
django_evolution/utils.py
django_evolution/utils.py
from django_evolution.db import evolver def write_sql(sql): "Output a list of SQL statements, unrolling parameters as required" for statement in sql: if isinstance(statement, tuple): print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1])) else: print unicode(statement) def execute_sql(cursor, sql): """ Execute a list of SQL statements on the provided cursor, unrolling parameters as required """ for statement in sql: if isinstance(statement, tuple): if not statement[0].startswith('--'): cursor.execute(*statement) else: if not statement.startswith('--'): try: cursor.execute(statement) except: print statement print sql raise Exception(statement)
from django_evolution.db import evolver def write_sql(sql): "Output a list of SQL statements, unrolling parameters as required" for statement in sql: if isinstance(statement, tuple): print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1])) else: print unicode(statement) def execute_sql(cursor, sql): """ Execute a list of SQL statements on the provided cursor, unrolling parameters as required """ for statement in sql: if isinstance(statement, tuple): if not statement[0].startswith('--'): cursor.execute(*statement) else: if not statement.startswith('--'): cursor.execute(statement)
Revert a debugging change that slipped in.
Revert a debugging change that slipped in. git-svn-id: 48f3d5eb0141859d8d7d81547b6bd7b3dde885f8@186 8655a95f-0638-0410-abc2-2f1ed958ef3d
Python
bsd-3-clause
clones/django-evolution
afddc5aeb2c9a28a4bf7314ee50ca8775494268a
misc/decode-mirax-stitching.py
misc/decode-mirax-stitching.py
#!/usr/bin/python import struct, sys, os f = open(sys.argv[1]) HEADER_OFFSET = 296 f.seek(HEADER_OFFSET) while True: x1 = struct.unpack("<h", f.read(2))[0] x2 = struct.unpack("<h", f.read(2))[0] y1 = struct.unpack("<h", f.read(2))[0] y2 = struct.unpack("<h", f.read(2))[0] zz = f.read(1) print '%10s %10s %10s %10s %s' % (x1, x2, y1, y2, zz)
#!/usr/bin/python import struct, sys, os f = open(sys.argv[1]) HEADER_OFFSET = 296 f.seek(HEADER_OFFSET) while True: x = struct.unpack("<i", f.read(4))[0] y = struct.unpack("<i", f.read(4))[0] zz = f.read(1) print '%10s %10s' % (x, y)
Update stitching script to ints again
Update stitching script to ints again
Python
lgpl-2.1
openslide/openslide,openslide/openslide,openslide/openslide,openslide/openslide
621ae7f7ff7d4b81af192ded1beec193748cfd90
rest_framework_ember/renderers.py
rest_framework_ember/renderers.py
import copy from rest_framework import renderers from rest_framework_ember.utils import get_resource_name class JSONRenderer(renderers.JSONRenderer): """ Render a JSON response the way Ember Data wants it. Such as: { "company": { "id": 1, "name": "nGen Works", "slug": "ngen-works", "date_created": "2014-03-13 16:33:37" } } """ def render(self, data, accepted_media_type=None, renderer_context=None): view = renderer_context.get('view') resource_name = get_resource_name(view) try: data_copy = copy.copy(data) content = data_copy.pop('results') data = {resource_name : content, "meta" : data_copy} except (TypeError, KeyError, AttributeError) as e: data = {resource_name : data} return super(JSONRenderer, self).render( data, accepted_media_type, renderer_context)
import copy from rest_framework import renderers from rest_framework_ember.utils import get_resource_name class JSONRenderer(renderers.JSONRenderer): """ Render a JSON response the way Ember Data wants it. Such as: { "company": { "id": 1, "name": "nGen Works", "slug": "ngen-works", "date_created": "2014-03-13 16:33:37" } } """ def render(self, data, accepted_media_type=None, renderer_context=None): view = renderer_context.get('view') resource_name = get_resource_name(view) if resource_name == False: return super(JSONRenderer, self).render( data, accepted_media_type, renderer_context) try: data_copy = copy.copy(data) content = data_copy.pop('results') data = {resource_name : content, "meta" : data_copy} except (TypeError, KeyError, AttributeError) as e: data = {resource_name : data} return super(JSONRenderer, self).render( data, accepted_media_type, renderer_context)
Return data when ``resource_name`` == False
Return data when ``resource_name`` == False
Python
bsd-2-clause
django-json-api/django-rest-framework-json-api,aquavitae/django-rest-framework-json-api,hnakamur/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api,schtibe/django-rest-framework-json-api,coUrbanize/rest_framework_ember,abdulhaq-e/django-rest-framework-json-api,pattisdr/django-rest-framework-json-api,pombredanne/django-rest-framework-json-api,django-json-api/rest_framework_ember,Instawork/django-rest-framework-json-api,scottfisk/django-rest-framework-json-api,martinmaillard/django-rest-framework-json-api,leo-naeka/rest_framework_ember,lukaslundgren/django-rest-framework-json-api,grapo/django-rest-framework-json-api,leo-naeka/django-rest-framework-json-api,kaldras/django-rest-framework-json-api,leifurhauks/django-rest-framework-json-api
5b2451ee653873b8fb166d291954c72a165af368
moderate/overlapping_rectangles/over_rect.py
moderate/overlapping_rectangles/over_rect.py
import sys def over_rect(line): line = line.rstrip() if line: line = line.split(',') rect_a = [int(item) for item in line[:4]] rect_b = [int(item) for item in line[4:]] return (rect_a[0] <= rect_b[0] <= rect_a[2] and (rect_a[3] <= rect_b[1] <= rect_a[1] or rect_a[3] <= rect_b[3] <= rect_a[1])) or \ (rect_b[0] <= rect_a[0] <= rect_b[2] and (rect_b[3] <= rect_a[1] <= rect_b[1] or rect_b[3] <= rect_a[3] <= rect_b[1])) if __name__ == '__main__': with open(sys.argv[1], 'rt') as f: for line in f: print over_rect(line)
import sys def over_rect(line): line = line.rstrip() if line: xula, yula, xlra, ylra, xulb, yulb, xlrb, ylrb = (int(i) for i in line.split(',')) h_overlap = True v_overlap = True if xlrb < xula or xulb > xlra: h_overlap = False if yulb < ylra or ylrb > yula: v_overlap = False return h_overlap and v_overlap if __name__ == '__main__': with open(sys.argv[1], 'rt') as f: for line in f: print over_rect(line)
Complete solution for overlapping rectangles
Complete solution for overlapping rectangles
Python
mit
MikeDelaney/CodeEval
2a5cc23be491fa3f42fe039b421ad436a94d59c2
corehq/messaging/smsbackends/smsgh/views.py
corehq/messaging/smsbackends/smsgh/views.py
from corehq.apps.sms.api import incoming from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.smsgh.models import SQLSMSGHBackend from django.http import HttpResponse, HttpResponseBadRequest class SMSGHIncomingView(IncomingBackendView): urlname = 'smsgh_sms_in' def get(self, request, api_key, *args, **kwargs): msg = request.GET.get('msg', None) snr = request.GET.get('snr', None) # We don't have a place to put this right now, but leaving it here # so we remember the parameter name in case we need it later to = request.GET.get('to', None) if not msg or not snr: return HttpResponseBadRequest("ERROR: Missing msg or snr") incoming(snr, msg, SQLSMSGHBackend.get_api_id()) return HttpResponse("") def post(self, request, api_key, *args, **kwargs): return self.get(request, api_key, *args, **kwargs)
from corehq.apps.sms.api import incoming from corehq.apps.sms.views import NewIncomingBackendView from corehq.messaging.smsbackends.smsgh.models import SQLSMSGHBackend from django.http import HttpResponse, HttpResponseBadRequest class SMSGHIncomingView(NewIncomingBackendView): urlname = 'smsgh_sms_in' @property def backend_class(self): return SQLSMSGHBackend def get(self, request, api_key, *args, **kwargs): msg = request.GET.get('msg', None) snr = request.GET.get('snr', None) # We don't have a place to put this right now, but leaving it here # so we remember the parameter name in case we need it later to = request.GET.get('to', None) if not msg or not snr: return HttpResponseBadRequest("ERROR: Missing msg or snr") incoming(snr, msg, SQLSMSGHBackend.get_api_id(), domain_scope=self.domain) return HttpResponse("") def post(self, request, api_key, *args, **kwargs): return self.get(request, api_key, *args, **kwargs)
Update SMSGH Backend view to be NewIncomingBackendView
Update SMSGH Backend view to be NewIncomingBackendView
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
1779970872afd457336334231bef3c8629dcd375
gem/tests/test_profiles.py
gem/tests/test_profiles.py
from molo.core.tests.base import MoloTestCaseMixin from django.test import TestCase, Client from django.contrib.auth.models import User from django.core.urlresolvers import reverse class GemRegistrationViewTest(TestCase, MoloTestCaseMixin): def setUp(self): self.client = Client() self.mk_main() def test_user_info_displaying_after_registration(self): self.user = User.objects.create_user( username='tester', email='tester@example.com', password='tester') self.user.profile.gender = 'female' self.user.profile.alias = 'useralias' self.user.profile.save() self.client.login(username='tester', password='tester') response = self.client.get(reverse('edit_my_profile')) print response self.assertContains(response, 'useralias') self.assertNotContains(response, '<option value="f">female</option>')
from molo.core.tests.base import MoloTestCaseMixin from django.test import TestCase, Client from django.contrib.auth.models import User from django.core.urlresolvers import reverse class GemRegistrationViewTest(TestCase, MoloTestCaseMixin): def setUp(self): self.client = Client() self.mk_main() def test_user_info_displaying_after_registration(self): self.user = User.objects.create_user( username='tester', email='tester@example.com', password='tester') self.client.login(username='tester', password='tester') response = self.client.get(reverse('edit_my_profile')) self.assertNotContains(response, 'useralias') self.assertContains(response, '<option value="f">female</option>') self.user.gem_profile.gender = 'f' self.user.profile.alias = 'useralias' self.user.gem_profile.save() self.user.profile.save() response = self.client.get(reverse('edit_my_profile')) self.assertContains(response, 'useralias') self.assertNotContains(response, '<option value="f">female</option>')
Update tests and fix the failing test
Update tests and fix the failing test
Python
bsd-2-clause
praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem
2880e0b8c38af68cfb17bbcc112f1a40b6a03a11
cinder/db/sqlalchemy/migrate_repo/versions/088_add_replication_info_to_cluster.py
cinder/db/sqlalchemy/migrate_repo/versions/088_add_replication_info_to_cluster.py
# Copyright (c) 2016 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Boolean, Column, MetaData, String, Table, text def upgrade(migrate_engine): """Add replication info to clusters table.""" meta = MetaData() meta.bind = migrate_engine clusters = Table('clusters', meta, autoload=True) replication_status = Column('replication_status', String(length=36), default="not-capable") active_backend_id = Column('active_backend_id', String(length=255)) frozen = Column('frozen', Boolean, nullable=False, default=False, server_default=text('false')) clusters.create_column(replication_status) clusters.create_column(frozen) clusters.create_column(active_backend_id)
# Copyright (c) 2016 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Boolean, Column, MetaData, String, Table from sqlalchemy.sql import expression def upgrade(migrate_engine): """Add replication info to clusters table.""" meta = MetaData() meta.bind = migrate_engine clusters = Table('clusters', meta, autoload=True) replication_status = Column('replication_status', String(length=36), default="not-capable") active_backend_id = Column('active_backend_id', String(length=255)) frozen = Column('frozen', Boolean, nullable=False, default=False, server_default=expression.false()) clusters.create_column(replication_status) clusters.create_column(frozen) clusters.create_column(active_backend_id)
Fix cannot add a column with non-constant default
Fix cannot add a column with non-constant default With newer versions of sqlite tests are failing on sqlite3.OperationalError : Cannot add a column with non-constant default. In SQL queries is boolean without apostrophes which causes sqlite3 error. This fix is solving this issue by replacing text('false') to expression.false() from sqlalchemy.sql which is working correct. Change-Id: Ia96255a2a61994a18b21acc235931ad03a8501ea Closes-Bug: #1773123
Python
apache-2.0
openstack/cinder,mahak/cinder,mahak/cinder,openstack/cinder
7173d3cf67bfd9a3b01f42c0832ce299c090f1d6
opendebates/tests/test_context_processors.py
opendebates/tests/test_context_processors.py
from django.core.cache import cache from django.test import TestCase from opendebates.context_processors import global_vars from opendebates.models import NUMBER_OF_VOTES_CACHE_ENTRY class NumberOfVotesTest(TestCase): def test_number_of_votes(self): cache.set(NUMBER_OF_VOTES_CACHE_ENTRY, 2) context = global_vars(None) self.assertEqual(2, int(context['NUMBER_OF_VOTES']))
from django.test import TestCase from mock import patch from opendebates.context_processors import global_vars class NumberOfVotesTest(TestCase): def test_number_of_votes(self): with patch('opendebates.utils.cache') as mock_cache: mock_cache.get.return_value = 2 context = global_vars(None) self.assertEqual(2, int(context['NUMBER_OF_VOTES']))
Fix new test to work without cache
Fix new test to work without cache
Python
apache-2.0
ejucovy/django-opendebates,caktus/django-opendebates,caktus/django-opendebates,ejucovy/django-opendebates,ejucovy/django-opendebates,caktus/django-opendebates,ejucovy/django-opendebates,caktus/django-opendebates
3bddeade05ca5ddc799733baa1545aa2b8b68060
hoomd/tune/custom_tuner.py
hoomd/tune/custom_tuner.py
from hoomd import _hoomd from hoomd.custom import ( _CustomOperation, _InternalCustomOperation, Action) from hoomd.operation import _Tuner class _TunerProperty: @property def updater(self): return self._action @updater.setter def updater(self, updater): if isinstance(updater, Action): self._action = updater else: raise ValueError( "updater must be an instance of hoomd.custom.Action") class CustomTuner(_CustomOperation, _TunerProperty, _Tuner): """Tuner wrapper for `hoomd.custom.Action` objects. For usage see `hoomd.custom._CustomOperation`. """ _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' def attach(self, simulation): self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) super().attach(simulation) self._action.attach(simulation) class _InternalCustomTuner( _InternalCustomOperation, _TunerProperty, _Tuner): _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner'
from hoomd import _hoomd from hoomd.operation import _Operation from hoomd.custom import ( _CustomOperation, _InternalCustomOperation, Action) from hoomd.operation import _Tuner class _TunerProperty: @property def tuner(self): return self._action @tuner.setter def tuner(self, tuner): if isinstance(tuner, Action): self._action = tuner else: raise ValueError( "updater must be an instance of hoomd.custom.Action") class CustomTuner(_CustomOperation, _TunerProperty, _Tuner): """Tuner wrapper for `hoomd.custom.Action` objects. For usage see `hoomd.custom._CustomOperation`. """ _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' def attach(self, simulation): self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) self._action.attach(simulation) _Operation.attach(self, simulation) class _InternalCustomTuner( _InternalCustomOperation, _TunerProperty, _Tuner): _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' def attach(self, simulation): self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) self._action.attach(simulation) _Operation.attach(self, simulation)
Fix attaching on custom tuners
Fix attaching on custom tuners
Python
bsd-3-clause
joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue
074c83285bba8a8805bf35dec9893771220b1715
foodsaving/users/stats.py
foodsaving/users/stats.py
from django.contrib.auth import get_user_model from django.db.models import Count from foodsaving.groups.models import GroupMembership from foodsaving.webhooks.models import EmailEvent def get_users_stats(): User = get_user_model() active_users = User.objects.filter(groupmembership__in=GroupMembership.objects.active(), deleted=False).distinct() active_membership_count = GroupMembership.objects.active().count() active_users_count = active_users.count() fields = { 'active_count': active_users_count, 'active_unverified_count': active_users.filter(mail_verified=False).count(), 'active_ignored_email_count': active_users.filter(email__in=EmailEvent.objects.ignored_addresses()).count(), 'active_with_location_count': active_users.exclude(latitude=None).exclude(longitude=None).count(), 'active_with_mobile_number_count': active_users.exclude(mobile_number='').count(), 'active_with_description_count': active_users.exclude(description='').count(), 'active_with_photo_count': active_users.exclude(photo='').count(), 'active_memberships_per_active_user_avg': active_membership_count / active_users_count, 'no_membership_count': User.objects.annotate(groups_count=Count('groupmembership')).filter(groups_count=0, deleted=False).count(), 'deleted_count': User.objects.filter(deleted=True).count(), } return fields
from django.contrib.auth import get_user_model from foodsaving.groups.models import GroupMembership from foodsaving.webhooks.models import EmailEvent def get_users_stats(): User = get_user_model() active_users = User.objects.filter(groupmembership__in=GroupMembership.objects.active(), deleted=False).distinct() active_membership_count = GroupMembership.objects.active().count() active_users_count = active_users.count() fields = { 'active_count': active_users_count, 'active_unverified_count': active_users.filter(mail_verified=False).count(), 'active_ignored_email_count': active_users.filter(email__in=EmailEvent.objects.ignored_addresses()).count(), 'active_with_location_count': active_users.exclude(latitude=None).exclude(longitude=None).count(), 'active_with_mobile_number_count': active_users.exclude(mobile_number='').count(), 'active_with_description_count': active_users.exclude(description='').count(), 'active_with_photo_count': active_users.exclude(photo='').count(), 'active_memberships_per_active_user_avg': active_membership_count / active_users_count, 'no_membership_count': User.objects.filter(groupmembership=None, deleted=False).count(), 'deleted_count': User.objects.filter(deleted=True).count(), } return fields
Use slightly better approach to count users without groups
Use slightly better approach to count users without groups
Python
agpl-3.0
yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core,yunity/yunity-core
48ab9fa0e54103a08fec54d8a4d4870dc701d918
genes/systemd/commands.py
genes/systemd/commands.py
#!/usr/bin/env python from subprocess import Popen from typing import List def systemctl(*args: List[str]): Popen(['systemctl'] + list(args)) def start(service: str): systemctl('start', service) def stop(service: str): systemctl('stop', service) def restart(service: str): systemctl('restart', service) def reload(service: str): systemctl('reload', service)
#!/usr/bin/env python from subprocess import Popen from typing import Tuple def systemctl(*args: Tuple[str, ...]) -> None: Popen(['systemctl'] + list(args)) def disable(*services: Tuple[str, ...]) -> None: return systemctl('disable', *services) def enable(*services: Tuple[str, ...]) -> None: return systemctl('enable', *services) def start(*services: Tuple[str, ...]) -> None: return systemctl('start', *services) def stop(*services: Tuple[str, ...]) -> None: return systemctl('stop', *services) def reload(*services: Tuple[str, ...]) -> None: return systemctl('reload', *services) def restart(services: Tuple[str, ...]) -> None: return systemctl('restart', *services)
Add more functions, improve type checking
Add more functions, improve type checking
Python
mit
hatchery/genepool,hatchery/Genepool2
7355a5cb7014d6494e40322736a2887369d47262
bin/trigger_upload.py
bin/trigger_upload.py
#!/bin/env python # -*- coding: utf8 -*- """ Triggers an upload process with the specified raw.xz URL. """ import argparse import logging import logging.config import multiprocessing.pool import fedmsg.config import fedimg.uploader logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLogger('fedmsg') def trigger_upload(compose_id, url, push_notifications): upload_pool = multiprocessing.pool.ThreadPool(processes=4) compose_meta = {'compose_id': compose_id} fedimg.uploader.upload(upload_pool, [url], compose_meta=compose_meta) def get_args(): parser = argparse.ArgumentParser( description="Trigger a manual upload process with the " "specified raw.xz URL") parser.add_argument( "-u", "--url", type=str, help=".raw.xz URL", required=True) parser.add_argument( "-c", "--compose-id", type=str, help="compose id of the .raw.xz file", required=True) parser.add_argument( "-p", "--push-notifications", help="Bool to check if we need to push fedmsg notifications", action="store_true", required=False) args = parser.parse_args() return args.url, args.compose_id, args.push_notifications def main(): url, compose_id, push_notifications = get_args() trigger_upload(url, compose_id, push_notifications) if __name__ == '__main__': main()
#!/bin/env python # -*- coding: utf8 -*- """ Triggers an upload process with the specified raw.xz URL. """ import argparse import logging import logging.config import multiprocessing.pool import fedmsg.config import fedimg.uploader logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLogger('fedmsg') def trigger_upload(compose_id, url, push_notifications): upload_pool = multiprocessing.pool.ThreadPool(processes=4) compose_meta = {'compose_id': compose_id} fedimg.uploader.upload(upload_pool, [url], compose_meta=compose_meta, push_notifications=push_notifications) def get_args(): parser = argparse.ArgumentParser( description="Trigger a manual upload process with the " "specified raw.xz URL") parser.add_argument( "-u", "--url", type=str, help=".raw.xz URL", required=True) parser.add_argument( "-c", "--compose-id", type=str, help="compose id of the .raw.xz file", required=True) parser.add_argument( "-p", "--push-notifications", help="Bool to check if we need to push fedmsg notifications", action="store_true", required=False) args = parser.parse_args() return args.url, args.compose_id, args.push_notifications def main(): url, compose_id, push_notifications = get_args() trigger_upload(url, compose_id, push_notifications) if __name__ == '__main__': main()
Add the missing push_notifications args
services.ec2: Add the missing push_notifications args Signed-off-by: Sayan Chowdhury <5f0367a2b3b757615b57f51d912cf16f2c0ad827@gmail.com>
Python
agpl-3.0
fedora-infra/fedimg,fedora-infra/fedimg
2c006d4fd1a823eba2cec933671a43182f0c10f5
src/dynmen/__init__.py
src/dynmen/__init__.py
# -*- coding: utf-8 -*- """ dynmen - A simple python interface to dynamic menus like dmenu or rofi import dynmen menu = dynmen.Menu(['dmenu', '-fn', 'Sans-30']) output = menu({'a': 1, 'b': 2, 'c': 3}) You can make the menu non-blocking by setting: menu.process_mode = 'futures' Please see the repository for more examples: https://github.com/frostidaho/dynmen """ from .menu import Menu, MenuError del menu def new_dmenu(**kwargs): from .dmenu import DMenu return DMenu(**kwargs) def new_rofi(**kwargs): from .rofi import Rofi return Rofi(**kwargs)
# -*- coding: utf-8 -*- """ dynmen - A simple python interface to dynamic menus like dmenu or rofi import dynmen menu = dynmen.Menu(['dmenu', '-fn', 'Sans-30']) output = menu({'a': 1, 'b': 2, 'c': 3}) You can make the menu non-blocking by setting: menu.process_mode = 'futures' Please see the repository for more examples: https://github.com/frostidaho/dynmen """ from .menu import Menu, MenuError, MenuResult del menu def new_dmenu(**kwargs): from .dmenu import DMenu return DMenu(**kwargs) def new_rofi(**kwargs): from .rofi import Rofi return Rofi(**kwargs)
Add MenuResult to the top-level namespace
Add MenuResult to the top-level namespace
Python
mit
frostidaho/dynmen
1dc1be8c5f705ff97d6b83171327fa5d1c59a385
src/utils/management/commands/run_upgrade.py
src/utils/management/commands/run_upgrade.py
from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('upgrade_module') def handle(self, *args, **options): translation.activate('en') upgrade_module_name = options.get('upgrade_module') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e)
import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings def get_modules(): path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade') root, dirs, files = next(os.walk(path)) return files class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('--path', required=False) def handle(self, *args, **options): if not options.get('path'): print('No upgrade selected. Available upgrade paths: ') for file in get_modules(): module_name = file.split('.')[0] print('- {module_name}'.format(module_name=module_name)) print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`') else: translation.activate('en') upgrade_module_name = options.get('path') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e)
Upgrade path is now not required, help text is output if no path supp.
Upgrade path is now not required, help text is output if no path supp.
Python
agpl-3.0
BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway
11323a28d90ed59f32d1120224c2f63bdbed0564
learning/stock/ethstock.py
learning/stock/ethstock.py
import io import random import numpy as np import pandas as pd import sklearn import requests def gettingData(): url = "https://www.coingecko.com/price_charts/export/279/eur.csv" content = requests.get(url).content data = pd.read_csv(io.StringIO(content.decode('utf-8'))) return data def preprocessing(data): #customize index data.snapped_at[0].split()[0] data.snapped_at = data.snapped_at.apply(lambda x: x.split()[0]) data.set_index('snapped_at', inplace=True) data.index = pd.to_datetime(data.index) def main(): data = gettingData() print("Retrieved data:") print(data.tail()) if __name__ == "__main__": main()
import io import random import numpy as np import pandas as pd import sklearn import requests def gettingData(): url = "https://www.coingecko.com/price_charts/export/279/eur.csv" content = requests.get(url).content data = pd.read_csv(io.StringIO(content.decode('utf-8'))) return data def preprocessing(data): #customize index data.snapped_at[0].split()[0] data.snapped_at = data.snapped_at.apply(lambda x: x.split()[0]) data.set_index('snapped_at', inplace=True) data.index = pd.to_datetime(data.index) ''' In some cases there is no sample for a certain date. ''' #Generate all the possible days and use them to reindex start = data.index[data.index.argmin()] end = data.index[data.index.argmax()] index_complete = pd.date_range(start, end) data = data.reindex(index_complete) #Fill the blanks with the mean between the previous and the day after print("\nLooking if the index is complete...") for idx in data.index: dayloc = data.index.get_loc(idx) day = data.loc[idx] if day.hasnans: #updating rg = slice(dayloc-1, dayloc+2) data.loc[idx] = data.iloc[rg].mean() print("Day <{}> updated with the mean".format(idx)) def main(): data = gettingData() print("\nRetrieved data:") print(data.tail()) preprocessing(data) if __name__ == "__main__": main()
Index is completed if there is no sample for a date
Index is completed if there is no sample for a date
Python
mit
samuxiii/prototypes,samuxiii/prototypes
e494e38b28fbafc70a1e5315a780d64e315113b4
more/chameleon/main.py
more/chameleon/main.py
import morepath import chameleon class ChameleonApp(morepath.App): pass @ChameleonApp.setting_section(section='chameleon') def get_setting_section(): return { 'auto_reload': False } @ChameleonApp.template_engine(extension='.pt') def get_chameleon_render(path, original_render, settings): config = {'auto_reload': settings.chameleon.auto_reload} template = chameleon.PageTemplateFile(path, **config) def render(content, request): variables = {'request': request} variables.update(content) return original_render(template.render(**variables), request) return render
import morepath import chameleon class ChameleonApp(morepath.App): pass @ChameleonApp.setting_section(section='chameleon') def get_setting_section(): return {'auto_reload': False} @ChameleonApp.template_engine(extension='.pt') def get_chameleon_render(path, original_render, settings): config = settings.chameleon.__dict__ template = chameleon.PageTemplateFile(path, **config) def render(content, request): variables = {'request': request} variables.update(content) return original_render(template.render(**variables), request) return render
Make the way chameleon settings are defined more generic; any Chameleon setting can now be in the chameleon config section.
Make the way chameleon settings are defined more generic; any Chameleon setting can now be in the chameleon config section.
Python
bsd-3-clause
morepath/more.chameleon
b88abd98834529f1342d69e2e91b79efd68e5e8d
backend/uclapi/dashboard/middleware/fake_shibboleth_middleware.py
backend/uclapi/dashboard/middleware/fake_shibboleth_middleware.py
from django.utils.deprecation import MiddlewareMixin class FakeShibbolethMiddleWare(MiddlewareMixin): def process_request(self, request): if request.POST.get("convert-post-headers") == "1": for key in request.POST: request.META[key] = request.POST[key]
from django.utils.deprecation import MiddlewareMixin class FakeShibbolethMiddleWare(MiddlewareMixin): def process_request(self, request): if request.POST.get("convert-post-headers") == "1": for key in request.POST: request.META[key] = request.POST[key] if request.GET.get("convert-get-headers") == "1": for key in request.GET: http_key = key.upper() http_key.replace("-", "_") http_key = "HTTP_" + http_key request.META[http_key] = request.GET[key]
Add get parameter parsing for fakeshibboleth auto mode
Add get parameter parsing for fakeshibboleth auto mode
Python
mit
uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi
2ba9eaba0bcb229055db09147f1cb654190badbf
notebooks/style_helpers.py
notebooks/style_helpers.py
import brewer2mpl import itertools from cycler import cycler cmap = brewer2mpl.get_map('Set1', 'Qualitative', 5, reverse=False) color_cycle = cycler('color', cmap.hex_colors) marker_cycle = cycler('marker', ['s', '^', 'o', 'D', 'v']) markersize_cycle = cycler('markersize', [10, 12, 11, 10, 12]) style_cycle = itertools.cycle(color_cycle + marker_cycle + markersize_cycle) cmap = brewer2mpl.get_map('Set1', 'Qualitative', 3, reverse=False) color_cycle = cycler('color', ['black', '#88CCDD', '#c73027']) marker_cycle = cycler('marker', [' ', ' ', ' ']) markersize_cycle = cycler('markersize', [8, 8, 8]) fillstyle_cycle = cycler('fillstyle', ['full', 'full', 'full']) linestyle_cycle = cycler('linestyle', ['dashed', 'solid', 'solid']) linewidth_cycle = cycler('linewidth', [2, 2.25, 2]) style_cycle_fig7 = (color_cycle + marker_cycle + markersize_cycle + fillstyle_cycle + linestyle_cycle + linewidth_cycle)
import brewer2mpl from cycler import cycler N = 5 cmap = brewer2mpl.get_map('Set1', 'Qualitative', N, reverse=False) color_cycle = cycler('color', cmap.hex_colors) marker_cycle = cycler('marker', ['s', '^', 'o', 'D', 'v']) markersize_cycle = cycler('markersize', [10, 12, 11, 10, 12]) style_cycle = list(color_cycle + marker_cycle + markersize_cycle)[:N] cmap = brewer2mpl.get_map('Set1', 'Qualitative', 3, reverse=False) color_cycle = cycler('color', ['black', '#88CCDD', '#c73027']) marker_cycle = cycler('marker', [' ', ' ', ' ']) markersize_cycle = cycler('markersize', [8, 8, 8]) fillstyle_cycle = cycler('fillstyle', ['full', 'full', 'full']) linestyle_cycle = cycler('linestyle', ['dashed', 'solid', 'solid']) linewidth_cycle = cycler('linewidth', [2, 2.25, 2]) style_cycle_fig7 = list(color_cycle + marker_cycle + markersize_cycle + fillstyle_cycle + linestyle_cycle + linewidth_cycle)[:N]
Use a list for the style cycle so that subsequent calls to the plotting functions don't mix up the line styles.
Use a list for the style cycle so that subsequent calls to the plotting functions don't mix up the line styles.
Python
mit
maxalbert/paper-supplement-nanoparticle-sensing
39b8cb70ffd6be60c6d757ecd4703a3a0ca2a415
dbaas/workflow/steps/build_database.py
dbaas/workflow/steps/build_database.py
# -*- coding: utf-8 -*- import logging from base import BaseStep from logical.models import Database LOG = logging.getLogger(__name__) class BuildDatabase(BaseStep): def __unicode__(self): return "Creating logical database..." def do(self, workflow_dict): try: if not workflow_dict['team'] or not workflow_dict['description'] or not workflow_dict['databaseinfra']: return False LOG.info("Creating Database...") database = Database.provision(name= workflow_dict['name'], databaseinfra= workflow_dict['databaseinfra']) workflow_dict['database'] = database database.team = workflow_dict['team'] if 'project' in workflow_dict: database.project = workflow_dict['project'] database.description = workflow_dict['description'] database.save() return True except Exception, e: print e return False def undo(self, workflow_dict): try: LOG.info("Destroying the database....") workflow_dict['database'].delete() return True except Exception, e: print e return False
# -*- coding: utf-8 -*- import logging from base import BaseStep from logical.models import Database import datetime LOG = logging.getLogger(__name__) class BuildDatabase(BaseStep): def __unicode__(self): return "Creating logical database..." def do(self, workflow_dict): try: if not workflow_dict['team'] or not workflow_dict['description'] or not workflow_dict['databaseinfra']: return False LOG.info("Creating Database...") database = Database.provision(name= workflow_dict['name'], databaseinfra= workflow_dict['databaseinfra']) LOG.info("Database %s created!" % database) workflow_dict['database'] = database LOG.info("Updating database team") database.team = workflow_dict['team'] if 'project' in workflow_dict: LOG.info("Updating database project") database.project = workflow_dict['project'] LOG.info("Updating database description") database.description = workflow_dict['description'] database.save() return True except Exception, e: print e return False def undo(self, workflow_dict): try: if not 'database' in workflow_dict: return False LOG.info("Destroying the database....") if not workflow_dict['database'].is_in_quarantine: LOG.info("Putting Database in quarentine...") database = workflow_dict['database'] database.is_in_quarantine= True database.quarantine_dt = datetime.datetime.now().date() database.save() database.delete() return True except Exception, e: print e return False
Improve logs and change delete pos
Improve logs and change delete pos
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
099ae768056a4ab160179be89c8750a2bfc06b2c
pyeda/test/test_bdd.py
pyeda/test/test_bdd.py
""" Test binary decision diagrams """
""" Test binary decision diagrams """ from pyeda.bdd import expr2bdd from pyeda.expr import var a, b, c = map(var, 'abc') def test_expr2bdd(): f = a * b + a * c + b * c bdd_f = expr2bdd(f) assert bdd_f.root == a.var assert bdd_f.low.root == b.var assert bdd_f.high.root == b.var assert bdd_f.low.low.root == 0 assert bdd_f.low.high.root == c.var assert bdd_f.high.low.root == c.var assert bdd_f.high.high.root == 1 assert bdd_f.low.high.low.root == 0 assert bdd_f.high.low.high.root == 1
Implement expr2bdd function and unique table
Implement expr2bdd function and unique table
Python
bsd-2-clause
GtTmy/pyeda,sschnug/pyeda,sschnug/pyeda,karissa/pyeda,sschnug/pyeda,GtTmy/pyeda,karissa/pyeda,pombredanne/pyeda,pombredanne/pyeda,GtTmy/pyeda,cjdrake/pyeda,pombredanne/pyeda,cjdrake/pyeda,karissa/pyeda,cjdrake/pyeda
019d33092226d1ff8fe36897c03d25ddd48e34b1
serve.py
serve.py
""" Flask server app. """ import datetime as dt import sys import flask import sqlalchemy as sa import coils import tables import mapping app = flask.Flask(__name__) # Load configuration file. CONFIG = sys.argv[1] if len(sys.argv)>=2 else 'wabbit.cfg' config = coils.Config(CONFIG) @app.route('/') def index(): """Render the index page.""" return flask.render_template('index.html') @app.route('/info') def info(): """Return JSON of server info.""" # Connect to database engine. engine = sa.create_engine( 'mysql://{}:{}@{}/{}'.format( config['username'], config['password'], config['host'], config['db_name'])) Session = sa.orm.sessionmaker(bind=engine) session = Session() now = dt.datetime.now() datum = session.query(mapping.Datum).\ filter(mapping.Datum.name=='size')[0] return flask.jsonify(server_time=now, db_size=datum.value) if __name__ == '__main__': app.run()
""" Flask server app. """ import datetime as dt import sys import flask from flask.ext.sqlalchemy import SQLAlchemy import coils import mapping # Load configuration file. CONFIG = sys.argv[1] if len(sys.argv)>=2 else 'wabbit.cfg' config = coils.Config(CONFIG) # Initialize Flask and SQLAlchemy. app = flask.Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{}:{}@{}/{}'.format( config['username'], config['password'], config['host'], config['db_name']) db = SQLAlchemy(app) @app.route('/') def index(): """Render the index page.""" return flask.render_template('index.html') @app.route('/info') def info(): """Return JSON of server info.""" now = dt.datetime.now() datum = db.session.query(mapping.Datum).\ filter(mapping.Datum.name=='size')[0] return flask.jsonify(server_time=now, db_size=datum.value) if __name__ == '__main__': app.run()
Use SQLAlchemy extension in Flask app.
Use SQLAlchemy extension in Flask app.
Python
mit
vmlaker/wabbit,vmlaker/wabbit,vmlaker/wabbit,vmlaker/wabbit
09e6c915e668c0b41eca75e3105ebac6f8bfcf58
setup.py
setup.py
import os from distutils.core import setup from sphinx.setup_command import BuildDoc import django_assets def find_packages(root): # so we don't depend on setuptools; from the Storm ORM setup.py packages = [] for directory, subdirectories, files in os.walk(root): if '__init__.py' in files: packages.append(directory.replace(os.sep, '.')) return packages setup( name = 'django-assets', version=".".join(map(str, django_assets.__version__)), description = 'Media asset management for the Django web framework.', long_description = 'Merges, minifies and compresses Javascript and ' 'CSS files, supporting a variety of different filters, including ' 'YUI, jsmin, jspacker or CSS tidy. Also supports URL rewriting ' 'in CSS files.', author = 'Michael Elsdoerfer', author_email = 'michael@elsdoerfer.info', license = 'BSD', url = 'http://launchpad.net/django-assets', classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries', ], packages = find_packages('django_assets'), cmdclass={'build_sphinx': BuildDoc}, )
import os from distutils.core import setup try: from sphinx.setup_command import BuildDoc cmdclass = {'build_sphinx': BuildDoc} except ImportError: print "Sphinx not installed--needed to build documentation" # default cmdclass to None to avoid cmdclass = {} import django_assets def find_packages(root): # so we don't depend on setuptools; from the Storm ORM setup.py packages = [] for directory, subdirectories, files in os.walk(root): if '__init__.py' in files: packages.append(directory.replace(os.sep, '.')) return packages setup( name = 'django-assets', version=".".join(map(str, django_assets.__version__)), description = 'Media asset management for the Django web framework.', long_description = 'Merges, minifies and compresses Javascript and ' 'CSS files, supporting a variety of different filters, including ' 'YUI, jsmin, jspacker or CSS tidy. Also supports URL rewriting ' 'in CSS files.', author = 'Michael Elsdoerfer', author_email = 'michael@elsdoerfer.info', license = 'BSD', url = 'http://launchpad.net/django-assets', classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries', ], packages = find_packages('django_assets'), cmdclass=cmdclass, )
Allow the package to be built without Sphinx being required.
Allow the package to be built without Sphinx being required.
Python
bsd-2-clause
glorpen/webassets,glorpen/webassets,0x1997/webassets,rs/webassets,aconrad/webassets,JDeuce/webassets,scorphus/webassets,florianjacob/webassets,heynemann/webassets,aconrad/webassets,wijerasa/webassets,john2x/webassets,aconrad/webassets,heynemann/webassets,0x1997/webassets,glorpen/webassets,john2x/webassets,wijerasa/webassets,scorphus/webassets,florianjacob/webassets,heynemann/webassets,JDeuce/webassets
0b1bcf6305f808f3ed1b862a1673e774dce67879
setup.py
setup.py
from distutils.core import setup setup( name = 'depedit', packages = ['depedit'], version = '2.1.2', description = 'A simple configurable tool for manipulating dependency trees', author = 'Amir Zeldes', author_email = 'amir.zeldes@georgetown.edu', url = 'https://github.com/amir-zeldes/depedit', license='Apache License, Version 2.0', download_url = 'https://github.com/amir-zeldes/depedit/releases/tag/2.1.2', keywords = ['NLP', 'parsing', 'syntax', 'dependencies', 'dependency', 'tree', 'treebank', 'conll', 'conllu', 'ud'], classifiers = ['Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent'], )
from distutils.core import setup setup( name = 'depedit', packages = ['depedit'], version = '2.1.2', description = 'A simple configurable tool for manipulating dependency trees', author = 'Amir Zeldes', author_email = 'amir.zeldes@georgetown.edu', url = 'https://github.com/amir-zeldes/depedit', install_requires=["six"], license='Apache License, Version 2.0', download_url = 'https://github.com/amir-zeldes/depedit/releases/tag/2.1.2', keywords = ['NLP', 'parsing', 'syntax', 'dependencies', 'dependency', 'tree', 'treebank', 'conll', 'conllu', 'ud'], classifiers = ['Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent'], )
Add six as a requirement
Add six as a requirement
Python
apache-2.0
amir-zeldes/DepEdit
5c5e49797358e7020d409adf74209c0647050465
setup.py
setup.py
from distutils.core import setup setup(name='fuzzywuzzy', version='0.2', description='Fuzzy string matching in python', author='Adam Cohen', author_email='adam@seatgeek.com', url='https://github.com/seatgeek/fuzzywuzzy/', packages=['fuzzywuzzy'])
from distutils.core import setup setup(name='fuzzywuzzy', version='0.2', description='Fuzzy string matching in python', author='Adam Cohen', author_email='adam@seatgeek.com', url='https://github.com/seatgeek/fuzzywuzzy/', packages=['fuzzywuzzy'], classifiers=( 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3' ) )
Add classifiers for python versions
Add classifiers for python versions
Python
mit
jayhetee/fuzzywuzzy,salilnavgire/fuzzywuzzy,beni55/fuzzywuzzy,beni55/fuzzywuzzy,blakejennings/fuzzywuzzy,shalecraig/fuzzywuzzy,pombredanne/fuzzywuzzy,salilnavgire/fuzzywuzzy,pombredanne/fuzzywuzzy,aeeilllmrx/fuzzywuzzy,medecau/fuzzywuzzy,zhahaoyu/fuzzywuzzy,zhahaoyu/fuzzywuzzy,jayhetee/fuzzywuzzy,shalecraig/fuzzywuzzy,aeeilllmrx/fuzzywuzzy,blakejennings/fuzzywuzzy
d041ab4a09da6a2181e1b14f3d0f323ed9c29c6f
applications/templatetags/applications_tags.py
applications/templatetags/applications_tags.py
# -*- encoding: utf-8 -*- from django import template from applications.models import Score register = template.Library() @register.filter def scored_by_user(value, arg): try: score = Score.objects.get(application=value, user=arg) return True if score.score else False except Score.DoesNotExist: return False @register.simple_tag def display_sorting_arrow(name, current_order): is_reversed = False if '-{}'.format(name) == current_order: is_reversed = True if is_reversed: return '<a href="?order={}">▼</a>'.format(name) else: return '<a href="?order=-{}">▲</a>'.format(name)
# -*- encoding: utf-8 -*- from django import template register = template.Library() @register.filter def scored_by_user(application, user): return application.is_scored_by_user(user) @register.simple_tag def display_sorting_arrow(name, current_order): is_reversed = False if '-{}'.format(name) == current_order: is_reversed = True if is_reversed: return '<a href="?order={}">▼</a>'.format(name) else: return '<a href="?order=-{}">▲</a>'.format(name)
Make scored_by_user filter call model method
Make scored_by_user filter call model method Ref #113
Python
bsd-3-clause
DjangoGirls/djangogirls,patjouk/djangogirls,DjangoGirls/djangogirls,DjangoGirls/djangogirls,patjouk/djangogirls,patjouk/djangogirls,patjouk/djangogirls
ad761908537b63c2d262f69a75e7b221f84e8647
ca_on_school_boards_english_public/__init__.py
ca_on_school_boards_english_public/__init__.py
from utils import CanadianJurisdiction from opencivicdata.divisions import Division from pupa.scrape import Organization class OntarioEnglishPublicSchoolBoards(CanadianJurisdiction): classification = 'legislature' # just to avoid clash division_id = 'ocd-division/country:ca/province:on' division_name = 'Ontario English Public School Board boundary"' name = 'Ontario English Public School Boards' url = 'http://www.edu.gov.on.ca/eng/sbinfo/boardList.html' def get_organizations(self): organization = Organization(self.name, classification=self.classification) for division in Division.get(self.division_id).children('school_district'): organization.add_post(role='Representative', label=division.name, division_id=division.id) yield organization
from utils import CanadianJurisdiction from opencivicdata.divisions import Division from pupa.scrape import Organization class OntarioEnglishPublicSchoolBoards(CanadianJurisdiction): classification = 'legislature' # just to avoid clash division_id = 'ocd-division/country:ca/province:on' division_name = 'Ontario English Public School Board boundary"' name = 'Ontario English Public School Boards' url = 'http://www.edu.gov.on.ca/eng/sbinfo/boardList.html' def get_organizations(self): organization = Organization(self.name, classification=self.classification) for division in Division.get(self.division_id).children('school_district'): for i in range (0, 15): # XXX made-up number organization.add_post(role='Representative (seat {})'.format(i), label=division.name, division_id=division.id) yield organization
Add stub for multiple posts in school boards
Add stub for multiple posts in school boards
Python
mit
opencivicdata/scrapers-ca,opencivicdata/scrapers-ca
4bf218a843c61886c910504a47cbc86c8a4982ae
bulbs/content/management/commands/migrate_to_ia.py
bulbs/content/management/commands/migrate_to_ia.py
from django.core.management.base import BaseCommand from bulbs.content.models import Content, FeatureType from bulbs.content.tasks import post_to_instant_articles_api import timezone class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('feature', nargs="+", type=str) def handle(self, *args, **options): feature_types = FeatureType.objects.all() feature = options['feature'][0] if feature: feature_types.objects.filter(slug=feature) for ft in feature_types: if ft.instant_article: # All published content belonging to feature type content = Content.objects.filter( feature_type=ft, published__isnull=False, published__lte=timezone.now()) for c in content: post_to_instant_articles_api.delay(c.id)
from django.core.management.base import BaseCommand from bulbs.content.models import Content, FeatureType from bulbs.content.tasks import post_to_instant_articles_api import timezone class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('feature', nargs="+", type=str) def handle(self, *args, **options): feature_types = FeatureType.objects.all(instant_article=True) feature = options['feature'][0] if feature: feature_types = feature_types.objects.filter(slug=feature) for ft in feature_types: # All published content belonging to feature type content = Content.objects.filter( feature_type=ft, published__isnull=False, published__lte=timezone.now()) for c in content: post_to_instant_articles_api.delay(c.id)
Fix migrate to ia script
Fix migrate to ia script
Python
mit
theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs
9343dbfa0d822cdf2f00deab8b18cf4d2e809063
services/display_routes.py
services/display_routes.py
# -*- coding: utf-8 -*- from database.database_access import get_dao from gtfslib.model import Route from gtfsplugins import decret_2015_1610 from database.database_access import get_dao def get_routes(agency_id): dao = get_dao(agency_id) parsedRoutes = list() for route in dao.routes(fltr=Route.route_type == Route.TYPE_BUS): parsedRoute = dict() parsedRoute["name"] = route.route_long_name parsedRoutes.append(parsedRoute) return parsedRoutes
# -*- coding: utf-8 -*- from database.database_access import get_dao from gtfslib.model import Route from services.check_urban import check_urban_category def get_routes(agency_id): dao = get_dao(agency_id) parsedRoutes = list() for route in dao.routes(fltr=Route.route_type == Route.TYPE_BUS): print(route) parsedRoute = dict() parsedRoute["id"] = route.route_id parsedRoute["name"] = route.route_long_name parsedRoute["category"] = check_urban_category(route.trips) parsedRoutes.append(parsedRoute) return parsedRoutes
Add id & category to routes list
Add id & category to routes list
Python
mit
LoveXanome/urbanbus-rest,LoveXanome/urbanbus-rest
3b83b8715e03b9096f9ae5611019fec4e52ca937
tests.py
tests.py
from os.path import isdir import pytest from filesystem_tree import FilesystemTree @pytest.yield_fixture def fs(): fs = FilesystemTree() yield fs fs.remove() def test_it_can_be_instantiated(): assert FilesystemTree().__class__.__name__ == 'FilesystemTree' def test_args_go_to_mk_not_root(): fs = FilesystemTree('foo', 'bar') assert fs.root != 'foo' def test_it_makes_a_directory(fs): assert isdir(fs.root) def test_remove_removes(fs): assert isdir(fs.root) fs.remove() assert not isdir(fs.root)
import os from os.path import isdir import pytest from filesystem_tree import FilesystemTree @pytest.yield_fixture def fs(): fs = FilesystemTree() yield fs fs.remove() def test_it_can_be_instantiated(): assert FilesystemTree().__class__.__name__ == 'FilesystemTree' def test_args_go_to_mk_not_root(): fs = FilesystemTree('foo', 'bar') assert fs.root != 'foo' def test_it_makes_a_directory(fs): assert isdir(fs.root) def test_resolve_resolves(fs): path = fs.resolve('some/dir') assert path == os.path.realpath(os.sep.join([fs.root, 'some', 'dir'])) def test_mk_makes_a_dir(fs): fs.mk('some/dir') assert isdir(fs.resolve('some/dir')) def test_remove_removes(fs): assert isdir(fs.root) fs.remove() assert not isdir(fs.root)
Add an initial test each for resolve and mk
Add an initial test each for resolve and mk
Python
mit
gratipay/filesystem_tree.py,gratipay/filesystem_tree.py
8a75cc4626bd38faeec102aea894d4e7ac08646c
viewer_examples/viewers/collection_viewer.py
viewer_examples/viewers/collection_viewer.py
""" ===================== CollectionViewer demo ===================== Demo of CollectionViewer for viewing collections of images. This demo uses successively darker versions of the same image to fake an image collection. You can scroll through images with the slider, or you can interact with the viewer using your keyboard: left/right arrows Previous/next image in collection. number keys, 0--9 0% to 90% of collection. For example, "5" goes to the image in the middle (i.e. 50%) of the collection. home/end keys First/last image in collection. """ import numpy as np from skimage import data from skimage.viewer import CollectionViewer from skimage.transform import build_gaussian_pyramid img = data.lena() img_collection = tuple(build_gaussian_pyramid(img)) view = CollectionViewer(img_collection) view.show()
""" ===================== CollectionViewer demo ===================== Demo of CollectionViewer for viewing collections of images. This demo uses the different layers of the gaussian pyramid as image collection. You can scroll through images with the slider, or you can interact with the viewer using your keyboard: left/right arrows Previous/next image in collection. number keys, 0--9 0% to 90% of collection. For example, "5" goes to the image in the middle (i.e. 50%) of the collection. home/end keys First/last image in collection. """ import numpy as np from skimage import data from skimage.viewer import CollectionViewer from skimage.transform import build_gaussian_pyramid img = data.lena() img_collection = tuple(build_gaussian_pyramid(img)) view = CollectionViewer(img_collection) view.show()
Update description of collection viewer example
Update description of collection viewer example
Python
bsd-3-clause
almarklein/scikit-image,juliusbierk/scikit-image,paalge/scikit-image,Hiyorimi/scikit-image,chriscrosscutler/scikit-image,oew1v07/scikit-image,bennlich/scikit-image,paalge/scikit-image,warmspringwinds/scikit-image,chriscrosscutler/scikit-image,bennlich/scikit-image,warmspringwinds/scikit-image,rjeli/scikit-image,vighneshbirodkar/scikit-image,ajaybhat/scikit-image,emon10005/scikit-image,pratapvardhan/scikit-image,newville/scikit-image,chintak/scikit-image,SamHames/scikit-image,emon10005/scikit-image,rjeli/scikit-image,SamHames/scikit-image,SamHames/scikit-image,Britefury/scikit-image,WarrenWeckesser/scikits-image,ClinicalGraphics/scikit-image,pratapvardhan/scikit-image,vighneshbirodkar/scikit-image,jwiggins/scikit-image,bsipocz/scikit-image,michaelpacer/scikit-image,blink1073/scikit-image,WarrenWeckesser/scikits-image,chintak/scikit-image,ofgulban/scikit-image,ClinicalGraphics/scikit-image,oew1v07/scikit-image,dpshelio/scikit-image,michaelpacer/scikit-image,bsipocz/scikit-image,vighneshbirodkar/scikit-image,Midafi/scikit-image,newville/scikit-image,ofgulban/scikit-image,michaelaye/scikit-image,paalge/scikit-image,rjeli/scikit-image,keflavich/scikit-image,blink1073/scikit-image,almarklein/scikit-image,Midafi/scikit-image,dpshelio/scikit-image,jwiggins/scikit-image,michaelaye/scikit-image,chintak/scikit-image,ajaybhat/scikit-image,ofgulban/scikit-image,SamHames/scikit-image,Britefury/scikit-image,robintw/scikit-image,GaZ3ll3/scikit-image,youprofit/scikit-image,chintak/scikit-image,almarklein/scikit-image,youprofit/scikit-image,Hiyorimi/scikit-image,keflavich/scikit-image,juliusbierk/scikit-image,GaZ3ll3/scikit-image,robintw/scikit-image,almarklein/scikit-image
f93fcd5cee878c201dd1be2102a2a9433a63c4b5
scripts/set-artist-streamable.py
scripts/set-artist-streamable.py
#!/usr/bin/env python import psycopg2 as ordbms import urllib, urllib2 import xml.etree.cElementTree as ElementTree class SetArtistStreamable: def __init__(self): self.conn = ordbms.connect ("dbname='librefm'") self.cursor = self.conn.cursor() def updateAll(self): """Sets artists streamable property if they have streamable tracks already in the database""" self.cursor.execute("SELECT DISTINCT(artist.name) FROM artist INNER JOIN track on artist.name=artist_name WHERE track.streamable = 1") for artist in self.cursor.fetchall(): name = artist[0] print "marking %s as streamable... " % name self.cursor.execute("UPDATE artist SET streamable = 1 WHERE name = %s", (name,)) print "Applying changes... ", self.conn.commit() print "done." if __name__ == '__main__': sas = SetArtistStreamable() sas.updateAll()
#!/usr/bin/env python import psycopg2 as ordbms import urllib, urllib2 import xml.etree.cElementTree as ElementTree class SetArtistStreamable: def __init__(self): self.conn = ordbms.connect ("dbname='librefm'") self.cursor = self.conn.cursor() def updateAll(self): """Sets artists streamable property if they have streamable tracks already in the database""" self.cursor.execute("SELECT DISTINCT(artist.name) FROM artist INNER JOIN track on artist.name=artist_name WHERE track.streamable = 1") for artist in self.cursor.fetchall(): name = artist[0] print "marking %s as streamable... " % name self.cursor.execute("UPDATE artist SET streamable = 1 WHERE name = %s", (name,)) self.conn.commit() if __name__ == '__main__': sas = SetArtistStreamable() sas.updateAll()
Make streamable artist updates as they happen, rather than commiting at the end of all artists
Make streamable artist updates as they happen, rather than commiting at the end of all artists
Python
agpl-3.0
foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm
564d2eedf6e2b62152869c60bf1f3ba18287d8c0
fullcalendar/templatetags/fullcalendar.py
fullcalendar/templatetags/fullcalendar.py
from django import template from fullcalendar.models import Occurrence register = template.Library() @register.inclusion_tag('events/agenda_tag.html') def show_agenda(*args, **kwargs): qs = Occurrence.objects.upcoming() if 'limit' in kwargs: qs = qs[:int(kwargs['limit'])] return { 'occurrences': qs, 'all_sites': True, } @register.assignment_tag def get_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: return qs[:int(kwargs['limit'])] return qs @register.inclusion_tag('events/agenda_tag.html') def show_site_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: qs = qs[:int(kwargs['limit'])] return { 'occurrences': qs } @register.assignment_tag def get_site_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: return qs[:int(kwargs['limit'])] return qs
from django import template from django.utils import timezone from fullcalendar.models import Occurrence register = template.Library() @register.inclusion_tag('events/agenda_tag.html') def show_agenda(*args, **kwargs): qs = Occurrence.objects.upcoming() if 'limit' in kwargs: qs = qs[:int(kwargs['limit'])] return { 'occurrences': qs, 'all_sites': True, } @register.assignment_tag def get_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: return qs[:int(kwargs['limit'])] return qs @register.inclusion_tag('events/agenda_tag.html') def show_site_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: qs = qs[:int(kwargs['limit'])] return { 'occurrences': qs } @register.assignment_tag def get_site_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: return qs[:int(kwargs['limit'])] return qs @register.simple_tag def occurrence_duration(occurrence): start = timezone.localtime(occurrence.start_time) end = timezone.localtime(occurrence.end_time) result = start.strftime('%A, %d %B %Y %H:%M') if (start.day == end.day and start.month == end.month and start.year == end.year): result += ' - {:%H:%M}'.format(end) else: result += ' - {:%A, %d %B %Y %H:%M}'.format(end) return result
Add extra tag which displays the occurrence duration in a smart way
Add extra tag which displays the occurrence duration in a smart way
Python
mit
jonge-democraten/mezzanine-fullcalendar
74577faa2468a0b944cef3c88c9b8a82a4881ff1
query/views.py
query/views.py
""" Views for the rdap_explorer project, query app. """ import ipwhois from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.views.decorators.cache import cache_page from json import dumps from .forms import QueryForm def index(request): if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): return HttpResponseRedirect(reverse( 'query:results', args=(form['query'].value(),) )) else: form = QueryForm() return render(request, 'query/index.html', { 'title': 'Query', 'form': form }) @cache_page(86400) def results(request, query): error = None result = {} form = QueryForm(initial={"query": query}) try: ip = ipwhois.IPWhois(query) result = ip.lookup_rdap(retry_count=1, depth=2, inc_raw=True) except (ValueError, ipwhois.exceptions.IPDefinedError) as e: error = e return render(request, 'query/index.html', { 'title': 'Results', 'error': error, 'form': form, 'result': dumps(result) })
""" Views for the rdap_explorer project, query app. """ import ipwhois from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.views.decorators.cache import cache_page from json import dumps from .forms import QueryForm def index(request): if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): return HttpResponseRedirect(reverse( 'query:results', args=(form['query'].value(),) )) else: form = QueryForm() return render(request, 'query/index.html', { 'title': 'Query', 'form': form }) @cache_page(86400) def results(request, query): title = 'Results' error = None result = {} form = QueryForm(initial={"query": query}) try: ip = ipwhois.IPWhois(query) result = ip.lookup_rdap(retry_count=1, depth=2, inc_raw=True) title = ip.address_str except (ValueError, ipwhois.exceptions.IPDefinedError) as e: error = e title = 'Error' return render(request, 'query/index.html', { 'title': title, 'error': error, 'form': form, 'result': dumps(result) })
Change results page title to include query (or "Error" on error).
Change results page title to include query (or "Error" on error).
Python
mit
cdubz/rdap-explorer,cdubz/rdap-explorer
27f47ef27654dfa9c68bb90d3b8fae2e3a281396
pitchfork/__init__.py
pitchfork/__init__.py
# Copyright 2014 Dave Kludt # # 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 flask import Flask, g from happymongo import HapPyMongo from config import config from adminbp import bp as admin_bp from manage_globals import bp as manage_bp from engine import bp as engine_bp from inspect import getmembers, isfunction import context_functions import views import template_filters app = Flask(__name__) app.config.from_object(config) app.register_blueprint(admin_bp, url_prefix='/admin') app.register_blueprint(manage_bp, url_prefix='/manage') app.register_blueprint(engine_bp, url_prefix='/engine') # Setup DB based on the app name mongo, db = HapPyMongo(config) custom_filters = { name: function for name, function in getmembers(template_filters) if isfunction(function) } app.jinja_env.filters.update(custom_filters) app.context_processor(context_functions.utility_processor) views.ProductsView.register(app) views.MiscView.register(app) @app.before_request def before_request(): g.db = db
# Copyright 2014 Dave Kludt # # 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 setup_application app, db = setup_application.create_app()
Move out app setup to setup file to finish cleaning up the init file
Move out app setup to setup file to finish cleaning up the init file
Python
apache-2.0
rackerlabs/pitchfork,oldarmyc/pitchfork,oldarmyc/pitchfork,rackerlabs/pitchfork,rackerlabs/pitchfork,oldarmyc/pitchfork
16d6dd0ba2b5218d211c25e3e197d65fe163b09a
helusers/providers/helsinki_oidc/views.py
helusers/providers/helsinki_oidc/views.py
import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView ) from .provider import HelsinkiOIDCProvider class HelsinkiOIDCOAuth2Adapter(OAuth2Adapter): provider_id = HelsinkiOIDCProvider.id access_token_url = 'https://api.hel.fi/sso-test/openid/token/' authorize_url = 'https://api.hel.fi/sso-test/openid/authorize/' profile_url = 'https://api.hel.fi/sso-test/openid/userinfo/' def complete_login(self, request, app, token, **kwargs): headers = {'Authorization': 'Bearer {0}'.format(token.token)} resp = requests.get(self.profile_url, headers=headers) assert resp.status_code == 200 extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(HelsinkiOIDCOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(HelsinkiOIDCOAuth2Adapter)
import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView ) from .provider import HelsinkiOIDCProvider class HelsinkiOIDCOAuth2Adapter(OAuth2Adapter): provider_id = HelsinkiOIDCProvider.id access_token_url = 'https://api.hel.fi/sso/openid/token/' authorize_url = 'https://api.hel.fi/sso/openid/authorize/' profile_url = 'https://api.hel.fi/sso/openid/userinfo/' def complete_login(self, request, app, token, **kwargs): headers = {'Authorization': 'Bearer {0}'.format(token.token)} resp = requests.get(self.profile_url, headers=headers) assert resp.status_code == 200 extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(HelsinkiOIDCOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(HelsinkiOIDCOAuth2Adapter)
Fix broken Helsinki OIDC provider links
Fix broken Helsinki OIDC provider links
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
3e280e64874d1a68b6bc5fc91a8b6b28968b74e3
meinberlin/apps/dashboard2/contents.py
meinberlin/apps/dashboard2/contents.py
class DashboardContents: _registry = {} content = DashboardContents()
class DashboardContents: _registry = {'project': {}, 'module': {}} def __getitem__(self, identifier): component = self._registry['project'].get(identifier, None) if not component: component = self._registry['module'].get(identifier) return component def __contains__(self, identifier): return (identifier in self._registry['project'] or identifier in self._registry['module']) def register_project(self, component): self._registry['project'][component.identifier] = component def register_module(self, component): self._registry['module'][component.identifier] = component def get_project_components(self): return self._registry['project'].items() def get_module_components(self): return self._registry['module'].items() content = DashboardContents()
Store project and module componentes separately
Store project and module componentes separately
Python
agpl-3.0
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
46ee9dad4030c8628d951abb84a667c7398dd834
src/coordinators/models.py
src/coordinators/models.py
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from locations.models import District class Coordinator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_manager = models.BooleanField() district = models.ForeignKey(District, verbose_name=_('District'), blank=True, null=True) def filter_by_district(qs, user, lookup): # superusers and managers see everything if (user.is_superuser or hasattr(user, 'coordinator') and user.coordinator.is_manager): return qs # don't show anything to unconfigured users if not hasattr(user, 'coordinator') or not user.coordinator.district: return qs.none() kwargs = { lookup: user.coordinator.district } return qs.filter(**kwargs)
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from locations.models import District class Coordinator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_manager = models.BooleanField() district = models.ForeignKey(District, verbose_name=_('District'), blank=True, null=True) def filter_by_district(qs, user, lookup): # superusers and managers see everything if (user.is_superuser or hasattr(user, 'coordinator') and user.coordinator.is_manager): return qs # don't show anything to unconfigured users if not hasattr(user, 'coordinator') or not user.coordinator.district: return qs.none() kwargs = { lookup: user.coordinator.district } return qs.filter(**kwargs).distinct()
Fix error when multiple objects were returned for coordinators in admin
Fix error when multiple objects were returned for coordinators in admin
Python
mit
mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign
72796a97a24c512cf43fd9559d6e6b47d2f72e72
preferences/models.py
preferences/models.py
import uuid from django.db import models from django.contrib.auth.models import User from opencivicdata.models.people_orgs import Person from django.contrib.auth.models import User class Preferences(models.Model): user = models.OneToOneField(User, related_name='preferences') address = models.CharField(max_length=100, blank=True) lat = models.FloatField(null=True, blank=True) lon = models.FloatField(null=True, blank=True) apikey = models.UUIDField(default=uuid.uuid4) class PersonFollow(models.Model): user = models.ForeignKey(User, related_name='person_follows') person = models.ForeignKey(Person, related_name='follows') class TopicFollow(models.Model): user = models.ForeignKey(User, related_name='topic_follows') topic = models.CharField(max_length=100) class LocationFollow(models.Model): user = models.ForeignKey(User, related_name='location_follows') location = models.CharField(max_length=100)
import uuid from django.db import models from django.contrib.auth.models import User from opencivicdata.models.people_orgs import Person class Preferences(models.Model): user = models.OneToOneField(User, related_name='preferences') address = models.CharField(max_length=100, blank=True, null=True) lat = models.FloatField(null=True, blank=True) lon = models.FloatField(null=True, blank=True) apikey = models.UUIDField(default=uuid.uuid4) class PersonFollow(models.Model): user = models.ForeignKey(User, related_name='person_follows') person = models.ForeignKey(Person, related_name='follows') class TopicFollow(models.Model): user = models.ForeignKey(User, related_name='topic_follows') topic = models.CharField(max_length=100) class LocationFollow(models.Model): user = models.ForeignKey(User, related_name='location_follows') location = models.CharField(max_length=100)
Allow address to be null
Allow address to be null
Python
mit
jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot
d7c41853277c1df53192b2f879f47f75f3c62fd5
server/covmanager/urls.py
server/covmanager/urls.py
from django.conf.urls import patterns, include, url from rest_framework import routers from covmanager import views router = routers.DefaultRouter() router.register(r'collections', views.CollectionViewSet, base_name='collections') router.register(r'repositories', views.RepositoryViewSet, base_name='repositories') urlpatterns = patterns('', url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^repositories/', views.repositories, name="repositories"), url(r'^collections/$', views.collections, name="collections"), url(r'^collections/api/$', views.CollectionViewSet.as_view({'get': 'list'}), name="collections_api"), url(r'^collections/(?P<collectionid>\d+)/browse/$', views.collections_browse, name="collections_browse"), url(r'^collections/(?P<collectionid>\d+)/browse/api/(?P<path>.*)', views.collections_browse_api, name="collections_browse_api"), url(r'^rest/', include(router.urls)), )
from django.conf.urls import patterns, include, url from rest_framework import routers from covmanager import views router = routers.DefaultRouter() router.register(r'collections', views.CollectionViewSet, base_name='collections') router.register(r'repositories', views.RepositoryViewSet, base_name='repositories') urlpatterns = patterns('', url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^$', views.index, name='index'), url(r'^repositories/', views.repositories, name="repositories"), url(r'^collections/$', views.collections, name="collections"), url(r'^collections/api/$', views.CollectionViewSet.as_view({'get': 'list'}), name="collections_api"), url(r'^collections/(?P<collectionid>\d+)/browse/$', views.collections_browse, name="collections_browse"), url(r'^collections/(?P<collectionid>\d+)/browse/api/(?P<path>.*)', views.collections_browse_api, name="collections_browse_api"), url(r'^rest/', include(router.urls)), )
Add redirect for / to collections
[CovManager] Add redirect for / to collections
Python
mpl-2.0
MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager
9940a61cd7dbe9b66dcd4c7e07f967e53d2951d4
pybossa/auth/token.py
pybossa/auth/token.py
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa 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. # # PyBossa 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 PyBossa. If not, see <http://www.gnu.org/licenses/>. from flask.ext.login import current_user def create(token=None): return False def read(token=None): return not current_user.is_anonymous() def update(token=None): return False def delete(token=None): return False
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa 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. # # PyBossa 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 PyBossa. If not, see <http://www.gnu.org/licenses/>. from flask.ext.login import current_user def create(token=None): return False def read(token=None): return not current_user.is_anonymous() def update(token): return False def delete(token): return False
Change signature to match other resources auth functions
Change signature to match other resources auth functions
Python
agpl-3.0
geotagx/pybossa,jean/pybossa,stefanhahmann/pybossa,harihpr/tweetclickers,Scifabric/pybossa,inteligencia-coletiva-lsd/pybossa,OpenNewsLabs/pybossa,PyBossa/pybossa,Scifabric/pybossa,geotagx/pybossa,jean/pybossa,harihpr/tweetclickers,stefanhahmann/pybossa,OpenNewsLabs/pybossa,inteligencia-coletiva-lsd/pybossa,PyBossa/pybossa
6fe48fc7499327d27f69204b7f8ec927fc975177
python/lexPythonMQ.py
python/lexPythonMQ.py
#!/usr/bin/python import tokenize; import zmq; context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://lo:32132") while True: # Wait for next request from client message = socket.recv()
#!/usr/bin/python import re, sys, tokenize, zmq; from StringIO import StringIO def err(msg): sys.err.write(str(msg) + '\n') class LexPyMQ(object): def __init__(self): self.zctx = zmq.Context() self.socket = self.zctx.socket(zmq.REP) def run(self): self.socket.bind("tcp://lo:32132") while True: msg = self.socket.recv_json(0) # there are definitely new lines in the code if not msg.get('python'): err('received non-python code') code = msg.get('body', '') self.socket.send_json(tokenize.generate_tokens(StringIO(code))) if __name__ == '__main__': LexPyMQ().run()
Implement python lexer ZMQ service.
Implement python lexer ZMQ service.
Python
agpl-3.0
orezpraw/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,abramhindle/UnnaturalCodeFork,orezpraw/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,abramhindle/UnnaturalCodeFork,orezpraw/estimate-charm,naturalness/unnaturalcode,orezpraw/unnaturalcode,orezpraw/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,abramhindle/UnnaturalCodeFork,naturalness/unnaturalcode,abramhindle/UnnaturalCodeFork
15de2fe886c52f0900deeb519f944d22bb5c6db4
mysite/project/views.py
mysite/project/views.py
from mysite.search.models import Project from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404 def project(request, project__name = None): p = Project.objects.get(name=project__name) return render_to_response('project/project.html', { 'the_user': request.user, 'project': p, 'contributors': p.get_contributors() } )
from mysite.search.models import Project import django.template import mysite.base.decorators from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404 @mysite.base.decorators.view def project(request, project__name = None): p = Project.objects.get(name=project__name) return (request, 'project/project.html', { 'project': p, 'contributors': p.get_contributors() }, )
Use the @view decorator to ensure that the project page gets user data.
Use the @view decorator to ensure that the project page gets user data.
Python
agpl-3.0
onceuponatimeforever/oh-mainline,vipul-sharma20/oh-mainline,nirmeshk/oh-mainline,onceuponatimeforever/oh-mainline,ehashman/oh-mainline,waseem18/oh-mainline,ehashman/oh-mainline,mzdaniel/oh-mainline,campbe13/openhatch,vipul-sharma20/oh-mainline,eeshangarg/oh-mainline,sudheesh001/oh-mainline,jledbetter/openhatch,jledbetter/openhatch,SnappleCap/oh-mainline,heeraj123/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,ojengwa/oh-mainline,ehashman/oh-mainline,sudheesh001/oh-mainline,SnappleCap/oh-mainline,willingc/oh-mainline,sudheesh001/oh-mainline,ojengwa/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,Changaco/oh-mainline,jledbetter/openhatch,jledbetter/openhatch,campbe13/openhatch,mzdaniel/oh-mainline,vipul-sharma20/oh-mainline,waseem18/oh-mainline,mzdaniel/oh-mainline,onceuponatimeforever/oh-mainline,waseem18/oh-mainline,ojengwa/oh-mainline,jledbetter/openhatch,ehashman/oh-mainline,vipul-sharma20/oh-mainline,Changaco/oh-mainline,eeshangarg/oh-mainline,campbe13/openhatch,heeraj123/oh-mainline,heeraj123/oh-mainline,SnappleCap/oh-mainline,moijes12/oh-mainline,heeraj123/oh-mainline,moijes12/oh-mainline,moijes12/oh-mainline,heeraj123/oh-mainline,willingc/oh-mainline,openhatch/oh-mainline,sudheesh001/oh-mainline,nirmeshk/oh-mainline,campbe13/openhatch,Changaco/oh-mainline,moijes12/oh-mainline,willingc/oh-mainline,SnappleCap/oh-mainline,SnappleCap/oh-mainline,vipul-sharma20/oh-mainline,onceuponatimeforever/oh-mainline,willingc/oh-mainline,nirmeshk/oh-mainline,ojengwa/oh-mainline,openhatch/oh-mainline,nirmeshk/oh-mainline,onceuponatimeforever/oh-mainline,eeshangarg/oh-mainline,ojengwa/oh-mainline,waseem18/oh-mainline,waseem18/oh-mainline,moijes12/oh-mainline,sudheesh001/oh-mainline,mzdaniel/oh-mainline,campbe13/openhatch,openhatch/oh-mainline,ehashman/oh-mainline,mzdaniel/oh-mainline,openhatch/oh-mainline,nirmeshk/oh-mainline,eeshangarg/oh-mainline,openhatch/oh-mainline,eeshangarg/oh-mainline,willingc/oh-mainline
d2a040618a1e816b97f60aa66f5b4c9ab4a3e6b9
refmanage/fs_utils.py
refmanage/fs_utils.py
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*- import os import glob import pathlib2 as pathlib def handle_files_args(paths_args): """ Handle files arguments from command line This method takes a list of strings representing paths passed to the cli. It expands the path arguments and creates a list of pathlib.Path objects which unambiguously point to the files indicated by the command line arguments. :param list paths_args: Paths to files. """ for paths_arg in paths_args: # Handle paths implicitly rooted at user home dir paths_arg = os.path.expanduser(paths_arg) # Expand wildcards paths_arg = glob.glob(paths_arg) # Create list of pathlib.Path objects paths = [pathlib.Path(path_arg) for path_arg in paths_arg] return paths
Add method to handle files args from cli
Add method to handle files args from cli
Python
mit
jrsmith3/refmanage
fa14c040e6483087f5b2c78bc1a7aeee9ad2274a
Instanssi/kompomaatti/misc/time_formatting.py
Instanssi/kompomaatti/misc/time_formatting.py
# -*- coding: utf-8 -*- import awesometime def compo_times_formatter(compo): compo.compo_time = awesometime.format_single(compo.compo_start) compo.adding_time = awesometime.format_single(compo.adding_end) compo.editing_time = awesometime.format_single(compo.editing_end) compo.voting_time = awesometime.format_between(compo.voting_start, compo.voting_end) return compo
# -*- coding: utf-8 -*- import awesometime def compo_times_formatter(compo): compo.compo_time = awesometime.format_single(compo.compo_start) compo.adding_time = awesometime.format_single(compo.adding_end) compo.editing_time = awesometime.format_single(compo.editing_end) compo.voting_time = awesometime.format_between(compo.voting_start, compo.voting_end) return compo def competition_times_formatter(competition): competition.start_time = awesometime.format_single(competition.start) competition.participation_end_time = awesometime.format_single(competition.participation_end) return competition
Add time formatter for competitions
kompomaatti: Add time formatter for competitions
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
ae78bd758c690e28abaae2c07e8a3890e76044e0
pylearn2/scripts/papers/maxout/tests/test_mnist.py
pylearn2/scripts/papers/maxout/tests/test_mnist.py
import os import numpy as np import pylearn2 from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix from pylearn2.termination_criteria import EpochCounter from pylearn2.utils.serial import load_train_file def test_mnist(): """ Test the mnist.yaml file from the dropout paper on random input """ train = load_train_file(os.path.join(pylearn2.__path__[0], "scripts/papers/maxout/mnist.yaml")) random_X = np.random.rand(10, 784) random_y = np.random.randint(0, 10, (10, 1)) train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10) train.algorithm.termination_criterion = EpochCounter(max_epochs=1) train.main_loop()
import os import numpy as np import pylearn2 from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix from pylearn2.termination_criteria import EpochCounter from pylearn2.utils.serial import load_train_file def test_mnist(): """ Test the mnist.yaml file from the dropout paper on random input """ train = load_train_file(os.path.join(pylearn2.__path__[0], "scripts/papers/maxout/mnist.yaml")) random_X = np.random.rand(10, 784) random_y = np.random.randint(0, 10, (10, 1)) train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10) train.algorithm.termination_criterion = EpochCounter(max_epochs=1) train.algorithm._set_monitoring_dataset(train.dataset) train.main_loop()
Allow papers/maxout to be tested without MNIST data
Allow papers/maxout to be tested without MNIST data
Python
bsd-3-clause
KennethPierce/pylearnk,KennethPierce/pylearnk,Refefer/pylearn2,JesseLivezey/plankton,goodfeli/pylearn2,theoryno3/pylearn2,alexjc/pylearn2,pkainz/pylearn2,fulmicoton/pylearn2,alexjc/pylearn2,alexjc/pylearn2,kastnerkyle/pylearn2,ddboline/pylearn2,se4u/pylearn2,hantek/pylearn2,jeremyfix/pylearn2,nouiz/pylearn2,abergeron/pylearn2,sandeepkbhat/pylearn2,chrish42/pylearn,msingh172/pylearn2,caidongyun/pylearn2,fulmicoton/pylearn2,Refefer/pylearn2,skearnes/pylearn2,sandeepkbhat/pylearn2,mclaughlin6464/pylearn2,hantek/pylearn2,sandeepkbhat/pylearn2,fyffyt/pylearn2,bartvm/pylearn2,fulmicoton/pylearn2,jamessergeant/pylearn2,se4u/pylearn2,mkraemer67/pylearn2,TNick/pylearn2,junbochen/pylearn2,sandeepkbhat/pylearn2,hyqneuron/pylearn2-maxsom,woozzu/pylearn2,CIFASIS/pylearn2,pombredanne/pylearn2,fishcorn/pylearn2,JesseLivezey/pylearn2,ashhher3/pylearn2,lunyang/pylearn2,mkraemer67/pylearn2,lisa-lab/pylearn2,pombredanne/pylearn2,daemonmaker/pylearn2,ddboline/pylearn2,junbochen/pylearn2,JesseLivezey/plankton,hantek/pylearn2,msingh172/pylearn2,ashhher3/pylearn2,ddboline/pylearn2,matrogers/pylearn2,abergeron/pylearn2,ashhher3/pylearn2,shiquanwang/pylearn2,goodfeli/pylearn2,pombredanne/pylearn2,nouiz/pylearn2,nouiz/pylearn2,matrogers/pylearn2,cosmoharrigan/pylearn2,kastnerkyle/pylearn2,shiquanwang/pylearn2,kose-y/pylearn2,aalmah/pylearn2,abergeron/pylearn2,junbochen/pylearn2,w1kke/pylearn2,fyffyt/pylearn2,daemonmaker/pylearn2,fyffyt/pylearn2,skearnes/pylearn2,JesseLivezey/plankton,mclaughlin6464/pylearn2,nouiz/pylearn2,hantek/pylearn2,se4u/pylearn2,lamblin/pylearn2,ddboline/pylearn2,lisa-lab/pylearn2,kastnerkyle/pylearn2,aalmah/pylearn2,lamblin/pylearn2,theoryno3/pylearn2,JesseLivezey/pylearn2,TNick/pylearn2,bartvm/pylearn2,shiquanwang/pylearn2,JesseLivezey/plankton,shiquanwang/pylearn2,chrish42/pylearn,CIFASIS/pylearn2,chrish42/pylearn,mclaughlin6464/pylearn2,jamessergeant/pylearn2,lancezlin/pylearn2,lisa-lab/pylearn2,jamessergeant/pylearn2,lancezlin/pylearn2,matrogers/pylearn2,mkraemer67/pylearn2,theoryno3/pylearn2,junbochen/pylearn2,daemonmaker/pylearn2,pkainz/pylearn2,theoryno3/pylearn2,CIFASIS/pylearn2,cosmoharrigan/pylearn2,jeremyfix/pylearn2,caidongyun/pylearn2,bartvm/pylearn2,se4u/pylearn2,kose-y/pylearn2,msingh172/pylearn2,KennethPierce/pylearnk,hyqneuron/pylearn2-maxsom,hyqneuron/pylearn2-maxsom,fishcorn/pylearn2,KennethPierce/pylearnk,fyffyt/pylearn2,kose-y/pylearn2,jamessergeant/pylearn2,lancezlin/pylearn2,caidongyun/pylearn2,lamblin/pylearn2,cosmoharrigan/pylearn2,skearnes/pylearn2,goodfeli/pylearn2,matrogers/pylearn2,fishcorn/pylearn2,fulmicoton/pylearn2,w1kke/pylearn2,caidongyun/pylearn2,CIFASIS/pylearn2,msingh172/pylearn2,pkainz/pylearn2,Refefer/pylearn2,aalmah/pylearn2,chrish42/pylearn,pkainz/pylearn2,bartvm/pylearn2,woozzu/pylearn2,jeremyfix/pylearn2,ashhher3/pylearn2,pombredanne/pylearn2,jeremyfix/pylearn2,Refefer/pylearn2,lunyang/pylearn2,lisa-lab/pylearn2,JesseLivezey/pylearn2,skearnes/pylearn2,lunyang/pylearn2,TNick/pylearn2,goodfeli/pylearn2,kose-y/pylearn2,woozzu/pylearn2,lancezlin/pylearn2,fishcorn/pylearn2,aalmah/pylearn2,lamblin/pylearn2,daemonmaker/pylearn2,kastnerkyle/pylearn2,JesseLivezey/pylearn2,mclaughlin6464/pylearn2,hyqneuron/pylearn2-maxsom,lunyang/pylearn2,woozzu/pylearn2,abergeron/pylearn2,w1kke/pylearn2,cosmoharrigan/pylearn2,alexjc/pylearn2,TNick/pylearn2,mkraemer67/pylearn2,w1kke/pylearn2
1e931e9aac18f393de786894d9e26ecccc251135
server/models/_generate_superpixels.py
server/models/_generate_superpixels.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### import os import sys # Worker-defined inputs originalFile = globals()['originalFile'] segmentation_helpersPath = globals()['segmentation_helpersPath'] segmentation_helpersDirPath = os.path.dirname(segmentation_helpersPath) if segmentation_helpersDirPath not in sys.path: sys.path.append(segmentation_helpersDirPath) from segmentation_helpers.scikit import ScikitSegmentationHelper # noqa with open(originalFile, 'rb') as originalFileStream: # Scikit-Image is ~70ms faster at decoding image data originalImageData = ScikitSegmentationHelper.loadImage(originalFileStream) superpixelsData = ScikitSegmentationHelper.superpixels(originalImageData) superpixelsEncodedStream = ScikitSegmentationHelper.writeImage( superpixelsData, 'png') superpixelsEncodedBytes = superpixelsEncodedStream.getvalue()
############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### import os import sys # Worker-defined inputs originalFile = globals()['originalFile'] segmentation_helpersPath = globals()['segmentation_helpersPath'] segmentation_helpersDirPath = os.path.dirname(segmentation_helpersPath) if segmentation_helpersDirPath not in sys.path: sys.path.append(segmentation_helpersDirPath) from segmentation_helpers.scikit import ScikitSegmentationHelper # noqa with open(originalFile, 'rb') as originalFileStream: # Scikit-Image is ~70ms faster at decoding image data originalImageData = ScikitSegmentationHelper.loadImage(originalFileStream) superpixelsData = ScikitSegmentationHelper.superpixels(originalImageData) superpixelsEncodedStream = ScikitSegmentationHelper.writeImage( superpixelsData, 'png') superpixelsEncodedBytes = superpixelsEncodedStream.getvalue()
Fix girder_work script bug: PEP 263 is not compatible with exec
Fix girder_work script bug: PEP 263 is not compatible with exec
Python
apache-2.0
ImageMarkup/isic-archive,ImageMarkup/isic-archive,ImageMarkup/isic-archive,ImageMarkup/isic-archive
a79a3f7c42c858ae42c618479654cd7589de05b9
zeeko/utils/tests/test_hmap.py
zeeko/utils/tests/test_hmap.py
# -*- coding: utf-8 -*- import pytest from ..hmap import HashMap @pytest.fixture(params=[0,1,5,9]) def n(request): """Number of items""" return request.param @pytest.fixture def items(n): """A list of strings.""" return ["item{0:d}".format(i) for i in range(n)] @pytest.mark.skip def test_hmap(items): """docstring for test""" h = HashMap(10) if len(items): with pytest.raises(KeyError): h[items[0]] for item in items: h.add(item) assert len(h) == len(items) for i, item in enumerate(items): assert h[item] == i assert repr(h) == "HashMap({0!r})".format(items) if len(items): item = items[0] del h[item] assert len(h) == len(items) - 1 assert item not in h
# -*- coding: utf-8 -*- import pytest from ..hmap import HashMap @pytest.fixture(params=[0,1,5,9]) def n(request): """Number of items""" return request.param @pytest.fixture def items(n): """A list of strings.""" return ["item{0:d}".format(i) for i in range(n)]
Remove unused tests for hash map
Remove unused tests for hash map
Python
bsd-3-clause
alexrudy/Zeeko,alexrudy/Zeeko
311a858ecbe7d34f9f68a18a3735db9da8b0e692
tests/utils.py
tests/utils.py
import atexit import tempfile import sys import mock from selenium import webdriver import os def build_mock_mapping(name): mock_driver = mock.Mock() browser_mapping = {name: mock_driver} mock_driver.return_value.name = name return browser_mapping test_driver = None def get_driver(): global test_driver if not test_driver: options = webdriver.ChromeOptions() options.add_argument('headless') chrome = webdriver.Chrome(chrome_options=options) atexit.register(chrome.quit) chrome.delete_all_cookies() chrome.switch_to.default_content() return chrome def make_temp_page(src): f = tempfile.mktemp(".html") fh = open(f, "w") fh.write(src.replace("\n", "")) fh.close() atexit.register(lambda: os.remove(f)) return "file://%s" % f def mock_open(): if sys.version_info >= (3, 0, 0): return mock.patch("builtins.open") return mock.patch("__builtin__.open")
import atexit import tempfile import sys import mock from selenium import webdriver import os def build_mock_mapping(name): mock_driver = mock.Mock() browser_mapping = {name: mock_driver} mock_driver.return_value.name = name return browser_mapping test_driver = None def get_driver(): global test_driver if not test_driver: options = webdriver.ChromeOptions() options.add_argument('headless') test_driver = webdriver.Chrome(chrome_options=options) atexit.register(test_driver.quit) test_driver.delete_all_cookies() test_driver.switch_to.default_content() return test_driver def make_temp_page(src): f = tempfile.mktemp(".html") fh = open(f, "w") fh.write(src.replace("\n", "")) fh.close() atexit.register(lambda: os.remove(f)) return "file://%s" % f def mock_open(): if sys.version_info >= (3, 0, 0): return mock.patch("builtins.open") return mock.patch("__builtin__.open")
Fix global test driver initialization
Fix global test driver initialization
Python
mit
alisaifee/holmium.core,alisaifee/holmium.core,alisaifee/holmium.core,alisaifee/holmium.core
e8da41193238a7c677ec7ff8339095ec3e71be3b
track_count.py
track_count.py
from report import * def show_track_count(S): print "Track Count\t\tSubmission Count" for (track, count) in S.track_count().items(): if track: print "%s\t\t%s" % (track.ljust(20), count) if __name__ == "__main__": # S = ALL.standard().vote_cutoff(4.0) S = ALL.standard().filter(lambda s: s.accepted) show_track_count(S)
from report import * def show_track_count(S): print "Track Count".ljust(40) + "\t\tSubmission Count" items = S.track_count().items() total = sum([count for (track, count) in items]) for (track, count) in sorted(items, cmp=lambda (a_track, a_count), (b_track, b_count): cmp(b_count, a_count)): if track: print "%s\t\t%s" % (track.ljust(40), count) print "Total".ljust(40) + "\t\t%s" % total if __name__ == "__main__": # S = ALL.standard().vote_cutoff(4.0) S = ALL.standard() #.filter(lambda s: s.accepted) show_track_count(S)
Fix formatting, show total and sort
Fix formatting, show total and sort
Python
epl-1.0
tracymiranda/pc-scripts,tracymiranda/pc-scripts
17015ecf48ec37909de6de2c299454fc89b592e9
tests/test_gmaps.py
tests/test_gmaps.py
# -*- coding: UTF-8 -*- from base import TestCase from jinja2_maps.gmaps import gmaps_url class TestGmaps(TestCase): def test_url_dict(self): url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z" self.assertEquals(url, gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42))
# -*- coding: UTF-8 -*- from base import TestCase from jinja2_maps.gmaps import gmaps_url class TestGmaps(TestCase): def test_url_dict(self): url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z" self.assertEquals(url, gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42)) def test_url_dict_no_zoom(self): url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,16z" self.assertEquals(url, gmaps_url(dict(latitude=12.34, longitude=56.78)))
Add failing test for URL without zoom
Add failing test for URL without zoom
Python
mit
bfontaine/jinja2_maps
73673598e1998252b16b48d31b800ab0fb441392
pml/cs.py
pml/cs.py
""" Template module to define control systems. """ class ControlSystem(object): """ Define a control system to be used with a device It uses channel access to comunicate over the network with the hardware. """ def __init__(self): raise NotImplementedError() def get(self, pv): raise NotImplementedError() def put(self, pv, value): raise NotImplementedError() class NullControlSystem(ControlSystem): def __init__(self): pass def get(self, pv): pass def put(self, pv, value): pass
""" Template module to define control systems. """ class ControlSystem(object): """ Define a control system to be used with a device. It uses channel access to comunicate over the network with the hardware. """ def __init__(self): raise NotImplementedError() def get(self, pv): """ Get the value of the given pv. Args: pv(string): The Pv to get the value of. Returns: Number: The numeric value of the pv. """ raise NotImplementedError() def put(self, pv, value): """ Put the value of a given pv. Args: pv(string): The string to put the value for. value(Number): The value to be set. """ raise NotImplementedError() class NullControlSystem(ControlSystem): """ Dummy control system to set the value of a pv.""" def __init__(self): pass def get(self, pv): """ Get the value of the given pv. Args: pv(string): The Pv to get the value of. Returns: Number: The numeric value of the pv. """ pass def put(self, pv, value): """ Put the value of a given pv. Args: pv(string): The string to put the value for. value(Number): The value to be set. """ pass
Add documentation for the control system
Add documentation for the control system
Python
apache-2.0
willrogers/pml,willrogers/pml
3c735d18bdcff28bbdd765b131649ba57fb612b0
hy/models/string.py
hy/models/string.py
# Copyright (c) 2013 Paul Tagliamonte <paultag@debian.org> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from hy.models import HyObject import sys if sys.version_info[0] >= 3: str_type = str else: str_type = unicode class HyString(HyObject, str_type): """ Generic Hy String object. Helpful to store string literals from Hy scripts. It's either a ``str`` or a ``unicode``, depending on the Python version. """ def __new__(cls, value): obj = str_type.__new__(cls, value) return obj
# Copyright (c) 2013 Paul Tagliamonte <paultag@debian.org> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from hy.models import HyObject import sys if sys.version_info[0] >= 3: str_type = str else: str_type = unicode class HyString(HyObject, str_type): """ Generic Hy String object. Helpful to store string literals from Hy scripts. It's either a ``str`` or a ``unicode``, depending on the Python version. """ pass
Revert "Revert "Remove useless code""
Revert "Revert "Remove useless code"" This reverts commit 262da59c7790cdadd60ea9612bc9e3c1616863fd. Conflicts: hy/models/string.py
Python
mit
ALSchwalm/hy,aisk/hy,paultag/hy,tianon/hy,hcarvalhoalves/hy,Foxboron/hy,Tritlo/hy,mtmiller/hy,michel-slm/hy,farhaven/hy,freezas/hy,zackmdavis/hy,tianon/hy,gilch/hy,aisk/hy,larme/hy,tuturto/hy,timmartin/hy,farhaven/hy,kirbyfan64/hy,farhaven/hy,algernon/hy,Foxboron/hy,hcarvalhoalves/hy,kirbyfan64/hy,adamfeuer/hy,jakirkham/hy,tianon/hy,larme/hy,larme/hy,kartikm/hy,aisk/hy
60870a3e471637d44da32f3aac74064e4ca60208
pyplot.py
pyplot.py
#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """Module to bundle plotting scripts `activate-global-python-argcomplete` must be run to enable auto completion """ import argparse import argcomplete import plotter def parse_arguments(): """Argument Parser, providing available scripts""" parser = argparse.ArgumentParser() subparsers = parser.add_subparsers( title = 'plotter', description = 'available plotting scripts' ) module_subparser = {} for module_str in plotter.__all__: module = __import__('.'.join(('plotter', module_str)), fromlist=module_str) module_subparser[module_str] = subparsers.add_parser( module_str, parents=[module.get_parser(add_help=False)], help=module.__doc__.split('\n', 1)[0] ) configure = subparsers.add_parser('configure', help='configure this script.') argcomplete.autocomplete(parser) args = parser.parse_args() return args if __name__ == '__main__': args = parse_arguments() from plotter.plotn import main main(args)
#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """Module to bundle plotting scripts `activate-global-python-argcomplete` must be run to enable auto completion """ import argparse import argcomplete import plotter def parse_arguments(): """Argument Parser, providing available scripts""" parser = argparse.ArgumentParser() subparsers = parser.add_subparsers( title = 'plotter', description = 'available plotting scripts', dest='used_subparser', ) module_subparser = {} for module_str in plotter.__all__: module = __import__('plotter.' + module_str, fromlist=module_str) module_subparser[module_str] = subparsers.add_parser( module_str, parents=[module.get_parser(add_help=False)], help=module.__doc__.split('\n', 1)[0] ) module_subparser[module_str].set_defaults(run=module.main) configure = subparsers.add_parser('configure', help='configure this script.') argcomplete.autocomplete(parser) args = parser.parse_args() return args if __name__ == '__main__': args = parse_arguments() args.run(args)
Use `set_defaults` of subparser to launch scripts
Use `set_defaults` of subparser to launch scripts
Python
mit
DerWeh/pyplot
aac598d64fc0fa50cc068fc50173068e5d89b3fd
segpy/ext/numpyext.py
segpy/ext/numpyext.py
"""Optional interoperability with Numpy.""" import numpy NUMPY_DTYPES = {'ibm': numpy.dtype('f4'), 'l': numpy.dtype('i4'), 'h': numpy.dtype('i2'), 'f': numpy.dtype('f4'), 'b': numpy.dtype('i1')} def make_dtype(data_sample_format): """Convert a SEG Y data sample format to a compatible numpy dtype. Note : IBM float data sample formats ('ibm') will correspond to IEEE float data types. Args: data_sample_format: A data sample format string. Returns: A numpy.dtype instance. Raises: ValueError: For unrecognised data sample format strings. """ try: return NUMPY_DTYPES[data_sample_format] except KeyError: raise ValueError("Unknown data sample format string {!r}".format(data_sample_format))
"""Optional interoperability with Numpy.""" import numpy NUMPY_DTYPES = {'ibm': numpy.dtype('f4'), 'int32': numpy.dtype('i4'), 'int16': numpy.dtype('i2'), 'float32': numpy.dtype('f4'), 'int8': numpy.dtype('i1')} def make_dtype(data_sample_format): """Convert a SEG Y data sample format to a compatible numpy dtype. Note : IBM float data sample formats ('ibm') will correspond to IEEE float data types. Args: data_sample_format: A data sample format string. Returns: A numpy.dtype instance. Raises: ValueError: For unrecognised data sample format strings. """ try: return NUMPY_DTYPES[data_sample_format] except KeyError: raise ValueError("Unknown data sample format string {!r}".format(data_sample_format))
Update numpy dtypes extension for correct type codes.
Update numpy dtypes extension for correct type codes.
Python
agpl-3.0
hohogpb/segpy,stevejpurves/segpy,abingham/segpy,asbjorn/segpy,kjellkongsvik/segpy,Kramer477/segpy,kwinkunks/segpy
2ba28c83de33ebc75f386d127d0c55e17248a94b
mapclientplugins/meshgeneratorstep/__init__.py
mapclientplugins/meshgeneratorstep/__init__.py
""" MAP Client Plugin """ __version__ = '0.2.0' __author__ = 'Richard Christie' __stepname__ = 'Mesh Generator' __location__ = '' # import class that derives itself from the step mountpoint. from mapclientplugins.meshgeneratorstep import step # Import the resource file when the module is loaded, # this enables the framework to use the step icon. from . import resources_rc
""" MAP Client Plugin """ __version__ = '0.2.0' __author__ = 'Richard Christie' __stepname__ = 'Mesh Generator' __location__ = 'https://github.com/ABI-Software/mapclientplugins.meshgeneratorstep' # import class that derives itself from the step mountpoint. from mapclientplugins.meshgeneratorstep import step # Import the resource file when the module is loaded, # this enables the framework to use the step icon. from . import resources_rc
Add location to step metadata.
Add location to step metadata.
Python
apache-2.0
rchristie/mapclientplugins.meshgeneratorstep
fb8c2fb065449a436dd8ffa11b469bb2f22a9ad1
spider.py
spider.py
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1']
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1'] rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']), 'parse_dataset')]
Add web crawling rule and dataset url regex exp
Add web crawling rule and dataset url regex exp
Python
mit
MaxLikelihood/CODE
a8283f5d2c1d970b7b676d491ad8c9472abfe667
boardinghouse/tests/test_template_tag.py
boardinghouse/tests/test_template_tag.py
from django.test import TestCase from .models import AwareModel, NaiveModel from ..templatetags.boardinghouse import * class TestTemplateTags(TestCase): def test_is_schema_aware_filter(self): self.assertTrue(is_schema_aware(AwareModel())) self.assertFalse(is_schema_aware(NaiveModel())) def test_is_shared_model_filter(self): self.assertFalse(is_shared_model(AwareModel())) self.assertTrue(is_shared_model(NaiveModel())) def test_schema_name_filter(self): Schema.objects.create(name='Schema Name', schema='foo') self.assertEquals('Schema Name', schema_name('foo')) self.assertEquals('no schema', schema_name(None)) self.assertEquals('no schema', schema_name('')) self.assertEquals('no schema', schema_name(False)) self.assertEquals('no schema', schema_name('foobar')) self.assertEquals('no schema', schema_name('foo_')) self.assertEquals('no schema', schema_name('foofoo'))
from django.test import TestCase from .models import AwareModel, NaiveModel from ..templatetags.boardinghouse import schema_name, is_schema_aware, is_shared_model from ..models import Schema class TestTemplateTags(TestCase): def test_is_schema_aware_filter(self): self.assertTrue(is_schema_aware(AwareModel())) self.assertFalse(is_schema_aware(NaiveModel())) def test_is_shared_model_filter(self): self.assertFalse(is_shared_model(AwareModel())) self.assertTrue(is_shared_model(NaiveModel())) def test_schema_name_filter(self): Schema.objects.create(name='Schema Name', schema='foo') self.assertEquals('Schema Name', schema_name('foo')) self.assertEquals('no schema', schema_name(None)) self.assertEquals('no schema', schema_name('')) self.assertEquals('no schema', schema_name(False)) self.assertEquals('no schema', schema_name('foobar')) self.assertEquals('no schema', schema_name('foo_')) self.assertEquals('no schema', schema_name('foofoo'))
Fix tests since we changed imports.
Fix tests since we changed imports. --HG-- branch : schema-invitations
Python
bsd-3-clause
schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse
0f49230309ac115ff78eddd36bcd153d7f3b75ea
data_aggregator/threads.py
data_aggregator/threads.py
import queue import threading from multiprocessing import Queue class ThreadPool(): def __init__(self, processes=20): self.processes = processes self.threads = [Thread() for _ in range(0, processes)] self.mp_queue = Queue() def yield_dead_threads(self): for thread in self.threads: if not thread.is_alive(): yield thread def map(self, func, values): completed_count = 0 values_iter = iter(values) while completed_count < len(values): try: self.mp_queue.get_nowait() completed_count += 1 except queue.Empty: pass for thread in self.yield_dead_threads(): try: # run next job job = next(values_iter) thread.run(func, job, self.mp_queue) except StopIteration: break def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): pass class Thread(): def __init__(self): self.thread = None def run(self, target, *args, **kwargs): self.thread = threading.Thread(target=target, args=args, kwargs=kwargs) self.thread.start() def is_alive(self): if self.thread: return self.thread.is_alive() else: return False
import queue import threading from multiprocessing import Queue class ThreadPool(): def __init__(self, processes=20): self.processes = processes self.threads = [Thread() for _ in range(0, processes)] self.mp_queue = Queue() def yield_dead_threads(self): for thread in self.threads: if not thread.is_alive(): yield thread def map(self, func, values): completed_count = 0 values_iter = iter(values) while completed_count < len(values): try: self.mp_queue.get_nowait() completed_count += 1 except queue.Empty: pass for thread in self.yield_dead_threads(): try: # run thread with the next value value = next(values_iter) thread.run(func, value, self.mp_queue) except StopIteration: break def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): pass class Thread(): def __init__(self): self.thread = None def run(self, target, *args, **kwargs): self.thread = threading.Thread(target=target, args=args, kwargs=kwargs) self.thread.start() def is_alive(self): if self.thread: return self.thread.is_alive() else: return False
Remove reference to "job" from ThreadPool
Remove reference to "job" from ThreadPool
Python
apache-2.0
uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics
de962f504db139500573457264a3dd1e257e8cc0
wagtail_mvc/decorators.py
wagtail_mvc/decorators.py
# -*- coding: utf-8 -*- """ wagtail_mvc decorators """ from __future__ import unicode_literals def wagtail_mvc_url(func): """ Decorates an existing method responsible for generating a url prepends the parent url to the generated url to account for :param func: The method to decorate :return: Full url """ def outer(self, *args, **kwargs): parts = self.get_parent().url.split('/') parts += func(self, *args, **kwargs).split('/') return '/{0}/'.format('/'.join([part for part in parts if part])) return outer
# -*- coding: utf-8 -*- """ wagtail_mvc decorators """ from __future__ import unicode_literals def wagtail_mvc_url(*decorator_args, **decorator_kwargs): """ Decorates an existing method responsible for generating a url prepends the parent url to the generated url to account for :param func: The method to decorate :return: Full url """ def decorator(func): def outer(self, *args, **kwargs): parent_attr = decorator_kwargs.get('parent_attr') if parent_attr: parent = getattr(self, parent_attr, None) else: parent = self.get_parent() parts = parent.url.split('/') parts += func(self, *args, **kwargs).split('/') return '/{0}/'.format('/'.join([part for part in parts if part])) return outer if len(decorator_args) == 1 and callable(decorator_args[0]): # We assume the decorator function has not been called # or passed any arguments and return the result of calling # the decorator function return decorator(decorator_args[0]) return decorator
Allow decorator to be called with optional args
Allow decorator to be called with optional args
Python
mit
fatboystring/Wagtail-MVC,fatboystring/Wagtail-MVC
fe676a041b793f55d33bfd27eb2b4fdfe7d93bb6
twilio/rest/resources/pricing/__init__.py
twilio/rest/resources/pricing/__init__.py
from .voice import ( Voice, VoiceCountry, VoiceCountries, VoiceNumber, VoiceNumbers, ) from .phone_numbers import ( PhoneNumberCountries, PhoneNumberCountry, PhoneNumbers, )
from twilio.rest.pricing.voice import ( Voice, VoiceCountry, VoiceCountries, VoiceNumber, VoiceNumbers, ) from twilio.rest.pricing.phone_number import ( PhoneNumberCountries, PhoneNumberCountry, PhoneNumber, )
Change import path for pricing
Change import path for pricing
Python
mit
tysonholub/twilio-python,twilio/twilio-python
0e779581be648ca80eea6b97f9963606d85659b9
opensfm/commands/__init__.py
opensfm/commands/__init__.py
import extract_metadata import detect_features import match_features import create_tracks import reconstruct import mesh import undistort import compute_depthmaps import export_ply import export_openmvs opensfm_commands = [ extract_metadata, detect_features, match_features, create_tracks, reconstruct, mesh, undistort, compute_depthmaps, export_ply, export_openmvs, ]
import extract_metadata import detect_features import match_features import create_tracks import reconstruct import mesh import undistort import compute_depthmaps import export_ply import export_openmvs import export_visualsfm opensfm_commands = [ extract_metadata, detect_features, match_features, create_tracks, reconstruct, mesh, undistort, compute_depthmaps, export_ply, export_openmvs, export_visualsfm, ]
Add exporter to VisualSfM format
Add exporter to VisualSfM format
Python
bsd-2-clause
BrookRoberts/OpenSfM,mapillary/OpenSfM,sunbingfengPI/OpenSFM_Test,BrookRoberts/OpenSfM,sunbingfengPI/OpenSFM_Test,sunbingfengPI/OpenSFM_Test,sunbingfengPI/OpenSFM_Test,oscarlorentzon/OpenSfM,BrookRoberts/OpenSfM,oscarlorentzon/OpenSfM,oscarlorentzon/OpenSfM,oscarlorentzon/OpenSfM,mapillary/OpenSfM,mapillary/OpenSfM,BrookRoberts/OpenSfM,BrookRoberts/OpenSfM,mapillary/OpenSfM,mapillary/OpenSfM,sunbingfengPI/OpenSFM_Test,oscarlorentzon/OpenSfM
416575ca3cc684925be0391b43b98a9fa1d9f909
ObjectTracking/testTrack.py
ObjectTracking/testTrack.py
from SimpleCV import ColorSegmentation, Image, Camera, VirtualCamera, Display # Open reference video cam=VirtualCamera('/media/bat/DATA/Baptiste/Nautilab/kite_project/zenith-wind-power-read-only/KiteControl-Qt/videos/kiteFlying.avi','video') # Select reference image img=cam.getFrame(50) modelImage = img.crop(255, 180, 70, 20) modelImage = Image('kite_detail.jpg') ts = [] disp=Display() for i in range(0,50): img = cam.getImage() while (disp.isNotDone()): img = cam.getImage() bb = (255, 180, 70, 20) ts = img.track("camshift",ts,modelImage,bb, num_frames = 1) # now here in first loop iteration since ts is empty, # img0 and bb will be considered. # New tracking object will be created and added in ts (TrackSet) # After first iteration, ts is not empty and hence the previous # image frames and bounding box will be taken from ts and img0 # and bb will be ignored. ts.drawPath() img.show()
from SimpleCV import ColorSegmentation, Image, Camera, VirtualCamera, Display, Color # Open reference video cam=VirtualCamera('/media/bat/DATA/Baptiste/Nautilab/kite_project/zenith-wind-power-read-only/KiteControl-Qt/videos/kiteFlying.avi','video') # Select reference image img=cam.getFrame(50) modelImage = img.crop(255, 180, 70, 20) modelImage = Image('kite_detail.jpg') ts = [] disp=Display() for i in range(0,50): img = cam.getImage() while (disp.isNotDone()): img = cam.getImage() bb = (255, 180, 70, 20) ts = img.track("camshift",ts,modelImage,bb, num_frames = 1) modelImage = Image('kite_detail.jpg') # now here in first loop iteration since ts is empty, # img0 and bb will be considered. # New tracking object will be created and added in ts (TrackSet) # After first iteration, ts is not empty and hence the previous # image frames and bounding box will be taken from ts and img0 # and bb will be ignored. ts.draw() ts.drawBB() ts.showCoordinates() img.show()
Save the image of the selection (to be able to reinitialise later)
Save the image of the selection (to be able to reinitialise later)
Python
mit
baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite
a0ac251bec891a6c511ea1c0b11faa6525b81545
bfg9000/languages.py
bfg9000/languages.py
ext2lang = { '.cpp': 'c++', '.c': 'c', }
ext2lang = { '.c' : 'c', '.cpp': 'c++', '.cc' : 'c++', '.cp' : 'c++', '.cxx': 'c++', '.CPP': 'c++', '.c++': 'c++', '.C' : 'c++', }
Support more C++ extensions by default
Support more C++ extensions by default
Python
bsd-3-clause
jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000
0788aaf316a2b200c5283fe9f5f902a8da701403
calexicon/internal/tests/test_julian.py
calexicon/internal/tests/test_julian.py
import unittest from calexicon.internal.julian import distant_julian_to_gregorian class TestJulian(unittest.TestCase): def test_distant_julian_to_gregorian(self): self.assertEqual(distant_julian_to_gregorian(9999, 12, 1), (10000, 2, 12))
import unittest from calexicon.internal.julian import distant_julian_to_gregorian, julian_to_gregorian class TestJulian(unittest.TestCase): def test_distant_julian_to_gregorian(self): self.assertEqual(distant_julian_to_gregorian(9999, 12, 1), (10000, 2, 12)) def test_julian_to_gregorian(self): self.assertEqual(julian_to_gregorian(1984, 2, 29), (1984, 3, 13))
Add a test for julian_to_gregorian.
Add a test for julian_to_gregorian.
Python
apache-2.0
jwg4/qual,jwg4/calexicon
7f1542bc52438e6c9796e776603553d7f5a9df7f
pySpatialTools/utils/util_classes/__init__.py
pySpatialTools/utils/util_classes/__init__.py
""" Util classes ------------ Classes which represent data types useful for the package pySpatialTools. """ from spdesc_mapper import Sp_DescriptorMapper from spatialelements import SpatialElementsCollection, Locations from Membership import Membership from general_mapper import General1_1Mapper from mapper_vals_i import Map_Vals_i, create_mapper_vals_i
""" Util classes ------------ Classes which represent data types useful for the package pySpatialTools. """ from spdesc_mapper import Sp_DescriptorMapper from spatialelements import SpatialElementsCollection, Locations from Membership import Membership from mapper_vals_i import Map_Vals_i, create_mapper_vals_i
Debug in importing deleted module.
Debug in importing deleted module.
Python
mit
tgquintela/pySpatialTools,tgquintela/pySpatialTools
62a76827ecf7c148101b62925dea04f63709012a
sublime/User/update_user_settings.py
sublime/User/update_user_settings.py
import json import urllib2 import sublime import sublime_plugin GIST_URL = u'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa class UpdateUserSettingsCommand(sublime_plugin.TextCommand): def run(self, edit): gist_settings = self._get_settings_from_gist(GIST_URL) sublime_settings = sublime.load_settings( 'Preferences.sublime-settings' ) self._update_settings(gist_settings, sublime_settings) @staticmethod def _get_settings_from_gist(url): try: response = urllib2.urlopen(url) settings = json.loads(response.read()) except (urllib2.URLError, ValueError) as e: sublime.error_message('Could not retrieve settings: {}'.format(e)) raise return settings @staticmethod def _update_settings(settings_dict, sublime_settings): for key, value in settings_dict.items(): sublime_settings.set(key, value) sublime.save_settings('Preferences.sublime-settings') sublime.status_message('Settings updated')
import json import urllib import sublime import sublime_plugin GIST_URL = 'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa class UpdateUserSettingsCommand(sublime_plugin.TextCommand): def run(self, edit): gist_settings = self._get_settings_from_gist(GIST_URL) sublime_settings = sublime.load_settings( 'Preferences.sublime-settings' ) self._update_settings(gist_settings, sublime_settings) @staticmethod def _get_settings_from_gist(url): try: response = urllib.request.urlopen(url) settings = json.loads(response.read().decode('utf-8')) except (urllib.error.URLError, ValueError) as e: sublime.error_message('Could not retrieve settings: {}'.format(e)) raise return settings @staticmethod def _update_settings(settings_dict, sublime_settings): for key, value in settings_dict.items(): sublime_settings.set(key, value) sublime.save_settings('Preferences.sublime-settings') sublime.status_message('Settings updated')
Update command to work with sublime 3
Update command to work with sublime 3
Python
apache-2.0
RomuloOliveira/dot-files,RomuloOliveira/unix-files,RomuloOliveira/dot-files
0ba9fa847a8b605363b298ecad40cb2fc5870cbb
build_modules.py
build_modules.py
import os, sys, subprocess, shutil def check_for_module_builder(): if os.path.exists("voxel_native/scripts/"): return print("Downloading P3DModuleBuilder...") cmd = [sys.executable, "-B", "voxel_native/download_P3DModuleBuilder.py"] try: output = subprocess.check_output(cmd, stderr=sys.stderr) except subprocess.CalledProcessError as errorMsg: print(errorMsg) print("Couldn't download P3DModuleBuilder.") sys.exit(-1) def build_modules(): print("Building native modules...") check_for_module_builder() cmd = [sys.executable, "-B", "-m", "voxel_native.build"] try: output = subprocess.run(cmd, stderr=sys.stderr, stdout=sys.stdout, check=True) except subprocess.CalledProcessError as errorMsg: print(errorMsg) print("Error building the native modules.") sys.exit(-1) shutil.move("voxel_native/voxel_native.pyd", "voxel/voxel_native.pyd") if __name__ == "__main__": build_modules()
import os, sys, subprocess, shutil def check_for_module_builder(): if os.path.exists("voxel_native/scripts/"): return print("Downloading P3DModuleBuilder...") cmd = [sys.executable, "-B", "voxel_native/download_P3DModuleBuilder.py"] try: output = subprocess.check_output(cmd, stderr=sys.stderr) except subprocess.CalledProcessError as errorMsg: print(errorMsg) print("Couldn't download P3DModuleBuilder.") sys.exit(-1) def build_modules(): print("Building native modules...") check_for_module_builder() cmd = [sys.executable, "-B", "-m", "voxel_native.build"] try: output = subprocess.run(cmd, stderr=sys.stderr, stdout=sys.stdout, check=True) except subprocess.CalledProcessError as errorMsg: print(errorMsg) print("Error building the native modules.") sys.exit(-1) from voxel_native.scripts.common import is_macos, is_windows, is_linux if is_windows(): shutil.move("voxel_native/voxel_native.pyd", "voxel/voxel_native.pyd") elif is_macos() or is_linux(): shutil.move("voxel_native/voxel_native.so", "voxel/voxel_native.so") if __name__ == "__main__": build_modules()
Update build script to work correctly on macOS and linux.
Update build script to work correctly on macOS and linux.
Python
mit
treamology/panda3d-voxels,treamology/panda3d-voxels,treamology/panda3d-voxels
115a71995f2ceae667c05114da8e8ba21c25c402
syncplay/__init__.py
syncplay/__init__.py
version = '1.6.5' revision = ' release' milestone = 'Yoitsu' release_number = '86' projectURL = 'https://syncplay.pl/'
version = '1.6.6' revision = ' development' milestone = 'Yoitsu' release_number = '87' projectURL = 'https://syncplay.pl/'
Move to 1.6.6 dev for further development
Move to 1.6.6 dev for further development
Python
apache-2.0
alby128/syncplay,alby128/syncplay,Syncplay/syncplay,Syncplay/syncplay
d6b1f7c03ec2b32823fe2c4214e6521e8074cd9f
commands/join.py
commands/join.py
from CommandTemplate import CommandTemplate from IrcMessage import IrcMessage class Command(CommandTemplate): triggers = ['join'] helptext = "Makes me join another channel, if I'm allowed to at least" def execute(self, message): """ :type message: IrcMessage """ replytext = u"" if message.messagePartsLength < 1: replytext = u"Please provide a channel for me to join" else: allowedChannels = message.bot.factory.settings.get('connection', 'allowedChannels').split(',') channel = message.messageParts[0] if channel.startswith('#'): channel = channel[1:] if channel not in allowedChannels and not message.bot.factory.isUserAdmin(message.user): replytext = u"I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission" else: channel = '#' + channel replytext = u"All right, I'll go to {}. See you there!".format(channel) message.bot.join(channel) message.bot.say(message.source, replytext)
from CommandTemplate import CommandTemplate from IrcMessage import IrcMessage class Command(CommandTemplate): triggers = ['join'] helptext = "Makes me join another channel, if I'm allowed to at least" def execute(self, message): """ :type message: IrcMessage """ replytext = u"" if message.messagePartsLength < 1: replytext = u"Please provide a channel for me to join" else: allowedChannels = message.bot.factory.settings.get('connection', 'allowedChannels').split(',') channel = message.messageParts[0].encode('utf8') #Make sure it's a str and not unicode, otherwise Twisted chokes on it if channel.startswith('#'): channel = channel[1:] if channel not in allowedChannels and not message.bot.factory.isUserAdmin(message.user): replytext = u"I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission" else: channel = '#' + channel replytext = u"All right, I'll go to {}. See you there!".format(channel) message.bot.join(channel) message.bot.say(message.source, replytext)
Make sure the 'channel' argument is not Unicode when we send it, because Twisted doesn't like that
[Join] Make sure the 'channel' argument is not Unicode when we send it, because Twisted doesn't like that
Python
mit
Didero/DideRobot
521e24fa115e69bca39d7cca89ce42e8efa3b077
tools/perf_expectations/PRESUBMIT.py
tools/perf_expectations/PRESUBMIT.py
#!/usr/bin/python # Copyright (c) 2009 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. """Presubmit script for perf_expectations. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for details on the presubmit API built into gcl. """ UNIT_TESTS = [ 'tests.perf_expectations_unittest', ] PERF_EXPECTATIONS = 'perf_expectations.json' def CheckChangeOnUpload(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == input_api.os_path.basename(path): run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) return output def CheckChangeOnCommit(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == input_api.os_path.basename(path): run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) output.extend(input_api.canned_checks.CheckDoNotSubmit(input_api, output_api)) return output
#!/usr/bin/python # Copyright (c) 2009 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. """Presubmit script for perf_expectations. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for details on the presubmit API built into gcl. """ UNIT_TESTS = [ 'tests.perf_expectations_unittest', ] PERF_EXPECTATIONS = 'tools/perf_expectations/perf_expectations.json' def CheckChangeOnUpload(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == path: run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) return output def CheckChangeOnCommit(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == path: run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) output.extend(input_api.canned_checks.CheckDoNotSubmit(input_api, output_api)) return output
Use full pathname to perf_expectations in test.
Use full pathname to perf_expectations in test. BUG=none TEST=none Review URL: http://codereview.chromium.org/266055 git-svn-id: http://src.chromium.org/svn/trunk/src@28770 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: f9d8e0a8dae19e482d3c435a76b4e38403e646b5
Python
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
b326d43a94058390a559c4c9f55e9cd88dcac747
adhocracy4/emails/mixins.py
adhocracy4/emails/mixins.py
from email.mime.image import MIMEImage from django.contrib.staticfiles import finders from .base import EmailBase class PlatformEmailMixin: """ Attaches the static file images/logo.png so it can be used in an html email. """ def get_attachments(self): attachments = super().get_attachments() filename = ( finders.find('images/email_logo.png') or finders.find('images/email_logo.svg') ) if filename: with open(filename, 'rb') as f: logo = MIMEImage(f.read()) logo.add_header('Content-ID', '<{}>'.format('logo')) return attachments + [logo] return attachments class SyncEmailMixin(EmailBase): """Send Emails synchronously.""" @classmethod def send(cls, object, *args, **kwargs): """Call dispatch immediately""" return cls().dispatch(object, *args, **kwargs)
from email.mime.image import MIMEImage from django.contrib.staticfiles import finders from .base import EmailBase class PlatformEmailMixin: """ Attaches the static file images/logo.png so it can be used in an html email. """ def get_attachments(self): attachments = super().get_attachments() filename = ( finders.find('images/email_logo.png') or finders.find('images/email_logo.svg') ) if filename: if filename.endswith('.png'): imagetype = 'png' else: imagetype = 'svg+xml' with open(filename, 'rb') as f: logo = MIMEImage(f.read(), imagetype) logo.add_header('Content-ID', '<{}>'.format('logo')) return attachments + [logo] return attachments class SyncEmailMixin(EmailBase): """Send Emails synchronously.""" @classmethod def send(cls, object, *args, **kwargs): """Call dispatch immediately""" return cls().dispatch(object, *args, **kwargs)
Set propper mimetype for image attachment
Set propper mimetype for image attachment
Python
agpl-3.0
liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4
12cf7d220408971509b57cb3a60f2d87b4a37477
facebook_auth/models.py
facebook_auth/models.py
from uuid import uuid1 from django.conf import settings from django.contrib.auth import models as auth_models from django.db import models import facepy import simplejson from facebook_auth import utils class FacebookUser(auth_models.User): user_id = models.BigIntegerField(unique=True) access_token = models.TextField(blank=True, null=True) app_friends = models.ManyToManyField('self') @property def graph(self): return facepy.GraphAPI(self.access_token) @property def js_session(self): return simplejson.dumps({ 'access_token': self.access_token, 'uid': self.user_id }) @property def friends(self): return utils.get_from_graph_api(self.graph, "me/friends")['data'] def update_app_friends(self): friends = self.friends friends_ids = [f['id'] for f in friends] self.app_friends.clear() self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids)) def get_auth_address(request, redirect_to, scope=''): state = unicode(uuid1()) request.session['state'] = state return 'https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s&scope=%s&state=%s' % ( settings.FACEBOOK_APP_ID, redirect_to, scope, state )
from django.contrib.auth import models as auth_models from django.db import models import facepy import simplejson from facebook_auth import utils class FacebookUser(auth_models.User): user_id = models.BigIntegerField(unique=True) access_token = models.TextField(blank=True, null=True) app_friends = models.ManyToManyField('self') @property def graph(self): return facepy.GraphAPI(self.access_token) @property def js_session(self): return simplejson.dumps({ 'access_token': self.access_token, 'uid': self.user_id }) @property def friends(self): return utils.get_from_graph_api(self.graph, "me/friends")['data'] def update_app_friends(self): friends = self.friends friends_ids = [f['id'] for f in friends] self.app_friends.clear() self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
Revert "Add support for server side authentication."
Revert "Add support for server side authentication." This reverts commit 10ae930f6f14c2840d0b87cbec17054b4cc318d2. Change-Id: Ied52c31f6f28ad635a6e5dae2171df22dc91e42c Reviewed-on: http://review.pozytywnie.pl:8080/5153 Reviewed-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com> Tested-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com>
Python
mit
jgoclawski/django-facebook-auth,pozytywnie/django-facebook-auth,pozytywnie/django-facebook-auth,jgoclawski/django-facebook-auth
4378aef47a7e2b80a4a22af2bbe69ce4b780ab6d
pokr/views/login.py
pokr/views/login.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- from flask import g, render_template, redirect, request, url_for from flask.ext.login import current_user, login_required, logout_user from social.apps.flask_app.template_filters import backends def register(app): @login_required @app.route('/done/') def done(): return redirect(request.referrer or url_for('main')) @app.route('/logout') def logout(): logout_user() return redirect(request.referrer or url_for('main')) @app.before_request def global_user(): g.user = current_user @app.context_processor def inject_user(): user = getattr(g, 'user') return { 'user': user, 'is_logged': user and not user.is_anonymous() } app.context_processor(backends)
#!/usr/bin/env python # -*- encoding: utf-8 -*- from flask import g, render_template, redirect, request, url_for from flask.ext.login import current_user, login_required, logout_user from social.apps.flask_app.template_filters import backends def register(app): @login_required @app.route('/done/') def done(): return redirect(request.referrer or url_for('main')) @app.route('/logout') def logout(): logout_user() return redirect(request.referrer or url_for('main')) @app.before_request def global_user(): g.user = current_user @app.context_processor def inject_user(): user = getattr(g, 'user') return { 'user': user, 'is_logged': user and user.is_authenticated } app.context_processor(backends)
Fix due to Flask-Login version up
Fix due to Flask-Login version up
Python
apache-2.0
teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr
f935eb48517627df679605aaee834165380d74db
django_db_geventpool/backends/postgresql_psycopg2/creation.py
django_db_geventpool/backends/postgresql_psycopg2/creation.py
# coding=utf-8 import django from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation as OriginalDatabaseCreation class DatabaseCreationMixin16(object): def _create_test_db(self, verbosity, autoclobber): self.connection.closeall() return super(DatabaseCreationMixin16, self)._create_test_db(verbosity, autoclobber) def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() return super(DatabaseCreationMixin16, self)._destroy_test_db(test_database_name, verbosity) class DatabaseCreationMixin17(object): def _create_test_db(self, verbosity, autoclobber, keepdb=False): self.connection.closeall() return super(DatabaseCreationMixin17, self)._create_test_db(verbosity, autoclobber, keepdb) def _destroy_test_db(self, test_database_name, verbosity, keepdb=False): self.connection.closeall() return super(DatabaseCreationMixin17, self)._destroy_test_db(test_database_name, verbosity, keepdb) if django.VERSION >= (1, 7): class DatabaseCreationMixin(DatabaseCreationMixin17): pass else: class DatabaseCreationMixin(DatabaseCreationMixin16): pass class DatabaseCreation(DatabaseCreationMixin, OriginalDatabaseCreation): pass
# coding=utf-8 import django from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation as OriginalDatabaseCreation class DatabaseCreationMixin16(object): def _create_test_db(self, verbosity, autoclobber): self.connection.closeall() return super(DatabaseCreationMixin16, self)._create_test_db(verbosity, autoclobber) def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() return super(DatabaseCreationMixin16, self)._destroy_test_db(test_database_name, verbosity) class DatabaseCreationMixin17(object): def _create_test_db(self, verbosity, autoclobber): self.connection.closeall() return super(DatabaseCreationMixin17, self)._create_test_db(verbosity, autoclobber) def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() return super(DatabaseCreationMixin17, self)._destroy_test_db(test_database_name, verbosity) if django.VERSION >= (1, 7): class DatabaseCreationMixin(DatabaseCreationMixin17): pass else: class DatabaseCreationMixin(DatabaseCreationMixin16): pass class DatabaseCreation(DatabaseCreationMixin, OriginalDatabaseCreation): pass
Fix DatabaseCreation from django 1.7
Fix DatabaseCreation from django 1.7
Python
apache-2.0
jneight/django-db-geventpool,PreppyLLC-opensource/django-db-geventpool
385655debed235fcb32e70a3f506a6885f3e4e67
c2cgeoportal/views/echo.py
c2cgeoportal/views/echo.py
from base64 import b64encode import os.path import re from pyramid.httpexceptions import HTTPBadRequest from pyramid.response import Response from pyramid.view import view_config def json_base64_encode_chunks(file, chunk_size=65536): """ Generate a JSON-wrapped base64-encoded string. See http://en.wikipedia.org/wiki/Base64 """ yield '{"data":"' while True: line = file.read(chunk_size) if not line: break yield b64encode(line) yield '"}' @view_config(route_name='echo') def echo(request): """ Echo an uploaded file back to the client as an text/html document so it can be handled by Ext. The response is JSON-wrapped and base64-encoded to ensure that there are no special HTML characters or charset problems and so that braindead ext doesn't barf on it. We use an iterator to avoid loading the whole file into memory. See http://docs.sencha.com/ext-js/3-4/#!/api/Ext.form.BasicForm-cfg-fileUpload """ if request.method != 'POST': raise HTTPBadRequest() try: file = request.POST['file'] except KeyError: raise HTTPBadRequest() response = Response() response.app_iter = json_base64_encode_chunks(file.file) response.content_type = 'text/html' return response
from base64 import b64encode import os.path import re from pyramid.httpexceptions import HTTPBadRequest from pyramid.response import Response from pyramid.view import view_config def json_base64_encode_chunks(file, chunk_size=65536): """ Generate a JSON-wrapped base64-encoded string. See http://en.wikipedia.org/wiki/Base64 """ yield '{"data":"' while True: line = file.read(chunk_size) if not line: break yield b64encode(line) yield '","success":true}' @view_config(route_name='echo') def echo(request): """ Echo an uploaded file back to the client as an text/html document so it can be handled by Ext. The response is JSON-wrapped and base64-encoded to ensure that there are no special HTML characters or charset problems and so that braindead ext doesn't barf on it. We use an iterator to avoid loading the whole file into memory. See http://docs.sencha.com/ext-js/3-4/#!/api/Ext.form.BasicForm-cfg-fileUpload """ if request.method != 'POST': raise HTTPBadRequest() try: file = request.POST['file'] except KeyError: raise HTTPBadRequest() response = Response() response.app_iter = json_base64_encode_chunks(file.file) response.content_type = 'text/html' return response
Add success=true to satisfy Ext
Add success=true to satisfy Ext
Python
bsd-2-clause
tsauerwein/c2cgeoportal,tsauerwein/c2cgeoportal,tsauerwein/c2cgeoportal,tsauerwein/c2cgeoportal
c1d889f637d6d2a931f81332a9eef3974dfa18e0
code/marv/marv/__init__.py
code/marv/marv/__init__.py
# Copyright 2016 - 2018 Ternaris. # SPDX-License-Identifier: AGPL-3.0-only import sys from pkg_resources import iter_entry_points from marv_node.io import Abort from marv_node.io import create_group from marv_node.io import create_stream from marv_node.io import fork from marv_node.io import get_logger from marv_node.io import get_requested from marv_node.io import get_stream from marv_node.io import make_file from marv_node.io import pull from marv_node.io import pull_all from marv_node.io import push from marv_node.io import set_header from marv_node.node import input, node from marv_node.tools import select from marv_webapi.tooling import api_endpoint from marv_webapi.tooling import api_group __all__ = [ 'Abort', 'api_endpoint', 'api_group', 'create_group', 'create_stream', 'fork', 'get_logger', 'get_requested', 'get_stream', 'input', 'make_file', 'node', 'pull', 'pull_all', 'push', 'select', 'set_header', ] MODULE = sys.modules[__name__] for ep in iter_entry_points(group='marv_deco'): assert not hasattr(MODULE, ep.name) setattr(MODULE, ep.name, ep.load()) del MODULE
# Copyright 2016 - 2018 Ternaris. # SPDX-License-Identifier: AGPL-3.0-only from marv_node.io import Abort from marv_node.io import create_group from marv_node.io import create_stream from marv_node.io import fork from marv_node.io import get_logger from marv_node.io import get_requested from marv_node.io import get_stream from marv_node.io import make_file from marv_node.io import pull from marv_node.io import pull_all from marv_node.io import push from marv_node.io import set_header from marv_node.node import input, node from marv_node.tools import select from marv_webapi.tooling import api_endpoint from marv_webapi.tooling import api_group __all__ = [ 'Abort', 'api_endpoint', 'api_group', 'create_group', 'create_stream', 'fork', 'get_logger', 'get_requested', 'get_stream', 'input', 'make_file', 'node', 'pull', 'pull_all', 'push', 'select', 'set_header', ]
Drop unused support to add decorators via entry points
Drop unused support to add decorators via entry points
Python
agpl-3.0
ternaris/marv-robotics,ternaris/marv-robotics
4c52b8f63fea11278536ec6800305b01d9bd02a8
blazar/plugins/dummy_vm_plugin.py
blazar/plugins/dummy_vm_plugin.py
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from blazar.plugins import base class DummyVMPlugin(base.BasePlugin): """Plugin for VM resource that does nothing.""" resource_type = 'virtual:instance' title = 'Dummy VM Plugin' description = 'This plugin does nothing.' def reserve_resource(self, reservation_id, values): return None def on_start(self, resource_id): """Dummy VM plugin does nothing.""" return 'VM %s should be waked up this moment.' % resource_id def on_end(self, resource_id): """Dummy VM plugin does nothing.""" return 'VM %s should be deleted this moment.' % resource_id
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from blazar.plugins import base class DummyVMPlugin(base.BasePlugin): """Plugin for VM resource that does nothing.""" resource_type = 'virtual:instance' title = 'Dummy VM Plugin' description = 'This plugin does nothing.' def reserve_resource(self, reservation_id, values): return None def update_reservation(self, reservation_id, values): return None def on_start(self, resource_id): """Dummy VM plugin does nothing.""" return 'VM %s should be waked up this moment.' % resource_id def on_end(self, resource_id): """Dummy VM plugin does nothing.""" return 'VM %s should be deleted this moment.' % resource_id
Add update_reservation to dummy plugin
Add update_reservation to dummy plugin update_reservation is now an abstract method. It needs to be added to all plugins. Change-Id: I921878bd5233613b804b17813af1aac5bdfed9e7 (cherry picked from commit 1dbc30202bddfd4f03bdc9a8005de3c363d2ac1d)
Python
apache-2.0
ChameleonCloud/blazar,ChameleonCloud/blazar
157197b330360ccfeaa0bbf54453702ee17d0106
Code/Python/Kamaelia/Kamaelia/Device/__init__.py
Code/Python/Kamaelia/Kamaelia/Device/__init__.py
# Needed to allow import # # Copyright (C) 2006 British Broadcasting Corporation and Kamaelia Contributors(1) # All Rights Reserved. # # You may only modify and redistribute this under the terms of any of the # following licenses(2): Mozilla Public License, V1.1, GNU General # Public License, V2.0, GNU Lesser General Public License, V2.1 # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://kamaelia.sourceforge.net/AUTHORS - please extend this file, # not this notice. # (2) Reproduced in the COPYING file, and at: # http://kamaelia.sourceforge.net/COPYING # Under section 3.5 of the MPL, we are using this text since we deem the MPL # notice inappropriate for this file. As per MPL/GPL/LGPL removal of this # notice is prohibited. # # Please contact us via: kamaelia-list-owner@lists.sourceforge.net # to discuss alternative licensing. # ------------------------------------------------------------------------- """ This is a doc string, will it be of use? """ # RELEASE: MH, MPS
# -*- coding: utf-8 -*- # Needed to allow import # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # 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. # ------------------------------------------------------------------------- """ This is a doc string, will it be of use? """ # RELEASE: MH, MPS
Change license to Apache 2
Change license to Apache 2
Python
apache-2.0
sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia
6f60f6257cbcd0328fcdb0873d88d55772731ba4
api/app.py
api/app.py
from flask import Flask from flask import request from flask import jsonify from y_text_recommender_system.recommender import recommend app = Flask(__name__) class InvalidUsage(Exception): status_code = 400 def __init__(self, message, payload=None): Exception.__init__(self) self.message = message self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response @app.route('/recommender/', methods=['POST']) def recommender(): content = request.get_json() if content is not None: doc = content.get('doc', {}) docs = content.get('docs', []) if doc == {}: msg = 'The parameter `doc` is missing or empty' raise InvalidUsage(msg) if len(docs) == 0: msg = 'The parameter `docs` is missing or empty' raise InvalidUsage(msg) result = recommend(doc, docs) return jsonify(result) else: msg = 'You need to send the parameters: doc and docs' raise InvalidUsage(msg)
from flask import Flask from flask import request from flask import jsonify from y_text_recommender_system.recommender import recommend app = Flask(__name__) class InvalidUsage(Exception): status_code = 400 def __init__(self, message, payload=None): Exception.__init__(self) self.message = message self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response @app.route('/recommender/', methods=['POST']) def recommender(): content = request.get_json() if content is not None: doc = content.get('doc', {}) docs = content.get('docs', []) _verify_parameters(doc, docs) result = recommend(doc, docs) return jsonify(result) else: msg = 'You need to send the parameters: doc and docs' raise InvalidUsage(msg) def _verify_parameters(doc, docs): if doc == {}: msg = 'The parameter `doc` is missing or empty' raise InvalidUsage(msg) if len(docs) == 0: msg = 'The parameter `docs` is missing or empty' raise InvalidUsage(msg)
Refactor to separate the function to clean the data
Refactor to separate the function to clean the data
Python
mit
joaojunior/y_text_recommender_system
7785d3129d089ce99aee340b3a72fd78d7e8f556
send.py
send.py
import os sender = str(raw_input("Your Username: ")) target = str(raw_input("Target's Username: ")) message = str(raw_input("Message: ")) #Messages are encoded like so "senderProgramVx.x##target##sender##message" #Example: "linuxV1.8##person87##NickGeek##Hey mate! What do you think of this WiN thing?" formattedMessage = "linuxVpre.release##"+target+"##"+sender+"##"+message #Write to file messageFile = open('msg.txt', 'w+') messageFile.write(formattedMessage) messageFile.close() os.system("python server.py")
import os if os.path.exists("account.conf") is False: sender = str(raw_input("Your Username: ")) accountFile = open('account.conf', 'w+') accountFile.write(sender) accountFile.close() else: accountFile = open('account.conf', 'r') sender = accountFile.read() accountFile.close() target = str(raw_input("Target's Username: ")) message = str(raw_input("Message: ")) #Messages are encoded like so "senderProgramVx.x##target##sender##message" #Example: "linuxV1.8##person87##NickGeek##Hey mate! What do you think of this WiN thing?" formattedMessage = "linuxVpre.release##"+target+"##"+sender+"##"+message #Write to file messageFile = open('msg.txt', 'w+') messageFile.write(formattedMessage) messageFile.close() os.system("python server.py")
Store your username in a file
Store your username in a file
Python
mit
NickGeek/WiN,NickGeek/WiN,NickGeek/WiN
42e4f42901872433f90dd84d5acf04fec76ab7f3
curious/commands/exc.py
curious/commands/exc.py
class CommandsError(Exception): pass class CheckFailureError(Exception): def __init__(self, ctx, check): self.ctx = ctx self.check = check def __repr__(self): if isinstance(self.check, list): return "The checks for {.name} failed.".format(self.ctx) return "The check {.__name__} for {.name} failed.".format(self.check, self.ctx) __str__ = __repr__ class MissingArgumentError(Exception): def __init__(self, ctx, arg): self.ctx = ctx self.arg = arg def __repr__(self): return "Missing required argument {} in {.name}.".format(self.arg, self.ctx) __str__ = __repr__ class CommandInvokeError(Exception): def __init__(self, ctx): self.ctx = ctx def __repr__(self): return "Command {.name} failed to invoke with error {}".format(self.ctx, self.__cause__) __str__ = __repr__ class ConversionFailedError(Exception): def __init__(self, ctx, arg: str, to_type: type): self.ctx = ctx self.arg = arg self.to_type = to_type def __repr__(self): return "Cannot convert {} to type {.__name__}".format(self.arg, self.to_type) __str__ = __repr__
class CommandsError(Exception): pass class CheckFailureError(Exception): def __init__(self, ctx, check): self.ctx = ctx self.check = check def __repr__(self): if isinstance(self.check, list): return "The checks for `{.name}` failed.".format(self.ctx) return "The check `{.__name__}` for `{.name}` failed.".format(self.check, self.ctx) __str__ = __repr__ class MissingArgumentError(Exception): def __init__(self, ctx, arg): self.ctx = ctx self.arg = arg def __repr__(self): return "Missing required argument `{}` in `{.name}`.".format(self.arg, self.ctx) __str__ = __repr__ class CommandInvokeError(Exception): def __init__(self, ctx): self.ctx = ctx def __repr__(self): return "Command {.name} failed to invoke with error `{}`.".format(self.ctx, self.__cause__) __str__ = __repr__ class ConversionFailedError(Exception): def __init__(self, ctx, arg: str, to_type: type): self.ctx = ctx self.arg = arg self.to_type = to_type def __repr__(self): return "Cannot convert `{}` to type `{.__name__}`.".format(self.arg, self.to_type) __str__ = __repr__
Add better __repr__s for commands errors.
Add better __repr__s for commands errors.
Python
mit
SunDwarf/curious
d8179c0006fb5b9983898e4cd93ffacfe3fdd54f
caminae/mapentity/templatetags/convert_tags.py
caminae/mapentity/templatetags/convert_tags.py
import urllib from django import template from django.conf import settings register = template.Library() @register.simple_tag def convert_url(request, sourceurl, format='pdf'): fullurl = request.build_absolute_uri(sourceurl) conversion_url = "%s?url=%s&to=%s" % (settings.CONVERSION_SERVER, urllib.quote(fullurl), format) return conversion_url
import urllib from mimetypes import types_map from django import template from django.conf import settings register = template.Library() @register.simple_tag def convert_url(request, sourceurl, format='pdf'): if '/' not in format: extension = '.' + format if not format.startswith('.') else format format = types_map[extension] fullurl = request.build_absolute_uri(sourceurl) conversion_url = "%s?url=%s&to=%s" % (settings.CONVERSION_SERVER, urllib.quote(fullurl), format) return conversion_url
Support conversion format as extension, instead of mimetype
Support conversion format as extension, instead of mimetype
Python
bsd-2-clause
makinacorpus/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,mabhub/Geotrek,GeotrekCE/Geotrek-admin,Anaethelion/Geotrek,johan--/Geotrek,camillemonchicourt/Geotrek,johan--/Geotrek,mabhub/Geotrek,Anaethelion/Geotrek,camillemonchicourt/Geotrek,GeotrekCE/Geotrek-admin,camillemonchicourt/Geotrek,mabhub/Geotrek,mabhub/Geotrek,makinacorpus/Geotrek,Anaethelion/Geotrek,johan--/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek
e853e0137e59314f5101c178c74fd626984c34ac
pygraphc/similarity/LogTextSimilarity.py
pygraphc/similarity/LogTextSimilarity.py
from pygraphc.preprocess.PreprocessLog import PreprocessLog from pygraphc.similarity.StringSimilarity import StringSimilarity from itertools import combinations class LogTextSimilarity(object): """A class for calculating cosine similarity between a log pair. This class is intended for non-graph based clustering method. """ def __init__(self, logtype, logfile): """The constructor of class LogTextSimilarity. Parameters ---------- logtype : str Type for event log, e.g., auth, syslog, etc. logfile : str Log filename. """ self.logtype = logtype self.logfile = logfile def get_cosine_similarity(self): """Get cosine similarity from a pair of log lines in a file. Returns ------- cosine_similarity : dict Dictionary of cosine similarity in non-graph clustering. Key: (log_id1, log_id2), value: cosine similarity distance. """ preprocess = PreprocessLog(self.logtype, self.logfile) preprocess.preprocess_text() events = preprocess.events_text # calculate cosine similarity cosines_similarity = {} for log_pair in combinations(preprocess.loglength, 2): cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'], events[log_pair[1]]['tf-idf'], events[log_pair[0]]['length'], events[log_pair[1]]['length']) return cosines_similarity
from pygraphc.preprocess.PreprocessLog import PreprocessLog from pygraphc.similarity.StringSimilarity import StringSimilarity from itertools import combinations class LogTextSimilarity(object): """A class for calculating cosine similarity between a log pair. This class is intended for non-graph based clustering method. """ def __init__(self, logtype, logs): """The constructor of class LogTextSimilarity. Parameters ---------- logtype : str Type for event log, e.g., auth, syslog, etc. logs : list List of every line of original logs. """ self.logtype = logtype self.logs = logs def get_cosine_similarity(self): """Get cosine similarity from a pair of log lines in a file. Returns ------- cosine_similarity : dict Dictionary of cosine similarity in non-graph clustering. Key: (log_id1, log_id2), value: cosine similarity distance. """ preprocess = PreprocessLog(self.logtype) preprocess.preprocess_text(self.logs) events = preprocess.events_text # calculate cosine similarity cosines_similarity = {} for log_pair in combinations(range(preprocess.loglength), 2): cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'], events[log_pair[1]]['tf-idf'], events[log_pair[0]]['length'], events[log_pair[1]]['length']) return cosines_similarity
Change input from previous processing not from a file
Change input from previous processing not from a file
Python
mit
studiawan/pygraphc