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 |
|---|---|---|---|---|---|---|---|---|---|
a5926a3ef469c4b323f994dd026b55cac7fa1b2f | turbustat/tests/test_dendro.py | turbustat/tests/test_dendro.py | # Licensed under an MIT open source license - see LICENSE
'''
Tests for Dendrogram statistics
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import Dendrogram_Stats, DendroDistance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_dista... | # Licensed under an MIT open source license - see LICENSE
'''
Tests for Dendrogram statistics
'''
import numpy as np
import numpy.testing as npt
from ..statistics import Dendrogram_Stats, DendroDistance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
min_deltas = np.logspace... | Update dendro tests and specify no periodic boundaries to be consistent w/ previous unit testing | Update dendro tests and specify no periodic boundaries to be consistent w/ previous unit testing
| Python | mit | Astroua/TurbuStat,e-koch/TurbuStat |
04069a5d5d6f5647394aba987ae5798629bf4a73 | Ghidra/Features/Python/ghidra_scripts/ImportSymbolsScript.py | Ghidra/Features/Python/ghidra_scripts/ImportSymbolsScript.py | #Imports a file with lines in the form "symbolName 0xADDRESS"
#@category Data
#@author
f = askFile("Give me a file to open", "Go baby go!")
for line in file(f.absolutePath): # note, cannot use open(), since that is in GhidraScript
pieces = line.split()
address = toAddr(long(pieces[1], 16))
print "creat... | # Imports a file with lines in the form "symbolName 0xADDRESS function_or_label" where "f" indicates a function and "l" a label
# @author unkown; edited by matedealer <git@matedealer.de>
# @category Data
#
from ghidra.program.model.symbol.SourceType import *
import string
functionManager = currentProgram.getFunctionM... | Add optional 3 option to ImportSymbolScript.py to allow importing function names. | Add optional 3 option to ImportSymbolScript.py to allow importing
function names.
Add python script to import functions and labels
Use print() instead of print
Merge ImportSymbolsScript.py and ImportFunctionAndLabels.py
Made third token optional
| Python | apache-2.0 | NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra |
f844f9e153406577b844a864110bcc54fd6b01f3 | nose2/tests/functional/support/scenario/expected_failures/expected_failures.py | nose2/tests/functional/support/scenario/expected_failures/expected_failures.py | import unittest
class TestWithExpectedFailures(unittest.TestCase):
@unittest.expectedFailure
def test_should_fail(self):
assert False
@unittest.expectedFailure
def test_should_pass(self):
assert True
def test_whatever(self):
assert True
def test_fails(sel... | from nose2.compat import unittest
class TestWithExpectedFailures(unittest.TestCase):
@unittest.expectedFailure
def test_should_fail(self):
assert False
@unittest.expectedFailure
def test_should_pass(self):
assert True
def test_whatever(self):
assert True
... | Fix for py26 and expectedFailure | Fix for py26 and expectedFailure | Python | bsd-2-clause | ojengwa/nose2,little-dude/nose2,ptthiem/nose2,ezigman/nose2,ptthiem/nose2,ezigman/nose2,little-dude/nose2,ojengwa/nose2 |
69f1f5f78477e6c89338661e71ecd9732a287673 | datafilters/views.py | datafilters/views.py | from django.views.generic.list import MultipleObjectMixin
__all__ = ('FilterFormMixin',)
class FilterFormMixin(MultipleObjectMixin):
"""
Mixin that adds filtering behaviour for Class Based Views.
Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and
get_... | from django.views.generic.list import MultipleObjectMixin
__all__ = ('FilterFormMixin',)
class FilterFormMixin(MultipleObjectMixin):
"""
Mixin that adds filtering behaviour for Class Based Views.
Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and
get_... | Make context name for a filter form configurable | Make context name for a filter form configurable
| Python | mit | zorainc/django-datafilters,freevoid/django-datafilters,zorainc/django-datafilters |
c95d6e0f215cb81a00a0af869595bb6e89e887e7 | test/lib/01-con-discon-success.py | test/lib/01-con-discon-success.py | #!/usr/bin/python
# Test whether a client produces a correct connect and subsequent disconnect.
import os
import subprocess
import socket
import sys
import time
from struct import *
rc = 1
keepalive = 60
connect_packet = pack('!BBH6sBBHH21s', 16, 12+2+21,6,"MQIsdp",3,2,keepalive,21,"01-con-discon-success")
connack_p... | #!/usr/bin/python
# Test whether a client produces a correct connect and subsequent disconnect.
import os
import subprocess
import socket
import sys
import time
from struct import *
rc = 1
keepalive = 60
connect_packet = pack('!BBH6sBBHH21s', 16, 12+2+21,6,"MQIsdp",3,2,keepalive,21,"01-con-discon-success")
connack_p... | Set SO_REUSEADDR in client test. | Set SO_REUSEADDR in client test.
| Python | bsd-3-clause | zlargon/mosquitto,zlargon/mosquitto,zlargon/mosquitto,zlargon/mosquitto,zlargon/mosquitto |
313a81093527c88631713f6b4ad8c652554edb50 | l10n_br_base/migrations/12.0.1.0.0/post-migration.py | l10n_br_base/migrations/12.0.1.0.0/post-migration.py | # -*- coding: utf-8 -*-
# Copyright 2018 KMEE INFORMATICA LTDA - Gabriel Cardoso de Faria
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
cr.execute(
'''INSERT INTO res_city(id, n... | # -*- coding: utf-8 -*-
# Copyright 2018 KMEE INFORMATICA LTDA - Gabriel Cardoso de Faria
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
_model_renames = [
('l10n_br_base.city', 'res.city'),
]
_table_renames = [
('l10n_br_base_city', 'res_city'),
... | Rename table _model_renames and _table_renames | [ADD] Rename table _model_renames and _table_renames
Signed-off-by: Luis Felipe Mileo <c9a5b4d335634d99740001a1172b3e56e4fc5aa8@kmee.com.br>
| Python | agpl-3.0 | akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,akretion/l10n-brazil |
ec33927709b1d9ce484e6f243068a334de389aa1 | example/app/models.py | example/app/models.py | # Define a custom User class to work with django-social-auth
from django.db import models
class CustomUserManager(models.Manager):
def create_user(self, username, email):
return self.model._default_manager.create(username=username)
class CustomUser(models.Model):
username = models.CharField(max_leng... | # Define a custom User class to work with django-social-auth
from django.db import models
class CustomUserManager(models.Manager):
def create_user(self, username, email):
return self.model._default_manager.create(username=username)
class CustomUser(models.Model):
username = models.CharField(max_leng... | Clean signal handler from example app | Clean signal handler from example app
| Python | bsd-3-clause | beswarm/django-social-auth,omab/django-social-auth,adw0rd/django-social-auth,gustavoam/django-social-auth,limdauto/django-social-auth,michael-borisov/django-social-auth,vuchau/django-social-auth,limdauto/django-social-auth,sk7/django-social-auth,caktus/django-social-auth,vxvinh1511/django-social-auth,duoduo369/django-s... |
1eab43e1b1402a53c2dec53abe61bcae5f4b3026 | robots/admin.py | robots/admin.py | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from robots.models import Url, Rule
from robots.forms import RuleAdminForm
class RuleAdmin(admin.ModelAdmin):
form = RuleAdminForm
fieldsets = (
(None, {'fields': ('robot', 'sites')}),
(_('URL patterns'),... | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from robots.models import Url, Rule
from robots.forms import RuleAdminForm
class RuleAdmin(admin.ModelAdmin):
form = RuleAdminForm
fieldsets = (
(None, {'fields': ('robot', 'sites')}),
(_('URL patterns'),... | Add filter_horizontal for for allowed and disallowed | Add filter_horizontal for for allowed and disallowed
| Python | bsd-3-clause | jazzband/django-robots,jezdez/django-robots,jezdez/django-robots,jscott1971/django-robots,jscott1971/django-robots,jazzband/django-robots |
4dc2bb7e2973f39dabb267fb8d6782fe61fe36a9 | sample/utils.py | sample/utils.py | import os
def open_lastrun_file(mode='r'):
'''Open and return lastrun file.'''
# path to data directory
data_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data')
os.makedirs(data_dir, exist_ok=True)
# path to lastrun file
lastrun_path = os.path.join(data_dir, 'lastrun.txt')... | import os
def open_lastrun_file(mode='r'):
'''Open and return lastrun file.'''
# path to data directory
data_dir = os.path.expanduser('~/.local/share/classer/')
os.makedirs(data_dir, exist_ok=True)
# path to lastrun file
lastrun_path = os.path.join(data_dir, 'lastrun.txt')
return open(la... | Change data dir to ~/.local/share/classer | Change data dir to ~/.local/share/classer
| Python | mit | lqmanh/classer |
b95e6069a1faa849b1c5b31daf0dfd4dd4b5be23 | electionleaflets/boundaries/models.py | electionleaflets/boundaries/models.py | from django.db import models
from legacy.models import Constituency
class Boundary(models.Model):
id = models.IntegerField(primary_key=True)
constituency_id = models.IntegerField()
boundary = models.TextField()
zoom = models.IntegerField()
north = models.FloatField()
south = models.FloatField()... | from django.db import models
from legacy.models import Constituency
class Boundary(models.Model):
constituency = models.ForeignKey( Constituency )
boundary = models.TextField()
zoom = models.IntegerField()
north = models.FloatField()
south = models.FloatField()
east = models.FloatField()
we... | Put the model back the way it was | Put the model back the way it was
| Python | mit | JustinWingChungHui/electionleaflets,electionleaflets/electionleaflets,electionleaflets/electionleaflets,JustinWingChungHui/electionleaflets,DemocracyClub/electionleaflets,JustinWingChungHui/electionleaflets,DemocracyClub/electionleaflets,DemocracyClub/electionleaflets,JustinWingChungHui/electionleaflets |
969ea8afcb111c68a145cc69791e531303807608 | insight_reloaded/tests/test_api.py | insight_reloaded/tests/test_api.py | # -*- coding: utf-8 -*-
import json
from mock import MagicMock
from tornado.testing import AsyncHTTPTestCase
from insight_reloaded.api import application
from insight_reloaded import __version__ as VERSION
class InsightApiHTTPTest(AsyncHTTPTestCase):
def get_app(self):
return application
def test_api... | # -*- coding: utf-8 -*-
import json
from mock import MagicMock
from tornado.testing import AsyncHTTPTestCase
from insight_reloaded.api import application
from insight_reloaded import __version__ as VERSION
from tornado import ioloop
class InsightApiHTTPTest(AsyncHTTPTestCase):
def get_new_ioloop(self):
... | Use global ioloop as we don't pass test ioloop to tornado redis | Use global ioloop as we don't pass test ioloop to tornado redis
| Python | bsd-3-clause | novapost/insight-reloaded |
a3a1ead4954500b29a1474b333336f90a95718db | thecodingloverss.py | thecodingloverss.py | import feedparser, sys, urllib2
from bs4 import BeautifulSoup as BS
from feedgen.feed import FeedGenerator
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
d = feedparser.parse('http://thecodinglove.com/rss')
fg = FeedGenerator()
fg.title('The coding love with images.')
fg... | import feedparser, sys, urllib2
from bs4 import BeautifulSoup as BS
from feedgen.feed import FeedGenerator
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
d = feedparser.parse('http://thecodinglove.com/rss')
fg = FeedGenerator()
fg.title('The coding love with images.')
fg... | Check that contributor exist in the source feed. | Check that contributor exist in the source feed.
Otherwise things will break sooner or later.
| Python | mit | chrillux/thecodingloverss |
d137f2cf16b088e2d9722568fce6dad89d950016 | Cauldron/ext/expose/keywords.py | Cauldron/ext/expose/keywords.py | # -*- coding: utf-8 -*-
"""
An extension for keywords which expose pieces of native python objects.
"""
from __future__ import absolute_import
from Cauldron.types import Integer, DispatcherKeywordType
from Cauldron.exc import NoWriteNecessary
__all__ = ['ExposeAttribute']
class ExposeAttribute(DispatcherKeywordType)... | # -*- coding: utf-8 -*-
"""
An extension for keywords which expose pieces of native python objects.
"""
from __future__ import absolute_import
from Cauldron.types import Integer, DispatcherKeywordType
from Cauldron.exc import NoWriteNecessary
__all__ = ['ExposeAttribute']
class ExposeAttribute(DispatcherKeywordType)... | FIx a bug in exposed attribute keyword | FIx a bug in exposed attribute keyword
| Python | bsd-3-clause | alexrudy/Cauldron |
75615b2328e521b6bb37321d1cd7dc75c4d3bfef | hecate/core/topology/border.py | hecate/core/topology/border.py | from hecate.core.topology.mixins import DimensionsMixin
class Border(DimensionsMixin):
"""
Base class for all types of borders.
"""
def __init__(self):
self.topology = None
class TorusBorder(Border):
supported_dimensions = list(range(1, 100))
def wrap_coords(self, coord_prefix):
... | from hecate.core.topology.mixins import DimensionsMixin
class Border(DimensionsMixin):
"""
Base class for all types of borders.
"""
def __init__(self):
self.topology = None
class TorusBorder(Border):
supported_dimensions = list(range(1, 100))
def wrap_coords(self, coord_prefix):
... | Fix incorrect TorusBorder wrapping in negative direction | Fix incorrect TorusBorder wrapping in negative direction
| Python | mit | a5kin/hecate,a5kin/hecate |
6189ded93330e9483e6d677e26b49319c649c9f0 | test/handler_fixture.py | test/handler_fixture.py | import unittest
import tempfile
import shutil
import groundstation.node
import groundstation.transfer.response
import groundstation.transfer.request
from groundstation.station import Station
class MockStream(list):
def enqueue(self, *args, **kwargs):
self.append(*args, **kwargs)
def MockTERMINATE():
... | import unittest
import tempfile
import shutil
import uuid
import groundstation.node
import groundstation.transfer.response
import groundstation.transfer.request
from groundstation.station import Station
class MockStream(list):
def enqueue(self, *args, **kwargs):
self.append(*args, **kwargs)
def MockTER... | Implement an origin on MockStation | Implement an origin on MockStation
| Python | mit | richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation |
39b6868042e95a5a412d3d3b9fa5f735e35ddb2c | umodbus/__init__.py | umodbus/__init__.py | from logging import getLogger
try:
from logging import NullHandler
# For Python 2.7 compatibility.
except ImportError:
from logging import Handler
class NullHandler(Handler):
def emit(self, record):
pass
log = getLogger('uModbus')
log.addHandler(NullHandler())
from .server import get... | from logging import getLogger, NullHandler
log = getLogger('uModbus')
log.addHandler(NullHandler())
from .server import get_server # NOQA
| Remove another piece of unreachable code. | Remove another piece of unreachable code.
| Python | mpl-2.0 | AdvancedClimateSystems/python-modbus,AdvancedClimateSystems/uModbus |
bc8675b170748b51403fb31d03ed06399268cb7b | examples/test_deferred_asserts.py | examples/test_deferred_asserts.py | """
This test demonstrates the use of deferred asserts.
Deferred asserts won't raise exceptions from failures until either
process_deferred_asserts() is called, or the test reaches the tearDown() step.
"""
import pytest
from seleniumbase import BaseCase
class DeferredAssertTests(BaseCase):
@pytest.mark.expected_f... | """
This test demonstrates the use of deferred asserts.
Deferred asserts won't raise exceptions from failures until either
process_deferred_asserts() is called, or the test reaches the tearDown() step.
Requires version 2.1.6 or newer for the deferred_assert_exact_text() method.
"""
import pytest
from seleniumbase impor... | Update an example test that uses deferred asserts | Update an example test that uses deferred asserts
| Python | mit | mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase |
f89d59d89af12473c609948bae518151a9adc64a | accelerator/migrations/0074_update_url_to_community.py | accelerator/migrations/0074_update_url_to_community.py | # Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRe... | # Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRe... | Fix the query for updating the people and mentor urls to community url | [AC-9046] Fix the query for updating the people and mentor urls to community url
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator |
672d491fc88683531e12e5576e10bc5e7d9a71bd | bindings/python/testsuite/test_timeline_file_source.py | bindings/python/testsuite/test_timeline_file_source.py | import gst
from common import TestCase
import ges
class TimelineFileSource(TestCase):
def testTimelineFileSource(self):
src = ges.TimelineFileSource("blahblahblah")
src.set_mute(True)
src.set_max_duration(long(100))
src.set_supported_formats("video")
assert (src.get_suppo... | import gst
from common import TestCase
import ges
class TimelineFileSource(TestCase):
def testTimelineFileSource(self):
src = ges.TimelineFileSource("file://blahblahblah")
src.set_mute(True)
src.set_max_duration(long(100))
src.set_supported_formats("video")
assert (src.ge... | Fix the timeline_file_source test suite | pyges: Fix the timeline_file_source test suite
Can't create a GESTimelineFileSource if you don't have the protocol in the uri
| Python | lgpl-2.1 | cfoch/gst-editing-services,MathieuDuponchelle/PitiviGes,volodymyrrudyi/gst-editing-services,cfoch/ges,freesteph/gst-editing-services,cfoch/gst-editing-services,cfoch/ges,freesteph/gst-editing-services,cfoch/ges,pitivi/gst-editing-services,MathieuDuponchelle/PitiviGes,volodymyrrudyi/gst-editing-services,cfoch/ges,pitivi... |
1456ebbf7621d257b7f67117a34bcf4c35de41d3 | K2fov/tests/test_k2onsilicon.py | K2fov/tests/test_k2onsilicon.py | """Test whether the K2onSilicon command-line tool works."""
import tempfile
from ..K2onSilicon import K2onSilicon_main
def test_K2onSilicon():
"""Test the basics: does K2onSilicon run without error on a dummy file?"""
csv = '0, 0, 0\n'
with tempfile.NamedTemporaryFile() as temp:
try:
... | """Test whether the `K2onSilicon` command-line tool works."""
import tempfile
import numpy as np
from ..K2onSilicon import K2onSilicon_main
def test_K2onSilicon():
"""Test the basics: does K2onSilicon run without error on a dummy file?"""
csv = '269.5, -28.5, 12\n0, 0, 20\n'
with tempfile.NamedTemporaryF... | Make the K2onSilicon unit test more comprehensive | Make the K2onSilicon unit test more comprehensive
| Python | mit | KeplerGO/K2fov,mrtommyb/K2fov |
98f6a07188cc9a9aa9373c3795db49b1e576c2a8 | iatidq/dqimportpublisherconditions.py | iatidq/dqimportpublisherconditions.py |
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3... |
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3... | Allow publisher conditions to be imported from text | Allow publisher conditions to be imported from text
| Python | agpl-3.0 | pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality |
82c57b4fad49b171cd0833b38867474d6578220c | client/examples/followbot.py | client/examples/followbot.py |
from botchallenge import *
USERNAME = "" # Put your minecraft username here
SERVER = "" # Put the address of the minecraft server here
robot = Robot(USERNAME, SERVER)
while True:
me = robot.get_location()
owner = robot.get_owner_location()
print(me.distance(owner))
if me.distance(owner) > 4:
... |
from botchallenge import *
import time
USERNAME = "" # Put your minecraft username here
SERVER = "" # Put the address of the minecraft server here
robot = Robot(USERNAME, SERVER)
while True:
me = robot.get_location()
owner = robot.get_owner_location()
print(me.distance(owner))
if me.distance(owner)... | Add timer to follow bot | Add timer to follow bot
| Python | mit | Rafiot/botchallenge,Rafiot/botchallenge,Rafiot/botchallenge,Rafiot/botchallenge |
2cadf977592bd1082f5914cf365849d3f9897b9c | admin/common_auth/models.py | admin/common_auth/models.py | from django.contrib.auth.models import (
AbstractBaseUser,
PermissionsMixin,
BaseUserManager,
)
from django.db import models
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')
... | from django.db import models
class AdminProfile(models.Model):
user = models.OneToOneField('osf.OSFUser', related_name='admin_profile')
desk_token = models.CharField(max_length=45, blank=True)
desk_token_secret = models.CharField(max_length=45, blank=True)
| Remove MyUser in favor of AdminProfile and OSFUser | Remove MyUser in favor of AdminProfile and OSFUser
Admin users are now the same as the OSFUser - AdminProfile gives access
to a few extra fields related to desk keys. AdminProfile has a one to
one relationship with a OSFUser.
| Python | apache-2.0 | mfraezz/osf.io,mattclark/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,Johnetordoff/osf.io,Nesiehr/osf.io,acshi/osf.io,chrisseto/osf.io,mattclark/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,Nesiehr/osf.io,crcresearch/osf.io,Nesiehr/osf.io,hmoco/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,TomBaxt... |
3072b6dd724255c3fba3bc6f837ec823d507e321 | grammpy_transforms/contextfree.py | grammpy_transforms/contextfree.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 10.08.2017 20:33
:Licence GNUv3
Part of grammpy-transforms
"""
from grammpy import Grammar
from .NongeneratingSymbolsRemove import remove_nongenerating_symbols
from .UnreachableSymbolsRemove import remove_unreachable_symbols
class ContextFree:
@staticme... | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 10.08.2017 20:33
:Licence GNUv3
Part of grammpy-transforms
"""
from grammpy import Grammar
from .NongeneratingSymbolsRemove import remove_nongenerating_symbols
from .UnreachableSymbolsRemove import remove_unreachable_symbols
class ContextFree:
@staticme... | Implement alg to remove useless symbols | Implement alg to remove useless symbols
| Python | mit | PatrikValkovic/grammpy |
092bd3d506ec281a24adcecef6ca498443df5f59 | kboard/board/urls.py | kboard/board/urls.py | # Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new... | # Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new... | Add 'comment_id' parameter in 'delete_comment' url | Add 'comment_id' parameter in 'delete_comment' url
| Python | mit | hyesun03/k-board,guswnsxodlf/k-board,hyesun03/k-board,kboard/kboard,guswnsxodlf/k-board,kboard/kboard,guswnsxodlf/k-board,cjh5414/kboard,darjeeling/k-board,hyesun03/k-board,kboard/kboard,cjh5414/kboard,cjh5414/kboard |
a2627a5e0fc68be04af50259e1fd504be389aeb1 | kino/utils/config.py | kino/utils/config.py |
from utils.data_handler import DataHandler
class Config(object):
class __Config:
def __init__(self):
self.data_handler = DataHandler()
self.fname = "config.json"
config = self.__read_config()
self.kino = config["kino"]
self.github = config["gith... | # -*- coding: utf-8 -*-
from utils.data_handler import DataHandler
class Config(object):
class __Config:
def __init__(self):
self.data_handler = DataHandler()
self.fname = "config.json"
config = self.__read_config()
self.kino = config["kino"]
se... | Add Config weather - (DARKSKY API KEY, HOME, WORK_PLACE | Add Config weather - (DARKSKY API KEY, HOME, WORK_PLACE
| Python | mit | DongjunLee/kino-bot |
57f2a438845cd0d7263da6ac66142d5403e41d98 | examples/markdown/build.py | examples/markdown/build.py | #!/usr/bin/env python3
# build.py
import os
# Markdown to HTML library
# https://pypi.org/project/Markdown/
import markdown
from staticjinja import Site
markdowner = markdown.Markdown(output_format="html5")
def md_context(template):
with open(template.filename) as f:
markdown_content = f.read()
... | #!/usr/bin/env python3
# build.py
import os
from pathlib import Path
import markdown
from staticjinja import Site
markdowner = markdown.Markdown(output_format="html5")
def md_context(template):
markdown_content = Path(template.filename).read_text()
return {"post_content_html": markdowner.convert(markdown_c... | Simplify markdown example using pathlib | example: Simplify markdown example using pathlib
| Python | mit | Ceasar/staticjinja,Ceasar/staticjinja |
986dc7064f1dfb651d6185c38a2b5070bf8926f8 | examples/restore_alerts.py | examples/restore_alerts.py | #!/usr/bin/env python
#
# Restore Alerts of the format in a JSON dumpfile from the list_alerts.py example.
#
import os
import sys
import json
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import SdcClient
#
# Parse arguments
#
if len(sys.argv) != 3:
print 'u... | #!/usr/bin/env python
#
# Restore Alerts of the format in a JSON dumpfile from the list_alerts.py example.
#
import os
import sys
import json
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import SdcClient
#
# Parse arguments
#
if len(sys.argv) != 3:
print 'u... | Append note to Description indicating the Alert was created programmatically | Append note to Description indicating the Alert was created programmatically
| Python | mit | draios/python-sdc-client,draios/python-sdc-client |
eecde2e8fdd3b105e68a5bd4bab16bdfb9767546 | eximhandler/eximhandler.py | eximhandler/eximhandler.py | import logging
from subprocess import Popen, PIPE
class EximHandler(logging.Handler):
"""
A handler class which sends an email using exim for each logging event.
"""
def __init__(self, toaddr, subject, exim_path="/usr/sbin/exim"):
"""
Initialize the handler.
"""
logging... | import logging
from subprocess import Popen, PIPE
class EximHandler(logging.Handler):
"""
A handler class which sends an email using exim for each logging event.
"""
def __init__(self, toaddr, subject, exim_path="/usr/sbin/exim"):
"""
Initialize the handler.
"""
logging... | Fix to allow overriding subject formatting | Fix to allow overriding subject formatting
| Python | unlicense | danmichaelo/eximhandler |
22b8e32cc350228b328f026ccf9e3e90ef9f2aed | manoseimas/settings/vagrant.py | manoseimas/settings/vagrant.py | from manoseimas.settings.base import * # noqa
from manoseimas.settings.development import * # noqa
INTERNAL_IPS = (
'127.0.0.1',
'10.0.2.2', # Vagrant host IP in default config
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'init_command': 'S... | from manoseimas.settings.base import * # noqa
from manoseimas.settings.development import * # noqa
INTERNAL_IPS = (
'127.0.0.1',
'10.0.2.2', # Vagrant host IP in default config
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'init_command': ('... | Set STRICT_ALL_TABLES on connection to prevent MySQL from silently truncating data. | Set STRICT_ALL_TABLES on connection to prevent MySQL from silently truncating data.
| Python | agpl-3.0 | ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt |
7a94ef4efddc639a13c00669c4cf10f07e8aa290 | mezzanine/pages/context_processors.py | mezzanine/pages/context_processors.py | from mezzanine.pages.models import Page
def page(request):
"""
Adds the current page to the template context and runs its
``set_helper`` method. This was previously part of
``PageMiddleware``, but moved to a context processor so that
we could assign these template context variables without
the... |
from mezzanine.pages.models import Page
def page(request):
"""
Adds the current page to the template context and runs its
``set_helper`` method. This was previously part of
``PageMiddleware``, but moved to a context processor so that
we could assign these template context variables without
th... | Clean up page context processor check. | Clean up page context processor check.
| Python | bsd-2-clause | wbtuomela/mezzanine,dsanders11/mezzanine,christianwgd/mezzanine,Cicero-Zhao/mezzanine,geodesign/mezzanine,promil23/mezzanine,sjdines/mezzanine,industrydive/mezzanine,sjuxax/mezzanine,dsanders11/mezzanine,christianwgd/mezzanine,ryneeverett/mezzanine,viaregio/mezzanine,geodesign/mezzanine,ryneeverett/mezzanine,vladir/mez... |
61d455cbc2b4177fbb4640211679f5c1948042ff | configurator/__init__.py | configurator/__init__.py | #
# Copyright 2015 Yasser Gonzalez Fernandez
#
# 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
#
"""Calculation of optimal configuration... | #
# Copyright 2015 Yasser Gonzalez Fernandez
#
# 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
#
"""Calculation of optimal configuration... | Hide stderr output when calling get to get version | Hide stderr output when calling get to get version
| Python | apache-2.0 | yasserglez/configurator,yasserglez/configurator |
e4193b7082cf3d891c993905443415a613630f8f | mailtemplates/model/sqla/models.py | mailtemplates/model/sqla/models.py | from sqlalchemy import ForeignKey, Column
from sqlalchemy import String
from sqlalchemy import Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import Unicode, Integer
from sqlalchemy.orm import backref, relation
from tgext.pluggable import app_model, primary_key
DeclarativeBase = de... | from sqlalchemy import ForeignKey, Column, UnicodeText
from sqlalchemy import String
from sqlalchemy import Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import Unicode, Integer
from sqlalchemy.orm import backref, relation
from tgext.pluggable import app_model, primary_key
Declara... | Change type from text to UnicodeText | Change type from text to UnicodeText
| Python | mit | axant/tgapp-mailtemplates,axant/tgapp-mailtemplates |
83966de4421094cf456f0002622f9f409ab4a694 | wger/gym/signals.py | wger/gym/signals.py | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | Delete the document from the disk on delete | Delete the document from the disk on delete
| Python | agpl-3.0 | kjagoo/wger_stark,rolandgeider/wger,wger-project/wger,petervanderdoes/wger,petervanderdoes/wger,DeveloperMal/wger,kjagoo/wger_stark,petervanderdoes/wger,DeveloperMal/wger,rolandgeider/wger,rolandgeider/wger,kjagoo/wger_stark,wger-project/wger,rolandgeider/wger,petervanderdoes/wger,DeveloperMal/wger,DeveloperMal/wger,kj... |
41d795736a7e759cf85cbe366567375eb9703a4a | aldryn_faq/admin.py | aldryn_faq/admin.py | # -*- coding: utf-8 -*-
from adminsortable.admin import SortableAdmin
from cms.admin.placeholderadmin import PlaceholderAdmin
from django.contrib import admin
from distutils.version import LooseVersion
from hvad.admin import TranslatableAdmin
import cms
from . import models
from aldryn_faq.forms import CategoryForm
... | # -*- coding: utf-8 -*-
from adminsortable.admin import SortableAdmin
from cms.admin.placeholderadmin import PlaceholderAdmin
from django.contrib import admin
from distutils.version import LooseVersion
from hvad.admin import TranslatableAdmin
import cms
from . import models
from aldryn_faq.forms import CategoryForm
... | Use appropriate order of classes | Use appropriate order of classes
| Python | bsd-3-clause | czpython/aldryn-faq,czpython/aldryn-faq,mkoistinen/aldryn-faq,czpython/aldryn-faq,czpython/aldryn-faq |
7427ee344545356070db1300aae83272d5568e89 | custom/icds_reports/tasks.py | custom/icds_reports/tasks.py | import os
from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from django.db import connections
@periodic_task(run_every=crontab(minute=0, hour=0, day_of_week=7))
def move_ucr_data_into_aggregation_tables():
with connections[settings.ICDS_UCR_DATABASE_ALIA... | import os
from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from django.db import connections
@periodic_task(run_every=crontab(minute=0, hour=0, day_of_week=7), acks_late=True)
def move_ucr_data_into_aggregation_tables():
with connections[settings.ICDS_U... | Add acks late to task | Add acks late to task
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq |
6d21aa9e6d52701d7beacd4ec519ab1bac488886 | machina/models/abstract_models.py | machina/models/abstract_models.py | # -*- coding: utf-8 -*-
# Standard library imports
from __future__ import unicode_literals
# Third party imports
from django.db import models
from django.utils.translation import ugettext_lazy as _
# Local application / specific library imports
class ActiveManager(models.Manager):
"""
Returns only active o... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
class ActiveManager(models.Manager):
"""
Returns only active objects.
"""
def get_queryset(self):
return super(ActiveManager, self).get_queryse... | Remove unnecessary compat code from ActiveManager | Remove unnecessary compat code from ActiveManager
| Python | bsd-3-clause | franga2000/django-machina,franga2000/django-machina,reinbach/django-machina,reinbach/django-machina,ellmetha/django-machina,franga2000/django-machina,reinbach/django-machina,ellmetha/django-machina,ellmetha/django-machina |
a146319132a21916747f98fa183fbe29139653ae | lib/pycall/python/investigator.py | lib/pycall/python/investigator.py | from distutils.sysconfig import get_config_var
import sys
for var in ('executable', 'exec_prefix', 'prefix'):
print(var + ': ' + str(getattr(sys, var)))
print('multiarch: ' + str(getattr(sys, 'implementation', sys)._multiarch))
for var in ('VERSION', 'INSTSONAME', 'LIBRARY', 'LDLIBRARY', 'LIBDIR', 'PYTHONFRAMEWORKPRE... | from distutils.sysconfig import get_config_var
import sys
for var in ('executable', 'exec_prefix', 'prefix'):
print(var + ': ' + str(getattr(sys, var)))
print('multiarch: ' + str(getattr(getattr(sys, 'implementation', sys), '_multiarch', None)))
for var in ('VERSION', 'INSTSONAME', 'LIBRARY', 'LDLIBRARY', 'LIBDIR', '... | Fix for python without _multiarch support | Fix for python without _multiarch support
| Python | mit | mrkn/pycall.rb,mrkn/pycall,mrkn/pycall.rb,mrkn/pycall,mrkn/pycall.rb,mrkn/pycall,mrkn/pycall,mrkn/pycall.rb |
3229340a11a1fcfe9f11ad0c5b558469043deaf4 | linkatos/firebase.py | linkatos/firebase.py | import pyrebase
def store_url(is_yes, url, FB_API_KEY, FB_USER, FB_PASS):
# do nothing if it's unnecessary
if is_yes is False:
return is_yes
# connect to firebase
config = {
"apiKey": FB_API_KEY,
"authDomain": "coses-acbe6.firebaseapp.com",
"databaseURL": "https://cose... | import pyrebase
def store_url(is_yes, url, FB_API_KEY, FB_USER, FB_PASS):
# do nothing if it's unnecessary
if not is_yes:
return is_yes
# connect to firebase
config = {
"apiKey": FB_API_KEY,
"authDomain": "coses-acbe6.firebaseapp.com",
"databaseURL": "https://coses-acb... | Change 'is False' to 'not' | refactor: Change 'is False' to 'not'
| Python | mit | iwi/linkatos,iwi/linkatos |
99470c7874a65ccf73693624454db8c4b20d59e1 | alerts/cloudtrail_public_bucket.py | alerts/cloudtrail_public_bucket.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/.
# Copyright (c) 2014 Mozilla Corporation
from lib.alerttask import AlertTask
from mozdef_util.qu... | #!/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/.
# Copyright (c) 2014 Mozilla Corporation
from lib.alerttask import AlertTask
from mozdef_util.qu... | Remove unused import from cloudtrail public bucket alert | Remove unused import from cloudtrail public bucket alert
| Python | mpl-2.0 | mpurzynski/MozDef,mozilla/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,mozilla/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,mozilla/MozDef,mozilla/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,jeffbryner/MozDef |
bd0cf3920121ada2c35928130b910667ce16a85a | downstream-farmer/client.py | downstream-farmer/client.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from heartbeat import Challenge
import requests
from .utils import urlify
from .exc import DownstreamError
class DownstreamClient(object):
def __init__(self, server_url):
self.server = server_url.strip('/')
self.challenges = []
def con... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import random
from heartbeat import Challenge
import requests
from .utils import urlify
from .exc import DownstreamError
class DownstreamClient(object):
def __init__(self, server_url):
self.server = server_url.strip('/')
self.challenges = [... | Add random_challenge method to choose a challenge to answer | Add random_challenge method to choose a challenge to answer
| Python | mit | Storj/downstream-farmer |
3ba739dccb1753d15b7e1911d9da1ef021ee1fb4 | gitxblob/commands/add.py | gitxblob/commands/add.py | """usage: git-xblob add <path> [...]"""
import os
from ..utils import git
def bail(code=1):
print __doc__.strip()
exit(code)
def run_add(paths):
if not paths:
bail()
missing_any = False
for path in paths:
if not os.path.exists(path):
print path, 'does not exist'
... | """usage: git-xblob add <path> [...]"""
import os
import re
from ..utils import git
def bail(code=1):
print __doc__.strip()
exit(code)
def run_add(paths):
if not paths:
bail()
missing_any = False
for path in paths:
if not os.path.exists(path):
print path, 'does no... | Clean up spaces (a little) | Clean up spaces (a little) | Python | bsd-3-clause | mikeboers/git-xblob |
b4b87f00f170828accb1974d51fc446694d8334c | examples/rev_rxns.py | examples/rev_rxns.py |
"""Example of reversible reaction."""
import os
from chemkinlib.utils import Parser
from chemkinlib.reactions import ReactionSystems
from chemkinlib.config import DATA_DIRECTORY
# USER INPUT: reaction (xml) file
xml_filename = os.path.join(DATA_DIRECTORY, "rxns_reversible.xml")
parser = Parser.ReactionParser(xml_f... |
"""Example of reversible reaction."""
import os
from chemkinlib.utils import Parser
from chemkinlib.reactions import ReactionSystems
from chemkinlib.config import DATA_DIRECTORY
# USER INPUT: reaction (xml) file
xml_filename = os.path.join(DATA_DIRECTORY, "rxns_reversible.xml")
parser = Parser.ReactionParser(xml_f... | Add documentation of the new functions | Add documentation of the new functions
| Python | mit | cs207-group11/cs207-FinalProject,hsim13372/cs207-FinalProject,krmotwani/cs207-FinalProject |
8eea97c45c3e40299db251867eb01a862ca1fdbc | app/dao/__init__.py | app/dao/__init__.py | from app import db
from app.dao.decorators import transactional
@transactional
def dao_create_record(record):
db.session.add(record)
@transactional
def dao_update_record(data_type, id, **kwargs):
return data_type.query.filter_by(id=id).update(
kwargs
)
def dao_get_record_by_id(data_type, id):
... | from app import db
from app.dao.decorators import transactional
@transactional
def dao_create_record(record):
db.session.add(record)
# @transactional
# def dao_update_record(data_type, id, **kwargs):
# return data_type.query.filter_by(id=id).update(
# kwargs
# )
# def dao_get_record_by_id(data... | Comment out generic db functions as not used yet | Comment out generic db functions as not used yet
| Python | mit | NewAcropolis/api,NewAcropolis/api,NewAcropolis/api |
bd761accdc38b4ed71f94048c3d9ceae05859925 | fabfile/tasks/ntp.py | fabfile/tasks/ntp.py | from fabfile.config import *
@task
@roles('all')
def get_all_time():
date = run("DATE=$( sudo date ); DATEMILLISEC=$( sudo date +%s ); echo $DATE; echo $DATEMILLISEC")
return tuple(date.split('\r\n'))
@task
@roles('build')
def verify_time_all():
result = execute('get_all_time')
print result
all_ti... | from fabfile.config import *
@task
@roles('all')
def get_all_time():
date = run("DATE=$( sudo date ); DATEMILLISEC=$( sudo date +%s ); echo $DATE; echo $DATEMILLISEC")
return tuple(date.split('\r\n'))
@task
@parallel
@roles('build')
def verify_time_all():
result = execute('get_all_time')
all_time = []... | Increase the time delta from 120 to 240 milli secs to decide the failure. | Increase the time delta from 120 to 240 milli secs to
decide the failure.
Change-Id: Ic51da36d79d4cd4ccac342d7242e56a23e21c07f
| Python | apache-2.0 | Juniper/contrail-fabric-utils,Juniper/contrail-fabric-utils |
93e46310b8ea9e61dbabf02bd3dd4b6b6748dd6e | erpnext/accounts/doctype/bank/bank_dashboard.py | erpnext/accounts/doctype/bank/bank_dashboard.py | from __future__ import unicode_literals
from frappe import _
def get_data():
return {
'fieldname': 'bank',
'non_standard_fieldnames': {
'Paymnet Order': 'company_bank'
},
'transactions': [
{
'label': _('Bank Deatils'),
'items': ['Bank Account', 'Bank Guarantee']
},
{
'items': ['Payme... | from __future__ import unicode_literals
from frappe import _
def get_data():
return {
'fieldname': 'bank',
'transactions': [
{
'label': _('Bank Deatils'),
'items': ['Bank Account', 'Bank Guarantee']
}
]
}
| Remove payment order from bank dashboard | fix: Remove payment order from bank dashboard
| Python | agpl-3.0 | gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext |
c72decbfaddc6fe697c8afa5330a40afded6ef6f | test/test_pickle.py | test/test_pickle.py | import RMF
import cPickle
b = RMF.BufferHandle()
f = RMF.create_rmf_buffer(b)
f.get_root_node().add_child("hi", RMF.ORGANIZATIONAL)
del f
picklestring = cPickle.dumps(b)
bb = cPickle.loads(picklestring)
f = RMF.open_rmf_buffer_read_only(bb)
print f.get_root_node().get_children()[0]
| import RMF
try:
import cPickle as pickle
except ImportError:
import pickle
b = RMF.BufferHandle()
f = RMF.create_rmf_buffer(b)
f.get_root_node().add_child("hi", RMF.ORGANIZATIONAL)
del f
picklestring = pickle.dumps(b)
bb = pickle.loads(picklestring)
f = RMF.open_rmf_buffer_read_only(bb)
print f.get_root_no... | Fix pickle import in Python 3. | Fix pickle import in Python 3.
| Python | apache-2.0 | salilab/rmf,salilab/rmf,salilab/rmf,salilab/rmf |
3c8bc9d7c7951e0728951c0e401a1b121e8a39b6 | open_municipio/locations/admin.py | open_municipio/locations/admin.py | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from open_municipio.locations.models import Location
class LocationAdmin(admin.ModelAdmin):
pass
admin.site.register(Location, LocationAdmin)
| from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from open_municipio.locations.models import Location
class LocationAdmin(admin.ModelAdmin):
list_display = ('name', 'count')
admin.site.register(Location, LocationAdmin)
| Add a column for count field | Add a column for count field | Python | agpl-3.0 | openpolis/open_municipio,openpolis/open_municipio,openpolis/open_municipio,openpolis/open_municipio |
a01981b818ca97f57da5a75c3342178639c08e3c | tests/test_suite.py | tests/test_suite.py | #!/usr/bin/python
from pywidl.pywidl import App
import unittest
from difflib import context_diff
import os.path
import sys
class TestPyWIdl(unittest.TestCase):
def _match(self, fromfile, tofile):
diff = context_diff(open(fromfile).readlines(), open(tofile).readlines(),
fromfile=fromfile, tofile=tofile... | #!/usr/bin/python
from pywidl.pywidl import App
import unittest
from difflib import context_diff
import os
import sys
class TestPyWIdl(unittest.TestCase):
def _match(self, fromfile, tofile):
diff = context_diff(open(fromfile).readlines(), open(tofile).readlines(),
fromfile=fromfile, tofile=tofile)
... | Remove received after successful diff. | Remove received after successful diff.
| Python | mit | VasilyStepanov/pywidl |
c89ce9429a85aaf0546c278c2de6fe5061e350e6 | django-geojson/djgeojson/views.py | django-geojson/djgeojson/views.py | from http import HttpJSONResponse
from serializers import Serializer as GeoJSONSerializer
from django.views.generic import ListView
class GeoJSONResponseMixin(object):
"""
A mixin that can be used to render a GeoJSON response.
"""
response_class = HttpJSONResponse
""" Select fields for properties ... | from django.views.generic import ListView
from django.utils.decorators import method_decorator
from django.views.decorators.gzip import gzip_page
from .http import HttpJSONResponse
from .serializers import Serializer as GeoJSONSerializer
class GeoJSONResponseMixin(object):
"""
A mixin that can be used to ren... | Add Gzip compression to geojson layer view | Add Gzip compression to geojson layer view
| Python | bsd-2-clause | johan--/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,johan--/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,camillemonchicourt/Geotrek,makinacorpus/Geotrek,makinacorpus/Geotrek,Anaethelion/Geotrek,Anaethelion/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,camillemonchicourt... |
5764b582fde86570fe15c71509c9b7d718d7303a | conference_scheduler/parameters.py | conference_scheduler/parameters.py | from typing import NamedTuple, Callable, List, Dict, Sequence
import pulp
from .resources import ScheduledItem
def variables(events: Sequence, rooms: Sequence, slots: Sequence):
"""Defines the required instances of pulp.LpVariable
Parameters
----------
events : List or Tuple
of resources.Even... | from typing import Sequence
import pulp
def variables(events: Sequence, rooms: Sequence, slots: Sequence):
"""Defines the required instances of pulp.LpVariable
Parameters
----------
events : List or Tuple
of resources.Event
rooms : List or Tuple
of resources.Room
slots : List ... | Tidy up layout and remove redundant code | Tidy up layout and remove redundant code
| Python | mit | PyconUK/ConferenceScheduler |
1a18bfed90f6423a0c52b3f3fe523b4ed77188af | examples/example_windows.py | examples/example_windows.py | import rumps
window = rumps.Window('Nothing...', 'ALERTZ')
window.title = 'WINDOWS jk'
window.message = 'Something.'
window.default_text = 'eh'
response = window.run()
print response
window.add_buttons('One', 'Two', 'Three')
print window.run()
print response
| import rumps
window = rumps.Window('Nothing...', 'ALERTZ')
window.title = 'WINDOWS jk'
window.message = 'Something.'
window.default_text = 'eh'
response = window.run()
print (response)
window.add_buttons('One', 'Two', 'Three')
print (window.run())
| Update example for Python 3 | Update example for Python 3 | Python | bsd-3-clause | jaredks/rumps,cbenhagen/rumps |
2d379a3bd04d2b687c719cb9ccca5f289b434d00 | plenum/server/i3pc_watchers.py | plenum/server/i3pc_watchers.py | from typing import Callable, Iterable
from plenum.server.quorums import Quorums
class NetworkI3PCWatcher:
def __init__(self, cb: Callable):
self.nodes = set()
self.connected = set()
self.callback = cb
self.quorums = Quorums(0)
def connect(self, name: str):
self.connect... | from typing import Callable, Iterable
from plenum.server.quorums import Quorums
class NetworkI3PCWatcher:
def __init__(self, cb: Callable):
self._nodes = set()
self.connected = set()
self.callback = cb
self.quorums = Quorums(0)
def connect(self, name: str):
self.connec... | Make interface of NetworkI3PCWatcher more clear | INDY-1199: Make interface of NetworkI3PCWatcher more clear
Signed-off-by: Sergey Khoroshavin <b770466c7a06c5fe47531d5f0e31684f1131354d@dsr-corporation.com>
| Python | apache-2.0 | evernym/plenum,evernym/zeno |
85cf0af73ddfdce0281a112e4e86d1104e0222e1 | appengine_config.py | appengine_config.py | import os
import site
import sys
approot = os.path.dirname(__file__)
sys.path.append(os.path.join(approot, 'lib'))
site.addsitedir(os.path.join(approot, 'site-packages'))
| import os
import site
import sys
approot = os.path.dirname(__file__)
sys.path.append(os.path.join(approot, 'lib'))
site.addsitedir(os.path.join(approot, 'site-packages'))
def webapp_add_wsgi_middleware(app):
from google.appengine.ext.appstats import recording
app = recording.appstats_wsgi_middleware(app)
return... | Add the appstats recording middleware | Add the appstats recording middleware
| Python | mit | xchewtoyx/pulldb |
d209020be5369345e04ba5d5cdd30cd8538409a1 | tt/utils.py | tt/utils.py | def without_spaces(the_str):
return "".join(the_str.split()) | def without_spaces(the_str):
return "".join(the_str.split())
def listwise_to_str(the_list):
return list(map(str, the_list)) | Add utility method for converting all elements in list to string. | Add utility method for converting all elements in list to string.
| Python | mit | welchbj/tt,welchbj/tt,welchbj/tt |
7b758788bdf8ca52d6b75892d8ee97484188d699 | bookworm/settings_mobile.py | bookworm/settings_mobile.py | from settings import *
import settings
TEMPLATE_DIRS_BASE = TEMPLATE_DIRS
TEMPLATE_DIRS = (
'%s/library/templates/mobile/auth' % ROOT_PATH,
'%s/library/templates/mobile' % ROOT_PATH,
)
TEMPLATE_DIRS += TEMPLATE_DIRS_BASE
MOBILE = True
| from settings import *
import settings
TEMPLATE_DIRS_BASE = TEMPLATE_DIRS
TEMPLATE_DIRS = (
'%s/library/templates/mobile/auth' % ROOT_PATH,
'%s/library/templates/mobile' % ROOT_PATH,
)
TEMPLATE_DIRS += TEMPLATE_DIRS_BASE
MOBILE = True
SESSION_COOKIE_NAME = 'bookworm_mobile'
| Change cookie name for mobile setting | Change cookie name for mobile setting | Python | bsd-3-clause | srilatha44/threepress,srilatha44/threepress,srilatha44/threepress,srilatha44/threepress |
a67b2c7280ab7e5ae831d372b1fc81f0a2f1f2ce | h5py/tests/hl/test_deprecation.py | h5py/tests/hl/test_deprecation.py | # This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2018 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
"""
Tests that deprecations work correctly
"""
from ... | # This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2018 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
"""
Tests that deprecations work correctly
"""
from ... | Fix test which appeared to not be run | BUG: Fix test which appeared to not be run
| Python | bsd-3-clause | h5py/h5py,h5py/h5py,h5py/h5py |
52679561fce3d03c0c2838c209067b070d664e94 | postgresql/types/io/pg_network.py | postgresql/types/io/pg_network.py | from .. import INETOID, CIDROID, MACADDROID
from . import lib
try:
import ipaddress
except ImportError:
import ipaddr as ipaddress
oid_to_type = {
MACADDROID : str,
INETOID: ipaddress._IPAddressBase,
CIDROID: ipaddress._BaseNetwork,
}
def inet_pack(ob, pack = lib.net_pack, Constructor = ipaddress.ip_address):
a... | from .. import INETOID, CIDROID, MACADDROID
from . import lib
try:
import ipaddress
except ImportError:
import ipaddr as ipaddress
oid_to_type = {
MACADDROID : str,
INETOID: ipaddress._IPAddressBase,
CIDROID: ipaddress._BaseNetwork,
}
def inet_pack(ob, pack = lib.net_pack, Constructor = ipaddress.ip_address):
a... | Use supernet interface for building the appropriate network. | Use supernet interface for building the appropriate network.
| Python | bsd-3-clause | python-postgres/fe,python-postgres/fe |
d3904489f03aaba94354be548589564d2104082d | ci/generate_pipeline_yml.py | ci/generate_pipeline_yml.py | #!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['1-12', '2-0', '2-1', '2-2', 'multi-az']
tiles = [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Template(f.read());
with open('pipeline.yml', 'w') as f:
... | #!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['1-12', '2-0', '2-1', '2-2']
tiles = [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Template(f.read());
with open('pipeline.yml', 'w') as f:
f.write(t.... | Remove multi-az env from CI pipeline. | Remove multi-az env from CI pipeline.
| Python | apache-2.0 | cf-platform-eng/tile-generator,cf-platform-eng/tile-generator,cf-platform-eng/tile-generator,cf-platform-eng/tile-generator |
f367d3122084c85e11efeb20d560a856e9f24d0e | zuice/django.py | zuice/django.py | django = __import__("django.conf.urls.defaults", {})
from zuice import Injector
def _view_builder(bindings):
def view(request, view_class, **kwargs):
view_injector = Injector(bindings)
view = view_injector.get_from_type(view_class)
bindings_for_response = bindings.copy()
bindings_... | django = __import__("django.conf.urls.defaults", {})
from zuice import Injector
def _view_builder(bindings):
def view(request, view_class, **kwargs):
view_injector = Injector(bindings)
view = view_injector.get_from_type(view_class)
bindings_for_response = bindings.copy()
bindings_... | Refactor url_to_class_builder so that the view is only built once | Refactor url_to_class_builder so that the view is only built once
| Python | bsd-2-clause | mwilliamson/zuice |
38006f3b68edcdd7707d2b9056fa6564126747d0 | infosystem/common/subsystem/__init__.py | infosystem/common/subsystem/__init__.py | import flask
from infosystem.common.subsystem.controller import *
from infosystem.common.subsystem.driver import *
from infosystem.common.subsystem.manager import *
from infosystem.common.subsystem.router import *
class Subsystem(flask.Blueprint):
def __init__(self, resource, router=None, controller=None, manag... | import flask
from infosystem.common.subsystem.controller import *
from infosystem.common.subsystem.driver import *
from infosystem.common.subsystem.manager import *
from infosystem.common.subsystem.router import *
class Subsystem(flask.Blueprint):
def __init__(self, resource=None, router=None, controller=None, ... | Allow subsystems to not map a sqlachemy entity | Allow subsystems to not map a sqlachemy entity
| Python | apache-2.0 | samueldmq/infosystem |
eac05dfe5c4190cc10b00d18aa9f03344eb3a6ea | fastats/core/single_pass.py | fastats/core/single_pass.py |
import numpy as np
from fastats.core.decorator import fs
def value(x): # pragma: no cover
return x
@fs
def single_pass(x):
"""
Performs a single iteration over the first
dimension of `x`.
Tests
-----
>>> def square(x):
... return x * x
>>> data = np.arange(10)
>>> sin... |
import numpy as np
from fastats.core.decorator import fs
def value(x):
return x
@fs
def single_pass(x):
"""
Performs a single iteration over the first
dimension of `x`.
Tests
-----
>>> def square(x):
... return x * x
>>> data = np.arange(10)
>>> single_pass(data, value... | Remove spurious no cover pragma | Remove spurious no cover pragma
| Python | mit | dwillmer/fastats,fastats/fastats |
1361b5ebb4afd0c3c80df5bf936f3817427cd917 | apps/pages/views.py | apps/pages/views.py | from django.views.generic import DetailView
from .models import Page
class PageView(DetailView):
model = Page
def get_object(self, queryset=None):
slug = self.kwargs.get('slug')
if not slug:
slug = 'index'
return self.get_queryset().get(slug=slug)
| from django.views.generic import DetailView
from django.shortcuts import get_object_or_404
from .models import Page
class PageView(DetailView):
model = Page
def get_object(self, queryset=None):
slug = self.kwargs.get('slug')
if not slug:
slug = 'index'
return get_object... | Return 404 in case page is not found | Return 404 in case page is not found
| Python | mit | MeirKriheli/debian.org.il,MeirKriheli/debian.org.il |
0668192acf349e02694daf6480e7858f67dfeba0 | pyethapp/__init__.py | pyethapp/__init__.py | # -*- coding: utf-8 -*-
# ############# version ##################
from pkg_resources import get_distribution, DistributionNotFound
import os.path
import subprocess
try:
_dist = get_distribution('pyethapp')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.n... | # -*- coding: utf-8 -*-
# ############# version ##################
from pkg_resources import get_distribution, DistributionNotFound
import os.path
import subprocess
try:
_dist = get_distribution('pyethapp')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.n... | Fix versioning from git after `setup.py install` | Fix versioning from git after `setup.py install`
When following the `README`, __init__.py raised an
"IOError: [Errno 2] No such file or directory:" about `setup.py`.
| Python | mit | ethereum/pyethapp,RomanZacharia/pyethapp,gsalgado/pyethapp,ethereum/pyethapp,gsalgado/pyethapp,changwu-tw/pyethapp,d-das/pyethapp,RomanZacharia/pyethapp,changwu-tw/pyethapp,vaporry/pyethapp |
8ef9618850794dd499617bb28b5044336f155568 | python/setup_fsurfer.py | python/setup_fsurfer.py | #!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurfer-libs
from distutils.core import setup
setup(name='fsurfer-libs',
version='PKG_VERSION',
description='Python module to help create freesurfer workflows',
author='Suchandra Thapa',
... | #!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurfer-libs
from distutils.core import setup
setup(name='fsurfer-libs',
version='PKG_VERSION',
description='Python module to help create freesurfer workflows',
author='Suchandra Thapa',
... | Update setup to include new scripts | Update setup to include new scripts
| Python | apache-2.0 | OSGConnect/freesurfer_workflow,OSGConnect/freesurfer_workflow |
8f0f1331fc554c2a15722543017da3ce3a3f894b | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# License: MIT
#
"""This module exports the Rubocop plugin class."""
from SublimeLinter.lint import RubyLinter
class Rubocop(RubyLinter):
"""Provides... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# License: MIT
#
"""This module exports the Rubocop plugin class."""
from SublimeLinter.lint import RubyLinter
class Rubocop(RubyLinter):
"""Provides... | Prepend '-S rubocop' to version args | Prepend '-S rubocop' to version args
Fixes #17
| Python | mit | SublimeLinter/SublimeLinter-rubocop |
ffaa2b98305c7a1368587cdb30724a7cabbe3237 | glitch/apikeys_sample.py | glitch/apikeys_sample.py | # Sample untracked-keys file
# If you get errors trying to 'import apikeys', do the following:
# 1) Copy this file to apikeys.py (keeping it in the package directory)
# 2) Replace all of the example values with real ones
# 3) Generate your own cookie key, possibly using urandom as per below
# You should then be able to... | # Sample untracked-keys file
# If you get errors trying to 'import apikeys', do the following:
# 1) Copy this file to apikeys.py (keeping it in the package directory)
# 2) Replace all of the example values with real ones
# 3) Generate your own cookie key, possibly using urandom as per below
# You should then be able to... | Drop the UUID; just use urandom | Drop the UUID; just use urandom
| Python | artistic-2.0 | Rosuav/appension,Rosuav/appension,MikeiLL/appension,Rosuav/appension,Rosuav/appension,MikeiLL/appension,MikeiLL/appension,MikeiLL/appension |
e2735cba808ac4eb33e555fbb3d5d5f774ace032 | swf/actors/helpers.py | swf/actors/helpers.py | #! -*- coding:utf-8 -*-
import time
import threading
class Heart(threading.Thread):
"""Implementation of an heart beating routine
To be used by actors to send swf heartbeats notifications
once in a while.
:param heartbeating_closure: Function to be called on heart
... | #! -*- coding:utf-8 -*-
import time
import threading
class Heart(threading.Thread):
"""Implementation of an heart beating routine
To be used by actors to send swf heartbeats notifications
once in a while.
:param heartbeating_closure: Function to be called on heart
... | Update Heart actors helper class to handle args | Update Heart actors helper class to handle args
| Python | mit | botify-labs/python-simple-workflow,botify-labs/python-simple-workflow |
e94503e25bff0ba986c28ce3f16636b3bb9f2c3d | green_django/__init__.py | green_django/__init__.py | import sys
from utils import module_exists
from gevent import monkey
def make_django_green():
monkey.patch_all()
if module_exists('psycogreen'):
from psycogreen.gevent.psyco_gevent import make_psycopg_green
make_psycopg_green()
if module_exists('pymysql'):
import pymysql
... | import sys
from utils import module_exists
from gevent import monkey
def make_django_green():
monkey.patch_all()
if module_exists('psycogreen'):
from psycogreen.gevent.psyco_gevent import make_psycopg_green
make_psycopg_green()
if module_exists('pymysql'):
import pymysql
... | Check for greened package - consistency | Check for greened package - consistency
| Python | mit | philipn/green-monkey |
d95d4da272915ad6a581260679df756bf24a6f4c | app/utils/db/__init__.py | app/utils/db/__init__.py | import logging
from app import db
logger = logging.getLogger(__name__)
def save_data(data):
try:
db.session.add(data)
db.session.commit()
except Exception as err:
logger.error(err)
| import logging
from app import db
logger = logging.getLogger(__name__)
def save_record(record):
try:
db.session.add(record)
db.session.commit()
except Exception as err:
logger.error(err)
def delete_record(record):
try:
db.session.delete(record)
db.session.commit()... | Rename save method for database to a more descriptive name | [FIX] Rename save method for database to a more descriptive name
| Python | mit | brayoh/bucket-list-api |
331b3987ba09db5d8f774509bedd30c3c6522795 | ooni/tests/test_utils.py | ooni/tests/test_utils.py | import os
import unittest
from ooni.utils import pushFilenameStack
class TestUtils(unittest.TestCase):
def test_pushFilenameStack(self):
basefilename = os.path.join(os.getcwd(), 'dummyfile')
f = open(basefilename, "w+")
f.write("0\n")
f.close()
for i in xrange(1, 5):
... | import os
from twisted.trial import unittest
from ooni.utils import pushFilenameStack
class TestUtils(unittest.TestCase):
def test_pushFilenameStack(self):
basefilename = os.path.join(os.getcwd(), 'dummyfile')
f = open(basefilename, "w+")
f.write("0\n")
f.close()
for i in xr... | Use trial unittest instead of python unittest | Use trial unittest instead of python unittest
| Python | bsd-2-clause | juga0/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe,kdmurray91/ooni-probe,lordappsec/ooni-probe,kd... |
d741b41e814930130a30e99b0fece893786f7190 | src/pybel/struct/mutation/__init__.py | src/pybel/struct/mutation/__init__.py | # -*- coding: utf-8 -*-
"""This module contains functions that mutate or make transformations on a network."""
from . import deletion, expansion, induction, inference, metadata, transfer
from .deletion import *
from .expansion import *
from .induction import *
from .inference import *
from .metadata import *
from .tr... | # -*- coding: utf-8 -*-
"""This module contains functions that mutate or make transformations on a network."""
from . import collapse, deletion, expansion, induction, inference, metadata, transfer
from .collapse import *
from .deletion import *
from .expansion import *
from .induction import *
from .inference import ... | Add collapse to star import | Add collapse to star import
| Python | mit | pybel/pybel,pybel/pybel,pybel/pybel |
5baa4fb91d9b6a80d748b47192b91e2a68b567d0 | verleihsystem/categories/views.py | verleihsystem/categories/views.py | from django.shortcuts import render_to_response
from categories.models import Category
def index(request):
category_list = Category.tree.all()
return render_to_response("home.html",
{'nodes': category_list})
| from django.shortcuts import render_to_response
from categories.models import Category
def index(request):
category_list = Category.tree.all()
return render_to_response("home.html",
{'nodes': category_list, 'request': request})
| Add request to return value. | Add request to return value.
| Python | isc | westphahl/verleihsystem,westphahl/verleihsystem,westphahl/verleihsystem |
52f510b64e4ded6e159119b2fa544de577b7d949 | classyfd/directory/directory.py | classyfd/directory/directory.py | """Contains a Directory class to represent real directories"""
from ..base import _BaseFileAndDirectoryInterface
class Directory(_BaseFileAndDirectoryInterface):
"""A class that groups together the (meta)data and behavior of
directories"""
def __init__(self, path):
"""
Construct the obje... | """Contains a Directory class to represent real directories"""
from ..base import _BaseFileAndDirectoryInterface
from ..exceptions import InvalidDirectoryValueError
class Directory(_BaseFileAndDirectoryInterface):
"""A class that groups together the (meta)data and behavior of
directories"""
def __init__... | Add custom exception logic to the Directory class | Add custom exception logic to the Directory class
If an empty string was passed to the Directory class, then an exception
needs to be raised as all of its methods assume a value for the path.
| Python | mit | SizzlingVortex/classyfd |
fe50ea0dd1ceb51fdff455484cb5d2d32c94b076 | spyder_unittest/__init__.py | spyder_unittest/__init__.py | from .unittest import UnitTestPlugin as PLUGIN_CLASS
| # -*- coding:utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) Spyder Project Developers
#
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
# -----------------------------------------------------------------------------
"""Spyde... | Add version information and header | Add version information and header | Python | mit | jitseniesen/spyder-unittest |
1cc10287a7a9666d7478adc1271250ba49663e24 | drf_to_s3/tests/test_parsers.py | drf_to_s3/tests/test_parsers.py | import unittest, urllib
from rest_framework.compat import BytesIO
class TestParser(unittest.TestCase):
def setUp(self):
from drf_to_s3.parsers import NestedFormParser
self.parser = NestedFormParser()
def test_form_parser_unflattens(self):
flattened = {
'user[name]': 'Foob... | # coding=utf-8
import unittest, urllib
from rest_framework.compat import BytesIO
class TestParser(unittest.TestCase):
def setUp(self):
from drf_to_s3.parsers import NestedFormParser
self.parser = NestedFormParser()
def test_form_parser_unflattens(self):
flattened = {
'use... | Add a failing unit test of unicode parsing | Add a failing unit test of unicode parsing
| Python | mit | pombredanne/drf-to-s3,pombredanne/drf-to-s3,bodylabs/drf-to-s3,pombredanne/drf-to-s3,bodylabs/drf-to-s3,bodylabs/drf-to-s3,bodylabs/drf-to-s3,pombredanne/drf-to-s3,bodylabs/drf-to-s3,pombredanne/drf-to-s3 |
6856c469da365c7463017e4c064e1ed25c12dfdc | foyer/tests/test_performance.py | foyer/tests/test_performance.py | import mbuild as mb
import parmed as pmd
import pytest
from foyer import Forcefield
from foyer.tests.utils import get_fn
@pytest.mark.timeout(1)
def test_fullerene():
fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True)
forcefield = Forcefield(get_fn('fullerene.xml'))
forcefield.apply(fulle... | import mbuild as mb
import parmed as pmd
import pytest
from foyer import Forcefield
from foyer.tests.utils import get_fn
@pytest.mark.timeout(1)
def test_fullerene():
fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True)
forcefield = Forcefield(get_fn('fullerene.xml'))
forcefield.apply(fulle... | Allow for some missing silica bond parameters | Allow for some missing silica bond parameters
| Python | mit | mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer,iModels/foyer |
85dedf4c02d28f9a4928d46757cbaa1baf8994ed | tingbot/quit.py | tingbot/quit.py | import sys, signal
import pygame
def fixup_sigterm_behaviour():
'''
SDL registers its own signal handler for SIGTERM, which pushes a SDL_QUIT event to the event
loop, instead of killing the process right away. This is a problem for us, because when using
the fbcon drivers, the process activates and loc... | import sys, signal
import pygame
def fixup_sigterm_behaviour():
'''
SDL registers its own signal handler for SIGTERM, which pushes a SDL_QUIT event to the event
loop, instead of killing the process right away. This is a problem for us, because when using
the fbcon drivers, the process activates and loc... | Remove pygame.display.init() call on import, not needed | Remove pygame.display.init() call on import, not needed
| Python | bsd-2-clause | furbrain/tingbot-python |
4f72617702881bde979648a8ddf240b0d721cf4e | girder/app/app/__init__.py | girder/app/app/__init__.py | from .configuration import Configuration
from girder.utility import setting_utilities
from .constants import Features
from girder.plugin import GirderPlugin
@setting_utilities.validator({
Features.NOTEBOOKS
})
class AppPlugin(GirderPlugin):
DISPLAY_NAME = 'OpenChemistry App'
def validateSettings(self, e... | from .configuration import Configuration
from girder.utility import setting_utilities
from .constants import Features
from girder.plugin import GirderPlugin
@setting_utilities.validator({
Features.NOTEBOOKS
})
def validateSettings(event):
pass
class AppPlugin(GirderPlugin):
DISPLAY_NAME = 'OpenChemistry ... | Put validateSettings() after girder decorator | Put validateSettings() after girder decorator
This was mistakenly put inside the class body. It
needs to be after the girder decorator instead.
Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>
| Python | bsd-3-clause | OpenChemistry/mongochemserver |
04a3f7e0e079f0db23f723c7a08e32841fc7a9fd | hierarchical_auth/admin.py | hierarchical_auth/admin.py | from django.contrib import admin
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.auth.admin import GroupAdmin
from django.contrib.auth.forms import UserChangeForm
try:
User = settings.AUTH_USER_MODEL
except:
from django.contrib.auth.models import User
try... | from django.contrib import admin
from django.conf import settings
from django.db.models import get_model
from django.contrib.auth.models import Group
from django.contrib.auth.admin import GroupAdmin
from django.contrib.auth.forms import UserChangeForm
try:
app_label, model_name = settings.AUTH_USER_MODEL.spli... | Work with custom user models in django >= 1.5 | Work with custom user models in django >= 1.5
settings only provide module strs, not real implementations | Python | bsd-3-clause | digitalemagine/django-hierarchical-auth,zhangguiyu/django-hierarchical-auth |
aec62c210bc1746c6fefa12030ada548730faf62 | plugins/titlegiver/titlegiver.py | plugins/titlegiver/titlegiver.py | import sys
import plugin
import re
import urllib2
from utils import url_parser
from twisted.python import log
title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE)
class Titlegiver(plugin.Plugin):
def __init__(self):
plugin.Plugin.__init__(self, "Titlegiver")
@staticmethod
def find_titl... | import sys
import plugin
import re
import urllib2
from utils import url_parser
from twisted.python import log
title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE|re.DOTALL)
class Titlegiver(plugin.Plugin):
def __init__(self):
plugin.Plugin.__init__(self, "Titlegiver")
@staticmethod
def... | Fix for titles containing cr | Fix for titles containing cr
| Python | mit | Tigge/platinumshrimp |
70a2196d7748a9b01a0c23e2b2bda6a074ae4c8a | python/setup_fsurfer_backend.py | python/setup_fsurfer_backend.py | #!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
import fsurfer
setup(name='fsurfer-backend',
version=fsurfer.__version__,
description='Scripts to handle background freesurfer processin... | #!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
import fsurfer
setup(name='fsurfer-backend',
version=fsurfer.__version__,
description='Scripts to handle background freesurfer processin... | Add purge and warn scripts | Add purge and warn scripts
| Python | apache-2.0 | OSGConnect/freesurfer_workflow,OSGConnect/freesurfer_workflow |
87d868283d1972330da593fa605bd05e574cf2fd | sslyze/cli/output_generator.py | sslyze/cli/output_generator.py |
from abc import ABCMeta, abstractmethod
from sslyze.cli import CompletedServerScan
from sslyze.cli import FailedServerScan
from sslyze.server_connectivity import ServerConnectivityInfo
class OutputGenerator(object):
"""The abstract class output generator classes should inherit from.
Each method must be imp... |
from abc import ABCMeta, abstractmethod
from sslyze.cli import CompletedServerScan
from sslyze.cli import FailedServerScan
from sslyze.server_connectivity import ServerConnectivityInfo
class OutputGenerator(object):
"""The abstract class output generator classes should inherit from.
Each method must be imp... | Document how output generators work | Document how output generators work
| Python | agpl-3.0 | nabla-c0d3/sslyze |
29178a5a1e258e0f7c7392233858f36bf67241d0 | tmc/exercise_tests/check.py | tmc/exercise_tests/check.py | import re
import xml.etree.ElementTree as ET
from os import path
from tmc.exercise_tests.basetest import BaseTest, TestResult
class CheckTest(BaseTest):
def __init__(self):
super().__init__("Check")
def applies_to(self, exercise):
return path.isfile(path.join(exercise.path(), "Makefile"))
... | import re
import xml.etree.ElementTree as ET
from os import path
from tmc.exercise_tests.basetest import BaseTest, TestResult
class CheckTest(BaseTest):
def __init__(self):
super().__init__("Check")
def applies_to(self, exercise):
return path.isfile(path.join(exercise.path(), "Makefile"))
... | Fix bug: trying to call .replace on NoneType | Fix bug: trying to call .replace on NoneType
| Python | mit | JuhaniImberg/tmc.py,JuhaniImberg/tmc.py |
339f5c6d7cc5b3a70fa71fd423c0a4226acc77e7 | valor/schema.py | valor/schema.py | import json
class Schema(dict):
"""
Lightweight encapsulation of a JSON Schema.
"""
@classmethod
def from_file(cls, path_or_stream):
"""
Create a schema from a file name or stream.
"""
if hasattr(path_or_stream, 'read'):
return cls(json.load(path_or_stre... | import json
import jsonpointer
class Schema(dict):
"""
Lightweight encapsulation of a JSON Schema.
"""
@classmethod
def from_file(cls, path_or_stream):
"""
Create a schema from a file name or stream.
"""
if hasattr(path_or_stream, 'read'):
return cls(jso... | Use jsonpointer instead of my own terrible Reference class. | Use jsonpointer instead of my own terrible Reference class.
| Python | bsd-3-clause | jacobian/valor |
bf6ab9532db2e2bc67cb72415674a0fdefe3bc46 | corehq/preindex/tasks.py | corehq/preindex/tasks.py | from celery.schedules import crontab
from celery.task.base import periodic_task
from corehq.preindex.accessors import index_design_doc, get_preindex_designs
from corehq.util.decorators import serial_task
from django.conf import settings
@periodic_task(run_every=crontab(minute='*/5'), queue=settings.CELERY_PERIODIC_Q... | from celery.schedules import crontab
from celery.task.base import periodic_task
from corehq.preindex.accessors import index_design_doc, get_preindex_designs
from corehq.util.decorators import serial_task
from django.conf import settings
@periodic_task(run_every=crontab(minute='*/5'), queue=settings.CELERY_PERIODIC_Q... | Use periodic queue to increase priority | Use periodic queue to increase priority
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
e679b7d45cd4fd552b1fe54b61b914f23aca2c94 | backdrop/__init__.py | backdrop/__init__.py | import os
import statsd as _statsd
__all__ = ['statsd']
class StatsClient(object):
"""Wrap statsd.StatsClient to allow data_set to be added to stat"""
def __init__(self, statsd):
self._statsd = statsd
def __getattr__(self, item):
if item in ['timer', 'timing', 'incr', 'decr', 'gauge']:
... | import os
import statsd as _statsd
__all__ = ['statsd']
class StatsClient(object):
"""Wrap statsd.StatsClient to allow data_set to be added to stat"""
def __init__(self, statsd):
self._statsd = statsd
def __getattr__(self, item):
if item in ['timer', 'timing', 'incr', 'decr', 'gauge']:
... | Add a prefix to the statsd key | Add a prefix to the statsd key
We have loads of stats at the top leve of our statsd stats in graphite.
It makes looking for things that aren't created by backdrop really
hard.
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop |
d756406ac78830a2f54308814979e497d43f5ec7 | cyder/cydhcp/workgroup/views.py | cyder/cydhcp/workgroup/views.py | import json
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, Http404
from cyder.base.utils import make_megafilter
from cyder.base.views import cy_detail
from cyder.cydhcp.workgroup.models import Workgroup
def workgroup_detail(request, pk):
workgroup = get_object_or_404(Workgr... | import json
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, Http404
from cyder.base.utils import make_megafilter
from cyder.base.views import cy_detail
from cyder.cydhcp.workgroup.models import Workgroup
def workgroup_detail(request, pk):
workgroup = get_object_or_404(Workgr... | Add containers to workgroup detail view | Add containers to workgroup detail view
| Python | bsd-3-clause | OSU-Net/cyder,akeym/cyder,akeym/cyder,drkitty/cyder,akeym/cyder,OSU-Net/cyder,drkitty/cyder,drkitty/cyder,murrown/cyder,drkitty/cyder,OSU-Net/cyder,murrown/cyder,murrown/cyder,OSU-Net/cyder,murrown/cyder,akeym/cyder |
12cc6a6bf3e0d6c55a1f2780b76aecd615dfa47a | datatableview/tests/testcase.py | datatableview/tests/testcase.py | # -*- encoding: utf-8 -*-
import django
from django.test import TestCase
from django.core.management import call_command
if django.VERSION >= (1, 7):
from django.test import override_settings
from django.apps import apps
initial_data_fixture = 'initial_data_modern'
clear_app_cache = apps.clear_cache
e... | # -*- encoding: utf-8 -*-
import django
from django.test import TestCase
from django.core.management import call_command
if django.VERSION >= (1, 7):
from django.test import override_settings
from django.apps import apps
migrate_command = 'migrate'
initial_data_fixture = 'initial_data_modern'
clea... | Adjust tests to run migrate when necessary | Adjust tests to run migrate when necessary
| Python | apache-2.0 | pivotal-energy-solutions/django-datatable-view,pivotal-energy-solutions/django-datatable-view,pivotal-energy-solutions/django-datatable-view,doganmeh/django-datatable-view,jangeador/django-datatable-view,doganmeh/django-datatable-view,doganmeh/django-datatable-view,jangeador/django-datatable-view,jangeador/django-datat... |
927d91239e9e374b36fead2f5c2e76b95f27b069 | skimage/filter/rank/__init__.py | skimage/filter/rank/__init__.py | from .rank import *
from .percentile_rank import *
from .bilateral_rank import *
| from .rank import (autolevel, bottomhat, equalize, gradient, maximum, mean,
meansubstraction, median, minimum, modal, morph_contr_enh,
pop, threshold, tophat, noise_filter, entropy, otsu)
from .percentile_rank import (percentile_autolevel, percentile_gradient,
... | Add __all__ to rank filter package | Add __all__ to rank filter package
| Python | bsd-3-clause | rjeli/scikit-image,chriscrosscutler/scikit-image,Hiyorimi/scikit-image,emon10005/scikit-image,GaZ3ll3/scikit-image,ClinicalGraphics/scikit-image,Britefury/scikit-image,chriscrosscutler/scikit-image,juliusbierk/scikit-image,Midafi/scikit-image,dpshelio/scikit-image,ofgulban/scikit-image,GaZ3ll3/scikit-image,SamHames/sci... |
e3d3c17988fee0a9f616cf4c0f0dc67a5a60fb34 | Constants.py | Constants.py | CTCP_DELIMITER = chr(1)
MAX_MESSAGE_LENGTH = 450 #Officially 512 including the newline characters, but let's be on the safe side
CHANNEL_PREFIXES = "#&!+.~" #All the characters that could possibly indicate something is a channel name (usually just '#' though)
#Since a grey separator is often used to separate parts of... | CTCP_DELIMITER = chr(1)
MAX_MESSAGE_LENGTH = 450 #Officially 512 including the newline characters, but let's be on the safe side
CHANNEL_PREFIXES = "#&!+.~" #All the characters that could possibly indicate something is a channel name (usually just '#' though)
#Since a grey separator is often used to separate parts of... | Expand IRC numerics to name list | Expand IRC numerics to name list
| Python | mit | Didero/DideRobot |
f0270de636bb84e89cbbb54896c6ed5037a48323 | spiralgalaxygame/precondition.py | spiralgalaxygame/precondition.py | class PreconditionError (TypeError):
def __init__(self, callee, *args):
TypeError.__init__(self, '{0.__name__}{1!r}'.format(callee, args))
| from types import FunctionType, MethodType
class PreconditionError (TypeError):
def __init__(self, callee, *args):
if isinstance(callee, MethodType):
name = '{0.im_class.__name__}.{0.im_func.__name__}'.format(callee)
elif isinstance(callee, type) or isinstance(callee, FunctionType):
... | Implement prettier method names in PreconditionErrors as per spec; not yet full branch coverage. | Implement prettier method names in PreconditionErrors as per spec; not yet full branch coverage.
| Python | agpl-3.0 | nejucomo/sgg,nejucomo/sgg,nejucomo/sgg |
671ccd8e82e0c106b0ccd9cb61b674f342319725 | mopidy/backends/spotify.py | mopidy/backends/spotify.py | import spytify
from mopidy import settings
from mopidy.backends.base import BaseBackend
class SpotifyBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(SpotifyBackend, self).__init__(*args, **kwargs)
self.spotify = spytify.Spytify(
settings.SPOTIFY_USERNAME.encode('utf-8'... | import sys
import spytify
from mopidy import settings
from mopidy.backends.base import BaseBackend
class SpotifyBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(SpotifyBackend, self).__init__(*args, **kwargs)
self.spotify = spytify.Spytify(self.username, self.password)
sel... | Exit if SPOTIFY_{USERNAME,PASSWORD} is not set | Exit if SPOTIFY_{USERNAME,PASSWORD} is not set
| Python | apache-2.0 | hkariti/mopidy,ali/mopidy,jcass77/mopidy,priestd09/mopidy,jmarsik/mopidy,pacificIT/mopidy,mopidy/mopidy,priestd09/mopidy,kingosticks/mopidy,vrs01/mopidy,jcass77/mopidy,bacontext/mopidy,bacontext/mopidy,woutervanwijk/mopidy,tkem/mopidy,mokieyue/mopidy,ZenithDK/mopidy,mopidy/mopidy,jodal/mopidy,swak/mopidy,bencevans/mopi... |
a41327614c610c5ca4be312b0b3b976d0092fe41 | cms/manage.py | cms/manage.py | #!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized t... | #!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. "
"It app... | Fix string layout for readability | Fix string layout for readability
| Python | agpl-3.0 | y12uc231/edx-platform,polimediaupv/edx-platform,EduPepperPDTesting/pepper2013-testing,atsolakid/edx-platform,arbrandes/edx-platform,zadgroup/edx-platform,msegado/edx-platform,Kalyzee/edx-platform,xuxiao19910803/edx,UXE/local-edx,RPI-OPENEDX/edx-platform,caesar2164/edx-platform,Lektorium-LLC/edx-platform,rationalAgent/e... |
34ba8742d576414a65a4f19b8bdc89e5e3c759b3 | astropy/io/ascii/tests/test_compressed.py | astropy/io/ascii/tests/test_compressed.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
import numpy as np
from ....tests.helper import pytest
from .. import read
ROOT = os.path.abspath(os.path.dirname(__file__))
@pytest.mark.parametrize('filename', ['t/daophot.dat.gz', 't/latex1.tex.gz',
't... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
import numpy as np
from ....tests.helper import pytest
from .. import read
ROOT = os.path.abspath(os.path.dirname(__file__))
@pytest.mark.parametrize('filename', ['t/daophot.dat.gz', 't/latex1.tex.gz',
't... | Use as_array() instead of _data in io.ascii compressed tests | Use as_array() instead of _data in io.ascii compressed tests
| Python | bsd-3-clause | dhomeier/astropy,StuartLittlefair/astropy,mhvk/astropy,saimn/astropy,saimn/astropy,astropy/astropy,aleksandr-bakanov/astropy,joergdietrich/astropy,DougBurke/astropy,dhomeier/astropy,stargaser/astropy,larrybradley/astropy,aleksandr-bakanov/astropy,joergdietrich/astropy,MSeifert04/astropy,astropy/astropy,lpsinger/astropy... |
bac9b62c40d0c69dcb346adfe82309e10a480276 | inonemonth/challenges/tests/test_forms.py | inonemonth/challenges/tests/test_forms.py | import unittest
import django.test
from django.core.exceptions import ValidationError
from core.tests.setups import RobrechtSocialUserFactory
from ..validators import RepoExistanceValidator
###############################################################################
# Forms ... | import unittest
import django.test
from django.core.exceptions import ValidationError
from core.tests.setups import RobrechtSocialUserFactory
from ..validators import RepoExistanceValidator
###############################################################################
# Forms ... | Write note for test that triggers get request | Write note for test that triggers get request
| Python | mit | robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth |
8033ce16b11ff7317ecc3c9ef7db448c44b72b1b | providers/popularity/torrentz.py | providers/popularity/torrentz.py | from providers.popularity.provider import PopularityProvider
from utils.torrent_util import torrent_to_search_string, remove_bad_torrent_matches
IDENTIFIER = "Torrentz"
class Provider(PopularityProvider):
PAGES_TO_FETCH = 1
def get_popular(self):
results = []
for page in range(Provider.PAGES_... | from providers.popularity.provider import PopularityProvider
from utils.torrent_util import torrent_to_search_string, remove_bad_torrent_matches
IDENTIFIER = "Torrentz"
class Provider(PopularityProvider):
PAGES_TO_FETCH = 1
def get_popular(self):
results = []
for page in range(Provider.PAGES_... | Remove bad torrents assumes torrent_to_search_string already ran. | Remove bad torrents assumes torrent_to_search_string already ran.
| Python | mit | EmilStenstrom/nephele |
ddc44c6673cff4121eaaa47d8d075d63b82a85fe | runreport.py | runreport.py | import os
import json
import saulify.sitespec as sitespec
SPEC_DIRECTORY = "sitespecs"
if __name__ == "__main__":
for fname in os.listdir(SPEC_DIRECTORY):
fpath = os.path.join(SPEC_DIRECTORY, fname)
test_cases = sitespec.load_testcases(fpath)
for test_case in test_cases:
resu... | import os
import json
import argparse
import saulify.sitespec as sitespec
SPEC_DIRECTORY = "sitespecs"
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--pretty", help="Pretty print test results",
action="store_true")
args = parser.parse_args()
def test_passed(report):
""" Whe... | Add optional pretty printing to test runner | Add optional pretty printing to test runner
| Python | agpl-3.0 | asm-products/saulify-web,asm-products/saulify-web,asm-products/saulify-web |
bd2c459b14103786f25aacf1daf3a7f23638df00 | base/app/main.py | base/app/main.py | # test.py
def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
#return [b"Hello World"] # python3
return ["Hello World from uwsgi-nginx:base"] # python2
| # test.py
def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
#return [b"Hello World"] # python3
return ["Hello World from default uWSGI app (default)"] # python2
| Add '(default)' to sample app | Add '(default)' to sample app
| Python | apache-2.0 | tiangolo/uwsgi-nginx-docker,tiangolo/uwsgi-nginx-docker |
afcb007c7c8b68bc4cace5ff6d634330f70603ec | channels/management/commands/runworker.py | channels/management/commands/runworker.py | from django.core.management import BaseCommand, CommandError
from channels import DEFAULT_CHANNEL_LAYER
from channels.layers import get_channel_layer
from channels.log import setup_logger
from channels.routing import get_default_application
from channels.worker import Worker
class Command(BaseCommand):
leave_lo... | from django.core.management import BaseCommand, CommandError
from channels import DEFAULT_CHANNEL_LAYER
from channels.layers import get_channel_layer
from channels.log import setup_logger
from channels.routing import get_default_application
from channels.worker import Worker
class Command(BaseCommand):
leave_lo... | Allow subclasses to customise the worker class | Allow subclasses to customise the worker class
| Python | bsd-3-clause | django/channels,andrewgodwin/django-channels,andrewgodwin/channels |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.