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
60ee6a5d2ad9e85fefd973c020ef65bd212e687c
astrobin/management/commands/notify_new_blog_entry.py
astrobin/management/commands/notify_new_blog_entry.py
from django.core.management.base import BaseCommand from django.contrib.auth.models import User from zinnia.models import Entry from astrobin.notifications import push_notification class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): ...
from django.core.management.base import BaseCommand from django.contrib.auth.models import User import persistent_messages from zinnia.models import Entry class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.a...
Fix management command to send notification about new blog post.
Fix management command to send notification about new blog post.
Python
agpl-3.0
astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin
1af1a7acface58cd8a6df5671d83b0a1a3ad4f3e
tiddlywebplugins/tiddlyspace/config.py
tiddlywebplugins/tiddlyspace/config.py
""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_...
""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_...
Set the tiddlywebwiki binary limit to 1MB.
Set the tiddlywebwiki binary limit to 1MB.
Python
bsd-3-clause
FND/tiddlyspace,FND/tiddlyspace,TiddlySpace/tiddlyspace,FND/tiddlyspace,TiddlySpace/tiddlyspace,TiddlySpace/tiddlyspace
18f29b2b1a99614b09591df4a60c1670c845aa9b
students/crobison/session04/dict_lab.py
students/crobison/session04/dict_lab.py
# Charles Robison # 2016.10.18 # Dictionary and Set Lab # Create a dictionary containing “name”, “city”, and “cake” # for “Chris” from “Seattle” who likes “Chocolate”. d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'}
# Charles Robison # 2016.10.18 # Dictionary and Set Lab # Create a dictionary containing “name”, “city”, and “cake” # for “Chris” from “Seattle” who likes “Chocolate”. d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} #Display the dictionary. d # Delete the entry for “cake”. del d['cake'] # Display the ...
Add first set of exercises.
Add first set of exercises.
Python
unlicense
Baumelbi/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,Baumelbi/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016
c9b6387702baee3da0a3bca8b302b619e69893f7
steel/chunks/iff.py
steel/chunks/iff.py
import collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'Form'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) payload = base...
import collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'ChunkList', 'Form'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) p...
Customize a ChunkList just for IFF chunks
Customize a ChunkList just for IFF chunks
Python
bsd-3-clause
gulopine/steel
f7d4a3df11a67e3ae679b4c8f25780538c4c3c32
core/management/commands/send_tweets.py
core/management/commands/send_tweets.py
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): ...
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): ...
Use the newer PostUpdate instead of PostMedia
Use the newer PostUpdate instead of PostMedia
Python
agpl-3.0
osamak/student-portal,enjaz/enjaz,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz
70a40f50e9988fadfbc42f236881c1e3e78f40f1
icekit/project/settings/_test.py
icekit/project/settings/_test.py
from ._develop import * # DJANGO ###################################################################### DATABASES['default'].update({ 'TEST': { 'NAME': DATABASES['default']['NAME'], # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLE...
from ._base import * # DJANGO ###################################################################### ALLOWED_HOSTS = ('*', ) CSRF_COOKIE_SECURE = False # Don't require HTTPS for CSRF cookie SESSION_COOKIE_SECURE = False # Don't require HTTPS for session cookie DATABASES['default'].update({ 'TEST': { '...
Extend base settings for test settings. Don't use live cache backend for tests.
Extend base settings for test settings. Don't use live cache backend for tests.
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
6c74e5c2bc08fd48af9e646dc911cff5e22064cb
django_performance_recorder/__init__.py
django_performance_recorder/__init__.py
# -*- coding:utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from .api import record # noqa: F401 __version__ = '1.0.0'
# -*- coding:utf-8 -*- """ isort:skip_file """ from __future__ import absolute_import, division, print_function, unicode_literals import six try: import pytest except ImportError: pytest = None if pytest is not None: if six.PY2: pytest.register_assert_rewrite(b'django_performance_recorder.api') ...
Make assert statement rich in pytest
Make assert statement rich in pytest
Python
mit
moumoutte/django-perf-rec,YPlan/django-perf-rec
89984eb5e9e8cdb8420ff1da07c54ce0dd265629
tests/test_git_pre_commit_hook_utils.py
tests/test_git_pre_commit_hook_utils.py
import git_pre_commit_hook_utils as utils def test_is_python_code_by_path(): file_at_index = utils.FileAtIndex( contents='', size=0, mode='', sha1='', status='', path='some/path/main.py', ) assert file_at_index.is_python_code() def test_is_python_code_by_c...
import git_pre_commit_hook_utils as utils import scripttest import os import copy def test_with_empty_repo(tmpdir): os_environ = copy.deepcopy(os.environ) os_environ['GIT_DIR'] = str(tmpdir) os_environ['GIT_WORK_TREE'] = str(tmpdir) env = scripttest.TestFileEnvironment( str(tmpdir), st...
Add test for commit to empty repo case
Add test for commit to empty repo case
Python
mit
evvers/git-pre-commit-hook-utils
30a173da5850a457393cfdf47b7c0db303cdd2e9
tests/test_utils.py
tests/test_utils.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'w...
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'w...
Test importing of module with unexisting target inside
Test importing of module with unexisting target inside There's a coverage case where a module exists, but what's inside it isn't covered.
Python
mit
cihai/cihai-python,cihai/cihai,cihai/cihai
fc259061ccf048af7e657888eb655da120a6606f
panoptes/test/mount/test_ioptron.py
panoptes/test/mount/test_ioptron.py
from nose.tools import raises import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @raises(AssertionError) def test_config_bad_commands(self): """ Passes in a default config ...
import nose.tools import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @nose.tools.raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @nose.tools.raises(AssertionError) def test_config_bad_commands(self): """ Passes in a defau...
Use nose.tools explicitly; test for port
Use nose.tools explicitly; test for port
Python
mit
fmin2958/POCS,Guokr1991/POCS,joshwalawender/POCS,panoptes/POCS,joshwalawender/POCS,panoptes/POCS,panoptes/POCS,Guokr1991/POCS,fmin2958/POCS,AstroHuntsman/POCS,AstroHuntsman/POCS,joshwalawender/POCS,AstroHuntsman/POCS,Guokr1991/POCS,panoptes/POCS,fmin2958/POCS,Guokr1991/POCS,AstroHuntsman/POCS
d448367d68e37c2d719063b8ec2ce543fec5b5e7
sphinxcontrib/reviewbuilder/__init__.py
sphinxcontrib/reviewbuilder/__init__.py
# -*- coding: utf-8 -*- """ sphinxcontrib-reviewbuilder ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2013 by the WAKAYAMA Shirou :license: LGPLv2, see LICENSE for details. """ from __future__ import absolute_import from docutils.nodes import Text, paragraph from sphinxcontrib.reviewbuilder.review...
# -*- coding: utf-8 -*- """ sphinxcontrib-reviewbuilder ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2013 by the WAKAYAMA Shirou :license: LGPLv2, see LICENSE for details. """ from __future__ import absolute_import from docutils import nodes from sphinxcontrib.reviewbuilder.reviewbuilder import R...
Access docutils standard nodes through nodes.*
Access docutils standard nodes through nodes.*
Python
lgpl-2.1
shirou/sphinxcontrib-reviewbuilder
f2f77cd326c3b121eb7e6e53dfcab3964f473451
fileupload/models.py
fileupload/models.py
from django.db import models class Picture(models.Model): file = models.ImageField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __unicode__(self): return self.file @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(...
from django.db import models class Picture(models.Model): # This is a small demo using FileField instead of ImageField, not # depending on PIL. You will probably want ImageField in your app. file = models.FileField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __uni...
Use FileField instead of ImageField, we don't need PIL in this demo.
Use FileField instead of ImageField, we don't need PIL in this demo.
Python
mit
extremoburo/django-jquery-file-upload,indrajithi/mgc-django,Imaginashion/cloud-vision,madteckhead/django-jquery-file-upload,sigurdga/django-jquery-file-upload,vaniakov/django-jquery-file-upload,extremoburo/django-jquery-file-upload,sigurdga/django-jquery-file-upload,Imaginashion/cloud-vision,Imaginashion/cloud-vision,m...
72c9a00d691b2b91bf39e1f5bdd1ef2358d8d671
updateCollection.py
updateCollection.py
from DataObjects.Collection import Collection from ObjectFactories.ItemFactory import ItemFactory import json def main(): updateCollection( Collection('item','Items', 'agarner', []), ItemFactory.factory('item', [0, 'someItem', 'date', 'date']), 'collections/agarner_collections/agarner_Item_...
from DataObjects.Collection import Collection from ObjectFactories.ItemFactory import ItemFactory from collections import OrderedDict import json def main(): updateCollection( Collection('item','Items', 'agarner', []), ItemFactory.factory('item', [0, 'someItem', 'date', 'date']), 'collectio...
Implement base json extraction to collection functionality
Implement base json extraction to collection functionality
Python
apache-2.0
AmosGarner/PyInventory
e6fb5ba043c2db08cbacb119664297b3f3668517
fluent_comments/forms/_captcha.py
fluent_comments/forms/_captcha.py
from django.core.exceptions import ImproperlyConfigured try: from captcha.fields import ReCaptchaField as CaptchaField except ImportError: try: from captcha.fields import CaptchaField except ImportError: raise ImportError( "To use the captcha contact form, you need to have " ...
from django.core.exceptions import ImproperlyConfigured class CaptchaFormMixin(object): def _reorder_fields(self, ordering): """ Test that the 'captcha' field is really present. This could be broken by a bad FLUENT_COMMENTS_FIELD_ORDER configuration. """ if 'captcha' not in...
Fix duplicate captcha import check
Fix duplicate captcha import check
Python
apache-2.0
django-fluent/django-fluent-comments,django-fluent/django-fluent-comments,edoburu/django-fluent-comments,django-fluent/django-fluent-comments,django-fluent/django-fluent-comments,edoburu/django-fluent-comments,edoburu/django-fluent-comments
7f1ddec9e170941e3a5159236ede817c2d569f38
graphical_tests/test_partition.py
graphical_tests/test_partition.py
""" Draw a solid circle off center in a blank image. Use the same array as both the image and the mask. The tiles should subdivide along the curved edge to trace out a smooth circle. """ from skimage import draw import matplotlib.pyplot as plt import numpy as np import photomosaic as pm img = np.zeros((1000, 1000)) rr...
""" Draw a solid circle off center in a blank image. Use the same array as both the image and the mask. The tiles should subdivide along the curved edge to trace out a smooth circle. """ from skimage import draw import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import photomosai...
Update test to match API.
TST: Update test to match API.
Python
bsd-3-clause
danielballan/photomosaic
8e1e6624fb9120b3f26ac373dc48e877240cccac
bootcamp/lesson5.py
bootcamp/lesson5.py
import datetime import csv # Question 1 # ---------- # Using the csv data file users.csv aggregate app users as well as registration date by month. The count of app # users should be one dictionary while the count of registration month should be another dictionary. There will be # no checking or test harness so simpl...
import datetime import csv # Question 1 # ---------- # Using the csv data file users.csv aggregate app users as well as registration date by month. The count of app # users should be one dictionary while the count of registration month should be another dictionary. There will be # no checking or test harness so simpl...
Add print function to demonstrate func calling
Add print function to demonstrate func calling
Python
mit
infoscout/python-bootcamp-pv
17ffc13ba4a5eab56b66b8fe144cc53e8d02d961
easyedit/TextArea.py
easyedit/TextArea.py
from PyQt5.Qsci import QsciScintilla, QsciLexerPython class TextArea(QsciScintilla): def __init__(self): super().__init__() self.filePath = "Untitled" self.pythonLexer = QsciLexerPython(self) self.setLexer(self.pythonLexer) self.setMargins(1) self.setMarginType(0,...
from PyQt5.Qsci import QsciScintilla, QsciLexerPython class TextArea(QsciScintilla): def __init__(self): super().__init__() self.filePath = "Untitled" self.pythonLexer = QsciLexerPython(self) self.setLexer(self.pythonLexer) self.setMargins(1) self.setMarginType(0,...
Remove debugging print statement from changeMarginWidth
Remove debugging print statement from changeMarginWidth
Python
mit
msklosak/EasyEdit
3f5b1e830eff73cdff013a423b647c795e21bef2
captcha/fields.py
captcha/fields.py
from django.conf import settings from django import forms from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ from recaptcha.client import captcha from captcha.widgets import ReCaptcha class ReCaptchaField(forms.CharField): default_error_messages = { ...
from django.conf import settings from django import forms from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ from recaptcha.client import captcha from captcha.widgets import ReCaptcha class ReCaptchaField(forms.CharField): default_error_messages = { ...
Revert "Enforce valid captcha only if required, so tests can relax captcha requirement"
Revert "Enforce valid captcha only if required, so tests can relax captcha requirement" This reverts commit c3c450b1a7070a1dd1b808e55371e838dd297857. It wasn't such a great idea.
Python
bsd-3-clause
mozilla/django-recaptcha
b48984747d0f33f8ad9a8721bf7489d8ff97c157
matador/commands/deploy_ticket.py
matador/commands/deploy_ticket.py
#!/usr/bin/env python from .command import Command from matador import utils class DeployTicket(Command): def _add_arguments(self, parser): parser.prog = 'matador deploy-ticket' parser.add_argument( '-e', '--environment', type=str, required=True, he...
#!/usr/bin/env python from .command import Command from matador import utils class DeployTicket(Command): def _add_arguments(self, parser): parser.prog = 'matador deploy-ticket' parser.add_argument( '-e', '--environment', type=str, required=True, he...
Add package argument to deploy-ticket
Add package argument to deploy-ticket
Python
mit
Empiria/matador
f6ce19f558bd298a6f0651ead865b65da3a2c479
spiff/sensors/tests.py
spiff/sensors/tests.py
from django.test import TestCase from spiff.api.tests import APITestMixin, withPermission import models class SensorTest(APITestMixin): def setUp(self): self.setupAPI() self.sensor = models.Sensor.objects.create( name = 'sensor', description = 'Test sensor', type = 0, ttl = 255 ) ...
from django.test import TestCase from spiff.api.tests import APITestMixin, withPermission import models class SensorTest(APITestMixin): def setUp(self): self.setupAPI() self.sensor = models.Sensor.objects.create( name = 'sensor', description = 'Test sensor', type = models.SENSOR_TYPE_BOOLEA...
Use a bool sensor for testing, and query the API instead of models
Use a bool sensor for testing, and query the API instead of models
Python
agpl-3.0
SYNHAK/spiff,SYNHAK/spiff,SYNHAK/spiff
600fe835ddce18a6aec5702766350003f2f90745
gen-android-icons.py
gen-android-icons.py
__author__ = 'Maksim Dmitriev' import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--foo', help='foo help', required=True) args = parser.parse_args()
__author__ = 'Maksim Dmitriev' import argparse import os if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', help='the icon to be resized', required=True) parser.add_argument('-d', '--dest', help='the directory where resized icons are saved') parser.add_...
Create an output directory unless it exists
Create an output directory unless it exists
Python
bsd-3-clause
MaksimDmitriev/Python-Scripts
a52039c139e0d5b1c5fedb1dfb160e2c9b9387b3
teuthology/task/tests/test_locking.py
teuthology/task/tests/test_locking.py
import pytest class TestLocking(object): def test_correct_os_type(self, ctx, config): os_type = ctx.config.get("os_type") if os_type is None: pytest.skip('os_type was not defined') for remote in ctx.cluster.remotes.iterkeys(): assert remote.os.name == os_type ...
import pytest class TestLocking(object): def test_correct_os_type(self, ctx, config): os_type = ctx.config.get("os_type") if os_type is None: pytest.skip('os_type was not defined') for remote in ctx.cluster.remotes.iterkeys(): assert remote.os.name == os_type ...
Make an exception for debian in tests.test_correct_os_version
Make an exception for debian in tests.test_correct_os_version This is because of a known issue where downburst gives us 7.1 when we ask for 7.0. We're ok with this behavior for now. See: issue #10878 Signed-off-by: Andrew Schoen <1bb641dc23c3a93cce4eee683bcf4b2bea7903a3@redhat.com>
Python
mit
SUSE/teuthology,yghannam/teuthology,dmick/teuthology,caibo2014/teuthology,dreamhost/teuthology,caibo2014/teuthology,t-miyamae/teuthology,ivotron/teuthology,SUSE/teuthology,ceph/teuthology,ivotron/teuthology,ktdreyer/teuthology,SUSE/teuthology,dmick/teuthology,t-miyamae/teuthology,robbat2/teuthology,zhouyuan/teuthology,...
65d2a5f08ee96e80752362f7545167888599819e
website/addons/figshare/exceptions.py
website/addons/figshare/exceptions.py
from website.util.sanitize import escape_html from website.addons.base.exceptions import AddonEnrichmentError class FigshareIsDraftError(AddonEnrichmentError): def __init__(self, file_guid): self.file_guid = file_guid @property def renderable_error(self): return ''' <div class="a...
from website.util.sanitize import escape_html from website.addons.base.exceptions import AddonEnrichmentError class FigshareIsDraftError(AddonEnrichmentError): def __init__(self, file_guid): self.file_guid = file_guid @property def can_delete(self): return True @property def ren...
Allow deletion of figshare drafts
Allow deletion of figshare drafts
Python
apache-2.0
zachjanicki/osf.io,DanielSBrown/osf.io,njantrania/osf.io,kushG/osf.io,erinspace/osf.io,GaryKriebel/osf.io,wearpants/osf.io,chrisseto/osf.io,samchrisinger/osf.io,caneruguz/osf.io,petermalcolm/osf.io,doublebits/osf.io,arpitar/osf.io,cldershem/osf.io,Nesiehr/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,mluo613/osf.io,patt...
96726f66fb4ac69328e84877ead5adb6c2037e5e
site/cgi/csv-upload.py
site/cgi/csv-upload.py
#!/usr/bin/python # Based on examples from # http://www.tutorialspoint.com/python/python_cgi_programming.htm import sys import cgi import os import cgitb cgitb.enable() CSV_DIR = '../csv/' # CSV upload directory form = cgi.FieldStorage() fileitem = form['filename'] # Get filename # Check if the file was uploaded ...
#!/usr/bin/python # Based on examples from # http://www.tutorialspoint.com/python/python_cgi_programming.htm import cgi import os import cgitb cgitb.enable() CSV_DIR = '../csv/' # CSV upload directory form = cgi.FieldStorage() fileitem = form['filename'] # Get filename # Check if the file was uploaded if fileitem...
Remove unused modules, fix HTML response
Remove unused modules, fix HTML response
Python
agpl-3.0
alejosanchez/CSVBenford,alejosanchez/CSVBenford
cb31dcc7be5e89c865686d9a2a07e8a64c9c0179
gamernews/apps/threadedcomments/views.py
gamernews/apps/threadedcomments/views.py
from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext as _ from django.views.generic.list import ListView from core.models import Account as User from django_c...
from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext as _ from django.views.generic.list import ListView from core.models import Account as User from django_c...
Remove name, url and email from comment form
Remove name, url and email from comment form
Python
mit
underlost/GamerNews,underlost/GamerNews
08da4c91853b14a264ea07fa5314be437fbce9d4
src/gui/graphscheme.py
src/gui/graphscheme.py
# -*- coding: utf-8 -*- from PySide import QtGui class GraphScheme( QtGui.QGraphicsScene): """ Graph scheme drawing class This class inherits from QtGui.QGraphicsScene and add functions for manage GraphBlocks objects in scheme. """ def __init__(self ): super(GraphSc...
# -*- coding: utf-8 -*- from PySide import QtGui, QtCore class GraphScheme( QtGui.QGraphicsScene): """ Graph scheme drawing class This class inherits from QtGui.QGraphicsScene and add functions for manage GraphBlocks objects in scheme. """ def __init__(self ): super...
Add gradient background to GraphScheme
Add gradient background to GraphScheme
Python
lgpl-2.1
anton-golubkov/Garland,anton-golubkov/Garland
c5742bb27aa8446cb5b4c491df6be9c733a1408f
unitary/examples/tictactoe/enums.py
unitary/examples/tictactoe/enums.py
# Copyright 2022 Google # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, soft...
# Copyright 2022 Google # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, soft...
Add enum for different rulesets
Add enum for different rulesets
Python
apache-2.0
quantumlib/unitary,quantumlib/unitary
ee37119a4f77eef5c8163936d982e178c42cbc00
src/adhocracy/lib/machine_name.py
src/adhocracy/lib/machine_name.py
import platform class IncludeMachineName(object): def __init__(self, app, config): self.app = app self.config = config def __call__(self, environ, start_response): def local_response(status, headers, exc_info=None): headers.append(('X-Server-Machine', platform.node())) ...
import os import platform class IncludeMachineName(object): def __init__(self, app, config): self.app = app self.config = config def __call__(self, environ, start_response): def local_response(status, headers, exc_info=None): machine_id = '%s:%s (PID %d)' % ( ...
Add Server Port and PID to the X-Server-Machine header
Add Server Port and PID to the X-Server-Machine header Fixes hhucn/adhocracy.hhu_theme#429
Python
agpl-3.0
liqd/adhocracy,liqd/adhocracy,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,liqd/adhocracy,alkadis/vcv,phihag/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,phihag/adhocracy,liqd/adhocracy,phihag/adhocracy,phihag/adhocracy,alkadis/vcv,phihag/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,DanielN...
60c4534b1d375aecfe39948e27bc06d0f34907f3
bioagents/resources/trips_ont_manager.py
bioagents/resources/trips_ont_manager.py
import os from indra.preassembler.hierarchy_manager import HierarchyManager # Make a TRIPS ontology _fname = os.path.join(os.path.dirname(__file__), 'trips_ontology.rdf') trips_ontology = HierarchyManager(_fname, uri_as_name=False) trips_ontology.relations_prefix = 'http://trips.ihmc.us/relations/' trips_ontology.init...
import os from indra.preassembler.hierarchy_manager import HierarchyManager # Make a TRIPS ontology _fname = os.path.join(os.path.dirname(__file__), 'trips_ontology.rdf') trips_ontology = HierarchyManager(_fname, uri_as_name=False, build_closure=True) trips_ontology.relations_prefix = 'http://trips.ihmc.us/relations/'...
Build closure for TRIPS ontology
Build closure for TRIPS ontology
Python
bsd-2-clause
sorgerlab/bioagents,bgyori/bioagents
89e2991109447893b06edf363f223c64e9cafb61
query_result_list.py
query_result_list.py
from query_result_document import QueryResultDocument class QueryResultList: def __init__(self, query, result_documents = []): self.result_documents = result_documents # Guaranteed to be in rank order self.query = query def add( self, rank, document ): self.result_documents.insert( int(rank) - 1, Que...
from query_result_document import QueryResultDocument class QueryResultList: def __init__(self, query): self.result_documents = [] # Guaranteed to be in rank order self.query = query def add( self, rank, document ): self.result_documents.insert( int(rank) - 1, QueryResultDocument( self, rank, documen...
Fix query result list having an empty list default parameter (default parameters get initialized only once!)
Fix query result list having an empty list default parameter (default parameters get initialized only once!)
Python
mit
fire-uta/iiix-data-parser
015bc46057db405107799d7214b0fe5264843277
run_deploy_job_wr.py
run_deploy_job_wr.py
#!/usr/bin/env python import json import os import subprocess import sys from tempfile import NamedTemporaryFile def main(): revision_build = os.environ['revision_build'] job_name = os.environ['JOB_NAME'] build_number = os.environ['BUILD_NUMBER'] prefix='juju-ci/products/version-{}/{}/build-{}'.format...
#!/usr/bin/env python import json import os from os.path import join import subprocess import sys from tempfile import NamedTemporaryFile def main(): revision_build = os.environ['revision_build'] job_name = os.environ['JOB_NAME'] build_number = os.environ['BUILD_NUMBER'] prefix='juju-ci/products/versi...
Fix artifact spec for deploy-job.
Fix artifact spec for deploy-job.
Python
agpl-3.0
mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju
f1e5e2cc7fd35e0446f105d619dc01d3ba837865
byceps/blueprints/admin/party/forms.py
byceps/blueprints/admin/party/forms.py
""" byceps.blueprints.admin.party.forms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from wtforms import BooleanField, DateTimeField, IntegerField, StringField from wtforms.validators import InputRequired, Length, Optional from .....
""" byceps.blueprints.admin.party.forms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from wtforms import BooleanField, DateTimeField, IntegerField, StringField from wtforms.validators import InputRequired, Length, Optional from .....
Introduce base party form, limit `archived` flag to update form
Introduce base party form, limit `archived` flag to update form
Python
bsd-3-clause
m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps
f9a0b8395adcf70c23c975a06e7667d673f74ac5
stoneridge_uploader.py
stoneridge_uploader.py
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import glob import os import requests import stoneridge class StoneRidgeUploader(object): ""...
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import glob import os import requests import stoneridge class StoneRidgeUploader(object): ""...
Fix uploader when there is nothing to upload
Fix uploader when there is nothing to upload
Python
mpl-2.0
mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge
32d7921de5768fd74983ebff6fa37212aed24e83
all/shellenv/_win.py
all/shellenv/_win.py
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import os import locale from ._types import str_cls _sys_encoding = locale.getpreferredencoding() def get_env(shell=None): """ Return environment variables for the current user :param shell: The...
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import os import locale import sys import ctypes from ._types import str_cls _sys_encoding = locale.getpreferredencoding() kernel32 = ctypes.windll.kernel32 kernel32.GetEnvironmentStringsW.argtypes = [] kernel32.Get...
Use kernel32 with ST2 on Windows to get unicode environmental variable values
Use kernel32 with ST2 on Windows to get unicode environmental variable values
Python
mit
codexns/shellenv
3eaf93f2ecee68fafa1ff4f75d4c6e7f09a37043
api/streams/views.py
api/streams/views.py
from api.streams.models import StreamConfiguration from django.http import JsonResponse from django.http.request import HttpRequest import requests def get_stream_status(request: HttpRequest, stream_slug: str): stream = StreamConfiguration.objects.get(slug=stream_slug) r = requests.get('http://{stream.host}:{...
from api.streams.models import StreamConfiguration from django.http import JsonResponse from django.http.request import HttpRequest import requests def get_stream_status(request: HttpRequest, stream_slug: str): stream = StreamConfiguration.objects.get(slug=stream_slug) r = requests.get('http://{stream.host}:{...
Add timeout to Icecast status request
Add timeout to Icecast status request
Python
mit
urfonline/api,urfonline/api,urfonline/api
655f46a10245de0b7f4d9727f816815c6493d230
tests/test_settings.py
tests/test_settings.py
# -*- coding:utf-8 -*- import os try: import unittest2 as unittest except ImportError: import unittest # NOQA from sigal.settings import read_settings class TestSettings(unittest.TestCase): "Read a settings file and check that the configuration is well done." def setUp(self): "Read the sa...
# -*- coding:utf-8 -*- import os try: import unittest2 as unittest except ImportError: import unittest # NOQA from sigal.settings import read_settings, get_thumb class TestSettings(unittest.TestCase): "Read a settings file and check that the configuration is well done." def setUp(self): "...
Add a test for the get_thumb function.
Add a test for the get_thumb function.
Python
mit
jdn06/sigal,Ferada/sigal,elaOnMars/sigal,kontza/sigal,kontza/sigal,t-animal/sigal,kontza/sigal,franek/sigal,cbosdo/sigal,cbosdo/sigal,saimn/sigal,saimn/sigal,jasuarez/sigal,xouillet/sigal,t-animal/sigal,muggenhor/sigal,saimn/sigal,elaOnMars/sigal,Ferada/sigal,franek/sigal,muggenhor/sigal,cbosdo/sigal,jdn06/sigal,xouill...
bba325111b47c9ba7dfc0bc9556a655e3f5afcee
tools/jtag/discover.py
tools/jtag/discover.py
#! /usr/bin/env python ''' Simplistic chain discovery ''' import sys sys.path.append('../..') from playtag.cables.digilent import Jtagger from playtag.jtag.discover import Chain print Chain(Jtagger())
#! /usr/bin/env python ''' Simplistic chain discovery ''' import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..')) from playtag.cables.digilent import Jtagger from playtag.jtag.discover import Chain print Chain(Jtagger())
Make it work when executed from a different directory
Make it work when executed from a different directory
Python
mit
E3V3A/playtag,proteus-cpi/playtag
6ecbcfd1b132b0c4acd2d413818348a2fe2b6bfe
Cauldron/utils/referencecompat.py
Cauldron/utils/referencecompat.py
# -*- coding: utf-8 -*- try: from __builtins__ import ReferenceError except (NameError, ImportError): # pragma: no cover from weakref import ReferenceError __all__ = ['ReferenceError']
# -*- coding: utf-8 -*- import sys try: if sys.version_info[0] < 3: from __builtins__ import ReferenceError else: from builtins import ReferenceError except (NameError, ImportError): # pragma: no cover from weakref import ReferenceError __all__ = ['ReferenceError']
Fix a py3 bug in reference compatibility
Fix a py3 bug in reference compatibility
Python
bsd-3-clause
alexrudy/Cauldron
492004049da87744cd96a6e6afeb9a6239a8ac44
ocradmin/lib/nodetree/registry.py
ocradmin/lib/nodetree/registry.py
""" Registry class and global node registry. """ class NotRegistered(KeyError): pass __all__ = ["NodeRegistry", "nodes"] class NodeRegistry(dict): NotRegistered = NotRegistered def register(self, node): """Register a node in the node registry. The node will be automatically instantiat...
""" Registry class and global node registry. """ import inspect class NotRegistered(KeyError): pass class NodeRegistry(dict): NotRegistered = NotRegistered def register(self, node): """Register a node class in the node registry.""" self[node.name] = inspect.isclass(node) and node or nod...
Fix missing import. Add method to get all nodes with a particular attribute
Fix missing import. Add method to get all nodes with a particular attribute
Python
apache-2.0
vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium
0225177c39df95bc12d9d9b53433f310d083905f
tests/test_heroku.py
tests/test_heroku.py
"""Tests for the Wallace API.""" import subprocess import re import os import requests class TestHeroku(object): """The Heroku test class.""" sandbox_output = subprocess.check_output( "cd examples/bartlett1932; wallace sandbox --verbose", shell=True) os.environ['app_id'] = re.search( '...
"""Tests for the Wallace API.""" import subprocess import re import os import requests class TestHeroku(object): """The Heroku test class.""" sandbox_output = subprocess.check_output( "cd examples/bartlett1932; wallace sandbox --verbose", shell=True) os.environ['app_id'] = re.search( '...
Add test for correct error for nonexistent routes
Add test for correct error for nonexistent routes
Python
mit
berkeley-cocosci/Wallace,jcpeterson/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,suchow/Wallace,Dallinger/Dallinger,berkeley-cocosci/Wallace,berkeley-cocosci/Wallace,jcpeterson/Dallinger,jcpeterson/Dallinger,suchow/Wallace,suchow/Wallace,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dalli...
f97d9d6462ce9e60c1811bd40428a1f30835ce95
hb_res/storage/FileExplanationStorage.py
hb_res/storage/FileExplanationStorage.py
from hb_res.storage import ExplanationStorage __author__ = 'skird' import codecs from hb_res.explanations.Explanation import Explanation class FileExplanationStorage(ExplanationStorage): """ Class representing explanation resource connected with some text file """ def __init__(self, path_to_file): ...
from hb_res.storage import ExplanationStorage from hb_res.explanations.Explanation import Explanation __author__ = 'skird' class FileExplanationStorage(ExplanationStorage): """ Class representing explanation resource connected with some text file """ def __init__(self, path_to_file): self.fi...
Fix permission-denied error in read-only context
Fix permission-denied error in read-only context
Python
mit
hatbot-team/hatbot_resources
c471a5d6421e32e9c6e3ca2db0f07eae45a85408
fuckit_commit.py
fuckit_commit.py
''' This module will send SMS reminders periodically, using Twilio. The aim is to encourage user to code, commit and push to GitHub everyday ''' import requests def set_configuration(): ''' Set Twilio configuration ''' pass def get_twilio_client(): ''' Connect to Twilio Client ''' pas...
''' This module will send SMS reminders periodically, using Twilio. The aim is to encourage user to code, commit and push to GitHub everyday ''' import requests from twilio.rest import TwilioRestClient def get_configuration(): ''' Set Twilio configuration ''' pass def get_twilio_client(config): '...
Add code to send sms
Add code to send sms
Python
mit
ueg1990/fuckit_commit
048994463cda7df1bbaf502bef2bf84036e73403
i18n/loaders/python_loader.py
i18n/loaders/python_loader.py
import os.path import sys from .loader import Loader, I18nFileLoadError class PythonLoader(Loader): """class to load python files""" def __init__(self): super(PythonLoader, self).__init__() def load_file(self, filename): path, name = os.path.split(filename) module_name, ext = os.p...
import os.path import sys from .loader import Loader, I18nFileLoadError class PythonLoader(Loader): """class to load python files""" def __init__(self): super(PythonLoader, self).__init__() def load_file(self, filename): path, name = os.path.split(filename) module_name, ext = os....
Fix bug in python loader.
Fix bug in python loader.
Python
mit
tuvistavie/python-i18n
7bc247550f136c5f0e34f411b868f9e5949e1ec4
api/tests/destinations/endpoint_tests.py
api/tests/destinations/endpoint_tests.py
import unittest from peewee import SqliteDatabase from playhouse.test_utils import test_database import api.tests.helpers as helpers from api.destinations.endpoint import * from api.destinations.endpoint import _get_destinations test_db = SqliteDatabase(':memory:') class DestinationsTests(unittest.TestCase): ...
from peewee import SqliteDatabase from api.destinations.endpoint import _get_destinations from api.tests.dbtestcase import DBTestCase test_db = SqliteDatabase(':memory:') class DestinationsTests(DBTestCase): def test_get_destinations_filters_zone(self): self.assertEqual(2, len(_get_destinations())) ...
Update destination endpoint tests to work with new version of peewee
Update destination endpoint tests to work with new version of peewee
Python
mit
mdowds/commutercalculator,mdowds/commutercalculator,mdowds/commutercalculator
4f9569037ad835b852e6389b082155d45a88774c
kokki/cookbooks/nginx/recipes/default.py
kokki/cookbooks/nginx/recipes/default.py
from kokki import * Package("nginx") Directory(env.config.nginx.log_dir, mode = 0755, owner = env.config.nginx.user, action = 'create') for nxscript in ('nxensite', 'nxdissite'): File("/usr/sbin/%s" % nxscript, content = Template("nginx/%s.j2" % nxscript), mode = 0755, owner ...
from kokki import * Package("nginx") Directory(env.config.nginx.log_dir, mode = 0755, owner = env.config.nginx.user, action = 'create') for nxscript in ('nxensite', 'nxdissite'): File("/usr/sbin/%s" % nxscript, content = Template("nginx/%s.j2" % nxscript), mode = 0755, owner ...
Add silverline environment to nginx
Add silverline environment to nginx
Python
bsd-3-clause
samuel/kokki
c1889a71be161400a42ad6b7c72b2559a84f69bf
src/nodeconductor_assembly_waldur/invoices/tests/test_report.py
src/nodeconductor_assembly_waldur/invoices/tests/test_report.py
from django.test import TestCase from nodeconductor_assembly_waldur.invoices.tasks import format_invoice_csv from .. import models from . import fixtures class TestReportFormatter(TestCase): def test_invoice_items_are_properly_formatted(self): fixture = fixtures.InvoiceFixture() package = fixtur...
from django.test import TestCase from nodeconductor_assembly_waldur.invoices.tasks import format_invoice_csv from .. import models from . import fixtures class TestReportFormatter(TestCase): def setUp(self): fixture = fixtures.InvoiceFixture() package = fixture.openstack_package invoice ...
Add unit test for report formatter
Add unit test for report formatter [WAL-905]
Python
mit
opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur
11c30f5dd765475a9f5f0f847f31c47af8c40a39
user_agent/device.py
user_agent/device.py
import os.path import json PACKAGE_DIR = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(PACKAGE_DIR, 'data/smartphone_dev_id.json')) as f: SMARTPHONE_DEV_IDS = json.load(open(f)) with open(os.path.join(PACKAGE_DIR, 'data/tablet_dev_id.json')) as f: TABLET_DEV_IDS = json.load(open())
import os.path import json PACKAGE_DIR = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(PACKAGE_DIR, 'data/smartphone_dev_id.json')) as f: SMARTPHONE_DEV_IDS = json.load(f) with open(os.path.join(PACKAGE_DIR, 'data/tablet_dev_id.json')) as f: TABLET_DEV_IDS = json.load(f)
Fix uses of file objects
Fix uses of file objects
Python
mit
lorien/user_agent
2158edb92cba6c19fa258f19445191d0308c4153
utils/async_tasks.py
utils/async_tasks.py
from utils.redis_store import store def data_from_async_task(task_func, task_args, task_kwargs, store_key, refresh_time=60): # Get task results previously stored in store output, elapsed_time = store.get(store_key, include_elapsed_time=True) # If there are no previously stored results (elapsed_time will ...
from utils.redis_store import store from celery.signals import task_postrun, task_prerun def data_from_async_task(task_func, task_args, task_kwargs, store_key, refresh_time=60, run_once=True): # Get task results previously stored in store output, elapsed_time = store.get(store_key, include_elapsed_time=True)...
Add option to run async tasks only on at a time
Add option to run async tasks only on at a time This is implemented with a simple lock like mechanism using redis.
Python
agpl-3.0
MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets
43e86a3ac5f63c702ce409c45e3aaaac60990fe9
python/ensure_haddock_coverage.py
python/ensure_haddock_coverage.py
#!/usr/bin/env python """ Tiny utility script to check that coverage statistics output by stack haddock are all 100%. """ import sys import re def main(): """Entry point to ensure-haddock-coverage.py.""" # Verify that the number of arguments is correct. if len(sys.argv) != 2: print("Usage: ./ensure...
#!/usr/bin/env python """ Tiny utility script to check that coverage statistics output by stack haddock are all 100%. """ import sys import re def main(): """Entry point to ensure-haddock-coverage.py.""" # Verify that the number of arguments is correct. if len(sys.argv) != 2: print("Usage: ./ensure...
Check for number of modules in haddock-checking script
Check for number of modules in haddock-checking script
Python
mit
gibiansky/jupyter-haskell
8b9ebbad9e87af3f56570ba3c32dcdb2d7ca4a39
django_iceberg/models/base_models.py
django_iceberg/models/base_models.py
from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ DEFAULT_ICEBERG_ENV = getattr(settings, 'ICEBERG_DEFAULT_ENVIRO', "prod") class IcebergBaseModel(models.Model): ICEBERG_PROD, ICEBERG_SANDBOX, ICEBERG_STAGE, ICEBERG_SANDBOX_STAGE = "prod", "sa...
from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ DEFAULT_ICEBERG_ENV = getattr(settings, 'ICEBERG_DEFAULT_ENVIRO', "prod") class IcebergBaseModel(models.Model): ICEBERG_PROD, ICEBERG_SANDBOX, ICEBERG_STAGE, ICEBERG_SANDBOX_STAGE = "prod", "sa...
Add app_name for django < 1.7 compatibility
Add app_name for django < 1.7 compatibility
Python
mit
izberg-marketplace/django-izberg,izberg-marketplace/django-izberg,Iceberg-Marketplace/django-iceberg,Iceberg-Marketplace/django-iceberg
0c186d8e0fb5bd7170ec55943e546f1e4e335839
masters/master.tryserver.chromium/master_site_config.py
masters/master.tryserver.chromium/master_site_config.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class TryServer(Master.Master4): project_name = 'Chromium Try Server' master_port = ...
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class TryServer(Master.Master4): project_name = 'Chromium Try Server' master_port = ...
Remove last good URL for tryserver.chromium
Remove last good URL for tryserver.chromium The expected behavior of this change is that the tryserver master no longer tries to resolve revisions to LKGR when trying jobs. BUG=372499, 386667 Review URL: https://codereview.chromium.org/394653002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@283469 0039d316-1...
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
94e344b48161e20fec5023fbeea4a14cdc736158
pynuts/filters.py
pynuts/filters.py
# -*- coding: utf-8 -*- """Jinja environment filters for Pynuts.""" from flask import escape from flask.ext.wtf import ( QuerySelectField, QuerySelectMultipleField, BooleanField) def data(field): """Field data beautifier. QuerySelectMultipleField Renders comma-separated data. QuerySelectField...
# -*- coding: utf-8 -*- """Jinja environment filters for Pynuts.""" from flask import escape from flask.ext.wtf import ( QuerySelectField, QuerySelectMultipleField, BooleanField) def data(field): """Field data beautifier. QuerySelectMultipleField Renders comma-separated data. QuerySelectField...
Return an "empty sequence" character instead of an empty list for empty select fields
Return an "empty sequence" character instead of an empty list for empty select fields
Python
bsd-3-clause
Kozea/Pynuts,Kozea/Pynuts,Kozea/Pynuts
7111860577c921dc3d1602fa16b22ddfb45b69ed
lots/migrations/0002_auto_20170717_2115.py
lots/migrations/0002_auto_20170717_2115.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-18 02:15 from __future__ import unicode_literals from django.db import models, migrations def load_data(apps, schema_editor): LotType = apps.get_model("lots", "LotType") LotType(name="Casa").save() LotType(name="Lote").save() class Migrat...
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-18 02:15 from __future__ import unicode_literals from django.db import models, migrations from lots.models import LotType def load_data(apps, schema_editor): LotType = apps.get_model("lots", "LotType") LotType(name="Casa").save() LotType(n...
Add reverse action to importing default lot types
Add reverse action to importing default lot types
Python
mpl-2.0
jackbravo/condorest-django,jackbravo/condorest-django,jackbravo/condorest-django
78f55cf57d88378e59cf1399d7ef80082d3f9555
bluebottle/partners/serializers.py
bluebottle/partners/serializers.py
from bluebottle.bluebottle_drf2.serializers import ImageSerializer from bluebottle.projects.models import PartnerOrganization from bluebottle.projects.serializers import ProjectPreviewSerializer as BaseProjectPreviewSerializer from rest_framework import serializers # This is a bit of a hack. We have an existing Proje...
from bluebottle.bluebottle_drf2.serializers import ImageSerializer from bluebottle.projects.models import PartnerOrganization from bluebottle.projects.serializers import ProjectPreviewSerializer from rest_framework import serializers class PartnerOrganizationPreviewSerializer(serializers.ModelSerializer): id = se...
Fix partner project serializer. (The comment was outdated btw)
Fix partner project serializer. (The comment was outdated btw)
Python
bsd-3-clause
onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle
b973a1686f269044e670704b56c07ca79336c29c
mythril/laser/ethereum/strategy/basic.py
mythril/laser/ethereum/strategy/basic.py
class DepthFirstSearchStrategy: def __init__(self, content, max_depth): self.content = content self.max_depth = max_depth def __iter__(self): return self def __next__(self): try: global_state = self.content.pop(0) if global_state.mstate.depth >= sel...
""" This module implements basic symbolic execution search strategies """ class DepthFirstSearchStrategy: """ Implements a depth first search strategy I.E. Follow one path to a leaf, and then continue to the next one """ def __init__(self, work_list, max_depth): self.work_list = work_list ...
Add documentation and fix pop
Add documentation and fix pop
Python
mit
b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril
052c0cfd1ce21b36c9c9a44193e3a9c89ca871f1
ciscripts/coverage/bii/coverage.py
ciscripts/coverage/bii/coverage.py
# /ciscripts/coverage/bii/coverage.py # # Submit coverage totals for a bii project to coveralls # # See /LICENCE.md for Copyright information """Submit coverage totals for a bii project to coveralls.""" import errno import os from contextlib import contextmanager @contextmanager def _bii_deps_in_place(cont): "...
# /ciscripts/coverage/bii/coverage.py # # Submit coverage totals for a bii project to coveralls # # See /LICENCE.md for Copyright information """Submit coverage totals for a bii project to coveralls.""" import errno import os from contextlib import contextmanager def _move_ignore_enoent(src, dst): """Move src ...
Make _bii_deps_in_place actually behave like a context manager
bii: Make _bii_deps_in_place actually behave like a context manager
Python
mit
polysquare/polysquare-ci-scripts,polysquare/polysquare-ci-scripts
08300895dc8d2abb740dd71b027e9acda8bb84dd
chatterbot/ext/django_chatterbot/views.py
chatterbot/ext/django_chatterbot/views.py
from django.views.generic import View from django.http import JsonResponse from django.conf import settings class ChatterBotView(View): def post(self, request, *args, **kwargs): input_statement = request.POST.get('text') response_data = settings.CHATTERBOT.get_response(input_statement) ...
from django.views.generic import View from django.http import JsonResponse from django.conf import settings from chatterbot import ChatBot class ChatterBotView(View): chatterbot = ChatBot( settings.CHATTERBOT['NAME'], storage_adapter='chatterbot.adapters.storage.DjangoStorageAdapter', inp...
Initialize ChatterBot in django view module instead of settings.
Initialize ChatterBot in django view module instead of settings.
Python
bsd-3-clause
Reinaesaya/OUIRL-ChatBot,Reinaesaya/OUIRL-ChatBot,vkosuri/ChatterBot,davizucon/ChatterBot,gunthercox/ChatterBot,maclogan/VirtualPenPal,Gustavo6046/ChatterBot
5c0c2f470451c69a2b4cbba3746d26207c6b17a9
lang/__init__.py
lang/__init__.py
from . import tokenizer, ast, codegen import sys, os, subprocess TRIPLES = { 'darwin': 'x86_64-apple-darwin11.0.0', 'linux2': 'x86_64-pc-linux-gnu', } def llir(fn, full=True): src = codegen.source(ast.parse(tokenizer.tokenize(open(fn)))) if not full: return src std = [] for fn in sorted(os.listdir('rt')):...
from . import tokenizer, ast, codegen import sys, os, subprocess BASE = os.path.dirname(__path__[0]) RT_DIR = os.path.join(BASE, 'rt') TRIPLES = { 'darwin': 'x86_64-apple-darwin11.0.0', 'linux2': 'x86_64-pc-linux-gnu', } def llir(fn, full=True): src = codegen.source(ast.parse(tokenizer.tokenize(open(fn)))) if ...
Fix up path to runtime library directory.
Fix up path to runtime library directory.
Python
mit
djc/runa,djc/runa,djc/runa,djc/runa
129cd22de51d58cc956ca5586fc15cd2e247446b
gpkitmodels/GP/aircraft/prop/propeller.py
gpkitmodels/GP/aircraft/prop/propeller.py
" propeller model " from numpy import pi from gpkit import Model, parse_variables, SignomialsEnabled, SignomialEquality class Propeller(Model): """ Propeller Model Variables --------- R 10 [m] prop radius """ def setup(self): exec parse_variables(Propeller._...
" propeller model " from numpy import pi from gpkit import Model, parse_variables, SignomialsEnabled, SignomialEquality class Propeller(Model): """ Propeller Model Variables --------- R 10 [m] prop radius W 10 [lbf] prop weight """ def ...
Add prop structure and performance models
Add prop structure and performance models
Python
mit
convexengineering/gplibrary,convexengineering/gplibrary
570bbe3add6a19a7ec6c14adfa04da76d14aa740
common/templatetags/lutris.py
common/templatetags/lutris.py
import copy from django import template from django.conf import settings from games import models register = template.Library() def get_links(user_agent): systems = ['ubuntu', 'fedora', 'linux'] downloads = copy.copy(settings.DOWNLOADS) main_download = None for system in systems: if system ...
import copy from django import template from django.conf import settings from games import models register = template.Library() def get_links(user_agent): systems = ['ubuntu', 'fedora', 'linux'] downloads = copy.copy(settings.DOWNLOADS) main_download = None for system in systems: if system ...
Fix bug in download links
Fix bug in download links
Python
agpl-3.0
Turupawn/website,Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,lutris/website,lutris/website,lutris/website
2c63efeb705637a068c909be7dc72f18e90561bf
cloudbridge/cloud/providers/azure/test/test_azure_resource_group.py
cloudbridge/cloud/providers/azure/test/test_azure_resource_group.py
from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group...
from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group...
Update resource group unit test
Update resource group unit test
Python
mit
ms-azure-cloudbroker/cloudbridge
d535cf76b3129c0e5b6908a720bdf3e3a804e41b
mopidy/mixers/gstreamer_software.py
mopidy/mixers/gstreamer_software.py
import multiprocessing from mopidy.mixers import BaseMixer from mopidy.utils.process import pickle_connection class GStreamerSoftwareMixer(BaseMixer): """Mixer which uses GStreamer to control volume in software.""" def __init__(self, *args, **kwargs): super(GStreamerSoftwareMixer, self).__init__(*arg...
from mopidy.mixers import BaseMixer class GStreamerSoftwareMixer(BaseMixer): """Mixer which uses GStreamer to control volume in software.""" def __init__(self, *args, **kwargs): super(GStreamerSoftwareMixer, self).__init__(*args, **kwargs) def _get_volume(self): return self.backend.output...
Update GStreamer software mixer to use new output API
Update GStreamer software mixer to use new output API
Python
apache-2.0
SuperStarPL/mopidy,bacontext/mopidy,dbrgn/mopidy,ali/mopidy,quartz55/mopidy,adamcik/mopidy,liamw9534/mopidy,ali/mopidy,swak/mopidy,liamw9534/mopidy,abarisain/mopidy,swak/mopidy,mopidy/mopidy,pacificIT/mopidy,swak/mopidy,diandiankan/mopidy,adamcik/mopidy,bencevans/mopidy,hkariti/mopidy,glogiotatidis/mopidy,vrs01/mopidy,...
104c136488d468f26c7fe247d0548636cbf3c6fe
random_4.py
random_4.py
""" How to generate a random 4 digit number not starting with 0 and having unique digits in python? """ import random l = [0,1,2,3,4,5,6,7,8,9] random.shuffle(l) if l[0] == 0: print(''.join(map(str, l[1:5]))) else: print(''.join(map(str, l[0:4])))
""" How to generate a random 4 digit number not starting with 0 and having unique digits in python? """ import random # 1. l = [0,1,2,3,4,5,6,7,8,9] random.shuffle(l) if l[0] == 0: pos = random.choice(range(1, len(l))) l[0], l[pos] = l[pos], l[0] print(''.join(map(str, l[0:4]))) # 2. # We create a set of dig...
Fix of shuffle. There should be random swap of leading zero with one from nine (non-zero) positions.
Fix of shuffle. There should be random swap of leading zero with one from nine (non-zero) positions.
Python
mit
foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard
863b12e503559b24de29407cd674d432bdcbbfc0
cs251tk/referee/send_email.py
cs251tk/referee/send_email.py
import smtplib def send_email(msg): # Send the message via our own SMTP server. with smtplib.SMTP_SSL('smtp.gmail.com', 465) as s: # s.starttls() s.set_debuglevel(2) s.send_message(msg)
import smtplib def send_email(msg): # Send the message via our own SMTP server. with smtplib.SMTP_SSL('smtp.gmail.com', 465) as s: s.send_message(msg)
Remove somore more lines related to email
Remove somore more lines related to email
Python
mit
StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit
1c0d42889b721cf68deb199711d8ae7700c40b66
marcottimls/tools/logsetup.py
marcottimls/tools/logsetup.py
import os import json import logging import logging.config def setup_logging(log_path, settings_path="logging.json", default_level=logging.INFO): """Setup logging configuration""" path = settings_path if os.path.exists(path): with open(path, 'rt') as f: config = json.load(f) co...
import os import json import logging import logging.config def setup_logging(settings_path="logging.json", default_level=logging.INFO): """Setup logging configuration""" path = settings_path if os.path.exists(path): with open(path, 'rt') as f: config = json.load(f) logging.conf...
Remove kludge from setup_logging as no longer necessary
Remove kludge from setup_logging as no longer necessary
Python
mit
soccermetrics/marcotti-mls
93be3585d269360641091f18a6443979eb8f1f98
cito/dump_db.py
cito/dump_db.py
"""Delete all documents every second forever""" __author__ = 'tunnell' import sys import time import json import pymongo if __name__ == "__main__": c = pymongo.MongoClient() db = c.data collection = db.test # Key to sort by so we can use an index for quick query sort_key = [("_id", pymongo.AS...
"""Delete all documents every second forever""" __author__ = 'tunnell' import sys import time import json import pymongo if __name__ == "__main__": c = pymongo.MongoClient() db = c.data collection = db.test # Key to sort by so we can use an index for quick query sort_key = [("_id", pymongo.AS...
Write concern bug fix in constantly deleting DB. It's on by default and w=1 does nothing.
BUG: Write concern bug fix in constantly deleting DB. It's on by default and w=1 does nothing.
Python
bsd-3-clause
tunnell/wax,tunnell/wax,tunnell/wax
44ed4ceffcbf95ed42e4bdebcc87a7137a97de50
been/source/markdown.py
been/source/markdown.py
from been.core import DirectorySource, source_registry class Markdown(DirectorySource): kind = 'markdown' def process_event(self, event): lines = event['content'].splitlines() event['title'] = lines[0] event['content'] = "\n".join(lines[1:]) event['summary'] = event['content'] ...
from been.core import DirectorySource, source_registry class MarkdownDirectory(DirectorySource): kind = 'markdown' def process_event(self, event): lines = event['content'].splitlines() event['title'] = lines[0] event['content'] = "\n".join(lines[1:]) event['summary'] = event['co...
Rename Markdown source to MarkdownDirectory.
Rename Markdown source to MarkdownDirectory.
Python
bsd-3-clause
chromakode/been
a28f6a45f37d906a9f9901d46d683c3ca5406da4
code/csv2map.py
code/csv2map.py
# csv2map.py -- Convert .csv into a .map format # Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map # # jean-daniel.granet@mines-paristech.fr import sys import argparse def main(): parser = argparse.ArgumentParser(description='Convert .csv to .map') parser.add_argument('cs...
# csv2map.py -- Convert .csv into a .map format # Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map # # jean-daniel.granet@mines-paristech.fr import sys import argparse def main(): parser = argparse.ArgumentParser(description='Convert .csv to .map') parser.add_argument('cs...
Add infos about MAP file
Add infos about MAP file
Python
mit
chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan
75225c176135b6d17c8f10ea67dabb4b0fc02505
nodeconductor/iaas/migrations/0009_add_min_ram_and_disk_to_image.py
nodeconductor/iaas/migrations/0009_add_min_ram_and_disk_to_image.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django_fsm class Migration(migrations.Migration): dependencies = [ ('iaas', '0008_add_instance_restarting_state'), ] operations = [ migrations.AddField( model_name...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django_fsm class Migration(migrations.Migration): dependencies = [ ('iaas', '0008_add_instance_restarting_state'), ] operations = [ migrations.AddField( model_name...
Remove field duplication from migrations(nc-301)
Remove field duplication from migrations(nc-301)
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
496fc83101155bd0cd2fb4256e2878007aec8eaa
api/base/exceptions.py
api/base/exceptions.py
from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.view...
from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.view...
Use source key instead of meta and detail fields
Use source key instead of meta and detail fields
Python
apache-2.0
asanfilippo7/osf.io,emetsger/osf.io,rdhyee/osf.io,cosenal/osf.io,haoyuchen1992/osf.io,haoyuchen1992/osf.io,DanielSBrown/osf.io,doublebits/osf.io,mluke93/osf.io,amyshi188/osf.io,monikagrabowska/osf.io,doublebits/osf.io,icereval/osf.io,sloria/osf.io,pattisdr/osf.io,ZobairAlijan/osf.io,adlius/osf.io,hmoco/osf.io,Johnetord...
0223b6fc332bdbc8a641832ebd06b79969b65853
pyfibot/modules/module_btc.py
pyfibot/modules/module_btc.py
# -*- encoding: utf-8 -*- from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display BTC exchange rates""" r = bot.get_url("http://bitcoincharts.com/t/weighted_prices.json") data = r.json() eur_rate = float(data['EUR']['24h']) usd_rate ...
# -*- encoding: utf-8 -*- from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display current BTC exchange rates from mtgox""" r = bot.get_url("http://data.mtgox.com/api/1/BTCUSD/ticker") btcusd = r.json()['return']['avg']['display_short'] r...
Use mtgox as data source
Use mtgox as data source
Python
bsd-3-clause
rnyberg/pyfibot,lepinkainen/pyfibot,EArmour/pyfibot,huqa/pyfibot,aapa/pyfibot,huqa/pyfibot,rnyberg/pyfibot,EArmour/pyfibot,lepinkainen/pyfibot,aapa/pyfibot
0868bbd0e445cb39217351cd13d2c3f7a173416c
mws/__init__.py
mws/__init__.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from .mws import MWS, MWSError from .apis import Feeds, Finances, InboundShipments, Inventory, MerchantFulfillment,\ OffAmazonPayments, Orders, OutboundShipments, Products, Recommendations,\ Reports, Sellers __all__ = [ ...
# -*- coding: utf-8 -*- from __future__ import absolute_import from .mws import MWS, MWSError from .apis import Feeds, Finances, InboundShipments, Inventory, MerchantFulfillment,\ OffAmazonPayments, Orders, OutboundShipments, Products, Recommendations,\ Reports, Sellers, Subscriptio...
Include the new Subscriptions stub
Include the new Subscriptions stub
Python
unlicense
GriceTurrble/python-amazon-mws,Bobspadger/python-amazon-mws
a91a81c16a27d72cdc41de322130e97889657561
marbaloo_mako/__init__.py
marbaloo_mako/__init__.py
import cherrypy from mako.lookup import TemplateLookup class Tool(cherrypy.Tool): _lookups = {} def __init__(self): cherrypy.Tool.__init__(self, 'before_handler', self.callable, priority=40) def callable(self, filenam...
import cherrypy from mako.lookup import TemplateLookup class Tool(cherrypy.Tool): _lookups = {} def __init__(self): cherrypy.Tool.__init__(self, 'before_handler', self.callable, priority=40) def callable(self, filenam...
Load template from `cherrypy.request.template` in handler.
Load template from `cherrypy.request.template` in handler.
Python
mit
marbaloo/marbaloo_mako
90a94b1d511aa17f167d783992fe0f874ad529c1
examples/python_interop/python_interop.py
examples/python_interop/python_interop.py
#!/usr/bin/env python # Copyright 2017 Stanford University # # 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 applicabl...
#!/usr/bin/env python # Copyright 2017 Stanford University # # 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 applicabl...
Test Python support for arguments.
examples: Test Python support for arguments.
Python
apache-2.0
StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion
f1fcce8f0c2022948fb310268a7769d9c9ef04ad
runtests.py
runtests.py
#!/usr/bin/env python import sys import logging from optparse import OptionParser from coverage import coverage from tests.config import configure logging.disable(logging.CRITICAL) def run_tests(options, *test_args): from django_nose import NoseTestSuiteRunner test_runner = NoseTestSuiteRunner(verbosity=opt...
#!/usr/bin/env python import sys import logging from optparse import OptionParser from tests.config import configure logging.disable(logging.CRITICAL) def run_tests(*test_args): from django_nose import NoseTestSuiteRunner test_runner = NoseTestSuiteRunner() if not test_args: test_args = ['tests'...
Rework test runner to generate coverage stats correctly.
Rework test runner to generate coverage stats correctly. Nose seems to pick up argv automatically - which is annoying. Will need to look into at some point.
Python
bsd-3-clause
michaelkuty/django-oscar,WillisXChen/django-oscar,lijoantony/django-oscar,Bogh/django-oscar,sasha0/django-oscar,okfish/django-oscar,nickpack/django-oscar,rocopartners/django-oscar,django-oscar/django-oscar,WillisXChen/django-oscar,makielab/django-oscar,jinnykoo/wuyisj.com,WillisXChen/django-oscar,jinnykoo/wuyisj.com,nf...
3c833053f6da71d1eed6d1a0720a1a8cb1997de7
runtests.py
runtests.py
#!/usr/bin/env python from os.path import dirname, abspath import sys from django.conf import settings if not settings.configured: from django import VERSION settings_dict = dict( INSTALLED_APPS=( 'localeurl', ), ROOT_URLCONF='localeurl.tests.test_urls', ) ...
#!/usr/bin/env python from os.path import dirname, abspath import sys from django.conf import settings if not settings.configured: from django import VERSION settings_dict = dict( INSTALLED_APPS=( 'localeurl', 'django.contrib.sites', # for sitemap test ), R...
Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2.
Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2.
Python
mit
extertioner/django-localeurl,gonnado/django-localeurl,carljm/django-localeurl
d873380a3ad382ac359ebf41f3f775f585b674f8
mopidy_gmusic/__init__.py
mopidy_gmusic/__init__.py
from __future__ import unicode_literals import os from mopidy import config, ext __version__ = '0.2.2' class GMusicExtension(ext.Extension): dist_name = 'Mopidy-GMusic' ext_name = 'gmusic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file...
from __future__ import unicode_literals import os from mopidy import config, ext __version__ = '0.2.2' class GMusicExtension(ext.Extension): dist_name = 'Mopidy-GMusic' ext_name = 'gmusic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file...
Use new extension setup() API
Use new extension setup() API
Python
apache-2.0
Tilley/mopidy-gmusic,jodal/mopidy-gmusic,mopidy/mopidy-gmusic,jaibot/mopidy-gmusic,hechtus/mopidy-gmusic,elrosti/mopidy-gmusic,jaapz/mopidy-gmusic
13f4373fc415faba717033f0e8b87a7c5cd83033
slackclient/_slackrequest.py
slackclient/_slackrequest.py
import json import requests import six class SlackRequest(object): @staticmethod def do(token, request="?", post_data=None, domain="slack.com"): post_data = post_data or {} for k, v in six.iteritems(post_data): if not isinstance(v, six.string_types): post_data[k]...
import json import requests import six class SlackRequest(object): @staticmethod def do(token, request="?", post_data=None, domain="slack.com"): post_data = post_data or {} for k, v in six.iteritems(post_data): if not isinstance(v, six.string_types): post_data[k]...
Add support for files.upload API call.
Add support for files.upload API call. Closes #64, #88.
Python
mit
slackapi/python-slackclient,slackhq/python-slackclient,slackapi/python-slackclient,slackapi/python-slackclient
0676485054c01abb41b95901c1af0af63fdcb650
AFQ/utils/volume.py
AFQ/utils/volume.py
import scipy.ndimage as ndim from skimage.filters import gaussian def patch_up_roi(roi, sigma=0.5): """ After being non-linearly transformed, ROIs tend to have holes in them. We perform a couple of computational geometry operations on the ROI to fix that up. Parameters ---------- roi : 3D...
import scipy.ndimage as ndim from skimage.filters import gaussian def patch_up_roi(roi, sigma=0.5, truncate=2): """ After being non-linearly transformed, ROIs tend to have holes in them. We perform a couple of computational geometry operations on the ROI to fix that up. Parameters ---------- ...
Truncate ROI-smoothing Gaussian at 2 STD per default.
Truncate ROI-smoothing Gaussian at 2 STD per default.
Python
bsd-2-clause
yeatmanlab/pyAFQ,yeatmanlab/pyAFQ,arokem/pyAFQ,arokem/pyAFQ
a24fe6cb58439d295455116574463ebdaf621f2c
mgsv_names.py
mgsv_names.py
import random, os global adjectives, animals, rares with open(os.path.join(os.path.dirname(__file__), 'adjectives.txt')) as f: adjectives = f.readlines() with open(os.path.join(os.path.dirname(__file__), 'animals.txt')) as f: animals = f.readlines() with open(os.path.join(os.path.dirname(__file__), 'rares.t...
from __future__ import unicode_literals, print_function import sqlite3, os, random _select = 'select {} from {} order by random() limit 1' _uncommon_select = 'select value from uncommons where key=?' def generate_name(): conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db')) cursor = conn...
Replace text files with database access.
Replace text files with database access.
Python
unlicense
rotated8/mgsv_names
33903a72a48a6d36792cec0f1fb3a6999c04b486
blendergltf/exporters/base.py
blendergltf/exporters/base.py
import json def _is_serializable(value): try: json.dumps(value) return True except TypeError: return False _IGNORED_CUSTOM_PROPS = [ '_RNA_UI', 'cycles', 'cycles_visibility', ] # pylint: disable=unused-argument class BaseExporter: gltf_key = '' blender_key = '' ...
import json def _is_serializable(value): try: json.dumps(value) return True except TypeError: return False _IGNORED_CUSTOM_PROPS = [ '_RNA_UI', 'cycles', 'cycles_visibility', ] # pylint: disable=unused-argument class BaseExporter: gltf_key = '' blender_key = '' ...
Convert custom properties before checking for serializability
Convert custom properties before checking for serializability
Python
apache-2.0
Kupoman/blendergltf
fc97832d0d96017ac71da125c3a7f29caceface6
app/mod_budget/model.py
app/mod_budget/model.py
from app import db from app.mod_auth.model import User class Category(db.Document): # The name of the category. name = db.StringField(required = True) class Entry(db.Document): # The amount of the entry. amount = db.DecimalField(precision = 2, required = True) # A short description for the entry....
from app import db from app.mod_auth.model import User class Category(db.Document): # The name of the category. name = db.StringField(required = True) class Entry(db.Document): # The amount of the entry. amount = db.DecimalField(precision = 2, required = True) # A short description for the entry....
Make category an optional field for an entry.
Make category an optional field for an entry. Income entries should not have a category. So the field should be made optional.
Python
mit
Zillolo/mana-vault,Zillolo/mana-vault,Zillolo/mana-vault
094cb428316ac0fceb0178d5a507e746550f4509
bin/task_usage_index.py
bin/task_usage_index.py
#!/usr/bin/env python3 import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib')) import glob, json import numpy as np import task_usage def main(data_path, index_path): count = 0 index = [] for path in sorted(glob.glob('{}/**/*.sqlite3'.format(data_path))): data = task...
#!/usr/bin/env python3 import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib')) import glob, json import numpy as np import task_usage def main(data_path, index_path, report_each=10000): print('Looking for data in "{}"...'.format(data_path)) paths = sorted(glob.glob('{}/**/*.sqli...
Print progress from the indexing script
Print progress from the indexing script
Python
mit
learning-on-chip/google-cluster-prediction
9ca46da9d0cf8b5f4b4a6e9234d7089665df5e8b
chef/tests/__init__.py
chef/tests/__init__.py
import os 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): """Base cla...
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 method to generate random names for testing.
Add a method to generate random names for testing.
Python
apache-2.0
jarosser06/pychef,dipakvwarade/pychef,coderanger/pychef,jarosser06/pychef,Scalr/pychef,dipakvwarade/pychef,cread/pychef,Scalr/pychef,coderanger/pychef,cread/pychef
86a992dc15482087773f1591752a667a6014ba5d
docker/settings/celery.py
docker/settings/celery.py
from .docker_compose import DockerBaseSettings class CeleryDevSettings(DockerBaseSettings): pass CeleryDevSettings.load_settings(__name__)
from .docker_compose import DockerBaseSettings class CeleryDevSettings(DockerBaseSettings): # Since we can't properly set CORS on Azurite container # (see https://github.com/Azure/Azurite/issues/55#issuecomment-503380561) # trying to fetch ``objects.inv`` from celery container fails because the # URL ...
Use proper domain for AZURE_MEDIA_STORAGE_HOSTNAME
Use proper domain for AZURE_MEDIA_STORAGE_HOSTNAME We can't access docs.dev.readthedocs.io from celery container because that domain points to 127.0.0.1 and we don't have the storage in that IP. So, we need to override the AZURE_MEDIA_STORAGE_HOSTNAME in the celery container to point to the storage. We should do this...
Python
mit
rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org
ac5ceee751b0c374ffcf1bd0e52ce085e8d7295c
nyucal/cli.py
nyucal/cli.py
# -*- coding: utf-8 -*- """Console script for nyucal. See click documentation at http://click.pocoo.org/ """ import io import click from nyucal import nyucal import requests @click.group() def main(args=None): """Console script for nyucal.""" click.echo("cli for nyucal") @main.command() def list(source...
# -*- coding: utf-8 -*- """Console script for nyucal. See click documentation at http://click.pocoo.org/ """ import io import click from nyucal import nyucal import requests @click.group() def main(args=None): """Console script for nyucal.""" pass @main.command() @click.option('--source', '-s', default...
Add the `get` command to the CLI.
Add the `get` command to the CLI.
Python
mit
nyumathclinic/nyucal,nyumathclinic/nyucal
019bca440c46039954a6228bbd22f79a5449aecd
custom/fri/management/commands/dump_fri_message_bank.py
custom/fri/management/commands/dump_fri_message_bank.py
from __future__ import absolute_import from __future__ import unicode_literals from couchexport.export import export_raw from custom.fri.models import FRIMessageBankMessage, FRIRandomizedMessage, FRIExtraMessage from django.core.management.base import BaseCommand from io import open class Command(BaseCommand): d...
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from custom.fri.models import FRIMessageBankMessage, FRIRandomizedMessage, FRIExtraMessage from django.core.management.base import BaseCommand from six import moves class Command(BaseCommand): def...
Update fri dump script to delete docs
Update fri dump script to delete docs
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
be82f1beac54f46fe9458c3ca26b8e3b786bc9f5
web/impact/impact/views/general_view_set.py
web/impact/impact/views/general_view_set.py
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from django.apps import apps from rest_framework import viewsets from rest_framework import permissions from rest_framework_tracking.mixins import LoggingMixin from impact.models.utils import snake_to_camel_case from impact.permissions import DynamicModelPermissi...
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from django.apps import apps from rest_framework import viewsets from rest_framework import permissions from rest_framework_tracking.mixins import LoggingMixin from impact.models.utils import snake_to_camel_case from impact.permissions import DynamicModelPermissi...
Create List of Model Attribute API Calls That Require Snake Case
[AC-5010] Create List of Model Attribute API Calls That Require Snake Case This commit creates a list of models that use attributes. Those calls have snake case in their model definition, and were breaking when converted back to camel case. This may not be the most efficient way to do this, but it is currently worki...
Python
mit
masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api
81b5c5c29747d7f8622828c0036504a4a5023794
parse-demo.py
parse-demo.py
#!/usr/bin/python3 import sys, os import nltk if len(sys.argv) < 2: print("Please supply a filename.") sys.exit(1) filename = sys.argv[1] with open(filename, 'r') as f: data = f.read() # Break the input down into sentences, then into words, and position tag # those words. sentences = [nltk.pos_tag(nltk...
#!/usr/bin/python3 import sys, os import nltk if len(sys.argv) < 2: print("Please supply a filename.") sys.exit(1) filename = sys.argv[1] with open(filename, 'r') as f: data = f.read() # Break the input down into sentences, then into words, and position tag # those words. raw_sentences = nltk.sent_toke...
Develop the Regex grammar slightly further
Develop the Regex grammar slightly further
Python
mit
alexander-bauer/syllabus-summary
ac14efc0a8facbfe2fe7288734c86b27eb9b2770
openprocurement/tender/openeu/adapters.py
openprocurement/tender/openeu/adapters.py
# -*- coding: utf-8 -*- from openprocurement.tender.core.adapters import TenderConfigurator from openprocurement.tender.openeu.models import Tender from openprocurement.tender.openua.constants import ( TENDERING_EXTRA_PERIOD ) from openprocurement.tender.openeu.constants import ( TENDERING_DURATION, PREQUALIFIC...
# -*- coding: utf-8 -*- from openprocurement.tender.core.adapters import TenderConfigurator from openprocurement.tender.openeu.models import Tender from openprocurement.tender.openua.constants import ( TENDERING_EXTRA_PERIOD, STATUS4ROLE ) from openprocurement.tender.openeu.constants import ( TENDERING_DURATION...
Add constant for complaint documents
Add constant for complaint documents
Python
apache-2.0
openprocurement/openprocurement.tender.openeu
7bdcc30612636d2c27ea01a7d14b1839696fa7a0
newsman/watchdog/clean_process.py
newsman/watchdog/clean_process.py
#!/usr/bin/env python #-*- coding: utf-8 -*- """ clean zombie processes """ # @author chengdujin # @contact chengdujin@gmail.com # @created Aug. 22, 2013 import sys reload(sys) sys.setdefaultencoding('UTF-8') import subprocess def clean(): """ kill zombie processes if there is any """ command ...
#!/usr/bin/env python #-*- coding: utf-8 -*- """ clean zombie processes """ # @author chengdujin # @contact chengdujin@gmail.com # @created Aug. 22, 2013 import sys reload(sys) sys.setdefaultencoding('UTF-8') import subprocess def clean(): """ kill zombie processes if there is any """ command ...
Add code to remove defunct python processes
Add code to remove defunct python processes
Python
agpl-3.0
chengdujin/newsman,chengdujin/newsman,chengdujin/newsman
b5e7cb7946d87fa39c2a006808a0c07975f9c4d4
endymion/box.py
endymion/box.py
from __future__ import unicode_literals, print_function import json import urllib2 class Box(object): """Downloads and parses metainformation about a Vagrant box""" def __init__(self, publisher, name): """Extract metainformation for a Vagrant box. publisher -- Atlas owner name -- Vag...
from __future__ import unicode_literals, print_function import json import urllib2 class Box(object): """Downloads and parses metainformation about a Vagrant box""" def __init__(self, publisher, name): """Extract metainformation for a Vagrant box. publisher -- Atlas owner name -- Vag...
Index the Atlas data by version and provider
Index the Atlas data by version and provider
Python
mit
lpancescu/atlas-lint
9a0f7e8b9da174008b33dd1d757b2e186b70e9f4
examples/network_correlations.py
examples/network_correlations.py
""" Cortical networks correlation matrix ==================================== """ import seaborn as sns import matplotlib.pyplot as plt sns.set(context="paper", font="monospace") df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0) corrmat = df.corr() f, ax = plt.subplots(figsize=(12, 9)) sns.heatm...
""" Cortical networks correlation matrix ==================================== """ import seaborn as sns import matplotlib.pyplot as plt sns.set(context="paper", font="monospace") df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0) corrmat = df.corr() f, ax = plt.subplots(figsize=(12, 9)) sns.heatm...
Improve networks heatmap gallery example
Improve networks heatmap gallery example
Python
bsd-3-clause
lukauskas/seaborn,mwaskom/seaborn,phobson/seaborn,parantapa/seaborn,drewokane/seaborn,cwu2011/seaborn,aashish24/seaborn,arokem/seaborn,bsipocz/seaborn,gef756/seaborn,mia1rab/seaborn,dimarkov/seaborn,muku42/seaborn,ebothmann/seaborn,petebachant/seaborn,anntzer/seaborn,lukauskas/seaborn,JWarmenhoven/seaborn,phobson/seabo...
393a2f5f0ccfedc1c5ebd7de987c870419ca2d89
scripts/calculate_lqr_gain.py
scripts/calculate_lqr_gain.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import scipy import control from dtk.bicycle import benchmark_state_space_vs_speed, benchmark_matrices def compute_whipple_lqr_gain(velocity): _, A, B = benchmark_state_space_vs_speed(*benchmark_matrices(), velocity) Q = np.diag([1e5, 1e3, 1e3, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import scipy import control from dtk.bicycle import benchmark_state_space_vs_speed, benchmark_matrices def compute_whipple_lqr_gain(velocity): _, A, B = benchmark_state_space_vs_speed(*benchmark_matrices(), velocity) Q = np.diag([1e5, 1e3, 1e3, ...
Change LQR gain element printing
Change LQR gain element printing Change printing of LQR gain elements for easier copying.
Python
bsd-2-clause
oliverlee/phobos,oliverlee/phobos,oliverlee/phobos,oliverlee/phobos
f2506c07caf66b3ad42f6f1c09325097edd2e169
src/django_healthchecks/contrib.py
src/django_healthchecks/contrib.py
import uuid from django.core.cache import cache from django.db import connection def check_database(): """Check if the application can perform a dummy sql query""" cursor = connection.cursor() cursor.execute('SELECT 1; -- Healthcheck') row = cursor.fetchone() return row[0] == 1 def check_cache_...
import uuid from django.core.cache import cache from django.db import connection def check_database(): """Check if the application can perform a dummy sql query""" with connection.cursor() as cursor: cursor.execute('SELECT 1; -- Healthcheck') row = cursor.fetchone() return row[0] == 1 d...
Make sure the cursor is properly closed after usage
Make sure the cursor is properly closed after usage
Python
mit
mvantellingen/django-healthchecks
1947acc37d4f45a6b1969edfe3f7f10065e647b2
src/layeredconfig/strategy.py
src/layeredconfig/strategy.py
# -*- coding: utf-8 -*- def add(new, previous=None): if previous is None: return new return previous + new def collect(new, previous=None): if previous is None: return [new] return previous + [new] def merge(new, previous=None): return add(new, previous)
# -*- coding: utf-8 -*- def add(next_, previous=None): if previous is None: return next_ return previous + next_ def collect(next_, previous=None): if previous is None: return [next_] return previous + [next_] def merge(next_, previous=None): return add(next_, previous)
Rename misleading new to next
Rename misleading new to next
Python
bsd-3-clause
hakkeroid/lcconcept
bba433a582a96f5acd59eedb3286e284d81f431d
src/nodeconductor_openstack/tests/test_backend.py
src/nodeconductor_openstack/tests/test_backend.py
import mock from rest_framework import test class MockedSession(mock.MagicMock): auth_ref = 'AUTH_REF' class BaseBackendTestCase(test.APITransactionTestCase): def setUp(self): self.session_patcher = mock.patch('keystoneauth1.session.Session', MockedSession) self.session_patcher.start() ...
import mock from rest_framework import test class MockedSession(mock.MagicMock): auth_ref = 'AUTH_REF' class BaseBackendTestCase(test.APITransactionTestCase): def setUp(self): self.session_patcher = mock.patch('keystoneauth1.session.Session', MockedSession) self.session_patcher.start() ...
Stop patcher in tear down
Stop patcher in tear down - itacloud-7198
Python
mit
opennode/nodeconductor-openstack
3b21631f8c0d3820359c1163e7e5340f153c3938
twitter_bot.py
twitter_bot.py
# Import json parsing library import json # Import the necessary methods from "twitter" library from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream # Import "ConfigParser" library to load settings ("configparser" in python 3) from ConfigParser import SafeConfigParser # Load API variables from setting...
# Import json parsing library import json # Import the necessary methods from "twitter" library from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream # Import "ConfigParser" library to load settings ("configparser" in python 3) from ConfigParser import SafeConfigParser # Load API variables from setting...
Add initial tweet extraction / load query term from config file
Add initial tweet extraction / load query term from config file
Python
mit
benhoyle/social-media-bot
efbab142afc824f9b2ba4968ffe102c20e0ad7c3
rpp/encoder.py
rpp/encoder.py
from uuid import UUID from scanner import Symbol def tostr(value): if isinstance(value, Symbol): return str(value) elif isinstance(value, str): return '"%s"' % value elif isinstance(value, UUID): return '{%s}' % value elif value is None: return '-' else: retu...
from uuid import UUID from scanner import Symbol def tostr(value): if isinstance(value, Symbol): return str(value) elif isinstance(value, str): return '"%s"' % value elif isinstance(value, float): return '%.14f' % value elif isinstance(value, UUID): return '{%s}' % str(v...
Correct representation of floats and uuids
Correct representation of floats and uuids
Python
bsd-3-clause
Perlence/rpp
fad97c21e2643e5df9759ebf260881b26e918d7c
api/api/views/hacker/get/csv/resume_links.py
api/api/views/hacker/get/csv/resume_links.py
""" Generates a CSV containing approved hackers' resumes """ from hackfsu_com.views.generic import StreamedCsvView from hackfsu_com.util import acl, files from django.conf import settings from api.models import Hackathon, HackerInfo class ResumeLinksCsv(StreamedCsvView): access_manager = acl.AccessManager(ac...
""" Generates a CSV containing approved hackers' resumes """ from hackfsu_com.views.generic import StreamedCsvView from hackfsu_com.util import acl, files from django.conf import settings from api.models import Hackathon, HackerInfo, UserInfo class ResumeLinksCsv(StreamedCsvView): access_manager = acl.Access...
Add Github+LinkedIn to Hacker Data export
Add Github+LinkedIn to Hacker Data export
Python
apache-2.0
andrewsosa/hackfsu_com,andrewsosa/hackfsu_com,andrewsosa/hackfsu_com,andrewsosa/hackfsu_com