commit stringlengths 40 40 | old_file stringlengths 5 117 | new_file stringlengths 5 117 | old_contents stringlengths 0 1.93k | new_contents stringlengths 19 3.3k | subject stringlengths 17 320 | message stringlengths 18 3.28k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 7 42.4k | completion stringlengths 19 3.3k | prompt stringlengths 21 3.65k |
|---|---|---|---|---|---|---|---|---|---|---|---|
358cdd4b89221cbb02e7b04fc83cebb06570b03a | mezzanine/twitter/defaults.py | mezzanine/twitter/defaults.py | """
Default settings for the ``mezzanine.twitter`` app. Each of these can be
overridden in your project's settings module, just like regular
Django settings. The ``editable`` argument for each controls whether
the setting is editable via Django's admin.
Thought should be given to how a setting is actually used before
... | """
Default settings for the ``mezzanine.twitter`` app. Each of these can be
overridden in your project's settings module, just like regular
Django settings. The ``editable`` argument for each controls whether
the setting is editable via Django's admin.
Thought should be given to how a setting is actually used before
... | Update the default twitter query since it's been flooded by movie tweets. | Update the default twitter query since it's been flooded by movie tweets.
| Python | bsd-2-clause | readevalprint/mezzanine,theclanks/mezzanine,dovydas/mezzanine,scarcry/snm-mezzanine,industrydive/mezzanine,ryneeverett/mezzanine,mush42/mezzanine,AlexHill/mezzanine,industrydive/mezzanine,spookylukey/mezzanine,eino-makitalo/mezzanine,Cajoline/mezzanine,Cajoline/mezzanine,webounty/mezzanine,gradel/mezzanine,dekomote/mez... | """
Default settings for the ``mezzanine.twitter`` app. Each of these can be
overridden in your project's settings module, just like regular
Django settings. The ``editable`` argument for each controls whether
the setting is editable via Django's admin.
Thought should be given to how a setting is actually used before
... | Update the default twitter query since it's been flooded by movie tweets.
"""
Default settings for the ``mezzanine.twitter`` app. Each of these can be
overridden in your project's settings module, just like regular
Django settings. The ``editable`` argument for each controls whether
the setting is editable via Django'... |
7534e9b2af5e30b2cce4e5e710600ebeb4f61e9a | appengine/swarming/swarming_bot/api/platforms/android.py | appengine/swarming/swarming_bot/api/platforms/android.py | # Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Android specific utility functions.
This file serves as an API to bot_config.py. bot_config.py can be replaced on
the server to allow additional serv... | # Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Android specific utility functions.
This file serves as an API to bot_config.py. bot_config.py can be replaced on
the server to allow additional serv... | Add kill_adb() and increase python-adb logging to WARNING. | Add kill_adb() and increase python-adb logging to WARNING.
It gives a master switch that can easily be temporarily increased to INFO or
even DEBUG when needed by simply pushing a new tainted swarming server version.
This helps quickly debugging issues. On the other hand, even INFO level is quite
verbose so keep it at ... | Python | apache-2.0 | luci/luci-py,luci/luci-py,luci/luci-py,luci/luci-py | # Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Android specific utility functions.
This file serves as an API to bot_config.py. bot_config.py can be replaced on
the server to allow additional serv... | Add kill_adb() and increase python-adb logging to WARNING.
It gives a master switch that can easily be temporarily increased to INFO or
even DEBUG when needed by simply pushing a new tainted swarming server version.
This helps quickly debugging issues. On the other hand, even INFO level is quite
verbose so keep it at ... |
658e0a3dbd260f2d27756ed5605794b2320ba728 | backend/src/pox/ext/gini/samples/packet_loss.py | backend/src/pox/ext/gini/samples/packet_loss.py | #!/usr/bin/python2
"""
packet_loss.py: Simulates packet loss by dropping all packets with a
probability of 25%.
"""
import random
from pox.core import core
import pox.openflow.libopenflow_01 as of
def packet_in(event):.
if random.random() >= 0.25:
msg = of.ofp_packet_out(data = event.ofp)
msg.ac... | #!/usr/bin/python2
"""
packet_loss.py: Simulates packet loss by dropping all packets with a
probability of 25%.
"""
import random
from pox.core import core
import pox.openflow.libopenflow_01 as of
def packet_in(event):
if random.random() >= 0.25:
msg = of.ofp_packet_out(data = event.ofp)
msg.act... | Fix bug in packet loss | Fix bug in packet loss
| Python | mit | anrl/gini3,michaelkourlas/gini,michaelkourlas/gini,anrl/gini3,michaelkourlas/gini,anrl/gini3,michaelkourlas/gini,anrl/gini3,anrl/gini3,michaelkourlas/gini | #!/usr/bin/python2
"""
packet_loss.py: Simulates packet loss by dropping all packets with a
probability of 25%.
"""
import random
from pox.core import core
import pox.openflow.libopenflow_01 as of
def packet_in(event):
if random.random() >= 0.25:
msg = of.ofp_packet_out(data = event.ofp)
msg.act... | Fix bug in packet loss
#!/usr/bin/python2
"""
packet_loss.py: Simulates packet loss by dropping all packets with a
probability of 25%.
"""
import random
from pox.core import core
import pox.openflow.libopenflow_01 as of
def packet_in(event):.
if random.random() >= 0.25:
msg = of.ofp_packet_out(data = e... |
15fd86ff33d4f585578ef4e67614e249b1e94d45 | jjvm.py | jjvm.py | #!/usr/bin/python
import argparse
import os
import struct
import sys
###############
### CLASSES ###
###############
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
###################
### SUBROUTIN... | #!/usr/bin/python
import argparse
import os
import struct
import sys
CP_STRUCT_SIZES = { 0xa:3 }
###############
### CLASSES ###
###############
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
####... | Use constants dictionary in lenCpStruct() | Use constants dictionary in lenCpStruct()
| Python | apache-2.0 | justinccdev/jjvm | #!/usr/bin/python
import argparse
import os
import struct
import sys
CP_STRUCT_SIZES = { 0xa:3 }
###############
### CLASSES ###
###############
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
####... | Use constants dictionary in lenCpStruct()
#!/usr/bin/python
import argparse
import os
import struct
import sys
###############
### CLASSES ###
###############
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys... |
6a74915c3f197ef197a34514c7ff313ac0a68d2f | corehq/apps/fixtures/migrations/0002_rm_blobdb_domain_fixtures.py | corehq/apps/fixtures/migrations/0002_rm_blobdb_domain_fixtures.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-09-08 10:23
from __future__ import unicode_literals
from django.db import migrations
from corehq.blobs import get_blob_db
from corehq.sql_db.operations import HqRunPython
FIXTURE_BUCKET = 'domain-fixtures'
def rm_blobdb_domain_fixtures(apps, schema_edito... | Add migration to delete existing cache values | Add migration to delete existing cache values | Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-09-08 10:23
from __future__ import unicode_literals
from django.db import migrations
from corehq.blobs import get_blob_db
from corehq.sql_db.operations import HqRunPython
FIXTURE_BUCKET = 'domain-fixtures'
def rm_blobdb_domain_fixtures(apps, schema_edito... | Add migration to delete existing cache values
| |
bad670aebbdeeb029a40762aae80eec1100268a2 | data_log/management/commands/generate_report_fixture.py | data_log/management/commands/generate_report_fixture.py | from django.core.management.base import BaseCommand
from django.core import serializers
from data_log import models
import json
class Command(BaseCommand):
help = 'Create Data Log Report fixtures'
def handle(self, *args, **kwargs):
self.stdout.write(self.style.HTTP_INFO('Creating fixtures for Data L... | from django.core.management.base import BaseCommand
from django.core import serializers
from data_log import models
import json
class Command(BaseCommand):
help = 'Create Data Log Report fixtures'
def handle(self, *args, **kwargs):
self.stdout.write(self.style.HTTP_INFO('Creating fixtures for Data L... | Fix data log fixture foreign keys | Fix data log fixture foreign keys
| Python | apache-2.0 | porksmash/swarfarm,porksmash/swarfarm,porksmash/swarfarm,porksmash/swarfarm | from django.core.management.base import BaseCommand
from django.core import serializers
from data_log import models
import json
class Command(BaseCommand):
help = 'Create Data Log Report fixtures'
def handle(self, *args, **kwargs):
self.stdout.write(self.style.HTTP_INFO('Creating fixtures for Data L... | Fix data log fixture foreign keys
from django.core.management.base import BaseCommand
from django.core import serializers
from data_log import models
import json
class Command(BaseCommand):
help = 'Create Data Log Report fixtures'
def handle(self, *args, **kwargs):
self.stdout.write(self.style.HTTP... |
8f75f1d02d44b0bc216b93ef163ac2f4e877e9ce | test/main.py | test/main.py | #! /usr/bin/env python
#
# Copyright (c) 2011 Red Hat, Inc.
#
# This software is licensed to you under the GNU Lesser General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (LGPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express... | Add for debugging w/o running as root. | Add for debugging w/o running as root.
| Python | lgpl-2.1 | jortel/gofer,credativ/gofer,credativ/gofer,kgiusti/gofer,kgiusti/gofer,jortel/gofer,splice/gofer,splice/gofer,splice/gofer | #! /usr/bin/env python
#
# Copyright (c) 2011 Red Hat, Inc.
#
# This software is licensed to you under the GNU Lesser General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (LGPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express... | Add for debugging w/o running as root.
| |
2acb7e7da11aabe6b9c30f6197492d4150e4f496 | test/test_words.py | test/test_words.py |
import unittest
import numpy as np
import numpy.testing as test
from word2gauss.words import Vocabulary, iter_pairs
DTYPE = np.float32
class TestIterPairs(unittest.TestCase):
def test_iter_pairs(self):
np.random.seed(1234)
vocab = Vocabulary({'zero': 0, 'one': 1, 'two': 2})
actual = list... | Add a test for iter_pairs | Add a test for iter_pairs
| Python | mit | seomoz/word2gauss,seomoz/word2gauss |
import unittest
import numpy as np
import numpy.testing as test
from word2gauss.words import Vocabulary, iter_pairs
DTYPE = np.float32
class TestIterPairs(unittest.TestCase):
def test_iter_pairs(self):
np.random.seed(1234)
vocab = Vocabulary({'zero': 0, 'one': 1, 'two': 2})
actual = list... | Add a test for iter_pairs
| |
cfd6c7c2d7af47329deac3e7ff618b66a078263c | ines/middlewares/logs.py | ines/middlewares/logs.py | # -*- coding: utf-8 -*-
import sys
from traceback import format_exception
from pyramid.decorator import reify
from pyramid.httpexceptions import HTTPInternalServerError
from pyramid.interfaces import IRequestFactory
from ines.middlewares import Middleware
from ines.utils import format_error_to_json
class LoggingMi... | # -*- coding: utf-8 -*-
import sys
from traceback import format_exception
from pyramid.decorator import reify
from pyramid.httpexceptions import HTTPInternalServerError
from pyramid.interfaces import IRequestFactory
from ines.convert import force_string
from ines.middlewares import Middleware
from ines.utils import ... | Set log with small message | Set log with small message
| Python | mit | hugobranquinho/ines | # -*- coding: utf-8 -*-
import sys
from traceback import format_exception
from pyramid.decorator import reify
from pyramid.httpexceptions import HTTPInternalServerError
from pyramid.interfaces import IRequestFactory
from ines.convert import force_string
from ines.middlewares import Middleware
from ines.utils import ... | Set log with small message
# -*- coding: utf-8 -*-
import sys
from traceback import format_exception
from pyramid.decorator import reify
from pyramid.httpexceptions import HTTPInternalServerError
from pyramid.interfaces import IRequestFactory
from ines.middlewares import Middleware
from ines.utils import format_err... |
ff3a6b35e85058c711a056401b7c3e2d7c7b1260 | crmapp/accounts/forms.py | crmapp/accounts/forms.py | from django import forms
from .models import Account
class AccountForm(forms.ModelForm):
class Meta:
model = Account
fields = ('name', 'desc', 'address_one',
'address_two', 'city', 'state', 'phone',
)
widgets = {
'name': forms.TextInput(
... | Create the Account Detail Page - Part II > New Account - Create Form | Create the Account Detail Page - Part II > New Account - Create Form
| Python | mit | deenaariff/Django,tabdon/crmeasyapp,tabdon/crmeasyapp | from django import forms
from .models import Account
class AccountForm(forms.ModelForm):
class Meta:
model = Account
fields = ('name', 'desc', 'address_one',
'address_two', 'city', 'state', 'phone',
)
widgets = {
'name': forms.TextInput(
... | Create the Account Detail Page - Part II > New Account - Create Form
| |
240d4d33dc6570c957ce568a952a1a282dc50736 | opps/article/views.py | opps/article/views.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from opps.article.models import Post
class OppsList(ListView):
context_object_name = "context"
@property
def template_name(self):
long_slug = self.kwa... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from opps.article.models import Post
class OppsList(ListView):
context_object_name = "context"
@property
def template_name(self):
long_slug = self.kwa... | Fix template name on entry home page (/) on detail page | Fix template name on entry home page (/) on detail page
| Python | mit | williamroot/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,opps/opps,opps/opps,williamroot/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,opps/opps | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from opps.article.models import Post
class OppsList(ListView):
context_object_name = "context"
@property
def template_name(self):
long_slug = self.kwa... | Fix template name on entry home page (/) on detail page
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from opps.article.models import Post
class OppsList(ListView):
context_object_name = "context"
@property
... |
f33bf5a99b9bb814fe6da6b7713e87014aae5fdf | src/journal/migrations/0035_journal_xsl.py | src/journal/migrations/0035_journal_xsl.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-11-03 20:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import journal.models
class Migration(migrations.Migration):
dependencies = [
('journal', '0034_migrate_issue_types'... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-11-03 20:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import journal.models
class Migration(migrations.Migration):
dependencies = [
('journal', '0034_migrate_issue_types'... | Fix migration tree for journal 0035 | Fix migration tree for journal 0035
| Python | agpl-3.0 | BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway | # -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-11-03 20:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import journal.models
class Migration(migrations.Migration):
dependencies = [
('journal', '0034_migrate_issue_types'... | Fix migration tree for journal 0035
# -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-11-03 20:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import journal.models
class Migration(migrations.Migration):
dependencies = [
(... |
f751b95912b5cc03c3fd60742de9159b00d92b79 | echonest/utils.py | echonest/utils.py | from django.conf import settings
from purl import Template
import requests
from .models import SimilarResponse
API_URL = Template("http://developer.echonest.com/api/v4/artist/similar"
"?api_key=%s&results=100&name={name}"
% settings.ECHONEST_API_KEY)
def get_similar_from_api(n... | from django.conf import settings
from purl import Template
import requests
from .models import SimilarResponse
API_URL = Template("http://developer.echonest.com/api/v4/artist/similar"
"?api_key=%s&results=100&name={name}"
% settings.ECHONEST_API_KEY)
def get_similar_from_api(n... | Fix bug in The Echo Nest API call | Fix bug in The Echo Nest API call
| Python | bsd-3-clause | FreeMusicNinja/api.freemusic.ninja | from django.conf import settings
from purl import Template
import requests
from .models import SimilarResponse
API_URL = Template("http://developer.echonest.com/api/v4/artist/similar"
"?api_key=%s&results=100&name={name}"
% settings.ECHONEST_API_KEY)
def get_similar_from_api(n... | Fix bug in The Echo Nest API call
from django.conf import settings
from purl import Template
import requests
from .models import SimilarResponse
API_URL = Template("http://developer.echonest.com/api/v4/artist/similar"
"?api_key=%s&results=100&name={name}"
% settings.ECHONEST_AP... |
d269568387b622861001fdc39eeeaff03ebd9a78 | formulamanager.py | formulamanager.py | import os
import imp
_formula_cache = {}
_default_search_path = [os.path.join(os.path.dirname(__file__), "..", "Formula")]
class FormulaManager:
@staticmethod
def _find(name, search_path=[]):
file_path = ""
for path in search_path + default_search_path:
if os.path.exists(os.path.j... | Implement class for managing formulas | Implement class for managing formulas
| Python | mit | peterl94/CLbundler,peterl94/CLbundler | import os
import imp
_formula_cache = {}
_default_search_path = [os.path.join(os.path.dirname(__file__), "..", "Formula")]
class FormulaManager:
@staticmethod
def _find(name, search_path=[]):
file_path = ""
for path in search_path + default_search_path:
if os.path.exists(os.path.j... | Implement class for managing formulas
| |
440593615adca029b11575e604d251c7b68942b4 | api/licenses/serializers.py | api/licenses/serializers.py | from rest_framework import serializers as ser
from api.base.serializers import (
JSONAPISerializer, LinksField, IDField, TypeField
)
from api.base.utils import absolute_reverse
class LicenseSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'name',
'id',
])
non_anonymized_... | from rest_framework import serializers as ser
from api.base.serializers import (
JSONAPISerializer, LinksField, IDField, TypeField
)
from api.base.utils import absolute_reverse
class LicenseSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'name',
'id',
])
non_anonymized_... | Add url to the license api serializer | Add url to the license api serializer
| Python | apache-2.0 | felliott/osf.io,baylee-d/osf.io,sloria/osf.io,baylee-d/osf.io,HalcyonChimera/osf.io,adlius/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,felliott/osf.io,mfraezz/osf.io,cslzchen/osf.io,icereval/osf.io,felliott/osf.io,adlius/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.... | from rest_framework import serializers as ser
from api.base.serializers import (
JSONAPISerializer, LinksField, IDField, TypeField
)
from api.base.utils import absolute_reverse
class LicenseSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'name',
'id',
])
non_anonymized_... | Add url to the license api serializer
from rest_framework import serializers as ser
from api.base.serializers import (
JSONAPISerializer, LinksField, IDField, TypeField
)
from api.base.utils import absolute_reverse
class LicenseSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'name',
... |
a0ab52fddc682e207667a927fc717ac23cecab52 | setup.py | setup.py | from setuptools import setup, find_packages
__version__ = '0.2.0'
__pkg_name__ = 'textsift'
setup(
name = __pkg_name__,
version = __version__,
description = 'Text modelling framework',
author='Andrew Chisholm',
packages = find_packages(),
license = 'MIT',
url = 'https://github.com/wikilink... | from setuptools import setup, find_packages
__version__ = '0.2.1'
__pkg_name__ = 'textsift'
setup(
name = __pkg_name__,
version = __version__,
description = 'Text modelling framework',
author='Andrew Chisholm',
packages = find_packages(),
license = 'MIT',
url = 'https://github.com/wikilink... | Remove all sift cli script command from package | Remove all sift cli script command from package
| Python | mit | wikilinks/sift,wikilinks/sift | from setuptools import setup, find_packages
__version__ = '0.2.1'
__pkg_name__ = 'textsift'
setup(
name = __pkg_name__,
version = __version__,
description = 'Text modelling framework',
author='Andrew Chisholm',
packages = find_packages(),
license = 'MIT',
url = 'https://github.com/wikilink... | Remove all sift cli script command from package
from setuptools import setup, find_packages
__version__ = '0.2.0'
__pkg_name__ = 'textsift'
setup(
name = __pkg_name__,
version = __version__,
description = 'Text modelling framework',
author='Andrew Chisholm',
packages = find_packages(),
licens... |
75a4097006e6ea5f1693b9d746456b060974d8a0 | mtglib/__init__.py | mtglib/__init__.py | __version__ = '1.5.2'
__author__ = 'Cameron Higby-Naquin'
| __version__ = '1.6.0'
__author__ = 'Cameron Higby-Naquin'
| Increment minor version for new feature release. | Increment minor version for new feature release.
| Python | mit | chigby/mtg,chigby/mtg | __version__ = '1.6.0'
__author__ = 'Cameron Higby-Naquin'
| Increment minor version for new feature release.
__version__ = '1.5.2'
__author__ = 'Cameron Higby-Naquin'
|
b78aebed4771015e6292638ac1980e3acaed4db9 | heufybot/connection.py | heufybot/connection.py | from twisted.words.protocols import irc
class HeufyBotConnection(irc.IRC):
def __init__(self, protocol):
self.protocol = protocol
self.nick = "PyHeufyBot" # TODO This will be set by a configuration at some point
self.ident = "PyHeufyBot" # TODO This will be set by a configuration at some... | from twisted.words.protocols import irc
class HeufyBotConnection(irc.IRC):
def __init__(self, protocol):
self.protocol = protocol
self.nick = "PyHeufyBot" # TODO This will be set by a configuration at some point
self.ident = "PyHeufyBot" # TODO This will be set by a configuration at some... | Add dictionaries for channels and usermodes | Add dictionaries for channels and usermodes
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot | from twisted.words.protocols import irc
class HeufyBotConnection(irc.IRC):
def __init__(self, protocol):
self.protocol = protocol
self.nick = "PyHeufyBot" # TODO This will be set by a configuration at some point
self.ident = "PyHeufyBot" # TODO This will be set by a configuration at some... | Add dictionaries for channels and usermodes
from twisted.words.protocols import irc
class HeufyBotConnection(irc.IRC):
def __init__(self, protocol):
self.protocol = protocol
self.nick = "PyHeufyBot" # TODO This will be set by a configuration at some point
self.ident = "PyHeufyBot" # TOD... |
52c02ceda3c6430a2f4bbb3f9054180699baaa93 | setup.py | setup.py | # -*- encoding: utf-8 *-*
#!/usr/bin/env python
import sys
from setuptools import setup, Extension
from Cython.Distutils import build_ext
dependencies = ['pycrypto', 'msgpack-python', 'pbkdf2.py', 'xattr', 'paramiko', 'Pyrex', 'Cython']
if sys.version_info < (2, 7):
dependencies.append('argparse')
setup(name='da... | # -*- encoding: utf-8 *-*
#!/usr/bin/env python
import os
import sys
from glob import glob
from setuptools import setup, Extension
from setuptools.command.sdist import sdist
hashindex_sources = ['darc/hashindex.pyx', 'darc/_hashindex.c']
try:
from Cython.Distutils import build_ext
import Cython.Compiler.Main a... | Include Cython output in sdist | Include Cython output in sdist
| Python | bsd-3-clause | ionelmc/borg,pombredanne/attic,edgimar/borg,raxenak/borg,RonnyPfannschmidt/borg,RonnyPfannschmidt/borg,edgimar/borg,mhubig/borg,edgewood/borg,RonnyPfannschmidt/borg,edgewood/borg,raxenak/borg,RonnyPfannschmidt/borg,ionelmc/borg,RonnyPfannschmidt/borg,mhubig/borg,level323/borg,jborg/attic,jborg/attic,mhubig/borg,ionelmc... | # -*- encoding: utf-8 *-*
#!/usr/bin/env python
import os
import sys
from glob import glob
from setuptools import setup, Extension
from setuptools.command.sdist import sdist
hashindex_sources = ['darc/hashindex.pyx', 'darc/_hashindex.c']
try:
from Cython.Distutils import build_ext
import Cython.Compiler.Main a... | Include Cython output in sdist
# -*- encoding: utf-8 *-*
#!/usr/bin/env python
import sys
from setuptools import setup, Extension
from Cython.Distutils import build_ext
dependencies = ['pycrypto', 'msgpack-python', 'pbkdf2.py', 'xattr', 'paramiko', 'Pyrex', 'Cython']
if sys.version_info < (2, 7):
dependencies.app... |
bc005622a6fcce2ec53bf93a9b6519f923904a61 | turbustat/statistics/stats_warnings.py | turbustat/statistics/stats_warnings.py | # Licensed under an MIT open source license - see LICENSE
from __future__ import print_function, absolute_import, division
class TurbuStatTestingWarning(Warning):
'''
Turbustat.statistics warning for untested methods.
''' | # Licensed under an MIT open source license - see LICENSE
from __future__ import print_function, absolute_import, division
class TurbuStatTestingWarning(Warning):
'''
Turbustat.statistics warning for untested methods.
'''
class TurbuStatMetricWarning(Warning):
'''
Turbustat.statistics warning fo... | Add warning for where a distance metric is being misused | Add warning for where a distance metric is being misused
| Python | mit | Astroua/TurbuStat,e-koch/TurbuStat | # Licensed under an MIT open source license - see LICENSE
from __future__ import print_function, absolute_import, division
class TurbuStatTestingWarning(Warning):
'''
Turbustat.statistics warning for untested methods.
'''
class TurbuStatMetricWarning(Warning):
'''
Turbustat.statistics warning fo... | Add warning for where a distance metric is being misused
# Licensed under an MIT open source license - see LICENSE
from __future__ import print_function, absolute_import, division
class TurbuStatTestingWarning(Warning):
'''
Turbustat.statistics warning for untested methods.
''' |
9b2a2f7aeb0f24c6c5e7cbb474cf377a89dd48d6 | evaluation/collectStatistics.py | evaluation/collectStatistics.py | import packages.project as project
import packages.primitive as primitive
import packages.utils as utils
import packages.processing
import packages.io
import argparse
from matplotlib import pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
from scipy.stats import norm,kstest,skewtest,kurtosistest,normalte... | Add a new script processing different iterations of a run and computing statistics | Add a new script processing different iterations of a run and computing statistics
| Python | apache-2.0 | amonszpart/globOpt,amonszpart/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,amonszpart/globOpt,amonszpart/globOpt,NUAAXXY/globOpt | import packages.project as project
import packages.primitive as primitive
import packages.utils as utils
import packages.processing
import packages.io
import argparse
from matplotlib import pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
from scipy.stats import norm,kstest,skewtest,kurtosistest,normalte... | Add a new script processing different iterations of a run and computing statistics
| |
1cb7581f63d0d9d4e6eca69316930912c41a4fb5 | Instanssi/admin_upload/models.py | Instanssi/admin_upload/models.py | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
class UploadedFile(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
description = models.TextField(u'Kuvaus', help_text=u'Lyhyt kuvaus siitä, mihin/missä tie... | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
import os.path
class UploadedFile(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
description = models.TextField(u'Kuvaus', help_text=u'Lyhyt kuvaus siitä, ... | Add helper function for getting name from UploadedFile, add model to admin. | admin_upload: Add helper function for getting name from UploadedFile, add model to admin.
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
import os.path
class UploadedFile(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
description = models.TextField(u'Kuvaus', help_text=u'Lyhyt kuvaus siitä, ... | admin_upload: Add helper function for getting name from UploadedFile, add model to admin.
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
class UploadedFile(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
... |
39b382770ecc1b4c4fc33273fac0467344ccadfc | relay_api/api/main.py | relay_api/api/main.py | from flask import Flask
import relay_api.api.server as backend
server = Flask(__name__)
backend.init_relays()
@server.route("/relay-api/relays/", methods=["GET"])
def get_all_relays():
js = backend.get_all_relays()
return js, 200
@server.route("/relay-api/relays/<relay_name>", methods=["GET"])
def get_re... | from flask import Flask
import relay_api.api.backend as backend
server = Flask(__name__)
backend.init_relays()
@server.route("/relay-api/relays/", methods=["GET"])
def get_all_relays():
js = backend.get_all_relays()
return js, 200
@server.route("/relay-api/relays/<relay_name>", methods=["GET"])
def get_r... | Fix issue with backend import | Fix issue with backend import
| Python | mit | pahumadad/raspi-relay-api | from flask import Flask
import relay_api.api.backend as backend
server = Flask(__name__)
backend.init_relays()
@server.route("/relay-api/relays/", methods=["GET"])
def get_all_relays():
js = backend.get_all_relays()
return js, 200
@server.route("/relay-api/relays/<relay_name>", methods=["GET"])
def get_r... | Fix issue with backend import
from flask import Flask
import relay_api.api.server as backend
server = Flask(__name__)
backend.init_relays()
@server.route("/relay-api/relays/", methods=["GET"])
def get_all_relays():
js = backend.get_all_relays()
return js, 200
@server.route("/relay-api/relays/<relay_name... |
7e407d1185235f4a89bddcaffcde240a33b522f4 | expand_region_handler.py | expand_region_handler.py | try:
import javascript
import html
except:
from . import javascript
from . import html
def expand(string, start, end, extension=None):
if(extension in ["html", "htm", "xml"]):
return html.expand(string, start, end)
return javascript.expand(string, start, end) | import re
try:
import javascript
import html
except:
from . import javascript
from . import html
def expand(string, start, end, extension=None):
if(re.compile("html|htm|xml").search(extension)):
return html.expand(string, start, end)
return javascript.expand(string, start, end) | Use html strategy for any file that has xml/html in file extension. This will will match shtml, xhtml and so on. | Use html strategy for any file that has xml/html in file extension. This will will match shtml, xhtml and so on.
| Python | mit | aronwoost/sublime-expand-region,johyphenel/sublime-expand-region,johyphenel/sublime-expand-region | import re
try:
import javascript
import html
except:
from . import javascript
from . import html
def expand(string, start, end, extension=None):
if(re.compile("html|htm|xml").search(extension)):
return html.expand(string, start, end)
return javascript.expand(string, start, end) | Use html strategy for any file that has xml/html in file extension. This will will match shtml, xhtml and so on.
try:
import javascript
import html
except:
from . import javascript
from . import html
def expand(string, start, end, extension=None):
if(extension in ["html", "htm", "xml"]):
return html.ex... |
29e491c5505d2068b46eb489044455968e53ab70 | test/400-bay-water.py | test/400-bay-water.py | assert_has_feature(
14, 2623, 6318, 'water',
{ 'kind': 'bay', 'label_placement': 'yes' })
| # osm_id: 43950409 name: San Pablo Bay
assert_has_feature(
14, 2623, 6318, 'water',
{ 'kind': 'bay', 'label_placement': 'yes' })
# osm_id: 360566115 name: Byron strait
assert_has_feature(
14, 15043, 8311, 'water',
{ 'kind': 'strait', 'label_placement': 'yes' })
# osm_id: -1451065 name: Horsens Fjord
a... | Add tests for strait and fjord | Add tests for strait and fjord
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource | # osm_id: 43950409 name: San Pablo Bay
assert_has_feature(
14, 2623, 6318, 'water',
{ 'kind': 'bay', 'label_placement': 'yes' })
# osm_id: 360566115 name: Byron strait
assert_has_feature(
14, 15043, 8311, 'water',
{ 'kind': 'strait', 'label_placement': 'yes' })
# osm_id: -1451065 name: Horsens Fjord
a... | Add tests for strait and fjord
assert_has_feature(
14, 2623, 6318, 'water',
{ 'kind': 'bay', 'label_placement': 'yes' })
|
cae249ff553083e3546e26b08779baf6abc69a69 | active_link/templatetags/active_link_tags.py | active_link/templatetags/active_link_tags.py | from django import VERSION as DJANGO_VERSION
from django import template
from django.conf import settings
if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9:
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
register = template.Library()
@register.simple_tag(takes_context=T... | from django import VERSION as DJANGO_VERSION
from django import template
from django.conf import settings
if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9:
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
register = template.Library()
@register.simple_tag(takes_context=T... | Improve how the active link is checked | Improve how the active link is checked
| Python | bsd-3-clause | valerymelou/django-active-link | from django import VERSION as DJANGO_VERSION
from django import template
from django.conf import settings
if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9:
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
register = template.Library()
@register.simple_tag(takes_context=T... | Improve how the active link is checked
from django import VERSION as DJANGO_VERSION
from django import template
from django.conf import settings
if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9:
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
register = template.Library(... |
0aff137a210debd9ea18793a98c043a5151d9524 | src/Compiler/VM/arithmetic_exprs.py | src/Compiler/VM/arithmetic_exprs.py | from Helpers.string import *
def binop_aexp(commands, env, op, left, right):
left.compile_vm(commands, env)
right.compile_vm(commands, env)
if op == '+':
value = assemble(Add)
elif op == '-':
value = assemble(Sub)
elif op == '*':
value = assemble(Mul)
elif op == '/':
... | from Helpers.string import *
def binop_aexp(commands, env, op, left, right):
left.compile_vm(commands, env)
right.compile_vm(commands, env)
if op == '+':
value = assemble(Add)
elif op == '-':
value = assemble(Sub)
elif op == '*':
value = assemble(Mul)
elif op == '/':
... | Fix compiling problem for runtime variables | Fix compiling problem for runtime variables
| Python | mit | PetukhovVictor/compiler,PetukhovVictor/compiler | from Helpers.string import *
def binop_aexp(commands, env, op, left, right):
left.compile_vm(commands, env)
right.compile_vm(commands, env)
if op == '+':
value = assemble(Add)
elif op == '-':
value = assemble(Sub)
elif op == '*':
value = assemble(Mul)
elif op == '/':
... | Fix compiling problem for runtime variables
from Helpers.string import *
def binop_aexp(commands, env, op, left, right):
left.compile_vm(commands, env)
right.compile_vm(commands, env)
if op == '+':
value = assemble(Add)
elif op == '-':
value = assemble(Sub)
elif op == '*':
... |
002d1ac1d2fcf88a7df46681ef7b3969f08e9a8f | qual/calendar.py | qual/calendar.py | from datetime import date
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
class ProlepticGregorianCalendar(object):
def date(self, year, month, day):
d = date(year, month, day)
return DateWithCalendar(Pro... | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar... | Allow conversion from Julian to ProlepticGregorian, also comparison of dates. | Allow conversion from Julian to ProlepticGregorian, also comparison of dates.
| Python | apache-2.0 | jwg4/qual,jwg4/calexicon | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar... | Allow conversion from Julian to ProlepticGregorian, also comparison of dates.
from datetime import date
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
class ProlepticGregorianCalendar(object):
def date(self, year, mont... |
fedd90e80a6c56ab406e52b9b0ece14b324fa5d5 | aldryn_apphooks_config/fields.py | aldryn_apphooks_config/fields.py | # -*- coding: utf-8 -*-
from django import forms
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .widgets import AppHookConfigWidget
class AppHookConfigField(models.ForeignKey):
def __init__(self, *args, **kwargs):
kwargs.update({'help_text': _(u'When selecting ... | # -*- coding: utf-8 -*-
from django import forms
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .widgets import AppHookConfigWidget
class AppHookConfigFormField(forms.ModelChoiceField):
def __init__(self, queryset, empty_label="---------", required=True,
wi... | Improve the ability for developers to extend or modify | Improve the ability for developers to extend or modify
| Python | bsd-3-clause | aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config | # -*- coding: utf-8 -*-
from django import forms
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .widgets import AppHookConfigWidget
class AppHookConfigFormField(forms.ModelChoiceField):
def __init__(self, queryset, empty_label="---------", required=True,
wi... | Improve the ability for developers to extend or modify
# -*- coding: utf-8 -*-
from django import forms
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .widgets import AppHookConfigWidget
class AppHookConfigField(models.ForeignKey):
def __init__(self, *args, **kwargs):... |
b55812bd94b20a31ba2f9a64eedbcbb811dc4257 | camkes/internal/dictutils.py | camkes/internal/dictutils.py | #
# Copyright 2014, NICTA
#
# This software may be distributed and modified according to the terms of
# the BSD 2-Clause license. Note that NO WARRANTY is provided.
# See "LICENSE_BSD2.txt" for details.
#
# @TAG(NICTA_BSD)
#
'''Various helpers for doing advanced things with dictionaries.'''
def get_fields(s):
'''... | #
# Copyright 2014, NICTA
#
# This software may be distributed and modified according to the terms of
# the BSD 2-Clause license. Note that NO WARRANTY is provided.
# See "LICENSE_BSD2.txt" for details.
#
# @TAG(NICTA_BSD)
#
'''Various helpers for doing advanced things with dictionaries.'''
import re
def get_fields(... | Support non-string formats in `get_fields`. | Support non-string formats in `get_fields`.
This commit rewrites the `get_fields` function to be simpler and more general.
The previous implementation relied on ad hoc dict mocking and only supported
format strings involving string-valued formats ('%(name)s'). From this commit
other formats (e.g. '%(name)04d') are sup... | Python | bsd-2-clause | smaccm/camkes-tool,smaccm/camkes-tool,smaccm/camkes-tool,smaccm/camkes-tool | #
# Copyright 2014, NICTA
#
# This software may be distributed and modified according to the terms of
# the BSD 2-Clause license. Note that NO WARRANTY is provided.
# See "LICENSE_BSD2.txt" for details.
#
# @TAG(NICTA_BSD)
#
'''Various helpers for doing advanced things with dictionaries.'''
import re
def get_fields(... | Support non-string formats in `get_fields`.
This commit rewrites the `get_fields` function to be simpler and more general.
The previous implementation relied on ad hoc dict mocking and only supported
format strings involving string-valued formats ('%(name)s'). From this commit
other formats (e.g. '%(name)04d') are sup... |
a3f981006fae846714bdb5aa0de98ac829a57bc0 | registration/__init__.py | registration/__init__.py | VERSION = (0, 9, 0, 'beta', 1)
def get_version():
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
| VERSION = (0, 9, 0, 'beta', 1)
def get_version():
try:
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
except ImportError:
return ".".join(str(n) for n in VERSION)
| Fix dependency order issue in get_version | Fix dependency order issue in get_version
| Python | bsd-3-clause | ildarsamit/django-registration,ildarsamit/django-registration | VERSION = (0, 9, 0, 'beta', 1)
def get_version():
try:
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
except ImportError:
return ".".join(str(n) for n in VERSION)
| Fix dependency order issue in get_version
VERSION = (0, 9, 0, 'beta', 1)
def get_version():
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
|
e271d355e057f72c85efe3f1a407c55e54faca74 | migrations/008_convert_ga_buckets_to_utc.py | migrations/008_convert_ga_buckets_to_utc.py | """
Convert Google Analytics buckets from Europe/London to UTC
"""
import logging
import copy
from itertools import imap, ifilter
from datetime import timedelta
from backdrop.core.records import Record
from backdrop.core.timeutils import utc
log = logging.getLogger(__name__)
GA_BUCKETS_TO_MIGRATE = [
"carers_al... | Add migration to convert GA timezone to UTC | Add migration to convert GA timezone to UTC
We are ignoring the timezone from GA requests so previous data needs to
be converted to account for this.
See https://www.pivotaltracker.com/story/show/62779118 for details.
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop | """
Convert Google Analytics buckets from Europe/London to UTC
"""
import logging
import copy
from itertools import imap, ifilter
from datetime import timedelta
from backdrop.core.records import Record
from backdrop.core.timeutils import utc
log = logging.getLogger(__name__)
GA_BUCKETS_TO_MIGRATE = [
"carers_al... | Add migration to convert GA timezone to UTC
We are ignoring the timezone from GA requests so previous data needs to
be converted to account for this.
See https://www.pivotaltracker.com/story/show/62779118 for details.
| |
845192bb91a2421c54a9bbb924e1e09e700aee66 | Lib/dialogKit/__init__.py | Lib/dialogKit/__init__.py | """
dialogKit: easy bake dialogs
"""
# determine the environment
try:
import FL
haveFL = True
except ImportError:
haveFL = False
try:
import vanilla
haveVanilla = True
except ImportError:
haveVanilla = False
# perform the environment specific import
if haveFL:
from _dkFL import *
if haveVan... | """
dialogKit: easy bake dialogs
"""
# determine the environment
haveFL = False
haveVanilla = False
try:
import FL
haveFL = True
except ImportError:
pass
if not haveFL:
try:
import vanilla
haveVanilla = True
except ImportError:
pass
# perform the environment specific import
... | Stop trying imports after something has been successfully loaded. | Stop trying imports after something has been successfully loaded.
| Python | mit | anthrotype/dialogKit,daltonmaag/dialogKit,typesupply/dialogKit | """
dialogKit: easy bake dialogs
"""
# determine the environment
haveFL = False
haveVanilla = False
try:
import FL
haveFL = True
except ImportError:
pass
if not haveFL:
try:
import vanilla
haveVanilla = True
except ImportError:
pass
# perform the environment specific import
... | Stop trying imports after something has been successfully loaded.
"""
dialogKit: easy bake dialogs
"""
# determine the environment
try:
import FL
haveFL = True
except ImportError:
haveFL = False
try:
import vanilla
haveVanilla = True
except ImportError:
haveVanilla = False
# perform the enviro... |
44e88adcc2ba62892828e1ec98543dff9218524a | setup.py | setup.py | __author__ = 'katharine'
import sys
from setuptools import setup, find_packages
requires = [
'backports.ssl-match-hostname==3.4.0.2',
'gevent>=1.1b5',
'gevent-websocket==0.9.3',
'greenlet==0.4.9',
'peewee==2.4.7',
'pygeoip==0.3.2',
'pypng==0.0.17',
'python-dateutil==2.4.1',
'requests==2.5.0',
'sh=... | __author__ = 'katharine'
import sys
from setuptools import setup, find_packages
requires = [
'backports.ssl-match-hostname==3.4.0.2',
'gevent>=1.1b5',
'gevent-websocket==0.9.3',
'greenlet==0.4.9',
'peewee==2.4.7',
'pygeoip==0.3.2',
'pypng==0.0.17',
'python-dateutil==2.4.1',
'requests==2.5.0',
'sh=... | Address review comments, remove zip_safe=True because GeoIP | Address review comments, remove zip_safe=True because GeoIP
| Python | mit | pebble/pypkjs | __author__ = 'katharine'
import sys
from setuptools import setup, find_packages
requires = [
'backports.ssl-match-hostname==3.4.0.2',
'gevent>=1.1b5',
'gevent-websocket==0.9.3',
'greenlet==0.4.9',
'peewee==2.4.7',
'pygeoip==0.3.2',
'pypng==0.0.17',
'python-dateutil==2.4.1',
'requests==2.5.0',
'sh=... | Address review comments, remove zip_safe=True because GeoIP
__author__ = 'katharine'
import sys
from setuptools import setup, find_packages
requires = [
'backports.ssl-match-hostname==3.4.0.2',
'gevent>=1.1b5',
'gevent-websocket==0.9.3',
'greenlet==0.4.9',
'peewee==2.4.7',
'pygeoip==0.3.2',
'pypng==0.0... |
ab3dc6466b617a5bf5a0bec2c122eca645c1d29f | cloudera-framework-assembly/src/main/resources/python/script_util.py | cloudera-framework-assembly/src/main/resources/python/script_util.py | import os
def hdfs_make_qualified(path):
return path if 'CF_HADOOP_DEFAULT_FS' not in os.environ else os.environ['CF_HADOOP_DEFAULT_FS'] + path
| import os
import re
def hdfs_make_qualified(path):
return path if (re.match(r'[.]*://[.]*', path) or 'CF_HADOOP_DEFAULT_FS' not in os.environ) \
else os.environ['CF_HADOOP_DEFAULT_FS'] + path
| Update python script util to detect if paths are already fully qualified | Update python script util to detect if paths are already fully qualified
| Python | apache-2.0 | ggear/cloudera-framework,ggear/cloudera-framework,ggear/cloudera-framework | import os
import re
def hdfs_make_qualified(path):
return path if (re.match(r'[.]*://[.]*', path) or 'CF_HADOOP_DEFAULT_FS' not in os.environ) \
else os.environ['CF_HADOOP_DEFAULT_FS'] + path
| Update python script util to detect if paths are already fully qualified
import os
def hdfs_make_qualified(path):
return path if 'CF_HADOOP_DEFAULT_FS' not in os.environ else os.environ['CF_HADOOP_DEFAULT_FS'] + path
|
d66e44fa9fd9b8e8944907b2490d32102c3fba82 | keystoneclient/hacking/checks.py | keystoneclient/hacking/checks.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Change hacking check to verify all oslo imports | Change hacking check to verify all oslo imports
The hacking check was verifying that specific oslo imports
weren't using the oslo-namespaced package. Since all the oslo
libraries used by keystoneclient are now changed to use the
new package name the hacking check can be simplified.
bp drop-namespace-packages
Change-... | Python | apache-2.0 | Mercador/python-keystoneclient,Mercador/python-keystoneclient,sdpp/python-keystoneclient,magic0704/python-keystoneclient,ging/python-keystoneclient,darren-wang/ksc,magic0704/python-keystoneclient,klmitch/python-keystoneclient,darren-wang/ksc,klmitch/python-keystoneclient,sdpp/python-keystoneclient,ging/python-keystonec... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Change hacking check to verify all oslo imports
The hacking check was verifying that specific oslo imports
weren't using the oslo-namespaced package. Since all the oslo
libraries used by keystoneclient are now changed to use the
new package name the hacking check can be simplified.
bp drop-namespace-packages
Change-... |
01935ec30bba8b3733f716acf52ba32cb3a03974 | setup.py | setup.py | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-argcache',
version='0.1',
... | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-argcache',
version='0.1',
... | Fix typo in package description | Fix typo in package description
| Python | agpl-3.0 | luac/django-argcache,luac/django-argcache | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-argcache',
version='0.1',
... | Fix typo in package description
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django... |
893679baff0367538bdf3b52b04f8bae72732be8 | zerver/migrations/0031_remove_system_avatar_source.py | zerver/migrations/0031_remove_system_avatar_source.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0030_realm_org_type'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
n... | Add migration to remove system avatar source. | Add migration to remove system avatar source.
Fixes the last commit having broken master.
| Python | apache-2.0 | sharmaeklavya2/zulip,isht3/zulip,joyhchen/zulip,susansls/zulip,zulip/zulip,punchagan/zulip,blaze225/zulip,PhilSk/zulip,samatdav/zulip,hackerkid/zulip,christi3k/zulip,brainwane/zulip,mahim97/zulip,kou/zulip,jackrzhang/zulip,amyliu345/zulip,paxapy/zulip,niftynei/zulip,samatdav/zulip,vikas-parashar/zulip,shubhamdhama/zuli... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0030_realm_org_type'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
n... | Add migration to remove system avatar source.
Fixes the last commit having broken master.
| |
62906d37cca8cde2617372f71881dc802f23d6b9 | h2/frame_buffer.py | h2/frame_buffer.py | # -*- coding: utf-8 -*-
"""
h2/frame_buffer
~~~~~~~~~~~~~~~
A data structure that provides a way to iterate over a byte buffer in terms of
frames.
"""
from hyperframe.frame import Frame
class FrameBuffer(object):
"""
This is a data structure that expects to act as a buffer for HTTP/2 data
that allows ite... | Define an iterable frame buffer. | Define an iterable frame buffer.
| Python | mit | vladmunteanu/hyper-h2,vladmunteanu/hyper-h2,python-hyper/hyper-h2,bhavishyagopesh/hyper-h2,Kriechi/hyper-h2,python-hyper/hyper-h2,Kriechi/hyper-h2,mhils/hyper-h2 | # -*- coding: utf-8 -*-
"""
h2/frame_buffer
~~~~~~~~~~~~~~~
A data structure that provides a way to iterate over a byte buffer in terms of
frames.
"""
from hyperframe.frame import Frame
class FrameBuffer(object):
"""
This is a data structure that expects to act as a buffer for HTTP/2 data
that allows ite... | Define an iterable frame buffer.
| |
62bdb6f2a6df565119661cf2ba1517d19126e26a | member.py | member.py | #!/usr/bin/python3
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class Member(Base):
__tablename__ = 'member'
id = ... | #!/usr/bin/python3
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class Member(Base):
__tablename__ = 'member'
id = ... | Make globalName nullable for now. | Make globalName nullable for now.
| Python | agpl-3.0 | dark-echo/Bay-Oh-Woolph,freiheit/Bay-Oh-Woolph | #!/usr/bin/python3
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class Member(Base):
__tablename__ = 'member'
id = ... | Make globalName nullable for now.
#!/usr/bin/python3
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class Member(Base):
... |
e00ebeaa185ed2fc50c68eddd282194d8633a89c | setup.py | setup.py | __doc__ = """
Manipulate audio with an simple and easy high level interface.
See the README file for details, usage info, and a list of gotchas.
"""
from setuptools import setup
setup(
name='pydub',
version='0.16.3',
author='James Robert',
author_email='jiaaro@gmail.com',
description='Manipulate ... | __doc__ = """
Manipulate audio with an simple and easy high level interface.
See the README file for details, usage info, and a list of gotchas.
"""
from setuptools import setup
setup(
name='pydub',
version='0.16.4',
author='James Robert',
author_email='jiaaro@gmail.com',
description='Manipulate ... | Increment version for 24-bit wav bug fix | Increment version for 24-bit wav bug fix | Python | mit | jiaaro/pydub | __doc__ = """
Manipulate audio with an simple and easy high level interface.
See the README file for details, usage info, and a list of gotchas.
"""
from setuptools import setup
setup(
name='pydub',
version='0.16.4',
author='James Robert',
author_email='jiaaro@gmail.com',
description='Manipulate ... | Increment version for 24-bit wav bug fix
__doc__ = """
Manipulate audio with an simple and easy high level interface.
See the README file for details, usage info, and a list of gotchas.
"""
from setuptools import setup
setup(
name='pydub',
version='0.16.3',
author='James Robert',
author_email='jiaaro... |
884e7254bffcef4e5d3733b26f6eb0ea34b11da6 | core/project/Project.py | core/project/Project.py | """
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
self.title = title
self.fixedData = fixe... | """
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
self.title = title
self.fixedData = fixe... | Add transformations property to projects. | Add transformations property to projects.
| Python | mit | berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop | """
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
self.title = title
self.fixedData = fixe... | Add transformations property to projects.
"""
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
... |
254702c1b5a76701a1437d6dc3d732ec27ebaa81 | backslash/api_object.py | backslash/api_object.py |
class APIObject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotImplemented
return self.client is other.cli... |
class APIObject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotImplemented
return self.client is other.cli... | Make `refresh` return self for chaining actions | Make `refresh` return self for chaining actions
| Python | bsd-3-clause | slash-testing/backslash-python,vmalloc/backslash-python |
class APIObject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotImplemented
return self.client is other.cli... | Make `refresh` return self for chaining actions
class APIObject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotIm... |
d57e4993ece29da34c370a96732c820798c5048b | fake-service/features/environment.py | fake-service/features/environment.py | #
# Copyright (c) 2014 ThoughtWorks, Inc.
#
# Pixelated is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pixelated is distrib... | #
# Copyright (c) 2014 ThoughtWorks, Inc.
#
# Pixelated is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pixelated is distrib... | Revert "increasing webdriver timeout on fake-service" | Revert "increasing webdriver timeout on fake-service"
This reverts commit a39a4b40a947db655c84af6eb62d5870cfd8b32c.
| Python | agpl-3.0 | alabeduarte/pixelated-user-agent,phazel/pixelated-user-agent,pixelated-project/pixelated-user-agent,sw00/pixelated-user-agent,SamuelToh/pixelated-user-agent,SamuelToh/pixelated-user-agent,PuZZleDucK/pixelated-user-agent,sw00/pixelated-user-agent,SamuelToh/pixelated-user-agent,phazel/pixelated-user-agent,pixelated/pixel... | #
# Copyright (c) 2014 ThoughtWorks, Inc.
#
# Pixelated is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pixelated is distrib... | Revert "increasing webdriver timeout on fake-service"
This reverts commit a39a4b40a947db655c84af6eb62d5870cfd8b32c.
#
# Copyright (c) 2014 ThoughtWorks, Inc.
#
# Pixelated 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 S... |
93eb8e085854996e28982fad67915810328f8dc8 | examples/adjacency_list.py | examples/adjacency_list.py | from collections import deque
from peewee import *
db = SqliteDatabase(':memory:')
class TreeNode(Model):
parent = ForeignKeyField('self', backref='children', null=True)
name = TextField()
class Meta:
database = db
def __str__(self):
return 'name=%s' % self.name
def dump(self,... | Add adjacency list example. Compare to SQA's. | Add adjacency list example. Compare to SQA's.
[skip ci]
| Python | mit | coleifer/peewee,coleifer/peewee,coleifer/peewee | from collections import deque
from peewee import *
db = SqliteDatabase(':memory:')
class TreeNode(Model):
parent = ForeignKeyField('self', backref='children', null=True)
name = TextField()
class Meta:
database = db
def __str__(self):
return 'name=%s' % self.name
def dump(self,... | Add adjacency list example. Compare to SQA's.
[skip ci]
| |
ac6c9f4ad35a8c2c8ede616366b50995afff6992 | hurricane/runner.py | hurricane/runner.py | #!/usr/bin/env python
import multiprocessing
import optparse
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from hurricane.utils import run_until_stopped
class ApplicationManager(object):
@run_until_stopped
def run(self):
parser = optparse.Op... | #!/usr/bin/env python
import multiprocessing
import optparse
from django.conf import settings as django_settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from hurricane.utils import run_until_stopped
class ApplicationManager(object):
@run_until_sto... | Configure django correctly when we setup our env | Configure django correctly when we setup our env
| Python | bsd-3-clause | ericflo/hurricane,ericflo/hurricane | #!/usr/bin/env python
import multiprocessing
import optparse
from django.conf import settings as django_settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from hurricane.utils import run_until_stopped
class ApplicationManager(object):
@run_until_sto... | Configure django correctly when we setup our env
#!/usr/bin/env python
import multiprocessing
import optparse
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from hurricane.utils import run_until_stopped
class ApplicationManager(object):
@run_until_stopp... |
82740c7956a2bae0baceedd658b9ad9352254ad0 | nlppln/wfgenerator.py | nlppln/wfgenerator.py | from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self, working_dir=None, copy_steps=True):
WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir,
copy_steps=copy_steps)
... | from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self, working_dir=None):
WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir)
def save(self, fname, validate=True, wd=True, inline=False, relative=... | Update to use newest (unreleased) scriptcwl options | Update to use newest (unreleased) scriptcwl options
| Python | apache-2.0 | WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln | from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self, working_dir=None):
WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir)
def save(self, fname, validate=True, wd=True, inline=False, relative=... | Update to use newest (unreleased) scriptcwl options
from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self, working_dir=None, copy_steps=True):
WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir,
... |
25e5b39113994769c01bf6a79a9ca65764861ab3 | spicedham/__init__.py | spicedham/__init__.py | from pkg_resources import iter_entry_points
from spicedham.config import config
# TODO: Wrap all of this in an object with this in an __init__ function
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
plugins.append(pluginClass())
def train(... | from pkg_resources import iter_entry_points
from spicedham.config import load_config
_plugins = None
def load_plugins():
"""
If not already loaded, load plugins.
"""
if _plugins == None
load_config()
_plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', ... | Fix code which executes on module load. | Fix code which executes on module load.
| Python | mpl-2.0 | mozilla/spicedham,mozilla/spicedham | from pkg_resources import iter_entry_points
from spicedham.config import load_config
_plugins = None
def load_plugins():
"""
If not already loaded, load plugins.
"""
if _plugins == None
load_config()
_plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', ... | Fix code which executes on module load.
from pkg_resources import iter_entry_points
from spicedham.config import config
# TODO: Wrap all of this in an object with this in an __init__ function
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
p... |
867c71f0f2d3c2898815334a5d76063cd7671fae | processors/fix_changeline_budget_titles.py | processors/fix_changeline_budget_titles.py | import json
if __name__ == "__main__":
input = sys.argv[1]
output = sys.argv[2]
processor = fix_changeline_budget_titles().process(input,output,[])
class fix_changeline_budget_titles(object):
def process(self,inputs,output):
out = []
budgets = {}
changes_jsons, budget_jsons... | import json
import logging
if __name__ == "__main__":
input = sys.argv[1]
output = sys.argv[2]
processor = fix_changeline_budget_titles().process(input,output,[])
class fix_changeline_budget_titles(object):
def process(self,inputs,output):
out = []
budgets = {}
changes_json... | Fix bug in changeling title fix - it used to remove some lines on the way... | Fix bug in changeling title fix - it used to remove some lines on the way...
| Python | mit | OpenBudget/open-budget-data,OpenBudget/open-budget-data,omerbartal/open-budget-data,omerbartal/open-budget-data | import json
import logging
if __name__ == "__main__":
input = sys.argv[1]
output = sys.argv[2]
processor = fix_changeline_budget_titles().process(input,output,[])
class fix_changeline_budget_titles(object):
def process(self,inputs,output):
out = []
budgets = {}
changes_json... | Fix bug in changeling title fix - it used to remove some lines on the way...
import json
if __name__ == "__main__":
input = sys.argv[1]
output = sys.argv[2]
processor = fix_changeline_budget_titles().process(input,output,[])
class fix_changeline_budget_titles(object):
def process(self,inputs,output)... |
28a7077b7f05f52d0bff7a849f8b50f82f73dbdb | idx2md5.py | idx2md5.py | #! /usr/bin/python
from __future__ import print_function
import sys
import photo.index
idx = photo.index.Index(idxfile=sys.argv[1])
for i in idx:
print("%s %s" % (i.md5, i.filename))
| Add a script to convert an index to a md5 file. | Add a script to convert an index to a md5 file.
| Python | apache-2.0 | RKrahl/photo-tools | #! /usr/bin/python
from __future__ import print_function
import sys
import photo.index
idx = photo.index.Index(idxfile=sys.argv[1])
for i in idx:
print("%s %s" % (i.md5, i.filename))
| Add a script to convert an index to a md5 file.
| |
77ef603520652ab894128bf55f1f435bc17927c5 | memcached_status.py | memcached_status.py | #!/usr/bin/env python
import os
import socket
import subprocess
import telnetlib
def can_connect(host, port):
"""Check that we can make a connection to Memcached."""
try:
c = telnetlib.Telnet(host, port)
except socket.error:
return False
c.close()
return True
def main():
if n... | Add rudimentary status check for memcached | Add rudimentary status check for memcached
| Python | apache-2.0 | prometheanfire/rpc-openstack,jpmontez/rpc-openstack,andymcc/rpc-openstack,xeregin/rpc-openstack,robb-romans/rpc-openstack,stevelle/rpc-openstack,nrb/rpc-openstack,byronmccollum/rpc-openstack,briancurtin/rpc-maas,cloudnull/rpc-maas,nrb/rpc-openstack,cloudnull/rpc-maas,darrenchan/rpc-openstack,briancurtin/rpc-maas,stevel... | #!/usr/bin/env python
import os
import socket
import subprocess
import telnetlib
def can_connect(host, port):
"""Check that we can make a connection to Memcached."""
try:
c = telnetlib.Telnet(host, port)
except socket.error:
return False
c.close()
return True
def main():
if n... | Add rudimentary status check for memcached
| |
e18f4bd7db18743bb290fed276ff21a9e63e6922 | petulant/meme/tests.py | petulant/meme/tests.py | from django.test import TestCase
# Create your tests here.
| import json
from django.test import TestCase, Client
class MemeTests(TestCase):
def test_can_post_to_db(self):
response = json.loads(self.client.post('/', {'url':'https://foo.bar/baz.gif', 'keywords':'omg, this, is, great'}).content)
self.assertTrue(response['success'])
| Add test for posting content to the server | Add test for posting content to the server
| Python | apache-2.0 | AutomatedTester/petulant-meme,AutomatedTester/petulant-meme,AutomatedTester/petulant-meme | import json
from django.test import TestCase, Client
class MemeTests(TestCase):
def test_can_post_to_db(self):
response = json.loads(self.client.post('/', {'url':'https://foo.bar/baz.gif', 'keywords':'omg, this, is, great'}).content)
self.assertTrue(response['success'])
| Add test for posting content to the server
from django.test import TestCase
# Create your tests here.
|
68e056459dd3818ebb0c5dbdc8b4f1089bec9f07 | tests/selection_test.py | tests/selection_test.py | import os
import pytest
import yaml
from photoshell.selection import Selection
@pytest.fixture
def sidecar(tmpdir):
tmpdir.join("test.sidecar").write(yaml.dump({
'developed_path': os.path.join(tmpdir.strpath, "test.jpeg"),
'datetime': '2014-10-10 00:00'
}, default_flow_style=False))
retur... | Add a few behavior tests for selection | Add a few behavior tests for selection
| Python | mit | photoshell/photoshell,SamWhited/photoshell,campaul/photoshell | import os
import pytest
import yaml
from photoshell.selection import Selection
@pytest.fixture
def sidecar(tmpdir):
tmpdir.join("test.sidecar").write(yaml.dump({
'developed_path': os.path.join(tmpdir.strpath, "test.jpeg"),
'datetime': '2014-10-10 00:00'
}, default_flow_style=False))
retur... | Add a few behavior tests for selection
| |
1103c498635480d516eeebbec615f8d13db51bb7 | api/tests/test_topic_api.py | api/tests/test_topic_api.py | import pytz
from datetime import datetime, timedelta
from django.test import TestCase
from api.factories import TopicFactory
from rest_framework.test import APIRequestFactory, force_authenticate
from api.factories import UserFactory
from api.serializers import TopicSerializer
from api.views.topics import TopicViewSet
... | Write tests for active and inactive list routes | Write tests for active and inactive list routes
| Python | mit | frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq | import pytz
from datetime import datetime, timedelta
from django.test import TestCase
from api.factories import TopicFactory
from rest_framework.test import APIRequestFactory, force_authenticate
from api.factories import UserFactory
from api.serializers import TopicSerializer
from api.views.topics import TopicViewSet
... | Write tests for active and inactive list routes
| |
10ddce342da23c3702c1c0def4534d37cf6769b7 | tests/test_threading.py | tests/test_threading.py | from unittest import TestCase
from pydatajson.threading_helper import apply_threading
class ThreadingTests(TestCase):
def test_threading(self):
elements = [1, 2, 3, 4]
def function(x):
return x ** 2
result = apply_threading(elements, function, 3)
self.assertEqual(r... | Test case que pase por threading | Test case que pase por threading
| Python | mit | datosgobar/pydatajson,datosgobar/pydatajson | from unittest import TestCase
from pydatajson.threading_helper import apply_threading
class ThreadingTests(TestCase):
def test_threading(self):
elements = [1, 2, 3, 4]
def function(x):
return x ** 2
result = apply_threading(elements, function, 3)
self.assertEqual(r... | Test case que pase por threading
| |
cf0110f2b1adc8fbf4b8305841961d67da33f8c7 | pybo/bayesopt/policies/thompson.py | pybo/bayesopt/policies/thompson.py | """
Acquisition functions based on (GP) UCB.
"""
# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# use this to simplify (slightly) the Thompson implementation with sampled
# models.
from collections import deque
# local imports
from ..util... | """
Implementation of Thompson sampling for continuous spaces.
"""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from collections import deque
from ..utils import params
__all__ = ['Thompson']
@params('n')
def Thompson(model, n=100, rng=None):
"""
... | Fix Thompson to pay attention to the RNG. | Fix Thompson to pay attention to the RNG.
| Python | bsd-2-clause | mwhoffman/pybo,jhartford/pybo | """
Implementation of Thompson sampling for continuous spaces.
"""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from collections import deque
from ..utils import params
__all__ = ['Thompson']
@params('n')
def Thompson(model, n=100, rng=None):
"""
... | Fix Thompson to pay attention to the RNG.
"""
Acquisition functions based on (GP) UCB.
"""
# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# use this to simplify (slightly) the Thompson implementation with sampled
# models.
from collection... |
a760beb8d66222b456b160344eb0b4b7fccbf84a | Lib/test/test_linuxaudiodev.py | Lib/test/test_linuxaudiodev.py | from test_support import verbose, findfile, TestFailed
import linuxaudiodev
import errno
import os
def play_sound_file(path):
fp = open(path, 'r')
data = fp.read()
fp.close()
try:
a = linuxaudiodev.open('w')
except linuxaudiodev.error, msg:
if msg[0] in (errno.EACCES, errno.ENODEV):
rais... | from test_support import verbose, findfile, TestFailed, TestSkipped
import linuxaudiodev
import errno
import os
def play_sound_file(path):
fp = open(path, 'r')
data = fp.read()
fp.close()
try:
a = linuxaudiodev.open('w')
except linuxaudiodev.error, msg:
if msg[0] in (errno.EACCES, errno.EN... | Raise TestSkipped, not ImportError. Honesty's the best policy. | Raise TestSkipped, not ImportError.
Honesty's the best policy.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | from test_support import verbose, findfile, TestFailed, TestSkipped
import linuxaudiodev
import errno
import os
def play_sound_file(path):
fp = open(path, 'r')
data = fp.read()
fp.close()
try:
a = linuxaudiodev.open('w')
except linuxaudiodev.error, msg:
if msg[0] in (errno.EACCES, errno.EN... | Raise TestSkipped, not ImportError.
Honesty's the best policy.
from test_support import verbose, findfile, TestFailed
import linuxaudiodev
import errno
import os
def play_sound_file(path):
fp = open(path, 'r')
data = fp.read()
fp.close()
try:
a = linuxaudiodev.open('w')
except linuxaudiode... |
0e6a7a805ff08f191c88bda67992cb874f538c2f | services/migrations/0097_alter_unitconnection_section_type.py | services/migrations/0097_alter_unitconnection_section_type.py | # Generated by Django 4.0.5 on 2022-06-22 05:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("services", "0096_create_syllables_fi_columns"),
]
operations = [
migrations.AlterField(
model_name="unitconnection",
... | Add migration for unitconnection section types | Add migration for unitconnection section types
| Python | agpl-3.0 | City-of-Helsinki/smbackend,City-of-Helsinki/smbackend | # Generated by Django 4.0.5 on 2022-06-22 05:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("services", "0096_create_syllables_fi_columns"),
]
operations = [
migrations.AlterField(
model_name="unitconnection",
... | Add migration for unitconnection section types
| |
c79cedf826a3b6ee89e6186954185ef3217dd901 | tomviz/python/InvertData.py | tomviz/python/InvertData.py | import tomviz.operators
NUMBER_OF_CHUNKS = 10
class InvertOperator(tomviz.operators.CancelableOperator):
def transform_scalars(self, dataset):
from tomviz import utils
import numpy as np
self.progress.maximum = NUMBER_OF_CHUNKS
scalars = utils.get_scalars(dataset)
if sca... | import tomviz.operators
NUMBER_OF_CHUNKS = 10
class InvertOperator(tomviz.operators.CancelableOperator):
def transform_scalars(self, dataset):
from tomviz import utils
import numpy as np
self.progress.maximum = NUMBER_OF_CHUNKS
scalars = utils.get_scalars(dataset)
if sca... | Add the minimum scalar value to the result of the InvertOperator | Add the minimum scalar value to the result of the InvertOperator
Without it, all results would be shifted so the minimum was 0.
| Python | bsd-3-clause | OpenChemistry/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,mathturtle/tomviz | import tomviz.operators
NUMBER_OF_CHUNKS = 10
class InvertOperator(tomviz.operators.CancelableOperator):
def transform_scalars(self, dataset):
from tomviz import utils
import numpy as np
self.progress.maximum = NUMBER_OF_CHUNKS
scalars = utils.get_scalars(dataset)
if sca... | Add the minimum scalar value to the result of the InvertOperator
Without it, all results would be shifted so the minimum was 0.
import tomviz.operators
NUMBER_OF_CHUNKS = 10
class InvertOperator(tomviz.operators.CancelableOperator):
def transform_scalars(self, dataset):
from tomviz import utils
... |
cb533d74f2e634d9e8c7d0515307fad107da36ef | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/apps/site/urls.py | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/apps/site/urls.py | from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse
from django.views import generic
from . import views
urlpatterns = (
url(r'^robots\.txt$', views.RobotsView.as_view(), name="robots"),
)
if getattr(settings, 'LOADERIO_TOKEN', None):
loaderio_token = setti... | from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse
from django.views import generic
from . import views
urlpatterns = (
url(r'^robots\.txt$', views.RobotsView.as_view(), name="robots"),
)
if getattr(settings, 'LOADERIO_TOKEN', None):
loaderio_token = sett... | Add a missing line between imports | Add a missing line between imports
| Python | mit | dulaccc/cookiecutter-django-herokuapp,dulaccc/cookiecutter-django-herokuapp,dulaccc/cookiecutter-django-herokuapp,dulaccc/cookiecutter-django-herokuapp | from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse
from django.views import generic
from . import views
urlpatterns = (
url(r'^robots\.txt$', views.RobotsView.as_view(), name="robots"),
)
if getattr(settings, 'LOADERIO_TOKEN', None):
loaderio_token = sett... | Add a missing line between imports
from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse
from django.views import generic
from . import views
urlpatterns = (
url(r'^robots\.txt$', views.RobotsView.as_view(), name="robots"),
)
if getattr(settings, 'LOADERIO_TOKEN... |
aaae5af0570ded8cab9cb330c9c992dac62778c3 | vcapp/geometry.py | vcapp/geometry.py | import math
def line_magnitude (x1, y1, x2, y2):
return math.sqrt(math.pow((x2 - x1), 2) + math.pow((y2 - y1), 2))
#Calc minimum distance from a point and a line segment (i.e. consecutive vertices in a polyline).
def distance_point_line (px, py, x1, y1, x2, y2):
#http://local.wasp.uwa.edu.au/~pbourke/geometry... | Move geometric functions into a separate file | Move geometric functions into a separate file
| Python | cc0-1.0 | edwinsteele/visual-commute,edwinsteele/visual-commute | import math
def line_magnitude (x1, y1, x2, y2):
return math.sqrt(math.pow((x2 - x1), 2) + math.pow((y2 - y1), 2))
#Calc minimum distance from a point and a line segment (i.e. consecutive vertices in a polyline).
def distance_point_line (px, py, x1, y1, x2, y2):
#http://local.wasp.uwa.edu.au/~pbourke/geometry... | Move geometric functions into a separate file
| |
54054b4e007acbb5f1389a5e2091824a4c083e91 | examples/plotting/LineAnimator_examples.py | examples/plotting/LineAnimator_examples.py | """
=============
LineAnimator
=============
This example shows off some ways in which you can use the
LineAnimator object to animate line plots.
"""
import numpy as np
import matplotlib.pyplot as plt
from sunpy.visualization.animator import LineAnimator
##############################################################... | """
=============
LineAnimator
=============
This example shows off some ways in which you can use the
LineAnimator object to animate line plots.
"""
import numpy as np
import matplotlib.pyplot as plt
from sunpy.visualization.animator import LineAnimator
##############################################################... | Fix LineAnimator example to adhere to new pixel edges axis_ranges API. | Fix LineAnimator example to adhere to new pixel edges axis_ranges API.
| Python | bsd-2-clause | dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy | """
=============
LineAnimator
=============
This example shows off some ways in which you can use the
LineAnimator object to animate line plots.
"""
import numpy as np
import matplotlib.pyplot as plt
from sunpy.visualization.animator import LineAnimator
##############################################################... | Fix LineAnimator example to adhere to new pixel edges axis_ranges API.
"""
=============
LineAnimator
=============
This example shows off some ways in which you can use the
LineAnimator object to animate line plots.
"""
import numpy as np
import matplotlib.pyplot as plt
from sunpy.visualization.animator import Line... |
357a37d607b4b85d46e26fa4d2409f23d923d176 | src/client/keyboard/win.py | src/client/keyboard/win.py | #!/usr/bin/env python
import re, sys, os
if len(sys.argv) != 2:
print >>sys.stderr, "Usage: win.py path/to/WinUser.h"
sys.exit(1)
OUT = 'win2.txt'
TMP = OUT + '.tmp'
f = open(TMP, 'w')
try:
print >>f, '; Automatically generated by "win.py"'
VK = re.compile('#define\s*VK_(\w+)\s+(\w+)')
for line in o... | Add keycode table generator for Windows | Add keycode table generator for Windows
| Python | bsd-2-clause | depp/sglib,depp/sglib | #!/usr/bin/env python
import re, sys, os
if len(sys.argv) != 2:
print >>sys.stderr, "Usage: win.py path/to/WinUser.h"
sys.exit(1)
OUT = 'win2.txt'
TMP = OUT + '.tmp'
f = open(TMP, 'w')
try:
print >>f, '; Automatically generated by "win.py"'
VK = re.compile('#define\s*VK_(\w+)\s+(\w+)')
for line in o... | Add keycode table generator for Windows
| |
ac9123c7926c04af7ac68949e2636a81f771fd7d | ncdc_download/download_mapper2.py | ncdc_download/download_mapper2.py | #!/usr/bin/env python3
import ftplib
import gzip
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s... | #!/usr/bin/env python3
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing ... | Decompress downloaded files from disk, not in memory | Decompress downloaded files from disk, not in memory
| Python | mit | simonbrady/cat,simonbrady/cat | #!/usr/bin/env python3
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing ... | Decompress downloaded files from disk, not in memory
#!/usr/bin/env python3
import ftplib
import gzip
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
s... |
95d3401b29d2cba2d282256cdd2513c67e3df858 | ipython_notebook_config.py | ipython_notebook_config.py | # Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
c.Notebo... | # Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
c.Notebo... | Set the content security policy | Set the content security policy
| Python | bsd-3-clause | jupyter/nature-demo,jupyter/nature-demo,jupyter/nature-demo | # Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
c.Notebo... | Set the content security policy
# Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if... |
e9ec19e68ccefaee9a975a6adc26cb6e5f1f7f33 | pymodels/middlelayer/devices/__init__.py | pymodels/middlelayer/devices/__init__.py | from .dcct import DCCT
from .li_llrf import LiLLRF
from .rf import RF
from .sofb import SOFB
from .kicker import Kicker
from .septum import Septum
from .screen import Screen
from .bpm import BPM
from .ict import ICT
from .ict import TranspEff
from .egun import Bias
from .egun import Filament
from .egun import HVPS
| from .dcct import DCCT
from .li_llrf import LiLLRF
from .rf import RF
from .sofb import SOFB
from .kicker import Kicker
from .septum import Septum
from .screen import Screen
from .bpm import BPM
from .ict import ICT
from .ict import TranspEff
from .egun import Bias
from .egun import Filament
from .egun import HVPS
from... | Add timing in devices init | DEV.ENH: Add timing in devices init
| Python | mit | lnls-fac/sirius | from .dcct import DCCT
from .li_llrf import LiLLRF
from .rf import RF
from .sofb import SOFB
from .kicker import Kicker
from .septum import Septum
from .screen import Screen
from .bpm import BPM
from .ict import ICT
from .ict import TranspEff
from .egun import Bias
from .egun import Filament
from .egun import HVPS
from... | DEV.ENH: Add timing in devices init
from .dcct import DCCT
from .li_llrf import LiLLRF
from .rf import RF
from .sofb import SOFB
from .kicker import Kicker
from .septum import Septum
from .screen import Screen
from .bpm import BPM
from .ict import ICT
from .ict import TranspEff
from .egun import Bias
from .egun import... |
87babdfba0236de5d0742f9e336f8e3dbf603c65 | temba/flows/migrations/0046_flowrun_responded_unnull.py | temba/flows/migrations/0046_flowrun_responded_unnull.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('flows', '0045_populate_responded'),
]
operations = [
migrations.AlterField(
mod... | Set FlowRun.respnoded to be non-nullable | Set FlowRun.respnoded to be non-nullable
| Python | agpl-3.0 | pulilab/rapidpro,reyrodrigues/EU-SMS,tsotetsi/textily-web,tsotetsi/textily-web,pulilab/rapidpro,reyrodrigues/EU-SMS,tsotetsi/textily-web,tsotetsi/textily-web,pulilab/rapidpro,ewheeler/rapidpro,ewheeler/rapidpro,tsotetsi/textily-web,pulilab/rapidpro,pulilab/rapidpro,ewheeler/rapidpro,reyrodrigues/EU-SMS,ewheeler/rapidpr... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('flows', '0045_populate_responded'),
]
operations = [
migrations.AlterField(
mod... | Set FlowRun.respnoded to be non-nullable
| |
e4c33d57ddc9743cec1c43bf0bb8d6fae185aff7 | ticketus/urls.py | ticketus/urls.py | from django.conf import settings
from django.conf.urls import patterns, include
from django.contrib import admin
urlpatterns = patterns('',
(r'^ticket/', include('ticketus.ui.urls')),
(r'^grappelli/', include('grappelli.urls')),
(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
import debug... | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
url(r'^$', RedirectView.as_view(pattern_name='ticket_list', permanent=False)),
(r'^ticket/', include('ticketus.ui.u... | Add CBV for redirecting / to /ticket | Add CBV for redirecting / to /ticket
| Python | bsd-2-clause | sjkingo/ticketus,sjkingo/ticketus,sjkingo/ticketus,sjkingo/ticketus | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
url(r'^$', RedirectView.as_view(pattern_name='ticket_list', permanent=False)),
(r'^ticket/', include('ticketus.ui.u... | Add CBV for redirecting / to /ticket
from django.conf import settings
from django.conf.urls import patterns, include
from django.contrib import admin
urlpatterns = patterns('',
(r'^ticket/', include('ticketus.ui.urls')),
(r'^grappelli/', include('grappelli.urls')),
(r'^admin/', include(admin.site.urls)),
... |
aaac1ae0667dabe6fd038c9f5a42c157b9457ef1 | tests/test_parse.py | tests/test_parse.py | from hypothesis_auto import auto_pytest_magic
from isort import parse
from isort.settings import default
TEST_CONTENTS = """
import xyz
import abc
def function():
pass
"""
def test_file_contents():
(
in_lines,
out_lines,
import_index,
place_imports,
import_placement... | from hypothesis_auto import auto_pytest_magic
from isort import parse
from isort.settings import Config
TEST_CONTENTS = """
import xyz
import abc
def function():
pass
"""
def test_file_contents():
(
in_lines,
out_lines,
import_index,
place_imports,
import_placements... | Fix use of default config to match new refactor | Fix use of default config to match new refactor
| Python | mit | PyCQA/isort,PyCQA/isort | from hypothesis_auto import auto_pytest_magic
from isort import parse
from isort.settings import Config
TEST_CONTENTS = """
import xyz
import abc
def function():
pass
"""
def test_file_contents():
(
in_lines,
out_lines,
import_index,
place_imports,
import_placements... | Fix use of default config to match new refactor
from hypothesis_auto import auto_pytest_magic
from isort import parse
from isort.settings import default
TEST_CONTENTS = """
import xyz
import abc
def function():
pass
"""
def test_file_contents():
(
in_lines,
out_lines,
import_index... |
ab3d07cf5d169459515348777a68f825e182ba03 | scripts/print_view_hierarchy.py | scripts/print_view_hierarchy.py | """Prints the current view hierarchy.
Usage: pv
"""
def print_view_hierarchy(debugger, command, result, internal_dict):
debugger.HandleCommand('po [[UIWindow keyWindow] recursiveDescription]')
def __lldb_init_module(debugger, internal_dict):
debugger.HandleCommand('command script add -f print_view_hierarchy.prin... | """Prints the current view hierarchy.
Usage: pv
"""
def print_view_hierarchy(debugger, command, result, internal_dict):
debugger.GetCommandInterpreter().HandleCommand('po [[UIWindow keyWindow] recursiveDescription]', result)
def __lldb_init_module(debugger, internal_dict):
debugger.HandleCommand('command script ... | Update view hierarchy script to use the interpreter as needed for tests. | Update view hierarchy script to use the interpreter as needed for tests.
| Python | mit | mrhappyasthma/happydebugging,mrhappyasthma/HappyDebugging | """Prints the current view hierarchy.
Usage: pv
"""
def print_view_hierarchy(debugger, command, result, internal_dict):
debugger.GetCommandInterpreter().HandleCommand('po [[UIWindow keyWindow] recursiveDescription]', result)
def __lldb_init_module(debugger, internal_dict):
debugger.HandleCommand('command script ... | Update view hierarchy script to use the interpreter as needed for tests.
"""Prints the current view hierarchy.
Usage: pv
"""
def print_view_hierarchy(debugger, command, result, internal_dict):
debugger.HandleCommand('po [[UIWindow keyWindow] recursiveDescription]')
def __lldb_init_module(debugger, internal_dict):... |
43783e4ff07c9a2ff9f9a11b92515d49e66abcb2 | lms/djangoapps/open_ended_grading/controller_query_service.py | lms/djangoapps/open_ended_grading/controller_query_service.py | import json
import logging
import requests
from requests.exceptions import RequestException, ConnectionError, HTTPError
import sys
from grading_service import GradingService
from grading_service import GradingServiceError
from django.conf import settings
from django.http import HttpResponse, Http404
log = logging.get... | import json
import logging
import requests
from requests.exceptions import RequestException, ConnectionError, HTTPError
import sys
from grading_service import GradingService
from grading_service import GradingServiceError
from django.conf import settings
from django.http import HttpResponse, Http404
log = logging.get... | Add in an item to check for combined notifications | Add in an item to check for combined notifications
| Python | agpl-3.0 | apigee/edx-platform,motion2015/edx-platform,fly19890211/edx-platform,angelapper/edx-platform,yokose-ks/edx-platform,itsjeyd/edx-platform,chudaol/edx-platform,dkarakats/edx-platform,dsajkl/123,DNFcode/edx-platform,ferabra/edx-platform,iivic/BoiseStateX,marcore/edx-platform,UXE/local-edx,cyanna/edx-platform,praveen-pal/e... | import json
import logging
import requests
from requests.exceptions import RequestException, ConnectionError, HTTPError
import sys
from grading_service import GradingService
from grading_service import GradingServiceError
from django.conf import settings
from django.http import HttpResponse, Http404
log = logging.get... | Add in an item to check for combined notifications
import json
import logging
import requests
from requests.exceptions import RequestException, ConnectionError, HTTPError
import sys
from grading_service import GradingService
from grading_service import GradingServiceError
from django.conf import settings
from django.... |
c6b9bb93f268b7c1dc100c75a7c36326d63450d5 | tests/all_test.py | tests/all_test.py | import glob
import unittest
import os, sys
if __name__ == '__main__':
PROJECT_ROOT = os.path.dirname(__file__)
test_file_strings = glob.glob(os.path.join(PROJECT_ROOT, 'test_*.py'))
module_strings = [os.path.splitext(os.path.basename(str))[0] for str in test_file_strings]
suites = [unittest.defaultTest... | Add all test runner for command line. Now every test can be run for commandline | Add all test runner for command line. Now every test can be run for commandline
| Python | mit | kyamaguchi/SublimeObjC2RubyMotion,kyamaguchi/SublimeObjC2RubyMotion | import glob
import unittest
import os, sys
if __name__ == '__main__':
PROJECT_ROOT = os.path.dirname(__file__)
test_file_strings = glob.glob(os.path.join(PROJECT_ROOT, 'test_*.py'))
module_strings = [os.path.splitext(os.path.basename(str))[0] for str in test_file_strings]
suites = [unittest.defaultTest... | Add all test runner for command line. Now every test can be run for commandline
| |
aff229797b3914b6708920fd247861d7777ccc22 | framework/tasks/__init__.py | framework/tasks/__init__.py | # -*- coding: utf-8 -*-
"""Asynchronous task queue module."""
from celery import Celery
from celery.utils.log import get_task_logger
from kombu import Exchange, Queue
from raven import Client
from raven.contrib.celery import register_signal
from website import settings
app = Celery()
# TODO: Hardcoded settings mod... | # -*- coding: utf-8 -*-
"""Asynchronous task queue module."""
from celery import Celery
from celery.utils.log import get_task_logger
from raven import Client
from raven.contrib.celery import register_signal
from website import settings
app = Celery()
# TODO: Hardcoded settings module. Should be set using framework... | Use auto generated celery queues | Use auto generated celery queues
| Python | apache-2.0 | jmcarp/osf.io,MerlinZhang/osf.io,Nesiehr/osf.io,leb2dg/osf.io,emetsger/osf.io,GageGaskins/osf.io,ticklemepierce/osf.io,jinluyuan/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,caseyrygt/osf.io,kch8qx/osf.io,KAsante95/osf.io,crcresearch/osf.io,aaxelb/osf.io,zamattiac/osf.io,zamattiac/osf.io,cwisecarver/osf.io,fabia... | # -*- coding: utf-8 -*-
"""Asynchronous task queue module."""
from celery import Celery
from celery.utils.log import get_task_logger
from raven import Client
from raven.contrib.celery import register_signal
from website import settings
app = Celery()
# TODO: Hardcoded settings module. Should be set using framework... | Use auto generated celery queues
# -*- coding: utf-8 -*-
"""Asynchronous task queue module."""
from celery import Celery
from celery.utils.log import get_task_logger
from kombu import Exchange, Queue
from raven import Client
from raven.contrib.celery import register_signal
from website import settings
app = Celery... |
1f4d8b5f5f35b189aab5ff9e10d3ac2386124443 | behave/contrib/substep_dirs.py | behave/contrib/substep_dirs.py | # -*- coding: UTF-8 -*-
"""
Recipe for loading additional step definitions from sub-directories
in the "features/steps" directory.
.. code-block::
# -- FILE: features/steps/use_substep_dirs.py
# REQUIRES: path.py
from behave.runner_util import load_step_modules
from path import Path
HERE = P... | # -*- coding: UTF-8 -*-
"""
Recipe for loading additional step definitions from sub-directories
in the "features/steps" directory.
.. code-block::
# -- FILE: features/steps/use_substep_dirs.py
# REQUIRES: path.py
from behave.runner_util import load_step_modules
from path import Path
HERE = Path(_... | FIX TYPO: Uncovered by NaveenKVN | FIX TYPO: Uncovered by NaveenKVN
| Python | bsd-2-clause | jenisys/behave,jenisys/behave | # -*- coding: UTF-8 -*-
"""
Recipe for loading additional step definitions from sub-directories
in the "features/steps" directory.
.. code-block::
# -- FILE: features/steps/use_substep_dirs.py
# REQUIRES: path.py
from behave.runner_util import load_step_modules
from path import Path
HERE = Path(_... | FIX TYPO: Uncovered by NaveenKVN
# -*- coding: UTF-8 -*-
"""
Recipe for loading additional step definitions from sub-directories
in the "features/steps" directory.
.. code-block::
# -- FILE: features/steps/use_substep_dirs.py
# REQUIRES: path.py
from behave.runner_util import load_step_modules
from ... |
5afae8a39345ef3d334817234177d656cf12cff3 | scripts/bioinfo_project_status_update.py | scripts/bioinfo_project_status_update.py | #!/usr/bin/env python
import argparse
import os
import yaml
from genologics.lims import Lims
from genologics.entities import Project
from genologics.config import BASEURI, USERNAME, PASSWORD
import LIMS2DB.utils as lutils
from requests.exceptions import HTTPError
def main(args):
log = lutils.setupLog('bioinfolog... | Add script to update project closure in bioinfo_analysis db | Add script to update project closure in bioinfo_analysis db
| Python | mit | SciLifeLab/LIMS2DB | #!/usr/bin/env python
import argparse
import os
import yaml
from genologics.lims import Lims
from genologics.entities import Project
from genologics.config import BASEURI, USERNAME, PASSWORD
import LIMS2DB.utils as lutils
from requests.exceptions import HTTPError
def main(args):
log = lutils.setupLog('bioinfolog... | Add script to update project closure in bioinfo_analysis db
| |
37f2ebdeeb3f1ef6a3c61c7dfb5dca22673fd810 | setup.py | setup.py | from setuptools import setup, find_packages
package_data = ['static/css/*', 'static/img/*', 'static/js/*', 'static/js/templates/*', 'templates/djukebox/*']
dependencies = ['pillow', 'django-celery==2.5.5', 'mutagen', 'simplejson', 'django-bootstrap-form', 'django-tastypie==0.9.15']
setup(name = "djukebox",
versi... | from setuptools import setup, find_packages
package_data = ['static/css/*', 'static/img/*', 'static/js/*', 'static/js/templates/*', 'templates/djukebox/*']
dependencies = ['Pillow==2.1.0', 'django-celery==3.0.21', 'mutagen==1.21', 'simplejson==3.3.0', 'django-bootstrap-form', 'django-tastypie==0.9.15']
setup(name = "d... | Set full versions on all dependencies and updated most to latest version | Set full versions on all dependencies and updated most to latest version
| Python | bsd-2-clause | jmichalicek/djukebox,jmichalicek/djukebox | from setuptools import setup, find_packages
package_data = ['static/css/*', 'static/img/*', 'static/js/*', 'static/js/templates/*', 'templates/djukebox/*']
dependencies = ['Pillow==2.1.0', 'django-celery==3.0.21', 'mutagen==1.21', 'simplejson==3.3.0', 'django-bootstrap-form', 'django-tastypie==0.9.15']
setup(name = "d... | Set full versions on all dependencies and updated most to latest version
from setuptools import setup, find_packages
package_data = ['static/css/*', 'static/img/*', 'static/js/*', 'static/js/templates/*', 'templates/djukebox/*']
dependencies = ['pillow', 'django-celery==2.5.5', 'mutagen', 'simplejson', 'django-bootst... |
d6d4601a5a1238cf7d2f0a6bdf782a77318d28a3 | tests_django/integration_tests/test_output_adapter_integration.py | tests_django/integration_tests/test_output_adapter_integration.py | from django.test import TestCase
from chatterbot.ext.django_chatterbot.models import Statement
class OutputIntegrationTestCase(TestCase):
"""
Tests to make sure that output adapters
function correctly when using Django.
"""
def test_output_format_adapter(self):
from chatterbot.output impo... | Test that the output format adapter works with Django | Test that the output format adapter works with Django
| Python | bsd-3-clause | vkosuri/ChatterBot,Reinaesaya/OUIRL-ChatBot,maclogan/VirtualPenPal,gunthercox/ChatterBot,davizucon/ChatterBot,Gustavo6046/ChatterBot,Reinaesaya/OUIRL-ChatBot | from django.test import TestCase
from chatterbot.ext.django_chatterbot.models import Statement
class OutputIntegrationTestCase(TestCase):
"""
Tests to make sure that output adapters
function correctly when using Django.
"""
def test_output_format_adapter(self):
from chatterbot.output impo... | Test that the output format adapter works with Django
| |
ee662e6119ef31978eec62491b6e7ce35f292518 | python2.7-src/fibonacci_sequence.py | python2.7-src/fibonacci_sequence.py | #!/usr/bin/python
import sys
def fib(n):
a,b = 0,1
yield a
if n>0 :
yield b
for i in range(2,n+1):
a,b = b, a+b
yield b
num = int(sys.argv[1])
gen = fib(num)
for i in gen:
print i
| Add function for Fibonacci sequence | Add function for Fibonacci sequence
| Python | mit | diptin/dipti-coding-samples,diptin/dipti-coding-samples | #!/usr/bin/python
import sys
def fib(n):
a,b = 0,1
yield a
if n>0 :
yield b
for i in range(2,n+1):
a,b = b, a+b
yield b
num = int(sys.argv[1])
gen = fib(num)
for i in gen:
print i
| Add function for Fibonacci sequence
| |
d7a864a0df2723657d7ff5b02c7568042d49093f | oonib/deck/api.py | oonib/deck/api.py | from cyclone import web
from oonib.deck import handlers
from oonib import config
deckAPI = [
(r"/deck", handlers.DeckListHandler),
(r"/deck/([a-z0-9]{40})$", handlers.DeckDescHandler),
(r"/deck/([a-z0-9]{40})/yaml$", web.StaticFileHandler, {"path":
config.main.deck_dir}),
]
| from cyclone import web
from oonib.deck import handlers
from oonib import config
deckAPI = [
(r"/deck", handlers.DeckListHandler),
(r"/deck/([a-z0-9]{64})$", handlers.DeckDescHandler),
(r"/deck/([a-z0-9]{64})/yaml$", web.StaticFileHandler, {"path":
config.main.deck_dir}),
]
| Use sha256 as per oonib.md spec | Use sha256 as per oonib.md spec
| Python | bsd-2-clause | dstufft/ooni-backend,dstufft/ooni-backend,DoNotUseThisCodeJUSTFORKS/ooni-backend,DoNotUseThisCodeJUSTFORKS/ooni-backend | from cyclone import web
from oonib.deck import handlers
from oonib import config
deckAPI = [
(r"/deck", handlers.DeckListHandler),
(r"/deck/([a-z0-9]{64})$", handlers.DeckDescHandler),
(r"/deck/([a-z0-9]{64})/yaml$", web.StaticFileHandler, {"path":
config.main.deck_dir}),
]
| Use sha256 as per oonib.md spec
from cyclone import web
from oonib.deck import handlers
from oonib import config
deckAPI = [
(r"/deck", handlers.DeckListHandler),
(r"/deck/([a-z0-9]{40})$", handlers.DeckDescHandler),
(r"/deck/([a-z0-9]{40})/yaml$", web.StaticFileHandler, {"path":
config.main.deck_... |
90ac14b61066f6039df5d1522b7ac6bd76779b7b | tests.py | tests.py | from tfidf_lsa import calculate_corpus_var
import json
import os
import shutil
import subprocess
import unittest
class TestMoviePepper(unittest.TestCase):
def test_crawl(self):
try:
shutil.rmtree('./movie_scrape/crawls')
os.remove('./movie_scrape/imdb.json')
os.remove('... | Add a basic crawler and tfidf_lsa creation test | Add a basic crawler and tfidf_lsa creation test
| Python | mit | hugo19941994/movie-pepper-back,hugo19941994/movie-pepper-back | from tfidf_lsa import calculate_corpus_var
import json
import os
import shutil
import subprocess
import unittest
class TestMoviePepper(unittest.TestCase):
def test_crawl(self):
try:
shutil.rmtree('./movie_scrape/crawls')
os.remove('./movie_scrape/imdb.json')
os.remove('... | Add a basic crawler and tfidf_lsa creation test
| |
7a3e7365569c18c971db9698cd7cdd1a82756463 | table.py | table.py | import csv
class Table():
'''A Table is an object which represents a 2-dimensional CSV file. Both rows
and columns can be accessed via their key as in a dictionary. This means that
keys cannot appear as both a row and column label.'''
def __init__(self, filename):
self._internal_table = self.l... | Create Table object for representing phonetic inventory | Create Table object for representing phonetic inventory
| Python | mit | kdelwat/LangEvolve,kdelwat/LangEvolve,kdelwat/LangEvolve | import csv
class Table():
'''A Table is an object which represents a 2-dimensional CSV file. Both rows
and columns can be accessed via their key as in a dictionary. This means that
keys cannot appear as both a row and column label.'''
def __init__(self, filename):
self._internal_table = self.l... | Create Table object for representing phonetic inventory
| |
d78d944038dfa768a6aac5dc531d5220e6883a11 | tests/unit/models/reddit/test_modmail.py | tests/unit/models/reddit/test_modmail.py | from praw.models import ModmailConversation
from ... import UnitTest
class TestModmailConversation(UnitTest):
def test_parse(self):
conversation = ModmailConversation(self.reddit,
_data={'id': 'ik72'})
assert str(conversation) == 'ik72'
| Test that ModmailConversation.id is preserved after fetch | Test that ModmailConversation.id is preserved after fetch
| Python | bsd-2-clause | gschizas/praw,13steinj/praw,13steinj/praw,praw-dev/praw,gschizas/praw,darthkedrik/praw,praw-dev/praw,leviroth/praw,leviroth/praw,darthkedrik/praw | from praw.models import ModmailConversation
from ... import UnitTest
class TestModmailConversation(UnitTest):
def test_parse(self):
conversation = ModmailConversation(self.reddit,
_data={'id': 'ik72'})
assert str(conversation) == 'ik72'
| Test that ModmailConversation.id is preserved after fetch
| |
c4d58ef971b850d3f201903bb6091d159241112f | histomicstk/features/__init__.py | histomicstk/features/__init__.py | from .ReinhardNorm import ReinhardNorm
from .ReinhardSample import ReinhardSample
__all__ = (
'FeatureExtraction'
)
| __all__ = (
'FeatureExtraction'
)
| Resolve import issue in color_normalization_test | Resolve import issue in color_normalization_test
| Python | apache-2.0 | DigitalSlideArchive/HistomicsTK,DigitalSlideArchive/HistomicsTK | __all__ = (
'FeatureExtraction'
)
| Resolve import issue in color_normalization_test
from .ReinhardNorm import ReinhardNorm
from .ReinhardSample import ReinhardSample
__all__ = (
'FeatureExtraction'
)
|
8a09e49cbcb9a874619b0e06601c2d69d5dad738 | keystoneclient/__init__.py | keystoneclient/__init__.py | # Copyright 2012 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | # Copyright 2012 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | Fix --version to output version | Fix --version to output version
Change-Id: I7d8dc83ac7c2ad7519633d136c1c32ce8537dce8
Fixes: bug 1182675
| Python | apache-2.0 | alexpilotti/python-keystoneclient,alexpilotti/python-keystoneclient,jamielennox/python-keystoneclient,ntt-sic/python-keystoneclient,klmitch/python-keystoneclient,metacloud/python-keystoneclient,sdpp/python-keystoneclient,ging/python-keystoneclient,sdpp/python-keystoneclient,ging/python-keystoneclient,darren-wang/ksc,Me... | # Copyright 2012 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | Fix --version to output version
Change-Id: I7d8dc83ac7c2ad7519633d136c1c32ce8537dce8
Fixes: bug 1182675
# Copyright 2012 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# ... |
3672d178ac4f9a3f9308acf1e43e9eea663fe30a | OnlineParticipationDataset/pipelines.py | OnlineParticipationDataset/pipelines.py | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
from datetime import datetime
from scrapy.exporters import JsonLinesItemExporter
class Onlineparticipationdataset... | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json,os
from datetime import datetime
from scrapy.exporters import JsonLinesItemExporter
path = "downloads"
class Onl... | Create path if it doesnt exists | Create path if it doesnt exists
| Python | mit | Liebeck/OnlineParticipationDatasets | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json,os
from datetime import datetime
from scrapy.exporters import JsonLinesItemExporter
path = "downloads"
class Onl... | Create path if it doesnt exists
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
from datetime import datetime
from scrapy.exporters import JsonLinesItemExporter
... |
ab83da7b6152dfdc50cf40fa328f3c3d24c13861 | emailmgr/urls.py | emailmgr/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
email_send_activation, email_activate, email_make_primary
#add an email to a User account
urlpatterns = patterns('',
url(
... | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
email_send_activation, email_activate, email_make_primary
#add an email to a User account
urlpatterns = patterns('',
url(
r'^emai... | Fix import for django 1.6 | Fix import for django 1.6 | Python | bsd-3-clause | un33k/django-emailmgr,un33k/django-emailmgr | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
email_send_activation, email_activate, email_make_primary
#add an email to a User account
urlpatterns = patterns('',
url(
r'^emai... | Fix import for django 1.6
# -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
email_send_activation, email_activate, email_make_primary
#add an email to a User account
urlpatterns = pa... |
08bd3801c0ecc3d4ef9720094bcbf67acaf1b67b | Instanssi/admin_base/views.py | Instanssi/admin_base/views.py | # -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
@login_required(login_url='/control/auth/login/')
def index(request):
return HttpResponseRedirect("/control/files/")
@login_required(login_url='/control/auth/login/')
def eventchange... | # -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
@login_required(login_url='/control/auth/login/')
def index(request):
return HttpResponseRedirect("/control/events/")
@login_required(login_url='/control/auth/login/')
def eventchang... | Fix default refirect when url is /control/ | admin_base: Fix default refirect when url is /control/
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org | # -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
@login_required(login_url='/control/auth/login/')
def index(request):
return HttpResponseRedirect("/control/events/")
@login_required(login_url='/control/auth/login/')
def eventchang... | admin_base: Fix default refirect when url is /control/
# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
@login_required(login_url='/control/auth/login/')
def index(request):
return HttpResponseRedirect("/control/files/")
@login_re... |
4c080197dce0d452047203dbf06dd160086fcbdf | website/snat/forms.py | website/snat/forms.py | # -*- coding: utf-8 -*-
"""
website.snat.forms
~~~~~~~~~~~~~~~~~~
vpn forms:
/sant
:copyright: (c) 2014 by xiong.xiaox(xiong.xiaox@alibaba-inc.com).
"""
from flask_wtf import Form
from wtforms import TextField
from wtforms.validators import Required, IPAddress
class SnatForm(Form):
sou... | # -*- coding: utf-8 -*-
"""
website.snat.forms
~~~~~~~~~~~~~~~~~~
vpn forms:
/sant
:copyright: (c) 2014 by xiong.xiaox(xiong.xiaox@alibaba-inc.com).
"""
from flask_wtf import Form
from wtforms import TextField, ValidationError
from wtforms.validators import Required, IPAddress
def IPorNet(... | Add snat ip or net validator. | Add snat ip or net validator.
| Python | bsd-3-clause | sdgdsffdsfff/FlexGW,sdgdsffdsfff/FlexGW,alibaba/FlexGW,alibaba/FlexGW,sdgdsffdsfff/FlexGW,sdgdsffdsfff/FlexGW,alibaba/FlexGW,alibaba/FlexGW | # -*- coding: utf-8 -*-
"""
website.snat.forms
~~~~~~~~~~~~~~~~~~
vpn forms:
/sant
:copyright: (c) 2014 by xiong.xiaox(xiong.xiaox@alibaba-inc.com).
"""
from flask_wtf import Form
from wtforms import TextField, ValidationError
from wtforms.validators import Required, IPAddress
def IPorNet(... | Add snat ip or net validator.
# -*- coding: utf-8 -*-
"""
website.snat.forms
~~~~~~~~~~~~~~~~~~
vpn forms:
/sant
:copyright: (c) 2014 by xiong.xiaox(xiong.xiaox@alibaba-inc.com).
"""
from flask_wtf import Form
from wtforms import TextField
from wtforms.validators import Required, IPAddress
... |
18cc17e3f2ac36c0087b1867fcd18d0e876c34b8 | tracker/src/main/scripts/launch-workflow.py | tracker/src/main/scripts/launch-workflow.py | import sys
import os
import uuid
from time import sleep
if len(sys.argv) != 3:
print "Wrong number of args"
exit(1)
workflow_name = sys.argv[1]
num_runs = int(sys.argv[2])
for this_run in range(num_runs):
run_uuid = str(uuid.uuid4())
launch_command = "airflow trigger_dag -r " + run_uuid... | import sys
import os
import uuid
from time import sleep
if len(sys.argv) != 3:
print "Wrong number of args"
exit(1)
workflow_name = sys.argv[1]
num_runs = int(sys.argv[2])
for this_run in range(num_runs):
run_uuid = str(uuid.uuid4())
launch_command = "airflow trigger_dag -r " + run_uuid... | Use longer sleep time for workflow launcher. | Use longer sleep time for workflow launcher.
| Python | mit | llevar/germline-regenotyper,llevar/germline-regenotyper | import sys
import os
import uuid
from time import sleep
if len(sys.argv) != 3:
print "Wrong number of args"
exit(1)
workflow_name = sys.argv[1]
num_runs = int(sys.argv[2])
for this_run in range(num_runs):
run_uuid = str(uuid.uuid4())
launch_command = "airflow trigger_dag -r " + run_uuid... | Use longer sleep time for workflow launcher.
import sys
import os
import uuid
from time import sleep
if len(sys.argv) != 3:
print "Wrong number of args"
exit(1)
workflow_name = sys.argv[1]
num_runs = int(sys.argv[2])
for this_run in range(num_runs):
run_uuid = str(uuid.uuid4())
launch_... |
4a032ece106d4b3b3764420197453afd33475bf6 | donut/modules/permissions/helpers.py | donut/modules/permissions/helpers.py | import flask
from donut.modules.groups import helpers as groups
def has_permission(user_id, permission_id):
'''
Returns True if [user_id] holds a position that directly
or indirectly (through a position relation) grants
them [permission_id]. Otherwise returns False.
'''
if not (isinstance(u... | import flask
from donut.modules.groups import helpers as groups
def has_permission(user_id, permission_id):
'''
Returns True if [user_id] holds a position that directly
or indirectly (through a position relation) grants
them [permission_id]. Otherwise returns False.
'''
if not (isinstance(u... | Fix failing test and make lint | Fix failing test and make lint
| Python | mit | ASCIT/donut-python,ASCIT/donut,ASCIT/donut,ASCIT/donut-python,ASCIT/donut | import flask
from donut.modules.groups import helpers as groups
def has_permission(user_id, permission_id):
'''
Returns True if [user_id] holds a position that directly
or indirectly (through a position relation) grants
them [permission_id]. Otherwise returns False.
'''
if not (isinstance(u... | Fix failing test and make lint
import flask
from donut.modules.groups import helpers as groups
def has_permission(user_id, permission_id):
'''
Returns True if [user_id] holds a position that directly
or indirectly (through a position relation) grants
them [permission_id]. Otherwise returns False.
... |
3a57d826a957b864753895d8769dcf747d489e1b | administrator/serializers.py | administrator/serializers.py | from categories.models import Category, Keyword, Subcategory
from rest_framework import serializers
class SubcategoryListSerializer(serializers.ModelSerializer):
class Meta:
model = Subcategory
fields = ('pk', 'name')
class CategorySerializer(serializers.ModelSerializer):
subcategories = Sub... | from categories.models import Category, Keyword, Subcategory
from rest_framework import serializers
class SubcategoryListSerializer(serializers.ModelSerializer):
class Meta:
model = Subcategory
fields = ('pk', 'name')
class CategorySerializer(serializers.ModelSerializer):
subcategories = Sub... | Remove category serializer from subcategory serializer | Remove category serializer from subcategory serializer
| Python | apache-2.0 | belatrix/BackendAllStars | from categories.models import Category, Keyword, Subcategory
from rest_framework import serializers
class SubcategoryListSerializer(serializers.ModelSerializer):
class Meta:
model = Subcategory
fields = ('pk', 'name')
class CategorySerializer(serializers.ModelSerializer):
subcategories = Sub... | Remove category serializer from subcategory serializer
from categories.models import Category, Keyword, Subcategory
from rest_framework import serializers
class SubcategoryListSerializer(serializers.ModelSerializer):
class Meta:
model = Subcategory
fields = ('pk', 'name')
class CategorySerializ... |
783ce62c7dd6b553c37c984113a0964fa1837e76 | whats_fresh/settings.py | whats_fresh/settings.py | # flake8: noqa
# This module is how we import settings, and override settings with various
# precedences.
# First our base.py settings module is imported, with all of the
# important defaults.
#
# Next our yaml file is opened, read, and settings defined in the yaml config
# may override settings already defined.
impo... | # flake8: noqa
# This module is how we import settings, and override settings with various
# precedences.
# First our base.py settings module is imported, with all of the
# important defaults.
#
# Next our yaml file is opened, read, and settings defined in the yaml config
# may override settings already defined.
impo... | Use dict.get not dict[] to fail gracefully | Use dict.get not dict[] to fail gracefully
| Python | apache-2.0 | osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api | # flake8: noqa
# This module is how we import settings, and override settings with various
# precedences.
# First our base.py settings module is imported, with all of the
# important defaults.
#
# Next our yaml file is opened, read, and settings defined in the yaml config
# may override settings already defined.
impo... | Use dict.get not dict[] to fail gracefully
# flake8: noqa
# This module is how we import settings, and override settings with various
# precedences.
# First our base.py settings module is imported, with all of the
# important defaults.
#
# Next our yaml file is opened, read, and settings defined in the yaml config
# ... |
259555775c098153b1715f85561309b42e29ee7d | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
from avena import avena
_classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Progra... | #!/usr/bin/env python
from distutils.core import setup
from avena import avena
_classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Progra... | Install the script with the library. | Install the script with the library.
| Python | isc | eliteraspberries/avena | #!/usr/bin/env python
from distutils.core import setup
from avena import avena
_classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Progra... | Install the script with the library.
#!/usr/bin/env python
from distutils.core import setup
from avena import avena
_classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating ... |
40f8190029cf1431a14cd74dfab515d7bb106dd4 | pyscores/api_wrapper.py | pyscores/api_wrapper.py | import json
import os
import requests
class APIWrapper(object):
def __init__(self, base_url=None, auth_token=None):
if base_url:
self.base_url = base_url
else:
self.base_url = "http://api.football-data.org/v1"
if auth_token:
self.headers = {
... | Add the start of an api wrapper | Add the start of an api wrapper
| Python | mit | conormag94/pyscores | import json
import os
import requests
class APIWrapper(object):
def __init__(self, base_url=None, auth_token=None):
if base_url:
self.base_url = base_url
else:
self.base_url = "http://api.football-data.org/v1"
if auth_token:
self.headers = {
... | Add the start of an api wrapper
| |
f82861e1698d101dc61ca8891b38e68f57262334 | chroma-manager/chroma_cli/commands/__init__.py | chroma-manager/chroma_cli/commands/__init__.py | #
# ========================================================
# Copyright (c) 2012 Whamcloud, Inc. All rights reserved.
# ========================================================
from chroma_cli.commands.dispatcher import CommandDispatcher
CommandDispatcher # stupid pyflakes
| #
# ========================================================
# Copyright (c) 2012 Whamcloud, Inc. All rights reserved.
# ========================================================
| Remove some cruft that was accidentally pushed | Remove some cruft that was accidentally pushed
Change-Id: If75577316398c9d02230882766463f00aa13efd9
| Python | mit | intel-hpdd/intel-manager-for-lustre,intel-hpdd/intel-manager-for-lustre,intel-hpdd/intel-manager-for-lustre | #
# ========================================================
# Copyright (c) 2012 Whamcloud, Inc. All rights reserved.
# ========================================================
| Remove some cruft that was accidentally pushed
Change-Id: If75577316398c9d02230882766463f00aa13efd9
#
# ========================================================
# Copyright (c) 2012 Whamcloud, Inc. All rights reserved.
# ========================================================
from chroma_cli.commands.dispatcher i... |
49263d5e43be6ab9a5c3faf2ee6478840526cccb | flatten-array/flatten_array.py | flatten-array/flatten_array.py | def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
if isinstance(lst, (list, tuple)):
for item in lst:
if item is None:
continue
else:
... | def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
for item in lst:
if isinstance(item, (list, tuple)):
yield from _flatten(item)
elif item is not None:
... | Tidy and simplify generator code | Tidy and simplify generator code
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
for item in lst:
if isinstance(item, (list, tuple)):
yield from _flatten(item)
elif item is not None:
... | Tidy and simplify generator code
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
if isinstance(lst, (list, tuple)):
for item in lst:
if item is None:
... |
645cbd9a4445898f69b1ecd9f3db7d5e7b7b9dbd | libqtile/layout/__init__.py | libqtile/layout/__init__.py | from stack import Stack
from max import Max
from tile import Tile
from floating import Floating
from ratiotile import RatioTile
from tree import TreeTab
from slice import Slice
| from stack import Stack
from max import Max
from tile import Tile
from floating import Floating
from ratiotile import RatioTile
from tree import TreeTab
from slice import Slice
from xmonad import MonadTall
| Add MonadTall to layout module proper. | Add MonadTall to layout module proper.
Fixes #126
| Python | mit | nxnfufunezn/qtile,qtile/qtile,de-vri-es/qtile,jdowner/qtile,tych0/qtile,w1ndy/qtile,soulchainer/qtile,rxcomm/qtile,flacjacket/qtile,w1ndy/qtile,ramnes/qtile,andrewyoung1991/qtile,frostidaho/qtile,himaaaatti/qtile,cortesi/qtile,encukou/qtile,himaaaatti/qtile,de-vri-es/qtile,kopchik/qtile,qtile/qtile,zordsdavini/qtile,St... | from stack import Stack
from max import Max
from tile import Tile
from floating import Floating
from ratiotile import RatioTile
from tree import TreeTab
from slice import Slice
from xmonad import MonadTall
| Add MonadTall to layout module proper.
Fixes #126
from stack import Stack
from max import Max
from tile import Tile
from floating import Floating
from ratiotile import RatioTile
from tree import TreeTab
from slice import Slice
|
811eab1329a02a36244b7a8f79c23bf5bfce4dc6 | spotpy/unittests/test_objectivefunctions.py | spotpy/unittests/test_objectivefunctions.py | import unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
... | Add tests for bias and length mismatch | Add tests for bias and length mismatch
| Python | mit | thouska/spotpy,thouska/spotpy,bees4ever/spotpy,thouska/spotpy,bees4ever/spotpy,bees4ever/spotpy | import unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
... | Add tests for bias and length mismatch
| |
4bef46ef98591d47d653eeb4f74bf00a8a1d5d69 | correios/utils.py | correios/utils.py | from itertools import chain
from typing import Sized, Iterable, Container, Set
class RangeSet(Sized, Iterable, Container):
def __init__(self, *ranges):
self.ranges = []
for r in ranges:
if isinstance(r, range):
r = [r]
elif isinstance(r, RangeSet):
... | from itertools import chain
from typing import Container, Iterable, Sized
class RangeSet(Sized, Iterable, Container):
def __init__(self, *ranges):
self.ranges = []
for r in ranges:
if isinstance(r, range):
self.ranges.append(r)
continue
try... | Use duck typing when creating a RangeSet | Use duck typing when creating a RangeSet
| Python | apache-2.0 | osantana/correios,solidarium/correios,olist/correios | from itertools import chain
from typing import Container, Iterable, Sized
class RangeSet(Sized, Iterable, Container):
def __init__(self, *ranges):
self.ranges = []
for r in ranges:
if isinstance(r, range):
self.ranges.append(r)
continue
try... | Use duck typing when creating a RangeSet
from itertools import chain
from typing import Sized, Iterable, Container, Set
class RangeSet(Sized, Iterable, Container):
def __init__(self, *ranges):
self.ranges = []
for r in ranges:
if isinstance(r, range):
r = [r]
... |
82796dfb24c3e65b669d4336948e76e2a64cf73f | LR/lr/model/node_service.py | LR/lr/model/node_service.py | #!/usr/bin/pyton
# Copyright 2011 Lockheed Martin
'''
Created on Mar 17, 2011
Base model class for learning registry data model
@author: jpoyau
'''
from base_model import createBaseModel, ModelParser, defaultCouchServer, appConfig
from pylons import *
import datetime, logging
log = logging.getLogger(__name__)... | #!/usr/bin/pyton
# Copyright 2011 Lockheed Martin
'''
Created on Mar 17, 2011
Base model class for learning registry data model
@author: jpoyau
'''
from base_model import createBaseModel, ModelParser, defaultCouchServer, appConfig
from pylons import *
import datetime, logging
log = logging.getLogger(__name__)... | Add 'distribute' to the node services | Add 'distribute' to the node services
| Python | apache-2.0 | jimklo/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningR... | #!/usr/bin/pyton
# Copyright 2011 Lockheed Martin
'''
Created on Mar 17, 2011
Base model class for learning registry data model
@author: jpoyau
'''
from base_model import createBaseModel, ModelParser, defaultCouchServer, appConfig
from pylons import *
import datetime, logging
log = logging.getLogger(__name__)... | Add 'distribute' to the node services
#!/usr/bin/pyton
# Copyright 2011 Lockheed Martin
'''
Created on Mar 17, 2011
Base model class for learning registry data model
@author: jpoyau
'''
from base_model import createBaseModel, ModelParser, defaultCouchServer, appConfig
from pylons import *
import datetime, log... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.