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
88210804900c48a895c6ed90ae20dd08dc32e162
alfred_listener/views.py
alfred_listener/views.py
from flask import Blueprint, request, json from alfred_db.models import Repository, Commit from .database import db from .helpers import parse_hook_data webhooks = Blueprint('webhooks', __name__) @webhooks.route('/', methods=['POST']) def handler(): payload = request.form.get('payload', '') try: pa...
from flask import Blueprint, request, json from alfred_db.models import Repository, Commit from .database import db from .helpers import parse_hook_data webhooks = Blueprint('webhooks', __name__) @webhooks.route('/', methods=['POST']) def handler(): payload = request.form.get('payload') try: payloa...
Improve loading of payload from json
Improve loading of payload from json
Python
isc
alfredhq/alfred-listener
c86c32453e241543317509495357e05c73b57047
django_tenant_templates/middleware.py
django_tenant_templates/middleware.py
""" Middleware! """ from django_tenant_templates import local class TenantMiddleware(object): """Middleware for enabling tenant-aware template loading.""" slug_property_name = 'tenant_slug' def process_request(self, request): local.tenant_slug = getattr(request, self.slug_property_name, None)
""" Middleware! """ from django_tenant_templates import local class TenantMiddleware(object): """Middleware for enabling tenant-aware template loading.""" slug_property_name = 'tenant_slug' def process_request(self, request): local.tenant_slug = getattr(request, self.slug_property_name, None) ...
Remove the thread local on exceptions
Remove the thread local on exceptions
Python
mit
grampajoe/django-tenant-templates
cd5e52c8e1d481c8e1bf1e7a71b0c421e53c93c9
featureflow/__init__.py
featureflow/__init__.py
__version__ = '1.16.14' from model import BaseModel from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \ PickleFeature from extractor import Node, Graph, Aggregator, NotEnoughData from bytestream import ByteStream, ByteStreamFeature, ZipWrapper, iter_zip from data import \ IdProvider...
__version__ = '1.16.14' from model import BaseModel from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \ PickleFeature from extractor import Node, Graph, Aggregator, NotEnoughData from bytestream import ByteStream, ByteStreamFeature, ZipWrapper, iter_zip from data import \ IdProvider...
Add EventLog stuff to package-level exports
Add EventLog stuff to package-level exports
Python
mit
JohnVinyard/featureflow,JohnVinyard/featureflow
fca7ad2068dfec30ad210964234957b46e6436bc
tests/test_client.py
tests/test_client.py
import unittest from bluesnap.client import Client class ClientTestCase(unittest.TestCase): DUMMY_CREDENTIALS = { 'username': 'username', 'password': 'password', 'default_store_id': '1', 'seller_id': '1', } def setUp(self): self.client = Client(env='live', **self....
import unittest from bluesnap.client import Client class ClientTestCase(unittest.TestCase): DUMMY_CREDENTIALS = { 'username': 'username', 'password': 'password', 'default_store_id': '1', 'seller_id': '1', 'default_currency': 'GBP' } def setUp(self): self.c...
Send default_currency in Client init on client test
Send default_currency in Client init on client test
Python
mit
kowito/bluesnap-python,kowito/bluesnap-python,justyoyo/bluesnap-python,justyoyo/bluesnap-python
c83e0134104d4ee6de9a3e5b7d0e34be2a684daa
tests/test_shared.py
tests/test_shared.py
# -*- coding: utf-8 -*- from flask.ext.testing import TestCase import os import tempfile import shutil import websmash class ModelTestCase(TestCase): def create_app(self): self.app = websmash.app self.dl = websmash.dl self.app.config['TESTING'] = True self.app.config['SQLALCHEMY_DA...
# -*- coding: utf-8 -*- from flask.ext.testing import TestCase import os import tempfile import shutil import websmash class ModelTestCase(TestCase): def create_app(self): self.app = websmash.app self.dl = websmash.dl self.app.config['TESTING'] = True self.app.config['SQLALCHEMY_DA...
Fix the temp file initialization
tests: Fix the temp file initialization Signed-off-by: Kai Blin <94ddc6985b47aef772521e302594241f46a8f665@biotech.uni-tuebingen.de>
Python
agpl-3.0
antismash/ps-web,antismash/ps-web,antismash/websmash,antismash/ps-web
5547b0bfcd3903d7786be91c136366ada9c3ebae
detection.py
detection.py
import os import sys import datetime from django.utils import timezone from datetime import timedelta os.environ.setdefault("DJANGO_SETTINGS_MODULE", "madapp.settings") from django.core.management import execute_from_command_line from django.db.models import Count, Avg from madapp import settings from madapp.mad.mode...
import os import sys import datetime import django import commands from django.utils import timezone from datetime import timedelta os.environ.setdefault("DJANGO_SETTINGS_MODULE", "madapp.settings") from django.core.management import execute_from_command_line from django.db.models import Count, Avg import django.db....
Change in the Flows storage
Change in the Flows storage
Python
apache-2.0
gilneidp/TADD,gilneidp/TADD,gilneidp/TADD,gilneidp/TADD,gilneidp/TADD
474ba4b8983c0f0f40e7a9a7e045cec79dc6845f
SigmaPi/Secure/models.py
SigmaPi/Secure/models.py
from django.db import models from django.contrib.auth.models import Group class CalendarKey(models.Model): # The group which has access to this key. group = models.ForeignKey(Group, related_name="calendar_key", default=1) # The calendar key. key = models.CharField(max_length=100)
from django.db import models from django.contrib.auth.models import Group class CalendarKey(models.Model): # The group which has access to this key. group = models.ForeignKey(Group, related_name="calendar_key", default=1) # The calendar key. key = models.CharField(max_length=100) def __unicode__...
Add __unicode__ method to CalendarKey model.
Add __unicode__ method to CalendarKey model.
Python
mit
sigmapi-gammaiota/sigmapi-web,sigmapi-gammaiota/sigmapi-web,sigmapi-gammaiota/sigmapi-web,sigmapi-gammaiota/sigmapi-web
60f88e2e90ff411f121236a0e44100ca2022f9bb
test_sequencer.py
test_sequencer.py
def run(tests): print '=> Going to run', len(tests), 'tests' ok = [] fail = [] for number, test in enumerate(tests): print '\t-> [' + str(number) + '/' + str(len(tests)) + ']', test.__doc__ error = test() if error is None: ok.append((number, test)) else: ...
import sys # "Test" is a function. It takes no arguments and returns any encountered errors. # If there is no error, test should return 'None'. Tests shouldn't have any dependencies # amongst themselves. def run(tests): """If no arguments (sys.argv) are given, runs tests. If there are any arguments they are ...
Use formatted strings, add tests filter
Use formatted strings, add tests filter
Python
mit
fmfi-svt-deadlock/hw-testing,fmfi-svt-deadlock/hw-testing
9c42a7925d4e872a6245301ef68b2b9aa1f0aa7b
tests/__init__.py
tests/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com> # Copyright 2012 Google, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com> # Copyright 2012 Google, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ...
Declare unittest lib used within python version
Declare unittest lib used within python version
Python
apache-2.0
glorizen/watchdog,ymero/watchdog,javrasya/watchdog,mconstantin/watchdog,teleyinex/watchdog,gorakhargosh/watchdog,javrasya/watchdog,ymero/watchdog,javrasya/watchdog,mconstantin/watchdog,teleyinex/watchdog,teleyinex/watchdog,glorizen/watchdog,glorizen/watchdog,gorakhargosh/watchdog,mconstantin/watchdog,ymero/watchdog
3ae6c0f4c4f13207386dbf0fa2004655e9f2c8d6
UM/View/CompositePass.py
UM/View/CompositePass.py
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from UM.Application import Application from UM.Resources import Resources from UM.Math.Matrix import Matrix from UM.View.RenderPass import RenderPass from UM.View.GL.OpenGL import OpenGL class CompositePass(RenderPass): ...
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from UM.Application import Application from UM.Resources import Resources from UM.Math.Matrix import Matrix from UM.View.RenderPass import RenderPass from UM.View.GL.OpenGL import OpenGL class CompositePass(RenderPass): ...
Add explicit render layer binding instead of assuming all render passes can be used for compositing
Add explicit render layer binding instead of assuming all render passes can be used for compositing
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
46566c568b20a037006cf7bbebdc70353e163bb2
paintings/processors.py
paintings/processors.py
from random import randrange from paintings.models import Gallery, Painting def get_Galleries(request): return ( {'galleries' : Gallery.objects.all()} ) def get_random_canvasOilPainting(request): paintings = Painting.objects.filter(surface='canvas', material='oil').extra(where=['width > height']) rand_painting ...
from random import randrange from paintings.models import Gallery, Painting def get_Galleries(request): return ( {'galleries' : Gallery.objects.all()} ) def get_random_canvasOilPainting(request): try: paintings = Painting.objects.filter(surface='canvas', material='oil').extra(where=['width > height']) rand_p...
Fix bug with empty db
Fix bug with empty db
Python
mit
hombit/olgart,hombit/olgart,hombit/olgart,hombit/olgart
5b4c710df7149b0654fc731979978a9a561614a3
wluopensource/osl_flatpages/models.py
wluopensource/osl_flatpages/models.py
from django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) title = models.CharField(blank=True, max_length=100) description = models.CharField(blank=True, max_length=255) markdown_content = models.TextField('con...
from django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) title = models.CharField(blank=True, max_length=100) description = models.CharField(blank=True, max_length=255) markdown_content = models.TextField('con...
Change flatpage ordering to order by page name ascending
Change flatpage ordering to order by page name ascending
Python
bsd-3-clause
jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website
b9b095a2a66f79e36bbad1affaeb57b38e20803b
cwod_site/cwod/models.py
cwod_site/cwod/models.py
from django.db import models # Create your models here. class CongressionalRecordVolume(models.Model): congress = models.IntegerField(db_index=True) session = models.CharField(max_length=10, db_index=True) volume = models.IntegerField()
from django.db import models # Create your models here. class CongressionalRecordVolume(models.Model): congress = models.IntegerField(db_index=True) session = models.CharField(max_length=10, db_index=True) volume = models.IntegerField() class NgramDateCount(models.Model): """Storing the total number...
Create model for storing total n-gram counts by date
Create model for storing total n-gram counts by date
Python
bsd-3-clause
sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,propublica/Capitol-Words,propublica/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,propublica/Capitol-Words,propublica/Capitol-Words
906c71ed59a6349aed83cd18248dfe8463e3a028
src/integrate_tool.py
src/integrate_tool.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from bioblend import galaxy from bioblend import toolshed if __name__ == '__main__': gi_url = "http://172.21.23.6:8080/" ts_url = "http://172.21.23.6:9009/" name = "qiime" owner = "iuc" tool_panel_section_id = "qiime_rRNA_taxonomic_assignation" g...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse import re from bioblend import galaxy from bioblend import toolshed def retrieve_changeset_revision(ts_url, name, owner): ts = toolshed.ToolShedInstance(url=ts_url) ts_repositories = ts.repositories.get_repositories() ts_...
Improve integrate tool wrapper with arguments
Improve integrate tool wrapper with arguments
Python
apache-2.0
ASaiM/framework,ASaiM/framework
90fa23d1d1b2497d65507b7930323b118f512a25
disco_aws_automation/disco_acm.py
disco_aws_automation/disco_acm.py
""" Some code to manage the Amazon Certificate Service. """ import logging import boto3 import botocore class DiscoACM(object): """ A class to manage the Amazon Certificate Service """ def __init__(self, connection=None): self._acm = connection @property def acm(self): """ ...
""" Some code to manage the Amazon Certificate Service. """ import logging import boto3 import botocore class DiscoACM(object): """ A class to manage the Amazon Certificate Service """ def __init__(self, connection=None): self._acm = connection @property def acm(self): """ ...
Revert "Swallow proxy exception from requests"
Revert "Swallow proxy exception from requests" This reverts commit 8d9ccbb2bbde7c2f8dbe60b90f730d87b924d86e.
Python
bsd-2-clause
amplifylitco/asiaq,amplifylitco/asiaq,amplifylitco/asiaq
e3c12bd54e143086dd332a51195e4eb3f7305201
exercise3.py
exercise3.py
#!/usr/bin/env python """ Assignment 1, Exercise 3, INF1340, Fall, 2015. Troubleshooting Car Issues. This module contains one function diagnose_car(). It is an expert system to interactive diagnose car issues. """ __author__ = 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__...
#!/usr/bin/env python """ Assignment 1, Exercise 3, INF1340, Fall, 2015. Troubleshooting Car Issues. This module contains one function diagnose_car(). It is an expert system to interactive diagnose car issues. """ __author__ = 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__...
Update - First question yes, small coding done
Update - First question yes, small coding done
Python
mit
xueshen3/inf1340_2015_asst1
b6afc5f1db5c416fde43567623161bbe2244897b
docs/conf.py
docs/conf.py
#!/usr/bin/env python3 project = "dependencies" copyright = "2016-2018, Artem Malyshev" author = "Artem Malyshev" version = "0.15" release = "0.15" templates_path = ["templates"] source_suffix = ".rst" master_doc = "index" language = None exclude_patterns = ["_build"] pygments_style = "sphinx" html_theme = ...
#!/usr/bin/env python3 project = "dependencies" copyright = "2016-2018, Artem Malyshev" author = "Artem Malyshev" version = "0.15" release = "0.15" templates_path = ["templates"] source_suffix = ".rst" master_doc = "index" language = None exclude_patterns = ["_build"] pygments_style = "sphinx" html_theme = ...
Add Next/Previous page links to the docs.
Add Next/Previous page links to the docs.
Python
bsd-2-clause
proofit404/dependencies,proofit404/dependencies,proofit404/dependencies,proofit404/dependencies
ccc98ced56ee8dda02332720c7146e1548a3b53c
project/project/urls.py
project/project/urls.py
""" project URL Configuration """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^admin_tools/', include('admin_tools.urls')), url(r'^accounts/logout/$', 'allauth.account.views.logout', name='account_logout'), ...
""" project URL Configuration """ from django.conf.urls import include, url from django.conf import settings from django.contrib import admin from django.views.generic.base import RedirectView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^admin_tools/', include('admin_tools.urls')), ...
Set up redirect to login view
Set up redirect to login view
Python
mit
jonsimington/app,compsci-hfh/app,compsci-hfh/app,jonsimington/app
5dc63d9c544f0335cd037bc2f6c0ce613e7783ea
gerrit/documentation.py
gerrit/documentation.py
# -*- coding: utf-8 -*- URLS = { } class Documentation(object): """ This class provide documentation-related methods Documentation related REST endpoints: https://gerrit-review.googlesource.com/Documentation/rest-api-documentation.html """ def __init__(self, gerrit): self.gerrit = gerrit...
# -*- coding: utf-8 -*- URLS = { 'SEARCH': 'Documentation/?q=%(keyword)s', } class Documentation(object): """ This class provide documentation-related methods Documentation related REST endpoints: https://gerrit-review.googlesource.com/Documentation/rest-api-documentation.html """ def __init...
Add methods for Documentation Endpoints
Add methods for Documentation Endpoints Signed-off-by: Huang Yaming <ce2ec9fa26f071590d1a68b9e7447b51f2c76084@gmail.com>
Python
apache-2.0
yumminhuang/gerrit.py
c4df7c0de4cadffc665a353763f6d5cabada1b85
voicerecorder/settings.py
voicerecorder/settings.py
# -*- coding: utf-8 -*- import os import contextlib from PyQt5 import QtCore from . import __app_name__ from . import helperutils def _qsettings_group_factory(settings: QtCore.QSettings): @contextlib.contextmanager def qsettings_group_context(group_name: str): settings.beginGroup(group_name) ...
# -*- coding: utf-8 -*- import os import contextlib from PyQt5 import QtCore from . import __app_name__ from . import helperutils def _qsettings_group_factory(settings: QtCore.QSettings): @contextlib.contextmanager def qsettings_group_context(group_name: str): settings.beginGroup(group_name) ...
Add "s" attr for QSettings
Add "s" attr for QSettings
Python
mit
espdev/VoiceRecorder
fd4bc228c978019a7251fefe2c92899a16b8f95d
demosys/scene/shaders.py
demosys/scene/shaders.py
from pyrr import Matrix33 class MeshShader: def __init__(self, shader): self.shader = shader def draw(self, mesh, proj_mat, view_mat): """Minimal draw function. Should be overridden""" mesh.vao.bind(self.shader) self.shader.uniform_mat4("m_proj", proj_mat) self.shader...
from pyrr import Matrix33 class MeshShader: def __init__(self, shader, **kwargs): self.shader = shader def draw(self, mesh, proj_mat, view_mat): """Minimal draw function. Should be overridden""" mesh.vao.bind(self.shader) self.shader.uniform_mat4("m_proj", proj_mat) s...
Allow sending kwars to mesh shader
Allow sending kwars to mesh shader
Python
isc
Contraz/demosys-py
83efb4c86ea34e9f51c231a3b7c96929d2ba5ee6
bluebottle/utils/staticfiles_finders.py
bluebottle/utils/staticfiles_finders.py
from django.utils._os import safe_join import os from django.conf import settings from django.contrib.staticfiles.finders import FileSystemFinder from bluebottle.clients.models import Client class TenantStaticFilesFinder(FileSystemFinder): def find(self, path, all=False): """ Looks for files in ...
from django.utils._os import safe_join import os from django.conf import settings from django.contrib.staticfiles.finders import FileSystemFinder from bluebottle.clients.models import Client class TenantStaticFilesFinder(FileSystemFinder): def find(self, path, all=False): """ Looks for files in ...
Fix static files finder errors
Fix static files finder errors Conflicts: bluebottle/utils/staticfiles_finders.py
Python
bsd-3-clause
onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
59691ed33347c60fe15014facee272e00f58ed3a
server/plugins/cryptstatus/cryptstatus.py
server/plugins/cryptstatus/cryptstatus.py
import requests from collections import defaultdict from requests.exceptions import RequestException from django.conf import settings from django.utils.dateparse import parse_datetime import sal.plugin import server.utils as utils class CryptStatus(sal.plugin.DetailPlugin): description = 'FileVault Escrow Stat...
import requests from collections import defaultdict from requests.exceptions import RequestException from django.conf import settings from django.utils.dateparse import parse_datetime import sal.plugin import server.utils as utils class CryptStatus(sal.plugin.DetailPlugin): description = 'FileVault Escrow Stat...
Make sure `output` variable is in scope no matter what.
Make sure `output` variable is in scope no matter what.
Python
apache-2.0
salopensource/sal,sheagcraig/sal,salopensource/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal
0033a29537740592ea47b1e372a9aa3873120c35
i18n/main.py
i18n/main.py
#!/usr/bin/env python import importlib import sys def main(): try: command = sys.argv[1] except IndexError: sys.stderr.write('must specify a command\n') return -1 module = importlib.import_module('i18n.%s' % command) module.main.args = sys.argv[2:] return module.main() if _...
#!/usr/bin/env python import importlib import sys from path import path def get_valid_commands(): modules = [m.basename().split('.')[0] for m in path(__file__).dirname().files('*.py')] commands = [] for modname in modules: if modname == 'main': continue mod = importlib.import_mo...
Add helpful list of subcommands.
Add helpful list of subcommands.
Python
apache-2.0
baxeico/i18n-tools,baxeico/i18n-tools,edx/i18n-tools
3c534faee2f97dd8e2b5503fdbcac59737489f54
backend/scripts/ddirdenorm.py
backend/scripts/ddirdenorm.py
#!/usr/bin/env python import rethinkdb as r conn = r.connect('localhost', 30815, db='materialscommons') if __name__ == "__main__": selection = list(r.table('datadirs').run(conn)) for datadir in selection: print "Updating datadir %s" % (datadir['name']) ddir = {} ddir['id'] = datadir['...
#!/usr/bin/env python import rethinkdb as r import optparse if __name__ == "__main__": parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", help="rethinkdb port", default=30815) (options, args) = parser.parse_args() conn = r.connect('localhost', int(op...
Add options for setting the port.
Add options for setting the port.
Python
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
8139a3a49e4ee6d1fc8a2a71becbfd6d625b5c5f
apps/accounts/serializers.py
apps/accounts/serializers.py
from django.contrib.auth.models import User from rest_framework import serializers from rest_framework.fields import HyperlinkedIdentityField class MemberDetailSerializer(serializers.ModelSerializer): url = HyperlinkedIdentityField(view_name='member-detail') class Meta: model = User fields =...
from apps.bluebottle_utils.serializers import SorlImageField from django.contrib.auth.models import User from rest_framework import serializers from rest_framework.fields import HyperlinkedIdentityField class MemberDetailSerializer(serializers.ModelSerializer): url = HyperlinkedIdentityField(view_name='member-de...
Add picture field member detail api.
Add picture field member detail api.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
65b3a7fa7ae7ee467d3e8ef32b9a00b99b095c3e
humblemedia/processing_spooler.py
humblemedia/processing_spooler.py
import uwsgi import django django.setup() from resources.processing import BaseProcessor from resources.models import Attachment def content_processing(env): print (env) resource_id = int(env.get(b"id")) processor_name = env.get(b"processor").decode() att = Attachment.objects.get(id=resource_id) ...
import uwsgi import django django.setup() from resources.processing import BaseProcessor from resources.models import Attachment def content_processing(env): print (env) resource_id = int(env.get(b"id")) processor_name = env.get(b"processor").decode() try: att = Attachment.objects.get(id=res...
Return ok if db object does not exist in spooler
Return ok if db object does not exist in spooler
Python
mit
vladimiroff/humble-media,vladimiroff/humble-media
b58b270c707b57e9f6c245f1ebb31d68a247471c
mastering-python/ch05/Decorator.py
mastering-python/ch05/Decorator.py
import functools def logParams(function): @functools.wraps(function) # use this to prevent loss of function attributes def wrapper(*args, **kwargs): print("function: {}, args: {}, kwargs: {}".format(function.__name__, args, kwargs)) return function(*args, **kwargs) return wrapper def add...
import functools def logParams(function): @functools.wraps(function) # use this to prevent loss of function attributes def wrapper(*args, **kwargs): print("function: {}, args: {}, kwargs: {}".format(function.__name__, args, kwargs)) return function(*args, **kwargs) return wrapper def add...
Add class method decorator demo.
Add class method decorator demo.
Python
apache-2.0
precompiler/python-101
3f39c9d89da004556bcf53fa815f88a3092f600e
syft/frameworks/torch/tensors/native.py
syft/frameworks/torch/tensors/native.py
import random from syft.frameworks.torch.tensors import PointerTensor import syft class TorchTensor: """ This tensor is simply a more convenient way to add custom functions to all Torch tensor types. """ def __init__(self): self.id = None self.owner = syft.local_worker def ...
import random from syft.frameworks.torch.tensors import PointerTensor class TorchTensor: """ This tensor is simply a more convenient way to add custom functions to all Torch tensor types. """ def __init__(self): self.id = None self.owner = None def create_pointer( se...
Set local worker as default for SyftTensor owner
Undone: Set local worker as default for SyftTensor owner
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
ab0141d4ea11e20482bb1ae9d5642ed0e6fc3fac
saleor/product/utils.py
saleor/product/utils.py
from django.core.exceptions import ObjectDoesNotExist def get_attributes_display(variant, attributes): display = {} for attribute in attributes: value = variant.get_attribute(attribute.pk) if value: try: choice = attribute.values.get(pk=value) except Obj...
def get_attributes_display(variant, attributes): display = {} for attribute in attributes: value = variant.get_attribute(attribute.pk) if value: choices = attribute.values.all() if choices: for choice in attribute.values.all(): if choic...
Reduce number of queries of getting attributes display
Reduce number of queries of getting attributes display
Python
bsd-3-clause
UITools/saleor,laosunhust/saleor,avorio/saleor,tfroehlich82/saleor,Drekscott/Motlaesaleor,arth-co/saleor,car3oon/saleor,rchav/vinerack,itbabu/saleor,spartonia/saleor,arth-co/saleor,HyperManTT/ECommerceSaleor,car3oon/saleor,taedori81/saleor,Drekscott/Motlaesaleor,josesanch/saleor,maferelo/saleor,taedori81/saleor,HyperMa...
4e438122b5715f6a8765f50173c1dca1e18c6f8f
tests/__init__.py
tests/__init__.py
from __future__ import unicode_literals import gc import platform import cffi cffi.verifier.cleanup_tmpdir() def buffer_writer(string): """Creates a function that takes a ``buffer`` and ``buffer_size`` as the two last arguments and writes the given ``string`` to ``buffer``. """ def func(*args): ...
from __future__ import unicode_literals import gc import platform import cffi # Import the module so that ffi.verify() is run before cffi.verifier is used import spotify # noqa cffi.verifier.cleanup_tmpdir() def buffer_writer(string): """Creates a function that takes a ``buffer`` and ``buffer_size`` as the ...
Make specific test files runnable
tests: Make specific test files runnable
Python
apache-2.0
jodal/pyspotify,jodal/pyspotify,felix1m/pyspotify,mopidy/pyspotify,kotamat/pyspotify,mopidy/pyspotify,kotamat/pyspotify,felix1m/pyspotify,felix1m/pyspotify,kotamat/pyspotify,jodal/pyspotify
5fbf410e0042c82e524b3b08276b2d628d00b3c6
stickytape/prelude.py
stickytape/prelude.py
#!/usr/bin/env python import contextlib as __stickytape_contextlib @__stickytape_contextlib.contextmanager def __stickytape_temporary_dir(): import tempfile import shutil dir_path = tempfile.mkdtemp() try: yield dir_path finally: shutil.rmtree(dir_path) with __stickytape_temporar...
#!/usr/bin/env python import contextlib as __stickytape_contextlib @__stickytape_contextlib.contextmanager def __stickytape_temporary_dir(): import tempfile import shutil dir_path = tempfile.mkdtemp() try: yield dir_path finally: shutil.rmtree(dir_path) with __stickytape_temporar...
Undo accidental global leakage of sys
Undo accidental global leakage of sys
Python
bsd-2-clause
mwilliamson/stickytape
a253eac5e4d7319a7a31dc33c90ce60fe77dfe60
bin/commands/upstream.py
bin/commands/upstream.py
"""Get the current upstream branch.""" import re from subprocess import check_output def upstream(include_remote=False): """Get the upstream branch of the current branch.""" branch_info = check_output(['git', 'status', '--porcelain', '--branch']).splitlines()[0] regex = '^##\s[-_a-zA-Z0-9]+\.{3}([-_a-zA...
"""Get the current upstream branch.""" import re from subprocess import check_output, PIPE, Popen _MERGE_CONFIG = 'git config --local branch.{}.merge' _REMOTE_CONFIG = 'git config --local branch.{}.remote' def upstream(include_remote=False): """Get the upstream branch of the current branch.""" branch_name =...
Refactor how remote info is retrieved
Refactor how remote info is retrieved The old way of retrieving remote information was to parse `git status`. This was brittle and lazy. Now the config values storing the remote information are used.
Python
mit
Brickstertwo/git-commands
88a04efd1a7aa56a69b76b127908a5eca0c817bd
test/services/tv_remote/test_service.py
test/services/tv_remote/test_service.py
from roku import Roku from app.core.messaging import Receiver from app.core.servicemanager import ServiceManager from app.services.tv_remote.service import RokuScanner, RokuTV class TestRokuScanner(object): @classmethod def setup_class(cls): cls.service_manager = ServiceManager(None) cls.serv...
import os from roku import Roku from app.core.messaging import Receiver from app.core.servicemanager import ServiceManager from app.services.tv_remote.service import RokuScanner, RokuTV class TestRokuScanner(object): @classmethod def setup_class(cls): os.environ["USE_FAKE_REDIS"] = "TRUE" cl...
Use Fake redis for tests.
Use Fake redis for tests.
Python
mit
supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer
c4e791ea6175fbefce0ef0671051936a27fc9684
tests/vec_test.py
tests/vec_test.py
"""Tests for vectors.""" from sympy import sympify from drudge import Vec def test_vecs_has_basic_properties(): """Tests the basic properties of vector instances.""" base = Vec('v') v_ab = Vec('v', indices=['a', 'b']) v_ab_1 = base['a', 'b'] v_ab_2 = (base['a'])['b'] indices_ref = (sympify...
"""Tests for vectors.""" import pytest from sympy import sympify from drudge import Vec def test_vecs_has_basic_properties(): """Tests the basic properties of vector instances.""" base = Vec('v') v_ab = Vec('v', indices=['a', 'b']) v_ab_1 = base['a', 'b'] v_ab_2 = (base['a'])['b'] indices...
Add tests for disabled sympification of vectors
Add tests for disabled sympification of vectors
Python
mit
tschijnmo/drudge,tschijnmo/drudge,tschijnmo/drudge
2263ea4ec0322e09db92ae368aa219c4e34125d3
src/foremast/__init__.py
src/foremast/__init__.py
"""Tools for creating infrastructure and Spinnaker Applications."""
"""Tools for creating infrastructure and Spinnaker Applications.""" from . import (app, configs, dns, elb, iam, pipeline, s3, securitygroup, utils, consts, destroyer, exceptions, runner)
Bring modules into package level
fix: Bring modules into package level
Python
apache-2.0
gogoair/foremast,gogoair/foremast
bbe7431736afeae575fb3430437d3a0000d4b653
collectd_haproxy/__init__.py
collectd_haproxy/__init__.py
try: import collectd collectd.register_config collectd_present = True except (ImportError, AttributeError): collectd_present = False from .plugin import HAProxyPlugin version_info = (1, 1, 1) __version__ = ".".join(map(str, version_info)) if collectd_present: HAProxyPlugin.register(collectd)
try: import collectd collectd.register_config # pragma: no cover collectd_present = True # pragma: no cover except (ImportError, AttributeError): collectd_present = False from .plugin import HAProxyPlugin version_info = (1, 1, 1) __version__ = ".".join(map(str, version_info)) if collectd_present:...
Exclude init file from coverage reporting.
Exclude init file from coverage reporting.
Python
mit
wglass/collectd-haproxy
d5f782fc7a8c7835af0d4d2810a923d218dea938
mplwidget.py
mplwidget.py
from PyQt4 import QtGui import matplotlib as mpl from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure import matplotlib.mlab as mlab import matplotlib.gridspec as gri...
from PyQt4 import QtGui,QtCore import matplotlib as mpl from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure import matplotlib.mlab as mlab import matplotlib.gridspec...
Expand figure when window is resized
Expand figure when window is resized
Python
apache-2.0
scholi/pyOmicron
6510705d47a035279e1aa0cb6ce52f79935b2d10
bin/monitor/check_participant_status.py
bin/monitor/check_participant_status.py
import emission.core.get_database as edb for ue in edb.get_uuid_db().find(): trip_count = edb.get_analysis_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}) location_count = edb.get_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "backgr...
import emission.core.get_database as edb for ue in edb.get_uuid_db().find(): trip_count = edb.get_analysis_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}) location_count = edb.get_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "backgr...
Add first trip details as well
Add first trip details as well
Python
bsd-3-clause
e-mission/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server
1dcbaeca1d487e2eb773580f66600389ffbb1e34
test/integration/ggrc/converters/test_import_issues.py
test/integration/ggrc/converters/test_import_issues.py
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # pylint: disable=maybe-no-member, invalid-name """Test Issue import and updates.""" from collections import OrderedDict from ggrc import models from integration.ggrc.models import factories from integra...
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # pylint: disable=maybe-no-member, invalid-name """Test Issue import and updates.""" from collections import OrderedDict from ggrc import models from ggrc.converters import errors from integration.ggrc.m...
Add tests for audit changes on issue import
Add tests for audit changes on issue import
Python
apache-2.0
AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core
4ad8b1412be2da07e4713b54741aa22064ff33c5
gen_settings.py
gen_settings.py
import os settings = os.path.join(os.path.dirname(__file__),'lib','mapnik_settings.js') # this goes into a mapnik_settings.js file beside the C++ _mapnik.node settings_template = """ module.exports.paths = { 'fonts': %s, 'input_plugins': %s }; """ def write_mapnik_settings(fonts='undefined',input_plugins='un...
import os settings = os.path.join(os.path.dirname(__file__),'lib','mapnik_settings.js') # this goes into a mapnik_settings.js file beside the C++ _mapnik.node settings_template = """ module.exports.paths = { 'fonts': %s, 'input_plugins': %s }; """ def write_mapnik_settings(fonts='undefined',input_plugins='un...
Revert "stop reading fonts/input plugins from environ as we now have a working mapnik-config.bat on windows"
Revert "stop reading fonts/input plugins from environ as we now have a working mapnik-config.bat on windows" This reverts commit d87c71142ba7bcc0d99d84886f3534dea7617b0c.
Python
bsd-3-clause
mojodna/node-mapnik,mapnik/node-mapnik,mapnik/node-mapnik,Uli1/node-mapnik,tomhughes/node-mapnik,stefanklug/node-mapnik,mapnik/node-mapnik,mojodna/node-mapnik,langateam/node-mapnik,Uli1/node-mapnik,stefanklug/node-mapnik,tomhughes/node-mapnik,stefanklug/node-mapnik,gravitystorm/node-mapnik,Uli1/node-mapnik,CartoDB/node...
6bc5fe6c2ef7cc06436b81150639cf7039b9deeb
flocker/node/functional/test_script.py
flocker/node/functional/test_script.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Functional tests for the ``flocker-changestate`` command line tool. """ from os import getuid from subprocess import check_output from unittest import skipUnless from twisted.python.procutils import which from twisted.trial.unittest import TestCase fr...
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Functional tests for the ``flocker-changestate`` command line tool. """ from subprocess import check_output from unittest import skipUnless from twisted.python.procutils import which from twisted.trial.unittest import TestCase from ... import __versio...
Address review comment: Remove another root check.
Address review comment: Remove another root check.
Python
apache-2.0
mbrukman/flocker,moypray/flocker,hackday-profilers/flocker,adamtheturtle/flocker,moypray/flocker,wallnerryan/flocker-profiles,adamtheturtle/flocker,moypray/flocker,wallnerryan/flocker-profiles,Azulinho/flocker,achanda/flocker,AndyHuu/flocker,hackday-profilers/flocker,AndyHuu/flocker,1d4Nf6/flocker,LaynePeng/flocker,Lay...
d8fa685640f674b6f22dacc45c5a9b0152115fce
paystackapi/tests/test_tcontrol.py
paystackapi/tests/test_tcontrol.py
import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.tcontrol import TransferControl class TestTransfer(BaseTestCase): @httpretty.activate def test_check_balance(self): """Method defined to test check_balance.""" httpretty.register_uri( http...
import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.tcontrol import TransferControl class TestTransfer(BaseTestCase): @httpretty.activate def test_check_balance(self): """Method defined to test check_balance.""" httpretty.register_uri( http...
Add test for transfer control disable otp
Add test for transfer control disable otp
Python
mit
andela-sjames/paystack-python
628e3cb67fefd32382614af6816d380d36c0b32f
froide/publicbody/migrations/0007_auto_20171224_0744.py
froide/publicbody/migrations/0007_auto_20171224_0744.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-12-24 06:44 from __future__ import unicode_literals from django.db import migrations def create_classifications(apps, schema_editor): from ..models import Classification, PublicBody # Use treebeard API # Classification = apps.get_model('publicbody...
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-12-24 06:44 from __future__ import unicode_literals from django.db import migrations def create_classifications(apps, schema_editor): from ..models import Classification # Use treebeard API # Classification = apps.get_model('publicbody', 'Classifi...
Use historic PublicBody in data migration
Use historic PublicBody in data migration
Python
mit
stefanw/froide,fin/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide
37c0eea76d6aba1180f2a3eae90d7f38566bfc3f
packages/mono-master.py
packages/mono-master.py
import os class MonoMasterPackage(Package): def __init__(self): Package.__init__(self, 'mono', os.getenv('MONO_VERSION'), sources = ['git://github.com/mono/mono.git'], revision = os.getenv('MONO_BUILD_REVISION'), configure_flags = [ '--enable-nls=no', '--prefix=' + Package.profile.prefix, '--w...
import os class MonoMasterPackage(Package): def __init__(self): Package.__init__(self, 'mono', os.getenv('MONO_VERSION'), sources = [os.getenv('MONO_REPOSITORY') or 'git://github.com/mono/mono.git'], revision = os.getenv('MONO_BUILD_REVISION'), configure_flags = [ '--enable-nls=no', '--prefix=' + ...
Use MONO_REPOSITORY to set the repo URL
Use MONO_REPOSITORY to set the repo URL
Python
mit
mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,mono/bockbuild
ab88748dcd5f48dce753655e0e0802a8b4d7d8b8
pages/search_indexes.py
pages/search_indexes.py
"""Django haystack `SearchIndex` module.""" from pages.models import Page from haystack.indexes import SearchIndex, CharField, DateTimeField from haystack import site class PageIndex(SearchIndex): """Search index for pages content.""" text = CharField(document=True, use_template=True) title = CharField(m...
"""Django haystack `SearchIndex` module.""" from pages.models import Page from haystack.indexes import SearchIndex, CharField, DateTimeField from haystack import site class PageIndex(SearchIndex): """Search index for pages content.""" text = CharField(document=True, use_template=True) title = CharField(m...
Add a url attribute to the SearchIndex for pages.
Add a url attribute to the SearchIndex for pages. This is useful when displaying a list of search results because we can create a link to the result without having to hit the database for every object in the result list.
Python
bsd-3-clause
remik/django-page-cms,oliciv/django-page-cms,batiste/django-page-cms,pombredanne/django-page-cms-1,akaihola/django-page-cms,oliciv/django-page-cms,remik/django-page-cms,akaihola/django-page-cms,pombredanne/django-page-cms-1,remik/django-page-cms,remik/django-page-cms,batiste/django-page-cms,oliciv/django-page-cms,pombr...
bbbeca09a978d26fa2638c21802d9a27e1159b59
massa/api.py
massa/api.py
# -*- coding: utf-8 -*- from flask import Blueprint from flask.views import MethodView class MeasurementList(MethodView): def get(self): return 'GET: measurement list' class MeasurementItem(MethodView): def get(self, id): return 'GET: measurement item with ID %s' % id bp = Blueprint('api',...
# -*- coding: utf-8 -*- from flask import Blueprint, jsonify, g from flask.views import MethodView class MeasurementList(MethodView): def get(self): service = g.sl('measurement_service') return jsonify(items=service.find_all()) class MeasurementItem(MethodView): def get(self, id): s...
Replace dummy response with measurements.
Replace dummy response with measurements.
Python
mit
jaapverloop/massa
91c6c00a16252b2a43a1017ee17b7f6f0302e4be
controlbeast/__init__.py
controlbeast/__init__.py
# -*- coding: utf-8 -*- """ controlbeast ~~~~~~~~~~~~ :copyright: Copyright 2013 by the ControlBeast team, see AUTHORS. :license: ISC, see LICENSE for details. """ VERSION = (0, 1, 0, 'alpha', 0) COPYRIGHT = ('2013', 'the ControlBeast team') def get_version(*args, **kwargs): """ Returns PEP 3...
# -*- coding: utf-8 -*- """ controlbeast ~~~~~~~~~~~~ :copyright: Copyright 2013 by the ControlBeast team, see AUTHORS. :license: ISC, see LICENSE for details. """ VERSION = (0, 1, 0, 'alpha', 0) COPYRIGHT = ('2013', 'the ControlBeast team') DEFAULTS = { 'scm': 'Git' } def get_conf(key): ""...
Implement simple mechanism for configuration handling
Implement simple mechanism for configuration handling
Python
isc
daemotron/controlbeast,daemotron/controlbeast
dfe43823c32cf6181ef873095c6cecd13664079d
Algorithmia/errors.py
Algorithmia/errors.py
class ApiError(Exception): '''General error from the Algorithmia API''' pass class ApiInternalError(ApiError): '''Error representing a server error, typically a 5xx status code''' pass class DataApiError(ApiError): '''Error returned from the Algorithmia data API''' pass
class ApiError(Exception): '''General error from the Algorithmia API''' pass class ApiInternalError(ApiError): '''Error representing a server error, typically a 5xx status code''' pass class DataApiError(ApiError): '''Error returned from the Algorithmia data API''' pass class AlgorithmExcepti...
Add new Algorithm Exception class
Add new Algorithm Exception class
Python
mit
algorithmiaio/algorithmia-python
ec37dae820e49d816014c62f00711eaaeaf64597
transaction_hooks/test/settings_pg.py
transaction_hooks/test/settings_pg.py
import os from .settings import * # noqa DATABASES = { 'default': { 'ENGINE': 'transaction_hooks.backends.postgresql_psycopg2', 'NAME': 'dtc', }, } if 'DTC_PG_USERNAME' in os.environ: DATABASES['default'].update( { 'USER': os.environ['DTC_PG_USERNAME'], ...
import os try: from psycopg2cffi import compat compat.register() except ImportError: pass from .settings import * # noqa DATABASES = { 'default': { 'ENGINE': 'transaction_hooks.backends.postgresql_psycopg2', 'NAME': 'dtc', }, } if 'DTC_PG_USERNAME' in os.environ: DA...
Enable postgresql CFFI compatability if available.
Enable postgresql CFFI compatability if available.
Python
bsd-3-clause
carljm/django-transaction-hooks
7e054868d0df4e69c4b23cb1fb966505d559157f
calico_containers/tests/st/__init__.py
calico_containers/tests/st/__init__.py
import os import sh from sh import docker def setup_package(): """ Sets up docker images and host containers for running the STs. """ # Pull and save each image, so we can use them inside the host containers. print sh.bash("./build_node.sh").stdout docker.save("--output", "calico_containers/ca...
import os import sh from sh import docker def setup_package(): """ Sets up docker images and host containers for running the STs. """ # Pull and save each image, so we can use them inside the host containers. print sh.bash("./build_node.sh").stdout docker.save("--output", "calico_containers/ca...
Fix bug in file path.
Fix bug in file path. Former-commit-id: a1e1f0661331f5bf8faa81210eae2cad0c2ad7b3
Python
apache-2.0
alexhersh/libcalico,tomdee/libcalico,TrimBiggs/libnetwork-plugin,plwhite/libcalico,L-MA/libcalico,TrimBiggs/libnetwork-plugin,Symmetric/libcalico,insequent/libcalico,TrimBiggs/libcalico,projectcalico/libnetwork-plugin,caseydavenport/libcalico,djosborne/libcalico,tomdee/libnetwork-plugin,robbrockbank/libcalico,projectca...
c50d470492ed38aa05f147ad554c58877e5050ec
Execute/execute.py
Execute/execute.py
from importlib import import_module _modules = ['branching', 'data_processing'] class Execute(object): def __init__(self, registers, process_mode, memory): self.instruction = {} for module_name in _modules: mod = import_module("Execute." + module_name) for cls in [obj for ...
from importlib import import_module _modules = ['branching', 'data_processing'] class Execute(object): def __init__(self, registers, process_mode, memory): self.instruction = {} for module_name in _modules: mod = import_module("Execute." + module_name) for cls in [obj for ...
Check for duplicate instruction handlers
Check for duplicate instruction handlers
Python
mit
tdpearson/armdecode
9ac496491fccc1bd1ba55d3302608a0fe34957a1
tests/test_population.py
tests/test_population.py
import os from neat.population import Population from neat.config import Config def test_minimal(): # sample fitness function def eval_fitness(population): for individual in population: individual.fitness = 1.0 # creates the population local_dir = os.path.dirname(__file__) con...
import os from neat.population import Population from neat.config import Config from neat.statistics import get_average_fitness def test_minimal(): # sample fitness function def eval_fitness(population): for individual in population: individual.fitness = 1.0 # creates the population ...
Include statistics usage in existing tests.
Include statistics usage in existing tests.
Python
bsd-3-clause
drallensmith/neat-python,machinebrains/neat-python,CodeReclaimers/neat-python
9018093933e7f8d04ad5d7f753651e3c77c0cf12
pushbullet.py
pushbullet.py
import weechat from yapbl import PushBullet apikey = "" p = PushBullet(apikey) weechat.register("pushbullet", "kekskurse", "1.0", "GPL3", "Test Skript", "", "") weechat.prnt("", "Hallo, von einem python Skript!") def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message): if(i...
import weechat from yapbl import PushBullet apikey = "" p = PushBullet(apikey) weechat.register("pushbullet", "kekskurse", "1.0", "GPL3", "Test Skript", "", "") weechat.prnt("", "Hallo, von einem python Skript!") def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message): if(i...
Fix Nano (m() stuff and add nick name
Fix Nano (m() stuff and add nick name
Python
mit
sspssp/weechat-pushbullet
879ea9c4234a5d8435f213c6f9b082a86a794ecc
employees/serializers.py
employees/serializers.py
from .models import Employee from rest_framework import serializers class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'email', 'first_name', 'last_name', ...
from .models import Employee from rest_framework import serializers class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee depth = 1 fields = ('pk', 'username', 'email', 'first_name', 'last...
Add 1 level depth and also categories fields to employee serializer
Add 1 level depth and also categories fields to employee serializer
Python
apache-2.0
belatrix/BackendAllStars
b26bf17154e478ee02e0e2936d7623d71698e1f2
subprocrunner/_which.py
subprocrunner/_which.py
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ import errno import shutil from typing import Optional from .error import CommandError class Which: @property def command(self): return self.__command def __init__(self, command: str) -> None: if not command: ...
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ import errno import shutil from typing import Optional from .error import CommandError class Which: @property def command(self): return self.__command def __init__(self, command: str) -> None: if not command: ...
Modify an error handling when a command not specified for Which
Modify an error handling when a command not specified for Which
Python
mit
thombashi/subprocrunner,thombashi/subprocrunner
ae5a8bb000702ee4e0bbce863bc72d603ec6ca3d
polycircles/test/test_exceptions.py
polycircles/test/test_exceptions.py
import unittest from polycircles import polycircles from nose.tools import raises class TestExceptions(unittest.TestCase): @raises(ValueError) def test_less_than_3_vertices_no_1(self): polycircle = polycircles.Polycircle(latitude=30, longitude=30, ...
import unittest from polycircles import polycircles from nose.tools import raises class TestExceptions(unittest.TestCase): @raises(ValueError) def test_less_than_3_vertices_no_1(self): polycircle = polycircles.Polycircle(latitude=30, longitude=30, ...
Add nose tests to validate Exception raising.
Add nose tests to validate Exception raising.
Python
mit
adamatan/polycircles
1993a0adad94b0ed22557e2ee87326fc1eca0793
cumulusci/robotframework/locators_50.py
cumulusci/robotframework/locators_50.py
from cumulusci.robotframework import locators_49 import copy lex_locators = copy.deepcopy(locators_49.lex_locators) lex_locators["object"][ "button" ] = "//div[contains(@class, 'slds-page-header')]//*[self::a[@title='{title}'] or self::button[@name='{title}']]" lex_locators["record"]["header"][ "field_value_...
from cumulusci.robotframework import locators_49 import copy lex_locators = copy.deepcopy(locators_49.lex_locators) lex_locators["object"][ "button" ] = "//div[contains(@class, 'slds-page-header')]//*[self::a[@title='{title}'] or self::button[@name='{title}']]" lex_locators["record"]["header"][ "field_value_...
Update all related list locators
Update all related list locators
Python
bsd-3-clause
SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI
d292a81e95bd558f3902f88fa4d6d5641a4aa388
tests/io/open_append.py
tests/io/open_append.py
import sys try: import _os as os except ImportError: import os if not hasattr(os, "unlink"): print("SKIP") sys.exit() try: os.unlink("testfile") except OSError: pass # Should create a file f = open("testfile", "a") f.write("foo") f.close() f = open("testfile") print(f.read()) f.close() f = ...
import sys try: import _os as os except ImportError: import os if not hasattr(os, "unlink"): print("SKIP") sys.exit() # cleanup in case testfile exists try: os.unlink("testfile") except OSError: pass # Should create a file f = open("testfile", "a") f.write("foo") f.close() f = open("testfile...
Make io test cleanup after itself by removing 'testfile'.
tests: Make io test cleanup after itself by removing 'testfile'.
Python
mit
tobbad/micropython,ahotam/micropython,adafruit/circuitpython,mhoffma/micropython,noahchense/micropython,adamkh/micropython,vitiral/micropython,orionrobots/micropython,adafruit/circuitpython,pozetroninc/micropython,lowRISC/micropython,ernesto-g/micropython,SHA2017-badge/micropython-esp32,ChuckM/micropython,misterdanb/mi...
eb9fa38f2c4c82a5674474f9a535bc8c35f8e38e
tests/test_bookmarks.py
tests/test_bookmarks.py
import bookmarks import unittest class FlaskrTestCase(unittest.TestCase): def setUp(self): bookmarks.app.config['DATABASE_NAME'] = bookmarks.app.config['TEST_DATABASE_NAME'] bookmarks.app.testing = True self.app = bookmarks.app.test_client() with bookmarks.app.app_context(): ...
import bookmarks import unittest class FlaskrTestCase(unittest.TestCase): def setUp(self): self.app = bookmarks.app.test_client() with bookmarks.app.app_context(): bookmarks.database.init_db() def tearDown(self): with bookmarks.app.app_context(): bookmarks.data...
Adjust test file to match new env config options
Adjust test file to match new env config options
Python
apache-2.0
byanofsky/bookmarks,byanofsky/bookmarks,byanofsky/bookmarks
45e0605a178c36a4075b59026952ef5a797e09aa
examples/pystray_icon.py
examples/pystray_icon.py
from PIL import Image from pystray import Icon, Menu, MenuItem import webview import sys if sys.platform == 'darwin': raise NotImplementedError('This example does not work on macOS.') from threading import Thread from queue import Queue """ This example demonstrates running pywebview alongside with pystray ...
from PIL import Image from pystray import Icon, Menu, MenuItem import webview import sys import multiprocessing if sys.platform == 'darwin': ctx = multiprocessing.get_context('spawn') Process = ctx.Process Queue = ctx.Queue else: Process = multiprocessing.Process Queue = multiprocessing.Queue """...
Improve example, start pystray in main thread and webview in new process
Improve example, start pystray in main thread and webview in new process
Python
bsd-3-clause
r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview
5d4572f08c6e65a062fd2f00590f6eeb5e12ce38
src/zeit/content/article/edit/browser/tests/test_template.py
src/zeit/content/article/edit/browser/tests/test_template.py
# coding: utf8 import zeit.content.article.edit.browser.testing class ArticleTemplateTest( zeit.content.article.edit.browser.testing.EditorTestCase): def setUp(self): super(ArticleTemplateTest, self).setUp() self.add_article() self.selenium.waitForElementPresent('id=options-templa...
# coding: utf8 import zeit.content.article.edit.browser.testing class ArticleTemplateTest( zeit.content.article.edit.browser.testing.EditorTestCase): def setUp(self): super(ArticleTemplateTest, self).setUp() self.add_article() self.selenium.waitForElementPresent('id=options-templa...
Update test, the article now starts with a default value for `template` (belongs to commit:95a001d)
ZON-3178: Update test, the article now starts with a default value for `template` (belongs to commit:95a001d)
Python
bsd-3-clause
ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article
7cc76c2716ce54882b7eced67f4435acd100cd83
example/src/hello-world/hello-world.py
example/src/hello-world/hello-world.py
# Include the directory where cvui is so we can load it import sys sys.path.append('../../../') import numpy as np import cv2 import cvui cvui.random_number_generator(1, 2) # Create a black image img = np.zeros((512,512,3), np.uint8) cv2.namedWindow('Window') # Draw a diagonal blue line with thickness of 5 px cv2...
# Include the directory where cvui is so we can load it import sys sys.path.append('../../../') import numpy as np import cv2 import cvui cvui.random_number_generator(1, 2) # Create a black image img = np.zeros((512,512,3), np.uint8) cv2.namedWindow('Window') # Change background color img[:] = (49, 52, 49) # Dra...
Add a nice background color
Add a nice background color
Python
mit
Dovyski/cvui,Dovyski/cvui,Dovyski/cvui
3cf4ff417c36dfa6e858265b2a3daea24a1e00f6
openfisca_country_template/entities.py
openfisca_country_template/entities.py
# -*- coding: utf-8 -*- # This file defines the entities needed by our legislation. from openfisca_core.entities import build_entity Household = build_entity( key = "household", plural = "households", label = u'Household', roles = [ { 'key': 'parent', 'plural': 'parent...
# -*- coding: utf-8 -*- # This file defines the entities needed by our legislation. from openfisca_core.entities import build_entity Household = build_entity( key = "household", plural = "households", label = u'Household', doc = ''' A group entity. Contains multiple natural persons with speci...
Add documentation on every entity
Add documentation on every entity
Python
agpl-3.0
openfisca/country-template,openfisca/country-template
a7af81244972ae6ac30bd55260af46b7ce25a6e1
pre_commit_hooks/no_commit_to_branch.py
pre_commit_hooks/no_commit_to_branch.py
from __future__ import print_function import argparse import re from typing import Optional from typing import Sequence from typing import Set from pre_commit_hooks.util import CalledProcessError from pre_commit_hooks.util import cmd_output def is_on_branch(protected, patterns=set()): # type: (Set[str], Set[str...
from __future__ import print_function import argparse import re from typing import FrozenSet from typing import Optional from typing import Sequence from pre_commit_hooks.util import CalledProcessError from pre_commit_hooks.util import cmd_output def is_on_branch(protected, patterns=frozenset()): # type: (Froze...
Make optional argument use an immutable set for the default value in no-commit-to-branch. Make other sets immutable to satisfy type-checking and be consistent
Make optional argument use an immutable set for the default value in no-commit-to-branch. Make other sets immutable to satisfy type-checking and be consistent
Python
mit
pre-commit/pre-commit-hooks
df24541dc5fff6098c3d3c0d920359c34910221c
tests/test_ratelimit.py
tests/test_ratelimit.py
from disco.test import DiscoJobTestFixture, DiscoTestCase from disco.error import JobError class RateLimitTestCase(DiscoJobTestFixture, DiscoTestCase): inputs = [1] def getdata(self, path): return 'badger\n' * 1000 @staticmethod def map(e, params): msg(e) return [] def ru...
from disco.test import DiscoJobTestFixture, DiscoTestCase from disco.error import JobError from disco.events import Status class RateLimitTestCase(DiscoJobTestFixture, DiscoTestCase): inputs = [1] def getdata(self, path): return 'badger\n' * 1000 @staticmethod def map(e, params): msg(...
Add rate-limit test case for internal messages.
Add rate-limit test case for internal messages.
Python
bsd-3-clause
pavlobaron/disco_playground,simudream/disco,pombredanne/disco,pavlobaron/disco_playground,pooya/disco,simudream/disco,ktkt2009/disco,discoproject/disco,pombredanne/disco,simudream/disco,pavlobaron/disco_playground,beni55/disco,mwilliams3/disco,ErikDubbelboer/disco,oldmantaiter/disco,seabirdzh/disco,mozilla/disco,ErikDu...
0fa0d792bfc8ea22cd807b3b822edeb67a97943a
examples/connection.py
examples/connection.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
Enable occ cloud region for example
Enable occ cloud region for example Change-Id: I4f6fb7840b684e024ceca37bc5b7e2c858574665
Python
apache-2.0
dtroyer/python-openstacksdk,dudymas/python-openstacksdk,mtougeron/python-openstacksdk,stackforge/python-openstacksdk,openstack/python-openstacksdk,briancurtin/python-openstacksdk,stackforge/python-openstacksdk,briancurtin/python-openstacksdk,mtougeron/python-openstacksdk,dudymas/python-openstacksdk,dtroyer/python-opens...
f0c1c078e7edd76b418940f3cbddef405440b5d4
GPflowOpt/_version.py
GPflowOpt/_version.py
# Copyright 2017 Joachim van der Herten # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
# Copyright 2017 Joachim van der Herten # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
Exclude version file from test coverage
Exclude version file from test coverage
Python
apache-2.0
GPflow/GPflowOpt
b4e29b5e63e4cd93d4244e7a52f772a40f9a7772
testing/util.py
testing/util.py
from __future__ import absolute_import from __future__ import unicode_literals import contextlib import io import os.path TESTING_DIR = os.path.abspath(os.path.dirname(__file__)) @contextlib.contextmanager def cwd(path): pwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(...
from __future__ import absolute_import from __future__ import unicode_literals import contextlib import io import os.path TESTING_DIR = os.path.abspath(os.path.dirname(__file__)) @contextlib.contextmanager def cwd(path): pwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(...
Use newline='' to avoid automatic newline translation
Use newline='' to avoid automatic newline translation
Python
mit
pre-commit/pre-commit-hooks,Harwood/pre-commit-hooks,Coverfox/pre-commit-hooks
27fde5a910c5274e6f56bbb0b46dbb375822296d
server/lib/python/cartodb_services/cartodb_services/google/client_factory.py
server/lib/python/cartodb_services/cartodb_services/google/client_factory.py
#!/usr/local/bin/python # -*- coding: utf-8 -*- import googlemaps import base64 from exceptions import InvalidGoogleCredentials class GoogleMapsClientFactory(): clients = {} @classmethod def get(cls, client_id, client_secret): client = cls.clients.get(client_id) if not client: ...
#!/usr/local/bin/python # -*- coding: utf-8 -*- import googlemaps import base64 from exceptions import InvalidGoogleCredentials class GoogleMapsClientFactory(): clients = {} @classmethod def get(cls, client_id, client_secret): cache_key = "{}:{}".format(client_id, client_secret) client = ...
Use "{id}:{secret}" as caching key
Use "{id}:{secret}" as caching key
Python
bsd-3-clause
CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/dataservices-api,CartoDB/dataservices-api
c057f4865052c893af9abcae2c2f37ec02d56118
example_test_set/tests/test_set_root.py
example_test_set/tests/test_set_root.py
# test set for plugin testing # from IPython import embed import pytest class Dut(object): 'fake a device under test' _allowed = ('a', 'b', 'c') def __init__(self, mode=None): self._mode = mode def get_mode(self): return self._mode def set_mode(self, val): self._mode = v...
# test set for plugin testing # from IPython import embed import pytest class Dut(object): 'fake a device under test' _allowed = ('a', 'b', 'c') def __init__(self, mode=None): self._mode = mode def get_mode(self): return self._mode def set_mode(self, val): self._mode = v...
Tweak some example fixture ids
Tweak some example fixture ids
Python
mit
tgoodlet/pytest-interactive
d05db8b8074503d927847272f53b32edc42fe043
geotrek/trekking/apps.py
geotrek/trekking/apps.py
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class TrekkingConfig(AppConfig): name = 'geotrek.trekking' verbose_name = _("Trekking")
from django.apps import AppConfig from django.core.checks import register, Tags from django.utils.translation import gettext_lazy as _ class TrekkingConfig(AppConfig): name = 'geotrek.trekking' verbose_name = _("Trekking") def ready(self): from .forms import TrekForm def check_hidden_fie...
Add system checks for Trek form
Add system checks for Trek form
Python
bsd-2-clause
makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek
8402244112dfbd45f6d05ba5f89c7311a019fbe7
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'))
from flask import redirect, url_for from portal import app @app.route('/', methods=['GET']) def index(): return redirect(url_for('practices_index', _external=True))
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
affae124162f03ce8783ced01916c11777cff25f
flocker/cli/test/test_deploy_script.py
flocker/cli/test/test_deploy_script.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Unit tests for the implementation ``flocker-deploy``. """ from twisted.trial.unittest import TestCase, SynchronousTestCase from ...testtools import FlockerScriptTestsMixin, StandardOptionsTestsMixin from ..script import DeployScript, DeployOptions cl...
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Unit tests for the implementation ``flocker-deploy``. """ from twisted.trial.unittest import TestCase, SynchronousTestCase from ...testtools import FlockerScriptTestsMixin, StandardOptionsTestsMixin from ..script import DeployScript, DeployOptions cl...
Test that DeployOptions sets two options
Test that DeployOptions sets two options
Python
apache-2.0
mbrukman/flocker,runcom/flocker,LaynePeng/flocker,w4ngyi/flocker,LaynePeng/flocker,AndyHuu/flocker,hackday-profilers/flocker,runcom/flocker,achanda/flocker,achanda/flocker,Azulinho/flocker,1d4Nf6/flocker,lukemarsden/flocker,runcom/flocker,AndyHuu/flocker,hackday-profilers/flocker,agonzalezro/flocker,Azulinho/flocker,mo...
ba10a22c47ec2f6a27ddbc1cbddbfe8ec31e9955
netdumplings/__init__.py
netdumplings/__init__.py
from .dumpling import Dumpling, DumplingDriver from .dumplingchef import DumplingChef from .dumplingeater import DumplingEater from .dumplinghub import DumplingHub from .dumplingkitchen import DumplingKitchen from ._version import __version__ # Workaround to avoid F401 "imported but unused" linter errors. ( Dumpli...
from .dumpling import Dumpling, DumplingDriver from .dumplingchef import DumplingChef from .dumplingeater import DumplingEater from .exceptions import ( InvalidDumpling, InvalidDumplingPayload, NetDumplingsError, ) from .dumplinghub import DumplingHub from .dumplingkitchen import DumplingKitchen from ._version impo...
Make exceptions available at top-level netdumplings module
Make exceptions available at top-level netdumplings module
Python
mit
mjoblin/netdumplings,mjoblin/netdumplings,mjoblin/netdumplings
82700c4a5d11f01b971b8c031d8864cff2737f0e
accounts/models.py
accounts/models.py
from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) USERNAME_FIELD = 'email' def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) ...
from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin) class UserManager(BaseUserManager): def create_user(self, email): if not email: raise ValueError('Users must have an email address') user = self.model( ...
Add user manager to pass token tests
Add user manager to pass token tests
Python
mit
randomic/aniauth-tdd,randomic/aniauth-tdd
12b6814e558402032e0c12170c678657f1455d08
kpi/deployment_backends/mock_backend.py
kpi/deployment_backends/mock_backend.py
#!/usr/bin/python # -*- coding: utf-8 -*- from base_backend import BaseDeploymentBackend class MockDeploymentBackend(BaseDeploymentBackend): ''' only used for unit testing and interface testing. defines the interface for a deployment backend. ''' def connect(self, identifier=None, active=False):...
#!/usr/bin/python # -*- coding: utf-8 -*- from base_backend import BaseDeploymentBackend class MockDeploymentBackend(BaseDeploymentBackend): ''' only used for unit testing and interface testing. defines the interface for a deployment backend. ''' def connect(self, identifier=None, active=False):...
Add `get_enketo_survey_links` to mock backend
Add `get_enketo_survey_links` to mock backend
Python
agpl-3.0
onaio/kpi,onaio/kpi,kobotoolbox/kpi,onaio/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,onaio/kpi
4d4148ea831d425327a3047ebb9be8c3129eaff6
health_check/contrib/celery/backends.py
health_check/contrib/celery/backends.py
from django.conf import settings from health_check.backends import BaseHealthCheckBackend from health_check.exceptions import ( ServiceReturnedUnexpectedResult, ServiceUnavailable ) from .tasks import add class CeleryHealthCheck(BaseHealthCheckBackend): def check_status(self): timeout = getattr(sett...
from django.conf import settings from health_check.backends import BaseHealthCheckBackend from health_check.exceptions import ( ServiceReturnedUnexpectedResult, ServiceUnavailable ) from .tasks import add class CeleryHealthCheck(BaseHealthCheckBackend): def check_status(self): timeout = getattr(sett...
Clean results task Health Check
Clean results task Health Check
Python
mit
KristianOellegaard/django-health-check,KristianOellegaard/django-health-check
7a3ee543960495ed720cfcaccbbe7a8afcfed0dd
l10n_br_coa_generic/hooks.py
l10n_br_coa_generic/hooks.py
# Copyright (C) 2020 - Gabriel Cardoso de Faria <gabriel.cardoso@kmee.com.br> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import api, tools, SUPERUSER_ID def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) coa_generic_tmpl = env.ref( 'l10n_br_c...
# Copyright (C) 2020 - Gabriel Cardoso de Faria <gabriel.cardoso@kmee.com.br> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import api, tools, SUPERUSER_ID def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) coa_generic_tmpl = env.ref( 'l10n_br_c...
Use admin user to create COA
[FIX] l10n_br_coa_generic: Use admin user to create COA
Python
agpl-3.0
akretion/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil
93057b0bf30e1d4c4449fb5f3322042bf74d76e5
satchmo/shop/management/commands/satchmo_copy_static.py
satchmo/shop/management/commands/satchmo_copy_static.py
from django.core.management.base import NoArgsCommand import os import shutil class Command(NoArgsCommand): help = "Copy the satchmo static directory and files to the local project." def handle_noargs(self, **options): import satchmo static_src = os.path.join(satchmo.__path__[0],'static') ...
from django.core.management.base import NoArgsCommand import os import shutil class Command(NoArgsCommand): help = "Copy the satchmo static directory and files to the local project." def handle_noargs(self, **options): import satchmo static_src = os.path.join(satchmo.__path__[0],'static') ...
Add an error check to static copying
Add an error check to static copying
Python
bsd-3-clause
grengojbo/satchmo,grengojbo/satchmo
5d5d2e90e821a7d377e23d63bc0c7fbba223a1d7
easy_thumbnails/signals.py
easy_thumbnails/signals.py
import django.dispatch saved_file = django.dispatch.Signal(providing_args=['fieldfile']) """ A signal sent for each ``FileField`` saved when a model is saved. * The ``sender`` argument will be the model class. * The ``fieldfile`` argument will be the instance of the field's file that was saved. """ thumbnail_creat...
import django.dispatch saved_file = django.dispatch.Signal() """ A signal sent for each ``FileField`` saved when a model is saved. * The ``sender`` argument will be the model class. * The ``fieldfile`` argument will be the instance of the field's file that was saved. """ thumbnail_created = django.dispatch.Signal(...
Fix RemovedInDjango40Warning: The providing_args argument is deprecated. As it is purely documentational, it has no replacement
Fix RemovedInDjango40Warning: The providing_args argument is deprecated. As it is purely documentational, it has no replacement
Python
bsd-3-clause
SmileyChris/easy-thumbnails
47e27693788eb84baaabcc4a374e2e8cd6cb1101
image_cropping/thumbnail_processors.py
image_cropping/thumbnail_processors.py
def crop_corners(image, box=None, **kwargs): """ Crop corners to the selection defined by image_cropping """ if box: values = [int(x) for x in box.split(',')] box = ( int(values[0]), int(values[1]), int(values[2]), int(values[3]), ...
def crop_corners(image, box=None, **kwargs): """ Crop corners to the selection defined by image_cropping """ if box: values = [int(x) for x in box.split(',')] width = abs(values[2] - values[0]) height = abs(values[3] - values[1]) if width != image.size[0] or height != im...
Scale image only if necessary to avoid compression artefacts
Scale image only if necessary to avoid compression artefacts
Python
bsd-3-clause
henriquechehad/django-image-cropping,winzard/django-image-cropping,winzard/django-image-cropping,henriquechehad/django-image-cropping,henriquechehad/django-image-cropping,winzard/django-image-cropping
e380d669bc09e047282be1d91cc95a7651300141
farms/tests/test_models.py
farms/tests/test_models.py
"""Unit test the farms models.""" from farms.factories import AddressFactory from mock import MagicMock def test_address_factory_generates_valid_addresses_sort_of(mocker): """Same test, but using pytest-mock.""" mocker.patch('farms.models.Address.save', MagicMock(name="save")) address = AddressFactory....
"""Unit test the farms models.""" from ..factories import AddressFactory from ..models import Address import pytest def test_address_factory_generates_valid_address(): # GIVEN any state # WHEN building a new address address = AddressFactory.build() # THEN it has all the information we want asse...
Add integration test for Address model
Add integration test for Address model
Python
mit
FlowFX/sturdy-potato,FlowFX/sturdy-potato,FlowFX/sturdy-potato
bcaa91b14cd852b88c348aa47ab97b6dc8cde42c
knesset/browser_cases.py
knesset/browser_cases.py
# encoding: utf-8 from knesset.browser_test_case import BrowserTestCase, on_platforms # All browser test cases must inherit from BrowserTestCase which initializes the selenium framework # also, they must use the @on_platforms decorator. This decorator can run the test case several times - for different browser and pl...
# encoding: utf-8 from knesset.browser_test_case import BrowserTestCase, on_platforms # All browser test cases must inherit from BrowserTestCase which initializes the selenium framework # also, they must use the @on_platforms decorator. This decorator can run the test case several times - for different browser and pl...
Update test case for current state
Update test case for current state
Python
bsd-3-clause
MeirKriheli/Open-Knesset,OriHoch/Open-Knesset,OriHoch/Open-Knesset,MeirKriheli/Open-Knesset,alonisser/Open-Knesset,daonb/Open-Knesset,alonisser/Open-Knesset,daonb/Open-Knesset,MeirKriheli/Open-Knesset,OriHoch/Open-Knesset,alonisser/Open-Knesset,MeirKriheli/Open-Knesset,OriHoch/Open-Knesset,daonb/Open-Knesset,daonb/Open...
ea9dcbed73a2cec0135a54cd093b42bc04364818
test/unit_test/test_cut_number.py
test/unit_test/test_cut_number.py
from lexos.processors.prepare.cutter import split_keep_whitespace, \ count_words, cut_by_number class TestCutByNumbers: def test_split_keep_whitespace(self): assert split_keep_whitespace("Test string") == ["Test", " ", "string"] assert split_keep_whitespace("Test") == ["Test"] assert s...
from lexos.processors.prepare.cutter import split_keep_whitespace, \ count_words, cut_by_number class TestCutByNumbers: def test_split_keep_whitespace(self): assert split_keep_whitespace("Test string") == ["Test", " ", "string"] assert split_keep_whitespace("Test") == ["Test"] assert s...
Test how cut_by_number handles whitespace
Test how cut_by_number handles whitespace
Python
mit
WheatonCS/Lexos,WheatonCS/Lexos,WheatonCS/Lexos
075d6f1b8f232c1ae7cb7d288da8f8d1040f49c9
hooks/pre_gen_project.py
hooks/pre_gen_project.py
repo_name = '{{ cookiecutter.repo_name }}' assert_msg = 'Repo name should be valid Python identifier!' if hasattr(repo_name, 'isidentifier'): assert repo_name.isidentifier(), assert_msg else: import re identifier_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$") assert bool(identifier_re.match(repo_name)), a...
import sys import cookiecutter # Ensure cookiecutter is recent enough cookiecutter_min_version = '1.3.0' if cookiecutter.__version__ < cookiecutter_min_version: print("--------------------------------------------------------------") print("!! Your cookiecutter is too old, at least %s is required !!" % cookie...
Add check for cookiecutter version - at least 1.3.0 is required now
Add check for cookiecutter version - at least 1.3.0 is required now
Python
isc
thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template
a41c8b8f9d3901e8d2794981c6cec050bf086e92
conjureup/controllers/clouds/common.py
conjureup/controllers/clouds/common.py
import asyncio from juju.utils import run_with_interrupt from conjureup import events from conjureup.models.provider import LocalhostError, LocalhostJSONError class BaseCloudController: cancel_monitor = asyncio.Event() async def _monitor_localhost(self, provider, cb): """ Checks that localhost/lxd...
import asyncio from juju.utils import run_with_interrupt from conjureup import events from conjureup.models.provider import LocalhostError, LocalhostJSONError class BaseCloudController: cancel_monitor = asyncio.Event() async def _monitor_localhost(self, provider, cb): """ Checks that localhost/lxd...
Make sure _set_lxd_dir_env is always called in monitor loop
Make sure _set_lxd_dir_env is always called in monitor loop Signed-off-by: Adam Stokes <49c255c1d074742f60d19fdba5e2aa5a34add567@users.noreply.github.com>
Python
mit
Ubuntu-Solutions-Engineering/conjure,ubuntu/conjure-up,ubuntu/conjure-up,conjure-up/conjure-up,Ubuntu-Solutions-Engineering/conjure,conjure-up/conjure-up
99d0dc6a77144f39fce80b81247575d7c92ee4ac
footynews/db/models.py
footynews/db/models.py
from sqlalchemy import Column, Integer, String, DateTime from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() class Article(Base): """Model for Articles""" __tablename__ = 'articles' _id = Column(Int...
from sqlalchemy import Column, Integer, String, DateTime from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() class Article(Base): """Model for Articles""" __tablename__ = 'articles' _id = Column(Int...
Define repr for Article model
Define repr for Article model
Python
apache-2.0
footynews/fn_backend
50d0806e2826a5691f1f2ce8fac27c74d98b51c7
environments/default/bin/convertmp3.py
environments/default/bin/convertmp3.py
#!/usr/bin/python import glob import os import subprocess import sys files = sys.argv[1:] if len(sys.argv) > 1 else glob.glob('*') for file in files: if os.path.isfile(file): fileWithoutExtension = os.path.splitext(file)[0] fileWithMp3Extension = fileWithoutExtension + ".mp3"; print "Conve...
#!/usr/bin/python import glob import os import subprocess import sys files = sys.argv[1:] if len(sys.argv) > 1 else glob.glob('*') for file in files: if os.path.isfile(file): fileWithoutExtension = os.path.splitext(file)[0] fileWithMp3Extension = fileWithoutExtension + ".mp3"; print "Conve...
Use variable instead of concatenating string directly
Use variable instead of concatenating string directly
Python
mit
perdian/dotfiles,perdian/dotfiles,perdian/dotfiles
54b8d77fed6bc59f7e8926b9f1a8e08f25b26eac
corner_cubes_3d_laser/cut_generator.py
corner_cubes_3d_laser/cut_generator.py
# Program by Ankur Gupta # www.github.com/agupta231 # Jan 2017 # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy,...
# Program by Ankur Gupta # www.github.com/agupta231 # Jan 2017 # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy,...
Set up the basic parameters
Set up the basic parameters
Python
mit
agupta231/fractal_prints
4a7b48b29b0a2e476b21e27bda8d7122f9982dae
mica/report/tests/test_write_report.py
mica/report/tests/test_write_report.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db: HAS_SYBASE_ACCESS = True except: HAS_SYBASE_AC...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='jeanconn', database='axafvv') as db: HAS_SYBASE_ACCESS = True except: HAS_SYBASE_ACC...
Change sybase skip test to check for more restrictive vv creds
Change sybase skip test to check for more restrictive vv creds This should let the report-writing test that uses the axafvv query run as jeanconn user, but skip for other users.
Python
bsd-3-clause
sot/mica,sot/mica
ef285377df575e101dd59d11bfec9f5b5d12ab2e
gears/asset_handler.py
gears/asset_handler.py
from functools import wraps class BaseAssetHandler(object): def __call__(self, asset): raise NotImplementedError @classmethod def as_handler(cls, **initkwargs): @wraps(cls, updated=()) def handler(asset): return handler.handler_class(**initkwargs)(asset) handl...
# -*- coding: utf-8 -*- from functools import wraps class BaseAssetHandler(object): """Base class for all asset handlers (processors, compilers and compressors). A subclass has to implement :meth:`__call__` which is called with asset as argument. """ def __call__(self, asset): """Subclas...
Add docstrings to AssetHandler class
Add docstrings to AssetHandler class
Python
isc
gears/gears,gears/gears,gears/gears
089bce7ec9df43cc526342ba84e37fe87203ca11
gemini/gemini_amend.py
gemini/gemini_amend.py
import GeminiQuery from gemini_subjects import get_subjects from ped import load_ped_file, get_ped_fields from gemini_utils import quote_string import sqlite3 from database import database_transaction def amend(parser, args): if args.db is None: parser.print_help() exit("ERROR: amend needs a databa...
import GeminiQuery from gemini_subjects import get_subjects from ped import load_ped_file, get_ped_fields from gemini_utils import quote_string import sqlite3 from database import database_transaction def amend(parser, args): if args.db is None: parser.print_help() exit("ERROR: amend needs a databa...
Extend samples table with new columns when amending.
Extend samples table with new columns when amending. This allows you to add phenotype fields to your samples after you have already created the database.
Python
mit
xuzetan/gemini,brentp/gemini,heuermh/gemini,xuzetan/gemini,udp3f/gemini,bpow/gemini,heuermh/gemini,arq5x/gemini,brentp/gemini,arq5x/gemini,heuermh/gemini,bw2/gemini,bgruening/gemini,brentp/gemini,arq5x/gemini,heuermh/gemini,bw2/gemini,udp3f/gemini,brentp/gemini,bw2/gemini,bgruening/gemini,xuzetan/gemini,udp3f/gemini,ar...
c33aa32b868a33422f79103474cece38131a93c3
src/oscar/apps/customer/migrations/0005_auto_20170413_1857.py
src/oscar/apps/customer/migrations/0005_auto_20170413_1857.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-04-13 17:57 from __future__ import unicode_literals from django.db import migrations def forwards_func(apps, schema_editor): User = apps.get_model("auth", "User") for user in User.objects.all(): user.emails.update(email=user.email) class...
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-04-13 17:57 from __future__ import unicode_literals from django.db import migrations from oscar.core.compat import get_user_model User = get_user_model() def forwards_func(apps, schema_editor): for user in User.objects.all(): user.emails.upda...
Load current User model for customer email migration.
Load current User model for customer email migration.
Python
bsd-3-clause
solarissmoke/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,sonofatailor/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,sonofatailor/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,sasha0/django-oscar,sasha0/django-oscar,django-oscar/django-oscar,...
b776a97f6f12f7b424c45d73b1c975748c4c30ae
tasks/check_einstein.py
tasks/check_einstein.py
import json from cumulusci.tasks.salesforce import BaseSalesforceApiTask class CheckPermSetLicenses(BaseSalesforceApiTask): task_options = { "permission_sets": { "description": "List of permission set names to check for, (ex: EinsteinAnalyticsUser)", "required": True, } ...
import json from cumulusci.tasks.salesforce import BaseSalesforceApiTask class CheckPermSetLicenses(BaseSalesforceApiTask): task_options = { "permission_sets": { "description": "List of permission set names to check for, (ex: EinsteinAnalyticsUser)", "required": True, } ...
Remove debugging statement from CheckPermSetLicenses
Remove debugging statement from CheckPermSetLicenses
Python
bsd-3-clause
SalesforceFoundation/HEDAP,SalesforceFoundation/HEDAP,SalesforceFoundation/HEDAP
efe1417ad049e4bb78bf1f111db6b2ea9c603461
rapt/util.py
rapt/util.py
import sys import yaml import click def dump_yaml(obj): return yaml.dump(obj, default_flow_style=False) def edit_yaml(content='', footer=''): MARKER = '# Everything below is ignored\n\n' message = click.edit(content + '\n\n' + MARKER + footer, extension='.yaml') if message i...
import sys import yaml import click def load_yaml(fh_or_string): return yaml.safe_load(fh_or_string) def dump_yaml(obj): return yaml.dump(obj, default_flow_style=False) def edit_yaml(content='', footer=''): MARKER = '# Everything below is ignored\n\n' message = click.edit(content + '\n\n' + MARKER...
Add a load yaml helper
Add a load yaml helper
Python
bsd-3-clause
yougov/rapt,yougov/rapt
90b2c2b546aa6c4707273be29fe83c2ea36e0ad5
panoptes/state_machine/states/parked.py
panoptes/state_machine/states/parked.py
from . import PanState """ Parked State The Parked state occurs in the following conditions: * Daytime * Bad Weather * System error As such, the state needs to check for a number of conditions. """ class State(PanState): def main(self): return 'exit'
from . import PanState class State(PanState): def main(self): next_state = 'shutdown' # mount = self.panoptes.observatory.mount self.logger.info("I'm parked now.") return next_state
Change Parked state to something silly
Change Parked state to something silly
Python
mit
AstroHuntsman/POCS,AstroHuntsman/POCS,AstroHuntsman/POCS,panoptes/POCS,panoptes/POCS,panoptes/POCS,AstroHuntsman/POCS,panoptes/POCS,joshwalawender/POCS,joshwalawender/POCS,joshwalawender/POCS
5c41066e9c93c417253cbde325a18079c1c69d1a
scipy/sparse/linalg/isolve/__init__.py
scipy/sparse/linalg/isolve/__init__.py
"Iterative Solvers for Sparse Linear Systems" #from info import __doc__ from iterative import * from minres import minres from lgmres import lgmres from lsqr import lsqr __all__ = filter(lambda s:not s.startswith('_'),dir()) from numpy.testing import Tester test = Tester().test bench = Tester().bench
"Iterative Solvers for Sparse Linear Systems" #from info import __doc__ from iterative import * from minres import minres from lgmres import lgmres from lsqr import lsqr from lsmr import lsmr __all__ = filter(lambda s:not s.startswith('_'),dir()) from numpy.testing import Tester test = Tester().test bench = Tester()....
Add lsmr to isolve module.
ENH: Add lsmr to isolve module.
Python
bsd-3-clause
bkendzior/scipy,mikebenfield/scipy,anielsen001/scipy,nonhermitian/scipy,aeklant/scipy,apbard/scipy,jjhelmus/scipy,giorgiop/scipy,sonnyhu/scipy,befelix/scipy,jor-/scipy,gfyoung/scipy,piyush0609/scipy,pbrod/scipy,Shaswat27/scipy,pschella/scipy,chatcannon/scipy,Newman101/scipy,ilayn/scipy,Newman101/scipy,mtrbean/scipy,Sha...
993ada8e5e970399b98b40832b5a3d23874ae7fb
plugins/vetting/ontarget/system_info.py
plugins/vetting/ontarget/system_info.py
#!/usr/bin/env python ''' Automatron: Fact Finder Identify facts about a specified host * Hostname ''' import os import json # pylint: disable=C0103 system_info = { 'hostname' : os.uname()[1], 'os' : os.uname()[0], 'kernel' : os.uname()[2], } print json.dumps(system_info)
#!/usr/bin/env python ''' Automatron: Fact Finder Identify facts about a specified host * Hostname * Networking ''' import os import json import subprocess def get_linux_networking(): ''' Gather linux networking information ''' interfaces = [] if os.path.isdir("/sys/class/net/"): interface...
Revert "Revert "Adding ip interface facts""
Revert "Revert "Adding ip interface facts""
Python
apache-2.0
madflojo/automatron,madflojo/automatron,madflojo/automatron,madflojo/automatron
ff0631c625cda7c1aac3d86cbc7074a996ef0fc1
powerline/bindings/bar/powerline-bar.py
powerline/bindings/bar/powerline-bar.py
#!/usr/bin/env python # vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import sys import time from threading import Lock from argparse import ArgumentParser from powerline import Powerline from powerline.lib.monotonic import monotonic from powerline.l...
#!/usr/bin/env python # vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import sys import time from threading import Lock from argparse import ArgumentParser from powerline import Powerline from powerline.lib.monotonic import monotonic from powerline.l...
Make sure powerline class knows that it will use UTF-8
Make sure powerline class knows that it will use UTF-8
Python
mit
darac/powerline,darac/powerline,junix/powerline,dragon788/powerline,kenrachynski/powerline,junix/powerline,areteix/powerline,russellb/powerline,seanfisk/powerline,Liangjianghao/powerline,lukw00/powerline,xxxhycl2010/powerline,bezhermoso/powerline,bartvm/powerline,EricSB/powerline,cyrixhero/powerline,DoctorJellyface/pow...