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
703cdca6725438b55bf544962ce0c554598697be
shoop/admin/templatetags/shoop_admin.py
shoop/admin/templatetags/shoop_admin.py
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from bootstrap3.renderers import FormRenderer from django.utils.safestring ...
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from bootstrap3.renderers import FormRenderer from django.utils.safestring ...
Add template helper for datetime fields
Admin: Add template helper for datetime fields Refs SHOOP-1612
Python
agpl-3.0
suutari-ai/shoop,shoopio/shoop,suutari/shoop,jorge-marques/shoop,hrayr-artunyan/shuup,taedori81/shoop,shawnadelic/shuup,shawnadelic/shuup,shawnadelic/shuup,suutari-ai/shoop,shoopio/shoop,taedori81/shoop,akx/shoop,suutari/shoop,akx/shoop,shoopio/shoop,hrayr-artunyan/shuup,suutari-ai/shoop,suutari/shoop,hrayr-artunyan/sh...
ca32941b82f1c723465a480355242b37ca19848c
setup.py
setup.py
from datetime import datetime from distutils.core import setup import os import subprocess if os.path.exists("MANIFEST"): os.unlink("MANIFEST") VERSION = ("11", "06", "0", "alpha", "0") setup( name='armstrong', version=".".join(VERSION), description="Armstrong is an open-source publishing system desi...
from datetime import datetime from distutils.core import setup import os import subprocess if os.path.exists("MANIFEST"): os.unlink("MANIFEST") VERSION = ("11", "06", "0", "alpha", "0") setup( name='armstrong', version=".".join(VERSION), description="Armstrong is an open-source publishing system desi...
Add armstrong.cli to the mix
Add armstrong.cli to the mix
Python
apache-2.0
armstrong/armstrong
6f3b45cd6b5558a7d81472c0298aae7d04f64846
jsonit/utils.py
jsonit/utils.py
import os from django.http import HttpResponse from django.template import RequestContext, loader def ajax_aware_render(request, template_list, extra_context=None, **kwargs): if isinstance(template_list, basestring): template_list = [template_list] if request.is_ajax(): new_template_list = []...
import os from django.http import HttpResponse from django.template import RequestContext, loader def ajax_aware_render(request, template_list, extra_context=None, **kwargs): if isinstance(template_list, basestring): template_list = [template_list] if request.is_ajax(): ajax_template_list = [...
Change the ordering of templates to pick from for the ajax render helper
Change the ordering of templates to pick from for the ajax render helper
Python
bsd-3-clause
lincolnloop/django-jsonit
253e4e9df1b6a6cec7c20bc34a8ccf9423c8018e
scripts/create_neurohdf.py
scripts/create_neurohdf.py
#!/usr/bin/python # Create a project and stack associated HDF5 file with additional # data such as labels, meshes etc. import os.path as op import h5py from contextlib import closing import numpy as np project_id = 1 stack_id = 1 filepath = '/home/stephan/dev/CATMAID/django/hdf5' with closing(h5py.File(op.join(fil...
#!/usr/bin/python # Create a project and stack associated HDF5 file with additional # data such as labels, meshes etc. import os.path as op import h5py from contextlib import closing import numpy as np project_id = 1 stack_id = 2 filepath = '/home/stephan/dev/CATMAID/django/hdf5' with closing(h5py.File(op.join(fil...
Change in coordinates in the NeuroHDF create
Change in coordinates in the NeuroHDF create
Python
agpl-3.0
htem/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,fzadow/CATMAID
f06c7813663dc9ac4bf63601574617acf5d7324d
tests.py
tests.py
from models import AuthenticationError,AuthenticationRequired import trello import unittest import os class TestTrello(unittest.TestCase): def test_login(self): username = os.environ['TRELLO_TEST_USER'] password = os.environ['TRELLO_TEST_PASS'] try: trello.login(username, password) except AuthenticationEr...
from models import AuthenticationError,AuthenticationRequired from trello import Trello import unittest import os class BoardTestCase(unittest.TestCase): def setUp(self): self._trello = Trello(os.environ['TRELLO_TEST_USER'], os.environ['TRELLO_TEST_PASS']) def test01_list_boards(self): print "list boards" se...
Add some more test cases
Add some more test cases
Python
bsd-3-clause
mehdy/py-trello,sarumont/py-trello,nMustaki/py-trello,Wooble/py-trello,ntrepid8/py-trello,WoLpH/py-trello,portante/py-trello,merlinpatt/py-trello,gchp/py-trello
f2ef48c3b1753e4b53b86c1f9d7a3da517a6d136
web/impact/impact/models/utils.py
web/impact/impact/models/utils.py
# MIT License # Copyright (c) 2017 MassChallenge, Inc. import re LABEL_LENGTH = 255 def is_managed(db_table): return False def model_name_to_snake(value): original_model_string = re.findall('[A-Z][^A-Z]*', value) holder = "" for word in original_model_string: holder += word.lower() + "_" ...
# MIT License # Copyright (c) 2017 MassChallenge, Inc. import re from django.utils.text import camel_case_to_spaces LABEL_LENGTH = 255 def is_managed(db_table): return False def model_name_to_snake(value): original_model_string = camel_case_to_spaces(value) new_model_string = original_model_string.rep...
Remove Custom Reegex And Use Django Util For Case Conversion
[AC-5010] Remove Custom Reegex And Use Django Util For Case Conversion This commit uses the django built in to switch from camel case to lower case. Then the loop was removed in favor of replace().
Python
mit
masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api
28bf565f30a6d9b25bd6bc24ce5958a98a106161
mpi/__init__.py
mpi/__init__.py
#! /usr/bin/env python from mpi4py import MPI comm = MPI.COMM_WORLD def get_host(): return MPI.Get_processor_name() def get_rank(): return comm.Get_rank() def finalize(): return MPI.Finalize()
#! /usr/bin/env python from mpi4py import MPI comm = MPI.COMM_WORLD def get_host(): return MPI.Get_processor_name() def get_rank(): return comm.Get_rank() def host_rank_mapping(): """Get host to rank mapping Return dictionary mapping ranks to host """ d = {} for (host, rank) in com...
Add function to get the host-rank mapping of mpi tasks
Add function to get the host-rank mapping of mpi tasks
Python
mit
IanLee1521/utilities
67a5eb0921f746c205e555ae296b6c15e4eb7eab
property_transformation.py
property_transformation.py
from types import UnicodeType, StringType class PropertyMappingFailedException(Exception): pass def get_transformed_properties(source_properties, prop_map): results = {} for key, value in prop_map.iteritems(): if type(value) in (StringType, UnicodeType): if value in source_properties: ...
from types import UnicodeType, StringType class PropertyMappingFailedException(Exception): pass def get_transformed_properties(source_properties, prop_map): results = {} for key, value in prop_map.iteritems(): if type(value) in (StringType, UnicodeType): if value in source_properties: ...
Add support for null values in property mapping
Add support for null values in property mapping
Python
mit
OpenBounds/Processing
71a417d2558776cd29195c1a1b905070a08407b5
proteus/config/__init__.py
proteus/config/__init__.py
import platform if platform.node().startswith('garnet') or platform.node().startswith('copper'): from garnet import * else: from default import *
import os if 'HOSTNAME' in os.environ: if os.environ['HOSTNAME'].startswith('garnet') or os.environ['HOSTNAME'].startswith('copper'): from garnet import * else: from default import *
Correct detection on Garnet/Copper compute nodes
Correct detection on Garnet/Copper compute nodes
Python
mit
erdc/proteus,erdc/proteus,erdc/proteus,erdc/proteus
633c52cf90655981d1adc962d7571d5d67619ccb
genome_designer/genome_finish/contig_display_utils.py
genome_designer/genome_finish/contig_display_utils.py
from collections import namedtuple Junction = namedtuple('Junction', ['ref', 'ref_count', 'contig', 'contig_count']) def get_ref_jbrowse_link(contig, loc): return (contig.parent_reference_genome.get_client_jbrowse_link() + '&loc=' + str(loc)) def decorate_with_link_to_loc(contig, lo...
from collections import namedtuple import settings Junction = namedtuple('Junction', ['ref', 'ref_count', 'contig', 'contig_count']) def get_ref_jbrowse_link(contig, loc): sample_alignment = contig.experiment_sample_to_alignment bam_dataset = sample_alignment.dataset_set.get( type='BWA ...
Include more tracks in jbrowsing of junctions
Include more tracks in jbrowsing of junctions
Python
mit
churchlab/millstone,churchlab/millstone,woodymit/millstone,woodymit/millstone,woodymit/millstone,churchlab/millstone,woodymit/millstone,churchlab/millstone
bbe425da10607692c1aace560b1b61b089137704
frappe/patches/v12_0/rename_events_repeat_on.py
frappe/patches/v12_0/rename_events_repeat_on.py
import frappe from frappe.utils import get_datetime def execute(): weekdays = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] weekly_events = frappe.get_list("Event", filters={"repeat_this_event": 1, "repeat_on": "Every Week"}, fields=["name", "starts_on"]) frappe.reload_doc("desk", ...
import frappe from frappe.utils import get_datetime def execute(): weekdays = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] weekly_events = frappe.get_list("Event", filters={"repeat_this_event": 1, "repeat_on": "Every Week"}, fields=["name", "starts_on"]) frappe.reload_doc("desk", ...
Convert to SQL to set_value
fix: Convert to SQL to set_value
Python
mit
mhbu50/frappe,saurabh6790/frappe,vjFaLk/frappe,almeidapaulopt/frappe,vjFaLk/frappe,frappe/frappe,almeidapaulopt/frappe,vjFaLk/frappe,mhbu50/frappe,mhbu50/frappe,StrellaGroup/frappe,StrellaGroup/frappe,almeidapaulopt/frappe,adityahase/frappe,adityahase/frappe,yashodhank/frappe,almeidapaulopt/frappe,mhbu50/frappe,yashodh...
468f41f0bf734cdbb27dea7b5d910b6234f4c21a
homedisplay/control_milight/management/commands/run_timed.py
homedisplay/control_milight/management/commands/run_timed.py
from control_milight.models import LightAutomation from control_milight.views import update_lightstate from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.utils.timezone import now from ledcontroller import LedController import datetime import redis class Com...
from control_milight.models import LightAutomation from control_milight.views import update_lightstate from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.utils.timezone import now from ledcontroller import LedController import datetime import redis class Com...
Add support for weekend animations
Add support for weekend animations
Python
bsd-3-clause
ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display
18a3b758311174d0be2519789f985d8113438c90
tests/test_dirty_mark.py
tests/test_dirty_mark.py
def test_not_dirty_by_default(nested_config): assert not nested_config.is_dirty() assert not nested_config['a'].is_dirty() def test_set_parent(nested_config): nested_config.root.value += 1 assert nested_config.is_dirty() def test_set_child(nested_config): nested_config.root.a.value += 1 asser...
from confetti import Config def test_not_dirty_by_default(nested_config): assert not nested_config.is_dirty() assert not nested_config['a'].is_dirty() def test_set_parent(nested_config): nested_config.root.value += 1 assert nested_config.is_dirty() def test_set_child(nested_config): nested_con...
Add test for extending not being marked as dirty
Add test for extending not being marked as dirty
Python
bsd-3-clause
vmalloc/confetti
22e41d02d9c877703f21c5121202d295cb5fbcb0
test/swig/canvas.py
test/swig/canvas.py
# RUN: python %s | display-check - import uwhd def main(): version = 1 black_score = 3 white_score = 5 time = 42 mgr = uwhd.GameModelManager() print('# SET-VERSION: %d' % (version,)) print('# SET-STATE: FirstHalf') print('# SET-BLACK: %d' % (black_score,)) print('# SET-WHITE: %d' % (white_score,))...
# RUN: python %s | display-check - import uwhd def main(): version = 1 black_score = 3 white_score = 5 time = 42 # Build a GameModelManager with a known state: mgr = uwhd.GameModelManager() mgr.setGameStateFirstHalf() mgr.setBlackScore(black_score) mgr.setWhiteScore(white_score) mgr.setGameClock(...
Clean up the SWIG test. Add comments. NFC
[tests] Clean up the SWIG test. Add comments. NFC
Python
bsd-3-clause
Navisjon/uwh-display,Navisjon/uwh-display,Navisjon/uwh-display,jroelofs/uwh-display,Navisjon/uwh-display,jroelofs/uwh-display,jroelofs/uwh-display
02d7f2b946293169e3d46f84f50f2fa801a33c95
distarray/tests/test_client.py
distarray/tests/test_client.py
import unittest from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' ...
import unittest import numpy as np from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain van...
Add simple failing test for DistArrayProxy getitem.
Add simple failing test for DistArrayProxy getitem.
Python
bsd-3-clause
RaoUmer/distarray,enthought/distarray,enthought/distarray,RaoUmer/distarray
e99f7b6d25464f36accc2f04899edfa9e982bee2
tests/cpydiff/core_fstring_concat.py
tests/cpydiff/core_fstring_concat.py
""" categories: Core description: f-strings don't support concatenation with adjacent literals if the adjacent literals contain braces cause: MicroPython is optimised for code space. workaround: Use the + operator between literal strings when either is an f-string """ x = 1 print("aa" f"{x}") print(f"{x}" "ab") print(...
""" categories: Core description: f-strings don't support concatenation with adjacent literals if the adjacent literals contain braces or are f-strings cause: MicroPython is optimised for code space. workaround: Use the + operator between literal strings when either or both are f-strings """ x, y = 1, 2 print("aa" f"{...
Clarify f-string diffs regarding concatenation.
tests/cpydiff: Clarify f-string diffs regarding concatenation. Concatenation of any literals (including f-strings) should be avoided. Signed-off-by: Jim Mussared <e84f5c941266186d0c97dcc873413469b954847e@gmail.com>
Python
mit
adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython
55b0d7eba281fc2c13505c956f5c23bb49b34988
tests/test_qiniu.py
tests/test_qiniu.py
import os from os.path import dirname, join import uuid import qiniu.conf import qiniu.io import qiniu.rs import qiniu.rsf QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY') QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY') QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME') QINIU_BUCKET_DOMAIN = os.envir...
import os from os.path import dirname, join import uuid import qiniu.conf import qiniu.io import qiniu.rs import qiniu.rsf QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY') QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY') QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME') QINIU_BUCKET_DOMAIN = os.envir...
Test with even smaller files
Test with even smaller files
Python
mit
glasslion/django-qiniu-storage,jeffrey4l/django-qiniu-storage,Mark-Shine/django-qiniu-storage,jackeyGao/django-qiniu-storage
f67704c271b8b88ba97d1b44c73552119d79b048
tests/test_utils.py
tests/test_utils.py
import pickle from six.moves import range from fuel.utils import do_not_pickle_attributes @do_not_pickle_attributes("non_pickable", "bulky_attr") class TestClass(object): def __init__(self): self.load() def load(self): self.bulky_attr = list(range(100)) self.non_pickable = lambda x: ...
from numpy.testing import assert_raises, assert_equal from six.moves import range, cPickle from fuel.iterator import DataIterator from fuel.utils import do_not_pickle_attributes @do_not_pickle_attributes("non_picklable", "bulky_attr") class DummyClass(object): def __init__(self): self.load() def loa...
Increase test coverage in utils.py
Increase test coverage in utils.py
Python
mit
chrishokamp/fuel,ejls/fuel,harmdevries89/fuel,glewis17/fuel,EderSantana/fuel,rodrigob/fuel,markusnagel/fuel,bouthilx/fuel,janchorowski/fuel,aalmah/fuel,vdumoulin/fuel,rodrigob/fuel,orhanf/fuel,laurent-dinh/fuel,rizar/fuel,capybaralet/fuel,aalmah/fuel,hantek/fuel,mila-udem/fuel,janchorowski/fuel,hantek/fuel,dmitriy-serd...
527d460289cb574528f70a2a6c530e86627eb81a
framework/archiver/listeners.py
framework/archiver/listeners.py
from framework.tasks.handlers import enqueue_task from framework.archiver.tasks import archive, send_success_message from framework.archiver.utils import ( link_archive_provider, ) from framework.archiver import ( ARCHIVER_SUCCESS, ARCHIVER_FAILURE, ) from framework.archiver.exceptions import ArchiverCopyEr...
from framework.tasks.handlers import enqueue_task from framework.archiver.tasks import archive, send_success_message from framework.archiver.utils import ( link_archive_provider, ) from framework.archiver import ( ARCHIVER_SUCCESS, ARCHIVER_FAILURE, ) from framework.archiver.exceptions import ArchiverCopyEr...
Use list comp instead of unnecessary dict comp
Use list comp instead of unnecessary dict comp
Python
apache-2.0
pattisdr/osf.io,ticklemepierce/osf.io,billyhunt/osf.io,wearpants/osf.io,mluo613/osf.io,ckc6cz/osf.io,doublebits/osf.io,aaxelb/osf.io,chrisseto/osf.io,amyshi188/osf.io,abought/osf.io,DanielSBrown/osf.io,adlius/osf.io,Nesiehr/osf.io,laurenrevere/osf.io,monikagrabowska/osf.io,kwierman/osf.io,amyshi188/osf.io,reinaH/osf.io...
7932f3b5c3be34a37c82b1b6f08db63dc2f0eee7
lib/rapidsms/webui/urls.py
lib/rapidsms/webui/urls.py
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import os urlpatterns = [] # load the rapidsms configuration from rapidsms.config import Config conf = Config(os.environ["RAPIDSMS_INI"]) # iterate each of the active rapidsms apps (from the ini), # and (attempt to) import the urls.py from each. it's okay # if t...
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import os, sys urlpatterns = [] loaded = [] # load the rapidsms configuration from rapidsms.config import Config conf = Config(os.environ["RAPIDSMS_INI"]) # iterate each of the active rapidsms apps (from the ini), # and (attempt to) import the urls.py from each. it...
Print a list of which URLs got loaded. This doesn't help that much when trying to debug errors that keep URLs from getting loaded. But it's a start.
Print a list of which URLs got loaded. This doesn't help that much when trying to debug errors that keep URLs from getting loaded. But it's a start.
Python
bsd-3-clause
dimagi/rapidsms-core-dev,eHealthAfrica/rapidsms,unicefuganda/edtrac,ehealthafrica-ci/rapidsms,peterayeni/rapidsms,lsgunth/rapidsms,unicefuganda/edtrac,ken-muturi/rapidsms,rapidsms/rapidsms-core-dev,ehealthafrica-ci/rapidsms,eHealthAfrica/rapidsms,caktus/rapidsms,dimagi/rapidsms,lsgunth/rapidsms,dimagi/rapidsms-core-dev...
1e082f8c39dd1a1d41064f522db10478b0c820e1
icekit/page_types/layout_page/page_type_plugins.py
icekit/page_types/layout_page/page_type_plugins.py
from django.conf.urls import patterns, url from fluent_pages.extensions import page_type_pool from fluent_pages.integration.fluent_contents.page_type_plugins import FluentContentsPagePlugin from fluent_pages.models import UrlNode from . import admin, models # Register this plugin to the page plugin pool. @page_type_...
from django.conf.urls import patterns, url from fluent_pages.extensions import page_type_pool from fluent_pages.integration.fluent_contents.page_type_plugins import FluentContentsPagePlugin from fluent_pages.models import UrlNode from . import admin, models # Register this plugin to the page plugin pool. @page_type_...
Add smart template render method to LayoutPage
Add smart template render method to LayoutPage
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
95b6035b82ffeee73bbde953e5d036c50fa4fa8c
unit_tests/test_analyse_idynomics.py
unit_tests/test_analyse_idynomics.py
from nose.tools import * from analyse_idynomics import * from os.path import join, dirname, realpath class TestAnalyseiDynomics: expected_solutes = ['MyAtmos', 'pressure'] expected_species = ['MyBact'] def setUp(self): self.directory = join(dirname(realpath(__file__)), 'test_data') sel...
from nose.tools import * from analyse_idynomics import * from os.path import join, dirname, realpath class TestAnalyseiDynomics: expected_solutes = ['MyAtmos', 'pressure'] expected_species = ['MyBact'] expected_timesteps = 2 expected_dimensions = (20.0, 20.0, 2.0) def setUp(self): self...
Add unit tests for timesteps and dimensions
Add unit tests for timesteps and dimensions
Python
mit
fophillips/pyDynoMiCS
d5a00553101dd3d431dd79494b9b57cfa56cb4be
worker.py
worker.py
import os from redis import Redis from rq import Queue queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default' q = Queue(name=queue_name, connection=Redis()) def enqueue(*args, **kwargs): q.enqueue(*args, **kwargs)
import os from redis import Redis from rq import Queue queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default' # `srm` can take a long time on large files, so allow it run for up to an hour q = Queue(name=queue_name, connection=Redis(), default_timeout=3600) def enqueue(*args, **kwargs): ...
Increase job timeout for securely deleting files
Increase job timeout for securely deleting files
Python
agpl-3.0
mark-in/securedrop-app-code,mark-in/securedrop-app-code,mark-in/securedrop-app-code,mark-in/securedrop-app-code
d32e1d8349c115027e3095d61f8fa882fca1ab52
functions/test_lambda.py
functions/test_lambda.py
""" Explore how python works with lambda expressions. """ import unittest import string import random class TestGetWebsites(unittest.TestCase): def test_closure(self, m): """ See that python supports closures similar to JavaScript """ def gibberish(): """ Some random string """ ...
""" Explore how python works with lambda expressions. """ import unittest import string import random class TestGetWebsites(unittest.TestCase): def test_closure(self): """ See that python supports closures similar to JavaScript """ def gibberish(): """ Some random string """ ...
Add a test to generate a range of functions with closures. Check if it returns the expected value
Add a test to generate a range of functions with closures. Check if it returns the expected value
Python
mit
b-ritter/python-notes,b-ritter/python-notes
670a5ffe8de9f21fbb2fe65e72e006d143bfa8e3
pirx/utils.py
pirx/utils.py
import os def path(*p): import __main__ project_root = os.path.dirname(os.path.realpath(__main__.__file__)) return os.path.join(project_root, *p)
import os def path(*p): """Return full path of a directory inside project's root""" import __main__ project_root = os.path.dirname(os.path.realpath(__main__.__file__)) return os.path.join(project_root, *p)
Set docstring for "path" function
Set docstring for "path" function
Python
mit
piotrekw/pirx
384f7a8da21ca5e4ffa529e0e5f9407ce2ec0142
backend/unichat/models/user.py
backend/unichat/models/user.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class User(models.Model): MALE = -1 UNDEFINED = 0 FEMALE = 1 GENDER_CHOICES = ( (MALE, 'Male'), (UNDEFINED, 'Undefined'), (FEMALE, 'Female') ) school = models.ForeignKey('unich...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from .managers import UserManager class User(AbstractBaseUser, PermissionsMixin): email = models.EmailFiel...
Change User to use Django's AbstractBaseUser
Change User to use Django's AbstractBaseUser
Python
mit
dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet
b59d1dd5afd63422cd478d8ee519347bd1c43e3b
project/urls.py
project/urls.py
"""share URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based...
"""share URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based...
Change ember app prefix to 'share/'
Change ember app prefix to 'share/'
Python
apache-2.0
CenterForOpenScience/SHARE,aaxelb/SHARE,zamattiac/SHARE,aaxelb/SHARE,laurenbarker/SHARE,laurenbarker/SHARE,CenterForOpenScience/SHARE,zamattiac/SHARE,laurenbarker/SHARE,CenterForOpenScience/SHARE,aaxelb/SHARE,zamattiac/SHARE
048f2d9469b3f9eb266a343602ddf608e3bd6d86
highton/models/email_address.py
highton/models/email_address.py
from highton.models import HightonModel from highton.highton_constants import HightonConstants from highton import fields class EmailAddress( HightonModel, ): """ :ivar id: fields.IntegerField(name=HightonConstants.ID) :ivar location: fields.StringField(name=HightonConstants.LOCATION) :ivar addres...
from highton.models import HightonModel from highton.highton_constants import HightonConstants from highton import fields class EmailAddress( HightonModel, ): """ :ivar id: fields.IntegerField(name=HightonConstants.ID) :ivar location: fields.StringField(name=HightonConstants.LOCATION) :ivar addres...
Set EmailAddress Things to required
Set EmailAddress Things to required
Python
apache-2.0
seibert-media/Highton,seibert-media/Highton
01847c64869298a436980eb17c549d49f09d6a91
src/nodeconductor_openstack/openstack_tenant/perms.py
src/nodeconductor_openstack/openstack_tenant/perms.py
from nodeconductor.structure import perms as structure_perms PERMISSION_LOGICS = ( ('openstack_tenant.OpenStackTenantService', structure_perms.service_permission_logic), ('openstack_tenant.OpenStackTenantServiceProjectLink', structure_perms.service_project_link_permission_logic), )
from nodeconductor.core.permissions import StaffPermissionLogic from nodeconductor.structure import perms as structure_perms PERMISSION_LOGICS = ( ('openstack_tenant.OpenStackTenantService', structure_perms.service_permission_logic), ('openstack_tenant.OpenStackTenantServiceProjectLink', structure_perms.servi...
Add permissions to service properties
Add permissions to service properties - wal-94
Python
mit
opennode/nodeconductor-openstack
95d80b076d374ab8552e292014f9fbed08e7b6e1
ibmcnx/menu/MenuClass.py
ibmcnx/menu/MenuClass.py
###### # Class for Menus # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # class cnxMenu: def __init__( self ): self.menuitems = [] ...
###### # Class for Menus # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # class cnxMenu: def __init__( self ): self.menuitems = [] ...
Test all scripts on Windows
10: Test all scripts on Windows Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/10
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
f463247198354b0af1d0b8a4ff63c0757d4c2839
regression.py
regression.py
import subprocess subprocess.check_call(["coverage", "run", "--source", "toyplot", "-m", "nose"]) subprocess.check_call(["coverage", "run", "--append", "--source", "toyplot", "-m", "behave"]) subprocess.check_call(["coverage", "report"]) subprocess.check_call(["coverage", "html", "--directory", ".cover"])
import subprocess subprocess.check_call(["coverage", "run", "--source", "toyplot", "--omit", "toyplot/testing.py", "-m", "nose"]) subprocess.check_call(["coverage", "run", "--append", "--source", "toyplot", "--omit", "toyplot/testing.py", "-m", "behave"]) subprocess.check_call(["coverage", "report"]) subprocess.check_...
Exclude the testing module from coverage results.
Exclude the testing module from coverage results.
Python
bsd-3-clause
cmorgan/toyplot,cmorgan/toyplot
c458b78ccecc28971ef239de5a5366bd56d2562e
web/portal/views/home.py
web/portal/views/home.py
from flask import redirect, url_for from portal import app @app.route('/', methods=['GET']) def index(): return redirect(url_for('practices_index', _external=True))
from flask import redirect, url_for from portal import app @app.route('/', methods=['GET']) def index(): return redirect(url_for('practices_index', _external=True, _scheme="https"))
Fix incorrect protocol being using when behin reverse proxy
Fix incorrect protocol being using when behin reverse proxy
Python
mit
LCBRU/genvasc_portal,LCBRU/genvasc_portal,LCBRU/genvasc_portal,LCBRU/genvasc_portal
980a1a40aeb5f76bc8675890237f5624920b7602
pinax/stripe/management/commands/init_customers.py
pinax/stripe/management/commands/init_customers.py
from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from ...actions import customers class Command(BaseCommand): help = "Create customer objects for existing users that do not have one" def handle(self, *args, **options): User = get_user_model() ...
from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from ...actions import customers class Command(BaseCommand): help = "Create customer objects for existing users that do not have one" def handle(self, *args, **options): User = get_user_model() ...
Make sure the customer has no plan nor is charged
Make sure the customer has no plan nor is charged Stripe throws an error because we try to make a charge without having a card. Because we don't have a card for this user yet, it doesn't make sense to charge them immediately.
Python
mit
pinax/django-stripe-payments
e8708c28e79a9063469e684b5583114c69ec425f
datadog_checks_dev/datadog_checks/dev/spec.py
datadog_checks_dev/datadog_checks/dev/spec.py
# (C) Datadog, Inc. 2019-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import json import yaml from .utils import file_exists, path_join, read_file def load_spec(check_root): spec_path = get_spec_path(check_root) return yaml.safe_load(read_file(spec_path)) def g...
# (C) Datadog, Inc. 2019-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import json import yaml from .utils import file_exists, path_join, read_file def load_spec(check_root): spec_path = get_spec_path(check_root) return yaml.safe_load(read_file(spec_path)) def g...
Fix CI for logs E2E with v2 manifests
Fix CI for logs E2E with v2 manifests
Python
bsd-3-clause
DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core
a41d2e79dcf83793dab5c37c4a4b46ad6225d719
anchor/names.py
anchor/names.py
""" Names of the modalities """ # Set constants of the names of the models so they can always be referenced # as variables rather than strings # Most of the density is at 0 NEAR_ZERO = '~0' # Old "middle" modality - most of the density is at 0.5 NEAR_HALF = 'concurrent' # Most of the density is at 1 NEAR_ONE = '~1'...
""" Names of the modalities """ # Set constants of the names of the models so they can always be referenced # as variables rather than strings # Most of the density is at 0 NEAR_ZERO = 'excluded' # Old "middle" modality - most of the density is at 0.5 NEAR_HALF = 'concurrent' # Most of the density is at 1 NEAR_ONE ...
Use words for near zero and near one
Use words for near zero and near one
Python
bsd-3-clause
YeoLab/anchor
1c14d45ba620118401728c56e5ef3a189f9b4145
samples/fire.py
samples/fire.py
from asciimatics.renderers import FigletText, Fire from asciimatics.scene import Scene from asciimatics.screen import Screen from asciimatics.effects import Print from asciimatics.exceptions import ResizeScreenError from pyfiglet import Figlet import sys def demo(screen): scenes = [] effects = [ Prin...
from asciimatics.renderers import FigletText, Fire from asciimatics.scene import Scene from asciimatics.screen import Screen from asciimatics.effects import Print from asciimatics.exceptions import ResizeScreenError from pyfiglet import Figlet import sys def demo(screen): scenes = [] text = Figlet(font="bann...
Fix shadow for wide screens.
Fix shadow for wide screens.
Python
apache-2.0
peterbrittain/asciimatics,peterbrittain/asciimatics
f7a8c4a293538c4cd592ba23860b873cb378f28f
pyaxiom/netcdf/dataset.py
pyaxiom/netcdf/dataset.py
#!python # coding=utf-8 from netCDF4 import Dataset class EnhancedDataset(Dataset): def __init__(self, *args, **kwargs): super(EnhancedDataset, self).__init__(*args, **kwargs) def get_variables_by_attributes(self, **kwargs): vs = [] has_value_flag = False for vname in self.v...
#!python # coding=utf-8 from netCDF4 import Dataset class EnhancedDataset(Dataset): def __init__(self, *args, **kwargs): super(EnhancedDataset, self).__init__(*args, **kwargs) def get_variables_by_attributes(self, **kwargs): vs = [] has_value_flag = False for vname in self.v...
Add a close method to EnhancedDataset that won't raise a RuntimeError
Add a close method to EnhancedDataset that won't raise a RuntimeError
Python
mit
axiom-data-science/pyaxiom,ocefpaf/pyaxiom,ocefpaf/pyaxiom,axiom-data-science/pyaxiom
86968b5bc34a0c7f75ff04ad261ee59da8dcf94f
app/soc/models/host.py
app/soc/models/host.py
#!/usr/bin/env python2.5 # # Copyright 2008 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
#!/usr/bin/env python2.5 # # Copyright 2008 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
Replace the old Host model with a new one.
Replace the old Host model with a new one. The new Host model doesn't need the host user to have a profile. Instead it will contain the user to whom the Host entity belongs to as the parent of the Host entity to maintain transactionality between User and Host updates. --HG-- extra : rebase_source : cee68153ab1cfdb77c...
Python
apache-2.0
rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son
f023d6e112638c58ed1e0adc764263b64f50e15a
apps/documents/urls.py
apps/documents/urls.py
from django.conf.urls import url from . import views urlpatterns = [ url( r'^chapters/(?P<pk>\d+)/$', views.ChapterDetailView.as_view(), name='chapter-detail' ), url( r'^paragraphs/(?P<pk>\d+)/$', views.ParagraphDetailView.as_view(), name='paragraph-detail' ...
from django.conf.urls import url from . import views urlpatterns = [ url( r'^chapters/(?P<pk>\d+)/$', views.ChapterDetailView.as_view(), name='chapter-detail' ), url( r'^paragraphs/(?P<pk>\d+)/$', views.ParagraphDetailView.as_view(), name='paragraph-detail' ...
Unify url routes to plural
Unify url routes to plural
Python
agpl-3.0
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
17f3a2a491f8e4d1b1b6c2644a1642f02cfada17
apps/i4p_base/views.py
apps/i4p_base/views.py
# -*- coding: utf-8 -*- from django.http import QueryDict from django.shortcuts import render_to_response from django.template.context import RequestContext from django.utils import translation from apps.project_sheet.models import I4pProject from apps.project_sheet.utils import get_project_translations_from_parents,...
# -*- coding: utf-8 -*- from django.http import QueryDict from django.shortcuts import render_to_response from django.template.context import RequestContext from django.utils import translation from apps.project_sheet.models import I4pProject from apps.project_sheet.utils import get_project_translations_from_parents,...
Remove pre-selection of best-on filter
Remove pre-selection of best-on filter
Python
agpl-3.0
ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople
d7b3579edf9efb48fc80290fe0cf1c9c6db3b7bc
run-quince.py
run-quince.py
#!C:\Users\qlab\Anaconda3\envs\pyqt5\python.exe # coding: utf-8 # Raytheon BBN Technologies 2016 # Contributiors: Graham Rowlands # # This file runs the main loop from qtpy.QtWidgets import QApplication import sys import argparse from quince.view import * if __name__ == "__main__": parser = argparse.ArgumentPar...
#!C:\Users\qlab\Anaconda3\envs\pyqt5\python.exe # coding: utf-8 # Raytheon BBN Technologies 2016 # Contributiors: Graham Rowlands # # This file runs the main loop # Use PyQt5 by default import os os.environ["QT_API"] = 'pyqt5' from qtpy.QtWidgets import QApplication import sys import argparse from quince.view import...
Set desired qt version explicitly in run_quince.py
Set desired qt version explicitly in run_quince.py
Python
apache-2.0
BBN-Q/Quince
4965511fdb9843233e84a8aa9aa0414bf1c02133
mail/views.py
mail/views.py
from django.shortcuts import redirect from django.http import JsonResponse from django.core.mail import EmailMessage from django.middleware import csrf from rest_framework.decorators import api_view @api_view(['POST', 'GET']) def send_contact_message(request): if request.method == 'POST': to_address = re...
from django.shortcuts import redirect from django.http import JsonResponse from django.core.mail import EmailMessage from django.middleware import csrf from rest_framework.decorators import api_view @api_view(['POST', 'GET']) def send_contact_message(request): if request.method == 'POST': to_address = re...
Revert "return json of message being sent to debug mail issue"
Revert "return json of message being sent to debug mail issue"
Python
agpl-3.0
openstax/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,Connexions/openstax-cms
05b6eaf259117cc6254e2b13c5a02569713e6356
inbox/contacts/process_mail.py
inbox/contacts/process_mail.py
import uuid from inbox.models import Contact, MessageContactAssociation def update_contacts_from_message(db_session, message, account_id): with db_session.no_autoflush: for field in ('to_addr', 'from_addr', 'cc_addr', 'bcc_addr'): if getattr(message, field) is None: continue ...
import uuid from inbox.models import Contact, MessageContactAssociation def update_contacts_from_message(db_session, message, account_id): with db_session.no_autoflush: for field in ('to_addr', 'from_addr', 'cc_addr', 'bcc_addr'): if getattr(message, field) is None: continue ...
Fix filtering criterion when updating contacts from message.
Fix filtering criterion when updating contacts from message.
Python
agpl-3.0
gale320/sync-engine,closeio/nylas,wakermahmud/sync-engine,nylas/sync-engine,EthanBlackburn/sync-engine,jobscore/sync-engine,gale320/sync-engine,nylas/sync-engine,Eagles2F/sync-engine,PriviPK/privipk-sync-engine,Eagles2F/sync-engine,nylas/sync-engine,ErinCall/sync-engine,PriviPK/privipk-sync-engine,closeio/nylas,ErinCal...
523a25d30241ecdd0abdb7545b1454714b003edc
astrospam/pyastro16.py
astrospam/pyastro16.py
""" Python in Astronomy 2016 is the second iteration of the Python in Astronomy conference series. This is the docstring for the pyastro module, this gets included as the description for the module. """ import numpy as np def times(a, b): """ Multiply a by b. Parameters ---------- a : `numpy.n...
""" Python in Astronomy 2016 is the second iteration of the Python in Astronomy conference series. This is the docstring for the pyastro module, this gets included as the description for the module. """ import numpy as np def times(a, b): """ Multiply a by b. Parameters ---------- a : `numpy.n...
Add a subclass for the dot graph
Add a subclass for the dot graph
Python
mit
cdeil/sphinx-tutorial
aab9efbcec0bbded807bf207e2324266573fa3a6
tensorflow/python/tf2.py
tensorflow/python/tf2.py
# Copyright 2018 The TensorFlow Authors. 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 applica...
# Copyright 2018 The TensorFlow Authors. 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 applica...
Remove the redundant `else` condition.
Remove the redundant `else` condition. PiperOrigin-RevId: 302901741 Change-Id: I65281a07fc2789fbc13775c1365fd01789a1bb7e
Python
apache-2.0
petewarden/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,cxxgtxy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,petewarden/tensorflow,paolodedios/tensorflow,aldian/tensorflow,yongtang/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-experime...
51e9262ff273db870310453797dbeb48eefd4df7
logcollector/__init__.py
logcollector/__init__.py
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../logcollector.db' db = SQLAlchemy(app) @app.route("/") def hello(): return "Hello World!"
from flask import Flask, request, jsonify from flask.ext.sqlalchemy import SQLAlchemy from .models import DataPoint app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../logcollector.db' db = SQLAlchemy(app) @app.route("/new", methods=['POST']) def collect(): new_data = DataPoint(request.f...
Implement save functionality with POST request
Implement save functionality with POST request
Python
agpl-3.0
kissgyorgy/log-collector
a668afc87465989e85153c9bd2a608ba0ba54d9b
tests/test_containers.py
tests/test_containers.py
try: from http.server import SimpleHTTPRequestHandler except ImportError: from SimpleHTTPServer import SimpleHTTPRequestHandler try: from socketserver import TCPServer except ImportError: from SocketServer import TCPServer import os import threading import unittest import glob, os import containers ...
try: from http.server import SimpleHTTPRequestHandler except ImportError: from SimpleHTTPServer import SimpleHTTPRequestHandler try: from socketserver import TCPServer except ImportError: from SocketServer import TCPServer import glob import os import sys import threading import unittest import conta...
Add test that aci was downloaded
Add test that aci was downloaded
Python
mit
kragniz/containers
f3e1c74d9b85814cd56397560c5023e7ef536caa
tests/test_statuspage.py
tests/test_statuspage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import sys from helpers.statuspage import StatusPage from test_postgresql import MockConnect if sys.hexversion >= 0x03000000: from io import BytesIO as IO else: from StringIO import StringIO as IO class TestStatusPage(unittest.TestCase): de...
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import sys from helpers.statuspage import StatusPage from test_postgresql import MockConnect if sys.hexversion >= 0x03000000: from io import BytesIO as IO else: from StringIO import StringIO as IO class TestStatusPage(unittest.TestCase): de...
Remove some more unneccesary code.
Unittests: Remove some more unneccesary code.
Python
mit
zalando/patroni,zalando/patroni,sean-/patroni,pgexperts/patroni,sean-/patroni,pgexperts/patroni,jinty/patroni,jinty/patroni
550101a804cb48f07042014ac5d413071a0e29d7
coap/test/test_request.py
coap/test/test_request.py
from ..code_registry import MethodCode, MessageType from ..coap import Coap def test_build_message(): c = Coap('coap.me') result = c.get('hello') print str(bytearray(result.server_reply_list[0].payload)) c.destroy()
from ..code_registry import MethodCode, MessageType from ..coap import Coap import binascii def test_build_message(): c = Coap('coap.me') result1 = c.get('hello') assert str(bytearray(result1.server_reply_list[0].payload)) == '\xffworld' result2 = c.get('separate') assert str(bytearray(result2.ser...
Add very basic testing for Coap request.
Add very basic testing for Coap request.
Python
bsd-3-clause
samueldotj/pycoap
55d13c7f59d5500fbbf2cbe915a6f2fe8e538e14
example/layout/__year__/index.html.py
example/layout/__year__/index.html.py
__name__ = "Year View" __author__ = "Decklin Foster <decklin@red-bean.com>" __description__ = "Calendar of all dates in a given year." import time def make(instance, entries, all, vars): # we get all the entries for this year in ``entries``, in here we want to # build some monthly calendars to pass to the nex...
__name__ = "Year View" __author__ = "Decklin Foster <decklin@red-bean.com>" __description__ = "Calendar of all dates in a given year." import time def make(instance, entries, all, vars): # we get all the entries for this year in ``entries``, in here we want to # build some monthly calendars to pass to the nex...
Make this a bit more readable.
Make this a bit more readable.
Python
isc
decklin/ennepe
d1e2dc224b7b922d39f0f8f21affe39985769315
src/loader.py
src/loader.py
from scipy.io import loadmat def load_clean_data(): data = loadmat('data/cleandata_students.mat') return data['x'], data['y'] def load_noisy_data(): data = loadmat('data/noisydata_students.mat') return data['x'], data['y'] if __name__ == '__main__': print('Clean Data:') x, y = load_clean_data...
from scipy.io import loadmat def load_data(data_file): data = loadmat(data_file) return data['x'], data['y'] if __name__ == '__main__': print('Clean Data:') x, y = load_data('data/cleandata_students.mat') print('x:', x) print('y:', y) print() print('Noisy Data:') x, y = load_data...
Remove hard-coded data file path
Remove hard-coded data file path
Python
mit
MLNotWar/decision-trees-algorithm,MLNotWar/decision-trees-algorithm
6b5a4dd75bc1d6dc5187da4ea5e617f30e395b89
orchard/views/__init__.py
orchard/views/__init__.py
# -*- coding: utf-8 -*- """ Simple testing blueprint. Will be deleted once real functionality is added. """ import flask import flask_classful views = flask.Blueprint('views', __name__) class IndexView(flask_classful.FlaskView): """ A simple home page. """ route_base = '/' # noinspecti...
# -*- coding: utf-8 -*- """ Simple testing blueprint. Will be deleted once real functionality is added. """ import flask import flask_classful views = flask.Blueprint('views', __name__) class IndexView(flask_classful.FlaskView): """ A simple home page. """ route_base = '/' # noinspecti...
Remove the intentional throwing of internal server errors.
Remove the intentional throwing of internal server errors. Fixes failing tests.
Python
mit
BMeu/Orchard,BMeu/Orchard
969a4f011c7f78a04b6939768d59ba768ff4d160
Lib/importlib/__init__.py
Lib/importlib/__init__.py
"""Backport of importlib.import_module from 3.x.""" import sys def _resolve_name(name, package, level): """Return the absolute name of the module to be imported.""" level -= 1 try: if package.count('.') < level: raise ValueError("attempted relative import beyond top-level " ...
"""Backport of importlib.import_module from 3.x.""" # While not critical (and in no way guaranteed!), it would be nice to keep this # code compatible with Python 2.3. import sys def _resolve_name(name, package, level): """Return the absolute name of the module to be imported.""" level -= 1 try: if ...
Make importlib backwards-compatible to Python 2.2 (but this is not promised to last; just doing it to be nice).
Make importlib backwards-compatible to Python 2.2 (but this is not promised to last; just doing it to be nice). Also fix a message for an exception.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
22a889dd8f12a11ff22f1b1e167b3c888f892f88
typesetter/typesetter.py
typesetter/typesetter.py
from flask import Flask, render_template, jsonify app = Flask(__name__) app.config.update( JSONIFY_PRETTYPRINT_REGULAR=False, ) # Read in the entire wordlist at startup and keep it in memory. # Optimization for improving search response time. with open('typesetter/data/words.txt') as f: WORDS = f.read().spli...
from flask import Flask, render_template, jsonify app = Flask(__name__) app.config.update( # Reduce response size by avoiding pretty printing. JSONIFY_PRETTYPRINT_REGULAR=False, ) # Read in the entire wordlist at startup and keep it in memory. # Optimization for improving search response time. with open('typ...
Add clarifying comment about avoiding pretty printing
Add clarifying comment about avoiding pretty printing
Python
mit
rlucioni/typesetter,rlucioni/typesetter,rlucioni/typesetter
0d0434744efef091fd8d26725f21c8015a06d8be
opentreemap/treemap/templatetags/instance_config.py
opentreemap/treemap/templatetags/instance_config.py
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from django import template from treemap.json_field import get_attr_from_json_field register = template.Library() def _get_color_from_config(config, name): color = config.get(name) if color: ...
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from django import template from treemap.json_field import get_attr_from_json_field register = template.Library() def _get_color_from_config(config, name): color = config.get(name) if color: ...
Allow "writable" if *any* field is writable
Allow "writable" if *any* field is writable Fixes Internal Issue 598
Python
agpl-3.0
recklessromeo/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,clever-crow-consulting/otm-core,recklessromeo/otm-core,clever-crow-consulting/otm-core,maurizi/otm-core,RickMohr/otm-core,maurizi/otm-core,maurizi/otm-core,recklessromeo/otm-core,RickMohr/otm-core,recklessromeo/otm-core,maurizi/otm-core,RickMohr/o...
b03c0898897bbd89f8701e1c4d6d84d263bbd039
utils/publish_message.py
utils/publish_message.py
import amqp from contextlib import closing def publish_message(message_body, exchange, type, routing_key): """ Publish a message to an exchange with exchange type and routing key specified. A message is sent to a specified exchange with the provided routing_key. :param message_body: The body of the mess...
import amqp from contextlib import closing def __get_channel(connection): return connection.channel() def __get_message(message_body): return amqp.Message(message_body) def __declare_exchange(channel, exchange, type): channel.exchange_declare(exchange=exchange, type=type, durable=True, auto_delete=False...
Revert "EAFP and removing redundant functions"
Revert "EAFP and removing redundant functions" This reverts commit fbb9eeded41e46c8fe8c3ddaba7f8d9fd1e3bff3.
Python
mit
jdgillespie91/trackerSpend,jdgillespie91/trackerSpend
6d04f0f924df11968b85aa2c885bde30cf6af597
stack/vpc.py
stack/vpc.py
from troposphere import ( Ref, ) from troposphere.ec2 import ( InternetGateway, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( "InternetG...
from troposphere import ( Ref, ) from troposphere.ec2 import ( InternetGateway, Route, RouteTable, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) # Allow outgoing to outside VPC internet_gateway = Inte...
Add a public route table
Add a public route table
Python
mit
caktus/aws-web-stacks,tobiasmcnulty/aws-container-basics
90e557d681c9ea3f974ee5357ec67f294322d224
src/elm_doc/decorators.py
src/elm_doc/decorators.py
import functools import subprocess from doit.exceptions import TaskFailed def capture_subprocess_error(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except subprocess.CalledProcessError as e: return TaskFailed( ...
import functools import subprocess from doit.exceptions import TaskFailed def capture_subprocess_error(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except subprocess.CalledProcessError as e: command_string = e.cmd if isinstanc...
Clean error output when command is a string
Clean error output when command is a string
Python
bsd-3-clause
ento/elm-doc,ento/elm-doc
1107fc26cf9baa235d62813ea0006687d4710280
src/engine/file_loader.py
src/engine/file_loader.py
import os import json from lib import contract data_dir = os.path.join(os.environ['PORTER'], 'data') @contract.accepts(str) @contract.returns(list) def read_and_parse_json(data_type): sub_dir = os.path.join(data_dir, data_type) def full_path(file_name): return os.path.join(sub_dir, file_name) ...
import os import json from lib import contract data_dir = os.path.join(os.environ['PORTER'], 'data') @contract.accepts(str) @contract.returns(list) def read_and_parse_json(data_type): sub_dir = os.path.join(data_dir, data_type) def full_path(file_name): return os.path.join(sub_dir, file_name) ...
Add load_enum and load_struct functions
Add load_enum and load_struct functions Load enumeration list json Load full struct into dictionary
Python
mit
Tactique/game_engine,Tactique/game_engine
ab506307b6b3fc2997a7afd38c02cae630dbf90b
addons/hr_holidays/migrations/8.0.1.5/pre-migration.py
addons/hr_holidays/migrations/8.0.1.5/pre-migration.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module copyright (C) 2014 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of ...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module copyright (C) 2014 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of ...
Remove hr_holidays_meeting_id_fkey constrain to avoid migration issues.
Remove hr_holidays_meeting_id_fkey constrain to avoid migration issues. - The constraint will be reset by the ORM later. - Not doing it may both slow the migration and abort it altogether.
Python
agpl-3.0
OpenUpgrade-dev/OpenUpgrade,kirca/OpenUpgrade,bwrsandman/OpenUpgrade,sebalix/OpenUpgrade,kirca/OpenUpgrade,hifly/OpenUpgrade,grap/OpenUpgrade,Endika/OpenUpgrade,bwrsandman/OpenUpgrade,damdam-s/OpenUpgrade,blaggacao/OpenUpgrade,mvaled/OpenUpgrade,blaggacao/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,OpenUpgrade/OpenUpgrade,...
8799197befd1f52278a4344fc41ba94cc45c548a
src/you_get/json_output.py
src/you_get/json_output.py
import json # save info from common.print_info() last_info = None def output(video_extractor, pretty_print=True): ve = video_extractor out = {} out['url'] = ve.url out['title'] = ve.title out['site'] = ve.name out['streams'] = ve.streams if pretty_print: print(json.dumps(out, inde...
import json # save info from common.print_info() last_info = None def output(video_extractor, pretty_print=True): ve = video_extractor out = {} out['url'] = ve.url out['title'] = ve.title out['site'] = ve.name out['streams'] = ve.streams try: if ve.audiolang: out['audi...
Print audiolang in json output
Print audiolang in json output
Python
mit
zmwangx/you-get,zmwangx/you-get,xyuanmu/you-get,qzane/you-get,qzane/you-get,xyuanmu/you-get,cnbeining/you-get,cnbeining/you-get
1b36e4ec9c15a0f9064d605f7c7f60672416dcb0
workers/subscriptions.py
workers/subscriptions.py
import os import telegram from leonard import Leonard if __name__ == '__main__': os.chdir('../') telegram_client = telegram.Bot(os.environ['BOT_TOKEN']) bot = Leonard(telegram_client) i = 0 while True: if i % 10 == 0: bot.collect_plugins() for name, check, send in bot....
import os import time import telegram from leonard import Leonard if __name__ == '__main__': os.chdir('../') telegram_client = telegram.Bot(os.environ['BOT_TOKEN']) bot = Leonard(telegram_client) bot.collect_plugins() while True: for name, check, send in bot.subscriptions: sen...
Remove collecting plugins every second
Remove collecting plugins every second
Python
mit
sevazhidkov/leonard
24da0f84e1a844b1f53e5afafc34cfcc915a9a67
corehq/apps/userreports/tests/test_report_rendering.py
corehq/apps/userreports/tests/test_report_rendering.py
# coding: utf-8 from __future__ import absolute_import from __future__ import unicode_literals from django.test import SimpleTestCase from corehq.apps.userreports.reports.view import ConfigurableReportView class VeryFakeReportView(ConfigurableReportView): # note: this is very coupled to what it tests below, but i...
# coding: utf-8 from __future__ import absolute_import from __future__ import unicode_literals from django.test import SimpleTestCase from corehq.apps.userreports.reports.view import ConfigurableReportView from corehq.apps.userreports.reports.util import ReportExport class VeryFakeReportExport(ReportExport): de...
Update report_rendering test to use ReportExport
Update report_rendering test to use ReportExport
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
1768207c57b66812931d2586c5544c9b74446918
peering/management/commands/update_peering_session_states.py
peering/management/commands/update_peering_session_states.py
import logging from django.core.management.base import BaseCommand from peering.models import InternetExchange class Command(BaseCommand): help = "Update peering session states for Internet Exchanges." logger = logging.getLogger("peering.manager.peering") def handle(self, *args, **options): sel...
import logging from django.core.management.base import BaseCommand from peering.models import InternetExchange class Command(BaseCommand): help = "Update peering session states for Internet Exchanges." logger = logging.getLogger("peering.manager.peering") def handle(self, *args, **options): sel...
Fix command polling sessions for IX.
Fix command polling sessions for IX.
Python
apache-2.0
respawner/peering-manager,respawner/peering-manager,respawner/peering-manager,respawner/peering-manager
2fd3123eb00c16d325a7ec25dfcb6a92872a3849
tests/test_init.py
tests/test_init.py
import os from click.testing import CliRunner from morenines import application def test_init(data_dir): runner = CliRunner() result = runner.invoke(application.main, ['init', data_dir]) assert result.exit_code == 0 mn_dir = os.path.join(data_dir, '.morenines') assert os.path.isdir(mn_dir) ==...
import os from click.testing import CliRunner from morenines import application def test_init(data_dir): runner = CliRunner() result = runner.invoke(application.main, ['init', data_dir]) assert result.exit_code == 0 mn_dir = os.path.join(data_dir, '.morenines') assert os.path.isdir(mn_dir) ==...
Add commented-out test for init with no args
Add commented-out test for init with no args
Python
mit
mcgid/morenines,mcgid/morenines
c33ce5e8d998278d01310205598ceaf15b1573ab
logya/core.py
logya/core.py
# -*- coding: utf-8 -*- from logya.content import read_all from logya.template import init_env from logya.util import load_yaml, paths class Logya: """Object to store data such as site index and settings.""" def __init__(self, options): """Set required logya object properties.""" self.verbos...
# -*- coding: utf-8 -*- from logya.content import read_all from logya.template import init_env from logya.util import load_yaml, paths class Logya: """Object to store data such as site index and settings.""" def __init__(self, options): """Set required logya object properties.""" self.verbos...
Rename build_index to build and add logic to setup template env
Rename build_index to build and add logic to setup template env
Python
mit
elaOnMars/logya,elaOnMars/logya,elaOnMars/logya,yaph/logya,yaph/logya
a2cb560851cbbabab0474092f59e1700e1c93284
tests/chainer_tests/testing_tests/test_unary_math_function_test.py
tests/chainer_tests/testing_tests/test_unary_math_function_test.py
import unittest from chainer import testing class Dummy(object): pass class TestNoNumpyFunction(unittest.TestCase): def test_no_numpy_function(self): with self.assertRaises(ValueError): testing.unary_math_function_unittest(Dummy()) # no numpy.dummy testing.run_module(__name__, __fil...
import unittest from chainer import testing def dummy(): pass class TestNoNumpyFunction(unittest.TestCase): def test_no_numpy_function(self): with self.assertRaises(ValueError): testing.unary_math_function_unittest(dummy) # no numpy.dummy testing.run_module(__name__, __file__)
Fix test of math function testing helper.
Fix test of math function testing helper.
Python
mit
wkentaro/chainer,jnishi/chainer,jnishi/chainer,keisuke-umezawa/chainer,anaruse/chainer,okuta/chainer,ktnyt/chainer,niboshi/chainer,hvy/chainer,tkerola/chainer,ktnyt/chainer,hvy/chainer,niboshi/chainer,jnishi/chainer,chainer/chainer,wkentaro/chainer,hvy/chainer,ronekko/chainer,okuta/chainer,aonotas/chainer,keisuke-umeza...
850f6af90b99756e572b06803e40f55efd6734e6
test/test_pocket_parser.py
test/test_pocket_parser.py
import unittest import utils import os import sys import re import subprocess TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(os.path.join(TOPDIR, 'lib')) import cryptosite.pocket_parser class Tests(unittest.TestCase): def test_get_cnc(self): """Test get_cnc() func...
import unittest import utils import os import sys import re import subprocess import shutil TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) import cryptosite.pocket_parser class Tests(unittest.TestCase): def test_get_cnc(self): """Test get_cnc() func...
Test simple complete run of pocket_parser.
Test simple complete run of pocket_parser.
Python
lgpl-2.1
salilab/cryptosite,salilab/cryptosite,salilab/cryptosite
8680eac07c50546968c1525642cab41c1c99a6b3
{{cookiecutter.repo_name}}/pages/context_processors.py
{{cookiecutter.repo_name}}/pages/context_processors.py
from django.contrib.sites.shortcuts import get_current_site from urlparse import urljoin def site_url(request): scheme = 'https' if request.is_secure() else 'http' site = get_current_site(request) #domain = "{}://{}".format(scheme, site.domain) return { 'site_url': "{}://{}".format(scheme, sit...
from django.contrib.sites.shortcuts import get_current_site def site_url(request): scheme = 'https' if request.is_secure() else 'http' site = get_current_site(request) #domain = "{}://{}".format(scheme, site.domain) return { 'site_url': "{}://{}".format(scheme, site.domain), 'site_nam...
Remove urlparse import as not used and also renamed in Python 3 to urllib.parse
Remove urlparse import as not used and also renamed in Python 3 to urllib.parse
Python
mit
Parbhat/wagtail-cookiecutter-foundation,aksh1/wagtail-cookiecutter-foundation,Parbhat/wagtail-cookiecutter-foundation,ilendl2/wagtail-cookiecutter-foundation,Parbhat/wagtail-cookiecutter-foundation,ilendl2/wagtail-cookiecutter-foundation,Parbhat/wagtail-cookiecutter-foundation,Parbhat/wagtail-cookiecutter-foundation,ch...
23c1413c14a81ee40bbb0bb3adeb20e1a231b9c5
saleor/data_feeds/urls.py
saleor/data_feeds/urls.py
from django.conf.urls import url from django.views.generic.base import RedirectView from .google_merchant import get_feed_file_url urlpatterns = [ url(r'google/$', RedirectView.as_view( get_redirect_url=get_feed_file_url), name='google-feed')]
from django.conf.urls import url from django.views.generic.base import RedirectView from .google_merchant import get_feed_file_url urlpatterns = [ url(r'google/$', RedirectView.as_view( get_redirect_url=get_feed_file_url, permanent=True), name='google-feed')]
Update feeds url due to RemovedInDjango19Warning
Update feeds url due to RemovedInDjango19Warning
Python
bsd-3-clause
jreigel/saleor,maferelo/saleor,UITools/saleor,UITools/saleor,KenMutemi/saleor,tfroehlich82/saleor,UITools/saleor,jreigel/saleor,car3oon/saleor,mociepka/saleor,car3oon/saleor,maferelo/saleor,HyperManTT/ECommerceSaleor,itbabu/saleor,UITools/saleor,tfroehlich82/saleor,itbabu/saleor,UITools/saleor,HyperManTT/ECommerceSaleo...
3157a749cb7f4704e3fe4c949ee80772a9ed8eb3
samples/debugging/main.py
samples/debugging/main.py
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. All Rights Reserved. """Simple command-line example for Translate. Command-line application that translates some text. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import gflags import logging import pprint import sys from apicl...
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. All Rights Reserved. """Simple command-line example for Translate. Command-line application that translates some text. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import gflags import logging import pprint import sys from apicl...
Update sample to reflect final destination in wiki documentation.
Update sample to reflect final destination in wiki documentation.
Python
apache-2.0
googleapis/google-api-python-client,jonparrott/oauth2client,googleapis/oauth2client,google/oauth2client,jonparrott/oauth2client,google/oauth2client,googleapis/google-api-python-client,clancychilds/oauth2client,clancychilds/oauth2client,googleapis/oauth2client
6de2bd60922c012ae3ec179a49aaff950018076d
snactor/utils/variables.py
snactor/utils/variables.py
def assign_to_variable_spec(data, spec, value): if not spec.startswith('@') or not spec.endswith('@'): raise ValueError("{} is not a reference".format(spec)) parts = spec.strip('@').split('.') data[parts[0]] = {} gen = data[parts[0]] for part in parts[1:-1]: gen[part] = {} ge...
def assign_to_variable_spec(data, spec, value): if not spec.startswith('@') or not spec.endswith('@'): raise ValueError("{} is not a reference".format(spec)) parts = spec.strip('@').split('.') data[parts[0]] = {} gen = data[parts[0]] for part in parts[1:-1]: gen[part] = {} ge...
Allow empty data in value
Allow empty data in value
Python
apache-2.0
leapp-to/snactor
b3540f744efbcb0f14f9b4081aeffda1f5ccae3c
pyscraper/patchfilter.py
pyscraper/patchfilter.py
#! /usr/bin/python2.3 # vim:sw=8:ts=8:et:nowrap import os import shutil def ApplyPatches(filein, fileout): # Generate short name such as wrans/answers2003-03-31.html (rest, name) = os.path.split(filein) (rest, dir) = os.path.split(rest) fileshort = os.path.join(dir, name) # Lo...
#! /usr/bin/python2.3 # vim:sw=8:ts=8:et:nowrap import os import shutil def ApplyPatches(filein, fileout): # Generate short name such as wrans/answers2003-03-31.html (rest, name) = os.path.split(filein) (rest, dir) = os.path.split(rest) fileshort = os.path.join(dir, name) # Lo...
Remove code which blanks patch files
Remove code which blanks patch files
Python
agpl-3.0
mysociety/publicwhip,mysociety/publicwhip,mysociety/publicwhip
1eff8a7d89fd3d63f020200207d87213f6182b22
elasticsearch_flex/management/commands/flex_sync.py
elasticsearch_flex/management/commands/flex_sync.py
# coding: utf-8 import hues from django.core.management.base import BaseCommand from elasticsearch import exceptions from elasticsearch_dsl.connections import connections from elasticsearch_flex.indexes import registered_indices class Command(BaseCommand): help = 'Sync search indices, templates, and scripts.' ...
# coding: utf-8 import hues from django.core.management.base import BaseCommand from elasticsearch_dsl.connections import connections from elasticsearch_flex.indexes import registered_indices class Command(BaseCommand): help = 'Sync search indices, templates, and scripts.' def add_arguments(self, parser): ...
Use index context manager for sync
Use index context manager for sync
Python
mit
prashnts/dj-elasticsearch-flex,prashnts/dj-elasticsearch-flex
9742e372a6ccca843120cb5b4e8135033d30cdd6
cauth/controllers/root.py
cauth/controllers/root.py
#!/usr/bin/env python # # Copyright (C) 2014 eNovance SAS <licensing@enovance.com> # # 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 # # Unle...
#!/usr/bin/env python # # Copyright (C) 2014 eNovance SAS <licensing@enovance.com> # # 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 # # Unle...
Fix app crashing at startup if some auth methods are not configured
Fix app crashing at startup if some auth methods are not configured Change-Id: I201dbc646c6da39c5923a086a0498b7ccb854982
Python
apache-2.0
redhat-cip/cauth,enovance/cauth,redhat-cip/cauth,redhat-cip/cauth,enovance/cauth,enovance/cauth
5ef8b09a055326e2a92c9eccbcb187fa5362fb95
zipa/magic.py
zipa/magic.py
from types import ModuleType from .resource import Resource class SelfWrapper(ModuleType): def __init__(self, self_module, baked_args={}): for attr in ["__builtins__", "__doc__", "__name__", "__package__"]: setattr(self, attr, getattr(self_module, attr, None)) self.__path__ = [] ...
from types import ModuleType from .resource import Resource class SelfWrapper(ModuleType): def __init__(self, self_module, baked_args={}): for attr in ["__builtins__", "__doc__", "__name__", "__package__"]: setattr(self, attr, getattr(self_module, attr, None)) self.__path__ = [] ...
Add possibility of using apis with dashes without any workarounds
Add possibility of using apis with dashes without any workarounds
Python
apache-2.0
PressLabs/zipa
689d1d1f128b4a72aad6783ea2f770c21cd4c2da
queryset_transform/__init__.py
queryset_transform/__init__.py
from django.db import models class TransformQuerySet(models.query.QuerySet): def __init__(self, *args, **kwargs): super(TransformQuerySet, self).__init__(*args, **kwargs) self._transform_fns = [] def _clone(self, klass=None, setup=False, **kw): c = super(TransformQuerySet, self)._clone...
from django.db import models class TransformQuerySet(models.query.QuerySet): def __init__(self, *args, **kwargs): super(TransformQuerySet, self).__init__(*args, **kwargs) self._transform_fns = [] def _clone(self, klass=None, setup=False, **kw): c = super(TransformQuerySet, self)._clon...
Refactor the ever living hell out of this.
Refactor the ever living hell out of this.
Python
bsd-3-clause
alex/django-queryset-transform
4169f60ce8fa6666b28a1129845c816889a6459a
chef/tests/__init__.py
chef/tests/__init__.py
import os import random from unittest2 import TestCase from chef.api import ChefAPI TEST_ROOT = os.path.dirname(os.path.abspath(__file__)) def test_chef_api(): return ChefAPI('https://api.opscode.com/organizations/pycheftest', os.path.join(TEST_ROOT, 'client.pem'), 'unittests') class ChefTestCase(TestCase): ...
import os import random from unittest2 import TestCase from chef.api import ChefAPI TEST_ROOT = os.path.dirname(os.path.abspath(__file__)) def test_chef_api(): return ChefAPI('https://api.opscode.com/organizations/pycheftest', os.path.join(TEST_ROOT, 'client.pem'), 'unittests') class ChefTestCase(TestCase): ...
Add a system for tests to register objects for deletion.
Add a system for tests to register objects for deletion. They should be deleted no matter the outcome of the test.
Python
apache-2.0
coderanger/pychef,jarosser06/pychef,jarosser06/pychef,Scalr/pychef,Scalr/pychef,dipakvwarade/pychef,cread/pychef,coderanger/pychef,dipakvwarade/pychef,cread/pychef
44d701eea86f9c2152368f64e54c012cdb937bb1
alexandria/views/home.py
alexandria/views/home.py
from pyramid.view import ( view_config, notfound_view_config, ) # Always send the default index.html @notfound_view_config(renderer='templates/index.mako', accept='text/html') @view_config(renderer='templates/index.mako', accept='text/html') def index(request): return {}
from pyramid.view import ( view_config, notfound_view_config, ) # Always send the default index.html @notfound_view_config(renderer='templates/index.mako', xhr=False, accept='text/html') @view_config(renderer='templates/index.mako', xhr=False, accept='text/html') def index(request): return ...
Verify X-Requested-With is not set
Verify X-Requested-With is not set
Python
isc
bertjwregeer/alexandria,bertjwregeer/alexandria,cdunklau/alexandria,cdunklau/alexandria,cdunklau/alexandria
bb59028a3dab81139a83f9a0eb8a4c58b9c25829
sample_application/app.py
sample_application/app.py
import os from flask import Blueprint, Flask from flask import Flask, g from views import blueprint, Resources, UnixTime, PrintArg, ExampleApiUsage from flask.ext.restful import Api from client import Client def create_app(): api = Api(blueprint) api.add_resource(Resources, '/resources') api.add_resource(UnixTim...
import os from flask import Blueprint, Flask from flask import Flask, g from views import blueprint, Resources, UnixTime, PrintArg, ExampleApiUsage from flask.ext.restful import Api from client import Client def create_app(): api = Api(blueprint) api.add_resource(Resources, '/resources') api.add_resource(UnixTim...
Change config import strategy to config.from_pyfile()
Change config import strategy to config.from_pyfile()
Python
mit
adsabs/adsabs-webservices-blueprint,jonnybazookatone/adsabs-webservices-blueprint
20c8d494519b3d54bc3981aebdad18871deef3cb
src/sentry/auth/manager.py
src/sentry/auth/manager.py
from __future__ import absolute_import, print_function __all__ = ['ProviderManager'] from .exceptions import ProviderNotRegistered # Ideally this and PluginManager abstracted from the same base, but # InstanceManager has become convulated and wasteful class ProviderManager(object): def __init__(self): s...
from __future__ import absolute_import, print_function __all__ = ['ProviderManager'] from .exceptions import ProviderNotRegistered # Ideally this and PluginManager abstracted from the same base, but # InstanceManager has become convulated and wasteful class ProviderManager(object): def __init__(self): s...
Revert back to using key
Revert back to using key
Python
bsd-3-clause
argonemyth/sentry,gencer/sentry,JamesMura/sentry,vperron/sentry,nicholasserra/sentry,alexm92/sentry,jokey2k/sentry,zenefits/sentry,jokey2k/sentry,zenefits/sentry,Kryz/sentry,llonchj/sentry,llonchj/sentry,daevaorn/sentry,zenefits/sentry,ewdurbin/sentry,TedaLIEz/sentry,boneyao/sentry,nicholasserra/sentry,felixbuenemann/s...
2bf4aacbc2a43305506d2d16cef97c6c89c30ee9
pythontutorials/books/AutomateTheBoringStuff/Ch13/P3_combinePDFs.py
pythontutorials/books/AutomateTheBoringStuff/Ch13/P3_combinePDFs.py
#! python3 """Combine PDFs Combines all the PDFs in the current working directory into a single PDF. Note: * Example PDFs can be downloaded from http://nostarch.com/automatestuff/ * Book uses PyPDF2; I'm an overachiever that uses PyPDF4 """ def main(): import PyPDF4, os # Get all the PDF filenames...
#! python3 """Combine PDFs Combines all the PDFs in the current working directory into a single PDF. Note: * Example PDFs can be downloaded from http://nostarch.com/automatestuff/ * Book uses :py:mod:`PyPDF2`; I'm an overachiever that uses PyPDF4 """ def main(): import PyPDF4, os # Get all the PDF...
Update P2_combinePDF.py added module reference in docstring
Update P2_combinePDF.py added module reference in docstring
Python
mit
JoseALermaIII/python-tutorials,JoseALermaIII/python-tutorials
ce25cea7e8d10f9c318e2e7ef1dc1013921ed062
clint/textui/prompt.py
clint/textui/prompt.py
# -*- coding: utf8 -*- """ clint.textui.prompt ~~~~~~~~~~~~~~~~~~~ Module for simple interactive prompts handling """ from __future__ import absolute_import from re import match, I def yn(prompt, default='y', batch=False): # A sanity check against default value # If not y/n then y is assumed if defau...
# -*- coding: utf8 -*- """ clint.textui.prompt ~~~~~~~~~~~~~~~~~~~ Module for simple interactive prompts handling """ from __future__ import absolute_import, print_function from re import match, I def yn(prompt, default='y', batch=False): # A sanity check against default value # If not y/n then y is assum...
Use print() function to fix install on python 3
Use print() function to fix install on python 3 clint 0.3.2 can't be installed on python 3.3 because of a print statement.
Python
isc
1gitGrey/clint,thusoy/clint,wkentaro/clint,1gitGrey/clint,glorizen/clint,wkentaro/clint,tz70s/clint,Lh4cKg/clint,nathancahill/clint,kennethreitz/clint,nathancahill/clint
d677f3762e0daf16e1be05a88b058194ddf43e15
comics/comics/perrybiblefellowship.py
comics/comics/perrybiblefellowship.py
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "The Perry Bible Fellowship" language = "en" url = "http://www.pbfcomics.com/" start_date = "2001-01-01" rights = "Nicholas Gurewitch" class Cra...
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "The Perry Bible Fellowship" language = "en" url = "http://www.pbfcomics.com/" start_date = "2001-01-01" rights = "Nicholas Gurewitch" class Cra...
Rewrite "The Perry Bible Fellowship" after feed change
Rewrite "The Perry Bible Fellowship" after feed change
Python
agpl-3.0
datagutten/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics,datagutten/comics
241d1e6b36eb8f87a5c6111bfa52104feb821bb8
test/dependencies_test.py
test/dependencies_test.py
import luigi import sciluigi as sl import os TESTFILE_PATH = '/tmp/test.out' class TestTask(sl.Task): def out_data(self): return sl.TargetInfo(self, TESTFILE_PATH) def run(self): with self.out_data().open('w') as outfile: outfile.write('File written by luigi\n') class TestRunTas...
import logging import luigi import sciluigi as sl import os TESTFILE_PATH = '/tmp/test.out' log = logging.getLogger('sciluigi-interface') log.setLevel(logging.WARNING) class TestTask(sl.Task): def out_data(self): return sl.TargetInfo(self, TESTFILE_PATH) def run(self): with self.out_data()....
Set log level to WARNING when testing
Set log level to WARNING when testing
Python
mit
pharmbio/sciluigi,samuell/sciluigi,pharmbio/sciluigi
758a8bff354d1e1542b5c4614276bdfa229f3dbc
extended_choices/__init__.py
extended_choices/__init__.py
"""Little helper application to improve django choices (for fields)""" from __future__ import unicode_literals from .choices import Choices, OrderedChoices __author__ = 'Stephane "Twidi" Ange;' __contact__ = "s.angel@twidi.com" __homepage__ = "https://pypi.python.org/pypi/django-extended-choices" __version__ = "1.1....
"""Little helper application to improve django choices (for fields)""" from __future__ import unicode_literals from .choices import Choices, OrderedChoices __all__ = ['Choices', 'OrderedChoices'] __author__ = 'Stephane "Twidi" Ange;' __contact__ = "s.angel@twidi.com" __homepage__ = "https://pypi.python.org/pypi/djan...
Add `__all__` at package root level
Add `__all__` at package root level
Python
bsd-3-clause
twidi/django-extended-choices
ee4c8b806ecf0ada51916fe63f9da9e81c03850d
django_react_templatetags/tests/demosite/urls.py
django_react_templatetags/tests/demosite/urls.py
from django.urls import path from django_react_templatetags.tests.demosite import views urlpatterns = [ path( 'static-react-view', views.StaticReactView.as_view(), name='static_react_view', ), ]
from django.conf.urls import url from django_react_templatetags.tests.demosite import views urlpatterns = [ url( 'static-react-view', views.StaticReactView.as_view(), name='static_react_view', ), ]
Use url instead of path (to keep django 1 compat)
Use url instead of path (to keep django 1 compat)
Python
mit
Frojd/django-react-templatetags,Frojd/django-react-templatetags,Frojd/django-react-templatetags
78af5e585eb109049299bd1c826f93001e4f6c68
adama/store.py
adama/store.py
import collections import pickle import redis from .tools import location class Store(collections.MutableMapping): def __init__(self, db=0): host, port = location('redis', 6379) self._db = redis.StrictRedis(host=host, port=port, db=db) def __getitem__(self, key): obj = self._db.get...
import collections import pickle import redis class Store(collections.MutableMapping): def __init__(self, db=0): host, port = 'redis', 6379 self._db = redis.StrictRedis(host=host, port=port, db=db) def __getitem__(self, key): obj = self._db.get(key) if obj is None: ...
Use /etc/hosts to find redis
Use /etc/hosts to find redis
Python
mit
waltermoreira/adama-app,waltermoreira/adama-app,waltermoreira/adama-app
50f8e32521ccf871177b4402b6a410dad896b272
src/schema_matching/collector/description/_argparser.py
src/schema_matching/collector/description/_argparser.py
import utilities def parse(src): if src == ':': from ..description import default as desc elif src.startswith(':'): import importlib desc = importlib.import_module(src[1:]) else: import os, imp from .. import description as parent_package # needs to be imported before its child modules with open(src) a...
import importlib def parse(src): try: if src == ':': from ..description import default as desc elif src.startswith(':'): desc = importlib.import_module(src[1:], __package__.partition('.')[0]) else: desc = importlib.machinery.SourceFileLoader(src, src).load_module() except: raise ImportError(src) ...
Use importlib in favour of imp
Use importlib in favour of imp
Python
mit
davidfoerster/schema-matching
e94e3931ec254e432993d18d9f4ac79f559a2257
scripts/starting_py_program.py
scripts/starting_py_program.py
import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def main(argv=None): if argv is None: argv = sys.argv return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/env python3 # from __future__ import print_function #(if python2) import sys def eprint(*args, **kwargs): """ Just like the print function, but on stderr """ print(*args, file=sys.stderr, **kwargs) def main(argv=None): """ Program starting point, it can started by the OS or as normal fun...
Add docstrings to starting py program
Add docstrings to starting py program
Python
unlicense
paolobolzoni/useful-conf,paolobolzoni/useful-conf,paolobolzoni/useful-conf
13f8d6feebcfb28b96bb0f69d1e5625a337c22fa
demo/ok_test/tests/q1.py
demo/ok_test/tests/q1.py
test = { 'name': 'Question 1', 'points': 3, 'suites': [ { 'cases': [ { 'answer': 'Domain is numbers. Range is numbers', 'choices': [ 'Domain is numbers. Range is numbers', 'Domain is numbers. Range is strings', 'Domain is strings. Range is ...
test = { 'name': 'Question 1', 'points': 3, 'suites': [ { 'type': 'concept', 'cases': [ { 'answer': 'Domain is numbers. Range is numbers', 'choices': [ 'Domain is numbers. Range is numbers', 'Domain is numbers. Range is strings', 'Dom...
Add a demo for wwpp
Add a demo for wwpp
Python
apache-2.0
jathak/ok-client,Cal-CS-61A-Staff/ok-client,jackzhao-mj/ok-client
6dadf50366b1e142f96ef3bf4a356f7aa98f37be
geokey_export/__init__.py
geokey_export/__init__.py
from geokey.extensions.base import register VERSION = (0, 2, 0) __version__ = '.'.join(map(str, VERSION)) register( 'geokey_export', 'Export', display_admin=True, superuser=False, version=__version__ )
from geokey.extensions.base import register VERSION = (0, 2, 0) __version__ = '.'.join(map(str, VERSION)) register( 'geokey_export', 'Export', display_admin=True, superuser=False )
Undo previous commit (should not been on new branch) - Sorry!
Undo previous commit (should not been on new branch) - Sorry! Signed-off-by: Matthias Stevens <3e0606afd16757d2df162884117429808539458f@gmail.com>
Python
mit
ExCiteS/geokey-export,ExCiteS/geokey-export,ExCiteS/geokey-export
a6774092839f8c6aff743cf8f4cc982fe8ce2e63
interfaces/cython/cantera/mixmaster/utilities.py
interfaces/cython/cantera/mixmaster/utilities.py
import string import os, sys import types, traceback try: if sys.version_info[0] == 3: from tkinter import Tk from tkinter import messagebox else: from Tkinter import Tk import tkMessageBox _hasTk = 1 except: _hasTk = 0 def write_CSV(f,x): """write list x to file f...
import string import os, sys import types, traceback try: if sys.version_info[0] == 3: from tkinter import Tk from tkinter import messagebox else: from Tkinter import Tk import tkMessageBox as messagebox _hasTk = 1 except: _hasTk = 0 def write_CSV(f,x): """write li...
Fix displaying of errors when using Python 2
[MixMaster] Fix displaying of errors when using Python 2
Python
bsd-3-clause
Heathckliff/cantera,imitrichev/cantera,imitrichev/cantera,imitrichev/cantera,Heathckliff/cantera,Heathckliff/cantera,Heathckliff/cantera,imitrichev/cantera,Heathckliff/cantera,imitrichev/cantera,Heathckliff/cantera,imitrichev/cantera
f13e9ff10c79f58df2f6d43c8b840b642be56dab
core/admin.py
core/admin.py
# -*- encoding: UTF-8 -*- # # Copyright 2014-2015 # # STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es> # # This file is part of Portal del Investigador. # # Portal del Investigador is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero Gen...
# -*- encoding: UTF-8 -*- # # Copyright 2014-2015 # # STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es> # # This file is part of Portal del Investigador. # # Portal del Investigador is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero Gen...
Patch django submit_row templatetag so it takes into account button config sent in context
Patch django submit_row templatetag so it takes into account button config sent in context
Python
agpl-3.0
tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador
30bfe04e0fa1386e263cbd0e8dbc6f3689f9cb21
connector_carepoint/migrations/9.0.1.3.0/pre-migrate.py
connector_carepoint/migrations/9.0.1.3.0/pre-migrate.py
# -*- coding: utf-8 -*- # Copyright 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). def migrate(cr, version): cr.execute('ALTER TABLE carepoint_medical_prescription_order_line ' 'RENAME TO carepoint_rx_ord_ln') cr.execute('ALTER TABLE carepoint_carepoint_organ...
# -*- coding: utf-8 -*- # Copyright 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging _logger = logging.getLogger(__name__) def migrate(cr, version): try: cr.execute('ALTER TABLE carepoint_medical_prescription_order_line ' 'RENAME TO care...
Fix prescription migration * Add try/catch & rollback to db alterations in case server re-upgrades
[FIX] connector_carepoint: Fix prescription migration * Add try/catch & rollback to db alterations in case server re-upgrades
Python
agpl-3.0
laslabs/odoo-connector-carepoint
259ac1bf6390c050892fa678842c1793e7f1dda0
runtests.py
runtests.py
#!/usr/bin/env python import os import sys import unittest from huey import tests def _requirements_installed(): try: import django return True except Exception: return False def run_tests(*test_args): suite = unittest.TestLoader().loadTestsFromModule(tests) result = unittes...
#!/usr/bin/env python import os import sys import unittest from huey import tests def _requirements_installed(): try: import django return True except Exception: return False def run_tests(*test_args): suite = unittest.TestLoader().loadTestsFromModule(tests) result = unittes...
Allow running tests without Django.
Allow running tests without Django.
Python
mit
coleifer/huey,rsalmaso/huey,pombredanne/huey
650c94107106cddafccaf5d2021a6407fcac990e
bend/src/users/jwt_util.py
bend/src/users/jwt_util.py
from jwt_auth.forms import JSONWebTokenForm def loginUser(username, password): """Should login user and return a jwt token, piggyback on jwt_auth""" request = {"username": username, "password": password} form = JSONWebTokenForm(request) if not form.is_valid(): return print("JWT form not valid"...
from jwt_auth.forms import JSONWebTokenForm def loginUser(username, password): """Should login user and return a jwt token, piggyback on jwt_auth""" request = {"username": username, "password": password} form = JSONWebTokenForm(request) if not form.is_valid(): return print("JWT form not valid"...
Return the token string instead of object with string
Return the token string instead of object with string
Python
mit
ncrmro/ango,ncrmro/reango,ncrmro/ango,ncrmro/reango,ncrmro/ango,ncrmro/reango
994e185e7bb8b2ffb78f20012121c441ea6b73a1
comics/views.py
comics/views.py
from django.views import generic from gallery.models import GalleryImage from .models import Arc, Issue class IndexView(generic.ListView): model = Arc template_name = "comics/index.html" context_object_name = "arcs" class IssueView(generic.DetailView): model = Issue template_name = "comics/issu...
from django.views import generic from gallery.models import GalleryImage from .models import Arc, Issue class IndexView(generic.ListView): model = Arc template_name = "comics/index.html" context_object_name = "arcs" class IssueView(generic.DetailView): model = Issue template_name = "comics/issu...
Fix bug where arc slug could be literally anything
Fix bug where arc slug could be literally anything
Python
mit
evanepio/dotmanca,evanepio/dotmanca,evanepio/dotmanca
d624a1e638cf6f1fca7b7d8966f3ab7c6c9f7300
linter.py
linter.py
from SublimeLinter.lint import Linter, util class Cppcheck(Linter): cmd = ('cppcheck', '--template=gcc', '--inline-suppr', '--quiet', '${args}', '${file}') regex = ( r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\d+):)?\s+' r'((?P<error>error)|(?P<warning>warning|style|performance|portabilit...
from SublimeLinter.lint import Linter, util class Cppcheck(Linter): cmd = ('cppcheck', '--template={file}:{line}: {severity}: {message}', '--inline-suppr', '--quiet', '${args}', '${file}') regex = ( r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\d+):)?\s+' r'((?P<error>error)|(?P<warning>war...
Use explicit template instead of 'gcc'
Use explicit template instead of 'gcc' cppcheck 1.84 changed the meaning of --template=gcc to add a second line of output that confuses the linter plugin, so explicitly request the old format see https://github.com/danmar/cppcheck/commit/f058d9ad083a6111e9339b4b3506c5da7db579e0 for the details of that change
Python
mit
SublimeLinter/SublimeLinter-cppcheck
2b81d198b7d3dd9094f47d2f8e51f0275ee31463
osf/migrations/0084_migrate_node_info_for_target.py
osf/migrations/0084_migrate_node_info_for_target.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-11-13 16:14 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('osf', '0083_add_file_fields_for_target'), ] operations = [ migrations.RunSQL( ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-11-13 16:14 from __future__ import unicode_literals from django.db import migrations, models, connection from django.contrib.contenttypes.models import ContentType def set_basefilenode_target(apps, schema_editor): BaseFileNode = apps.get_model('osf', '...
Use batches instead of raw sql for long migration
Use batches instead of raw sql for long migration
Python
apache-2.0
baylee-d/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,mattclark/osf.io,aaxelb/osf.io,HalcyonChimera/osf.io,adlius/osf.io,felliott/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,...