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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
bc1409937a16698bdef21c0ec90d8b823db0bb97 | rackattack/physical/logconfig.py | rackattack/physical/logconfig.py | import logging
from rackattack.ssh import connection
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.getLogger('network').setLevel(logging.DEBUG)
logging.getLogger('network').propagate = False
logging.getLogger().setLevel(logging.DEBUG)
handler = logging.StreamHandler()
ha... | import logging
from rackattack.ssh import connection
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.getLogger('network').setLevel(logging.ERROR)
logging.getLogger('network').propagate = False
logging.getLogger().setLevel(logging.DEBUG)
handler = logging.StreamHandler()
ha... | Set the log level of the network logger to ERROR, since it's less needed now | Set the log level of the network logger to ERROR, since it's less needed now
| Python | apache-2.0 | eliran-stratoscale/rackattack-physical,Stratoscale/rackattack-physical,eliran-stratoscale/rackattack-physical,Stratoscale/rackattack-physical | import logging
from rackattack.ssh import connection
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.getLogger('network').setLevel(logging.ERROR)
logging.getLogger('network').propagate = False
logging.getLogger().setLevel(logging.DEBUG)
handler = logging.StreamHandler()
ha... | Set the log level of the network logger to ERROR, since it's less needed now
import logging
from rackattack.ssh import connection
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.getLogger('network').setLevel(logging.DEBUG)
logging.getLogger('network').propagate = False
lo... |
148af8380b93af6771541397e6956ed05f4fc0de | cogbot/extensions/faq.py | cogbot/extensions/faq.py | import json
import logging
import urllib.request
from discord.ext import commands
from discord.ext.commands import CommandError, Context
from cogbot import checks
from cogbot.cog_bot import CogBot
log = logging.getLogger(__name__)
class FaqConfig:
def __init__(self, **options):
self.database = options[... | Implement basic FAQ command with remote config | Implement basic FAQ command with remote config
| Python | mit | Arcensoth/cogbot | import json
import logging
import urllib.request
from discord.ext import commands
from discord.ext.commands import CommandError, Context
from cogbot import checks
from cogbot.cog_bot import CogBot
log = logging.getLogger(__name__)
class FaqConfig:
def __init__(self, **options):
self.database = options[... | Implement basic FAQ command with remote config
| |
50926966919fa5cf140e3f30815f86c93189cc49 | percy/utils.py | percy/utils.py | from __future__ import print_function
import sys
import hashlib
import base64
def print_error(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def to_unicode(content):
# TODO: considering using the 'six' library for this, for now just do something simple.
if sys.version_info >= (3,0):
ret... | from __future__ import print_function
import sys
import hashlib
import base64
def print_error(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def to_unicode(content):
# TODO: considering using the 'six' library for this, for now just do something simple.
if sys.version_info >= (3,0):
ret... | Return serializable string from base64encode. | Return serializable string from base64encode.
| Python | mit | percy/python-percy-client | from __future__ import print_function
import sys
import hashlib
import base64
def print_error(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def to_unicode(content):
# TODO: considering using the 'six' library for this, for now just do something simple.
if sys.version_info >= (3,0):
ret... | Return serializable string from base64encode.
from __future__ import print_function
import sys
import hashlib
import base64
def print_error(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def to_unicode(content):
# TODO: considering using the 'six' library for this, for now just do something simple... |
b8688879de84b405d8c54add3ca793df54e2f39a | bin/finnpos-restore-lemma.py | bin/finnpos-restore-lemma.py | #! /usr/bin/env python3
from sys import stdin
for line in stdin:
line = line.strip()
if line == '':
print('')
else:
wf, feats, lemma, label, ann = line.split('\t')
lemmas = ann
if ann.find(' ') != -1:
lemmas = ann[:ann.find(' ')]
ann = [ann.find(' ... | #! /usr/bin/env python3
from sys import stdin
def part_count(lemma):
return lemma.count('#')
def compile_dict(label_lemma_pairs):
res = {}
for label, lemma in label_lemma_pairs:
if label in res:
old_lemma = res[label]
if part_count(old_lemma) > part_count(lemma):
... | Choose lemma with fewest parts. | Choose lemma with fewest parts.
| Python | apache-2.0 | mpsilfve/FinnPos,mpsilfve/FinnPos,mpsilfve/FinnPos,mpsilfve/FinnPos | #! /usr/bin/env python3
from sys import stdin
def part_count(lemma):
return lemma.count('#')
def compile_dict(label_lemma_pairs):
res = {}
for label, lemma in label_lemma_pairs:
if label in res:
old_lemma = res[label]
if part_count(old_lemma) > part_count(lemma):
... | Choose lemma with fewest parts.
#! /usr/bin/env python3
from sys import stdin
for line in stdin:
line = line.strip()
if line == '':
print('')
else:
wf, feats, lemma, label, ann = line.split('\t')
lemmas = ann
if ann.find(' ') != -1:
lemmas = ann[:ann.find(' '... |
7af339d68d31e402df3a70b6596927439de0f2aa | doc/mkapidoc.py | doc/mkapidoc.py | #!/usr/bin/env python
# Generates the API documentation.
import os, re, sys
project = 'Exscript'
base_dir = os.path.join('..', 'src', project)
doc_dir = 'api'
# Create the documentation directory.
if not os.path.exists(doc_dir):
os.makedirs(doc_dir)
# Generate the API documentation.
os.system('epydoc ' + ' '.j... | #!/usr/bin/env python
# Generates the API documentation.
import os, re, sys
project = 'Exscript'
base_dir = os.path.join('..', 'src', project)
doc_dir = 'api'
# Create the documentation directory.
if not os.path.exists(doc_dir):
os.makedirs(doc_dir)
# Generate the API documentation.
os.system('epydoc ' + ' '.j... | Hide Exscript.protocols.AbstractMethod from the API docs. | Hide Exscript.protocols.AbstractMethod from the API docs.
| Python | mit | maximumG/exscript,knipknap/exscript,maximumG/exscript,knipknap/exscript | #!/usr/bin/env python
# Generates the API documentation.
import os, re, sys
project = 'Exscript'
base_dir = os.path.join('..', 'src', project)
doc_dir = 'api'
# Create the documentation directory.
if not os.path.exists(doc_dir):
os.makedirs(doc_dir)
# Generate the API documentation.
os.system('epydoc ' + ' '.j... | Hide Exscript.protocols.AbstractMethod from the API docs.
#!/usr/bin/env python
# Generates the API documentation.
import os, re, sys
project = 'Exscript'
base_dir = os.path.join('..', 'src', project)
doc_dir = 'api'
# Create the documentation directory.
if not os.path.exists(doc_dir):
os.makedirs(doc_dir)
# ... |
0eb7e39c726ced0e802de925c7ce3b3ec35c61d9 | src/billing/factories.py | src/billing/factories.py | import factory
import random
from billing.models import Billing, OrderBilling
from member.factories import ClientFactory
from order.factories import OrderFactory
class BillingFactory(factory.DjangoModelFactory):
class Meta:
model = Billing
client = factory.SubFactory(ClientFactory)
total_amount... | import factory
import random
from billing.models import Billing, OrderBilling
from member.factories import ClientFactory
from order.factories import OrderFactory
class BillingFactory(factory.DjangoModelFactory):
class Meta:
model = Billing
client = factory.SubFactory(ClientFactory)
total_amount... | Remove a BillingOrder factory class that wasn't use | Remove a BillingOrder factory class that wasn't use
There was a problem with this class... but since I couldn't find
code using it, I simply deleted it.
| Python | agpl-3.0 | savoirfairelinux/santropol-feast,madmath/sous-chef,savoirfairelinux/santropol-feast,savoirfairelinux/sous-chef,savoirfairelinux/sous-chef,madmath/sous-chef,savoirfairelinux/santropol-feast,madmath/sous-chef,savoirfairelinux/sous-chef | import factory
import random
from billing.models import Billing, OrderBilling
from member.factories import ClientFactory
from order.factories import OrderFactory
class BillingFactory(factory.DjangoModelFactory):
class Meta:
model = Billing
client = factory.SubFactory(ClientFactory)
total_amount... | Remove a BillingOrder factory class that wasn't use
There was a problem with this class... but since I couldn't find
code using it, I simply deleted it.
import factory
import random
from billing.models import Billing, OrderBilling
from member.factories import ClientFactory
from order.factories import OrderFactory
c... |
c29ec289d8fe252aa8fd8d913abb3f1bd263eab1 | scripts/web-server/alexa-pi.py | scripts/web-server/alexa-pi.py | from flask import Flask
from flask_ask import Ask, statement, convert_errors
import logging
from rfsend import rf_send
GPIO.setmode(GPIO.BCM)
app = Flask(__name__)
ask = Ask(app, '/')
logging.getLogger("flask_ask").setLevel(logging.DEBUG)
@ask.intent('LocationControlIntent', mapping={'status': 'status', 'location':... | Add Raspberry PI Alexa control server | Add Raspberry PI Alexa control server
| Python | bsd-3-clause | kbsezginel/raspberry-pi,kbsezginel/raspberry-pi,kbsezginel/raspberry-pi,kbsezginel/raspberry-pi | from flask import Flask
from flask_ask import Ask, statement, convert_errors
import logging
from rfsend import rf_send
GPIO.setmode(GPIO.BCM)
app = Flask(__name__)
ask = Ask(app, '/')
logging.getLogger("flask_ask").setLevel(logging.DEBUG)
@ask.intent('LocationControlIntent', mapping={'status': 'status', 'location':... | Add Raspberry PI Alexa control server
| |
d8bd544112ee268a58cc24be148d4b672a488128 | parse_dump.py | parse_dump.py | #!/usr/bin/python
#
# Copyright (c) 2007-2008 The PyAMF Project.
# See LICENSE for details.
"""
Extracts and displays information for files that contain AMF data.
"""
import glob
from optparse import OptionParser
from fnmatch import fnmatch
import pyamf
from pyamf import remoting
def parse_options():
"""
Pa... | Move ParseDump script to dumps folder. | Move ParseDump script to dumps folder.
| Python | mit | thijstriemstra/pyamf-dumps | #!/usr/bin/python
#
# Copyright (c) 2007-2008 The PyAMF Project.
# See LICENSE for details.
"""
Extracts and displays information for files that contain AMF data.
"""
import glob
from optparse import OptionParser
from fnmatch import fnmatch
import pyamf
from pyamf import remoting
def parse_options():
"""
Pa... | Move ParseDump script to dumps folder.
| |
b36f2518666572ccd3b98dd88536533e17a39e3f | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Server',
version='1.0',
description='REST Backend for SpaceScout',
install_requires=[
'Django>=1.7,<1.8',
'mock<=1.0.1',
'oauth2<=1.5.211',
... | #!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Server',
version='1.0',
description='REST Backend for SpaceScout',
install_requires=[
'Django>=1.7,<1.8',
'mock<=1.0.1',
'oauth2<=1.5.211',
... | Remove oauth_provider as that's the eggname for django-oauth-plus. | Remove oauth_provider as that's the eggname for django-oauth-plus.
| Python | apache-2.0 | uw-it-aca/spotseeker_server,uw-it-aca/spotseeker_server,uw-it-aca/spotseeker_server | #!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Server',
version='1.0',
description='REST Backend for SpaceScout',
install_requires=[
'Django>=1.7,<1.8',
'mock<=1.0.1',
'oauth2<=1.5.211',
... | Remove oauth_provider as that's the eggname for django-oauth-plus.
#!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Server',
version='1.0',
description='REST Backend for SpaceScout',
install_requires=[
'Django>=1.7,<1.8',
... |
172d3eecfbd92671a941303eff777436780c7d5e | setup.py | setup.py | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='windpowerlib',
version='0.2.0dev',
description='Creating time series of wind power plants.',
url='http://github.com/wind-python/windpowerlib',
author='oe... | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='windpowerlib',
version='0.2.0dev',
description='Creating time series of wind power plants.',
url='http://github.com/wind-python/windpowerlib',
author='oe... | Add new oedb data directory to package | Add new oedb data directory to package
| Python | mit | wind-python/windpowerlib | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='windpowerlib',
version='0.2.0dev',
description='Creating time series of wind power plants.',
url='http://github.com/wind-python/windpowerlib',
author='oe... | Add new oedb data directory to package
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='windpowerlib',
version='0.2.0dev',
description='Creating time series of wind power plants.',
url='http://github.com/win... |
7ce8e8e217e80098ce2b6371dd6c117009843602 | pyxform/tests_v1/test_whitespace.py | pyxform/tests_v1/test_whitespace.py | from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class WhitespaceTest(PyxformTestCase):
def test_over_trim(self):
self.assertPyxformXform(
name='issue96',
md="""
| survey | | | |
| | type | l... | from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class WhitespaceTest(PyxformTestCase):
def test_over_trim(self):
self.assertPyxformXform(
name='issue96',
md="""
| survey | | | |
| | type | l... | Remove test that can't be fulfilled | Remove test that can't be fulfilled
| Python | bsd-2-clause | XLSForm/pyxform,XLSForm/pyxform | from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class WhitespaceTest(PyxformTestCase):
def test_over_trim(self):
self.assertPyxformXform(
name='issue96',
md="""
| survey | | | |
| | type | l... | Remove test that can't be fulfilled
from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class WhitespaceTest(PyxformTestCase):
def test_over_trim(self):
self.assertPyxformXform(
name='issue96',
md="""
| survey | | | |
... |
bf93b3b4c8965e31e5b9b8ebdbf3f1b1d258e15e | tools/cvs2svn/profile-cvs2svn.py | tools/cvs2svn/profile-cvs2svn.py | #!/usr/bin/env python
#
# Use this script to profile cvs2svn.py using Python's hotshot profiler.
#
# The profile data is stored in cvs2svn.hotshot. To view the data using
# hotshot, run the following in python:
#
# import hotshot.stats
# stats = hotshot.stats.load('cvs2svn.hotshot')
# stats.strip_dirs(... | Add a new script to simplify profiling of cvs2svn.py. Document in the script how to use kcachegrind to view the results. | Add a new script to simplify profiling of cvs2svn.py. Document in the
script how to use kcachegrind to view the results.
* tools/cvs2svn/profile-cvs2svn.py: New script.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@848715 13f79535-47bb-0310-9956-ffa450edef68
| Python | apache-2.0 | YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,wbond/subversion,wbond/subversion,wbond/subversion | #!/usr/bin/env python
#
# Use this script to profile cvs2svn.py using Python's hotshot profiler.
#
# The profile data is stored in cvs2svn.hotshot. To view the data using
# hotshot, run the following in python:
#
# import hotshot.stats
# stats = hotshot.stats.load('cvs2svn.hotshot')
# stats.strip_dirs(... | Add a new script to simplify profiling of cvs2svn.py. Document in the
script how to use kcachegrind to view the results.
* tools/cvs2svn/profile-cvs2svn.py: New script.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@848715 13f79535-47bb-0310-9956-ffa450edef68
| |
2d4a3b82d982017fe51e2dd23eca7f1d83ad115f | plugoo/assets.py | plugoo/assets.py | class Asset:
"""
This is an ooni-probe asset. It is a python
iterator object, allowing it to be efficiently looped.
To create your own custom asset your should subclass this
and override the next_asset method and the len method for
computing the length of the asset.
"""
def __init__(self... | class Asset:
"""
This is an ooni-probe asset. It is a python
iterator object, allowing it to be efficiently looped.
To create your own custom asset your should subclass this
and override the next_asset method and the len method for
computing the length of the asset.
"""
def __init__(self... | Add a method for line by line asset parsing | Add a method for line by line asset parsing
| Python | bsd-2-clause | Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,lordappsec/ooni-probe,0xPoly/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,0xPoly/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,juga0/ooni-probe,kdmurray91/ooni-probe,hackerb... | class Asset:
"""
This is an ooni-probe asset. It is a python
iterator object, allowing it to be efficiently looped.
To create your own custom asset your should subclass this
and override the next_asset method and the len method for
computing the length of the asset.
"""
def __init__(self... | Add a method for line by line asset parsing
class Asset:
"""
This is an ooni-probe asset. It is a python
iterator object, allowing it to be efficiently looped.
To create your own custom asset your should subclass this
and override the next_asset method and the len method for
computing the lengt... |
6f995fbe0532fc4ea36f3f7cd24240d3525b115f | Ref.py | Ref.py | """
MoinMoin - Ref Macro
Collect and emit footnotes. Note that currently footnote
text cannot contain wiki markup.
@copyright: 2011 Jason L. Wright <jason@thought.net>
@license: BSD
"""
from MoinMoin import config, wikiutil
from MoinMoin.parser.text_moin_wiki import Parser as WikiParser
from Moin... | """
MoinMoin - Ref Macro
Collect and emit references (as footnotes)
@copyright: 2011 Jason L. Wright <jason@thought.net>
@license: BSD
"""
from MoinMoin import config, wikiutil
from MoinMoin.parser.text_moin_wiki import Parser as WikiParser
from MoinMoin.support.python_compatibility import hash_new
i... | Update text to reflect current usage | Update text to reflect current usage
| Python | bsd-2-clause | wrigjl/moin-ref-bibtex | """
MoinMoin - Ref Macro
Collect and emit references (as footnotes)
@copyright: 2011 Jason L. Wright <jason@thought.net>
@license: BSD
"""
from MoinMoin import config, wikiutil
from MoinMoin.parser.text_moin_wiki import Parser as WikiParser
from MoinMoin.support.python_compatibility import hash_new
i... | Update text to reflect current usage
"""
MoinMoin - Ref Macro
Collect and emit footnotes. Note that currently footnote
text cannot contain wiki markup.
@copyright: 2011 Jason L. Wright <jason@thought.net>
@license: BSD
"""
from MoinMoin import config, wikiutil
from MoinMoin.parser.text_moin_wiki... |
cbd8521891c97c1655a3b89863e1a2170d9edc6b | examples/missing_constants.py | examples/missing_constants.py | import numpy as np
from molml.features import Connectivity
from molml.constants import BOND_LENGTHS
# Currently, there are two recommended ways to work with elements that are not
# included in molml/constants.py. In this example, we will look at an iron
# complex (iron is not in the constants).
# Maybe at some point,... | Add an example script with missing constants | Add an example script with missing constants
| Python | mit | crcollins/molml | import numpy as np
from molml.features import Connectivity
from molml.constants import BOND_LENGTHS
# Currently, there are two recommended ways to work with elements that are not
# included in molml/constants.py. In this example, we will look at an iron
# complex (iron is not in the constants).
# Maybe at some point,... | Add an example script with missing constants
| |
54c48073dfb8ffd418efe234c0c107f7a5c303a9 | svg/templatetags/svg.py | svg/templatetags/svg.py | import logging
import os
from django import template
from django.conf import settings
from django.contrib.staticfiles import finders
from django.utils.safestring import mark_safe
from svg.exceptions import SVGNotFound
logger = logging.getLogger(__name__)
register = template.Library()
@register.simple_tag
def svg(f... | from __future__ import absolute_import
import logging
import os
from django import template
from django.conf import settings
from django.contrib.staticfiles import finders
from django.utils.safestring import mark_safe
from svg.exceptions import SVGNotFound
logger = logging.getLogger(__name__)
register = template.Lib... | Fix failing imports in Python 2 | Fix failing imports in Python 2
| Python | mit | mixxorz/django-inline-svg | from __future__ import absolute_import
import logging
import os
from django import template
from django.conf import settings
from django.contrib.staticfiles import finders
from django.utils.safestring import mark_safe
from svg.exceptions import SVGNotFound
logger = logging.getLogger(__name__)
register = template.Lib... | Fix failing imports in Python 2
import logging
import os
from django import template
from django.conf import settings
from django.contrib.staticfiles import finders
from django.utils.safestring import mark_safe
from svg.exceptions import SVGNotFound
logger = logging.getLogger(__name__)
register = template.Library()... |
1a0e277d23dfc41fc03799edde2a650b89cbcced | src/utils/utils.py | src/utils/utils.py | import logging
LOGGER = logging.getLogger(__name__)
def tidy_up_url(url):
if url.startswith("//"):
# If no protocol was supplied, add https
url = "https:" + url
if '?' in url:
url = url[:url.rfind('?')]
return url
def limit_file_name(file_name, length=65):
if len(file_name)... | import logging
LOGGER = logging.getLogger(__name__)
def tidy_up_url(url):
if url.startswith("//"):
# If no protocol was supplied, add https
url = "https:" + url
if '?' in url:
url = url[:url.rfind('?')]
if url.endswith("/"):
url = url[:-1]
return url
def limit_file... | Make sure that the Imgur ID can be correctly extracted from the URL | Make sure that the Imgur ID can be correctly extracted from the URL
This was made to address the case where the URL might end with '/'
| Python | apache-2.0 | CharlieCorner/pymage_downloader | import logging
LOGGER = logging.getLogger(__name__)
def tidy_up_url(url):
if url.startswith("//"):
# If no protocol was supplied, add https
url = "https:" + url
if '?' in url:
url = url[:url.rfind('?')]
if url.endswith("/"):
url = url[:-1]
return url
def limit_file... | Make sure that the Imgur ID can be correctly extracted from the URL
This was made to address the case where the URL might end with '/'
import logging
LOGGER = logging.getLogger(__name__)
def tidy_up_url(url):
if url.startswith("//"):
# If no protocol was supplied, add https
url = "https:" + url... |
0adc28fffafbce685dc74009891ced9333b76eb9 | minify.py | minify.py | """A Pelican plugin which minifies HTML pages."""
from logging import getLogger
from os import walk
from os.path import join
from htmlmin.minify import html_minify as min
from pelican import signals
logger = getLogger(__name__)
def minify_html(pelican):
"""Minify all HTML files.
:param pelican: The Peli... | """A Pelican plugin which minifies HTML pages."""
from logging import getLogger
from os import walk
from os.path import join
import sys
from htmlmin.minify import html_minify as min
from pelican import signals
# we need save unicode strings to files
if sys.version_info[0] < 3:
import codecs
_open_func_bak ... | Save unicode strings to file | Save unicode strings to file
Fix for #1 'ascii' codec can't encode character... | Python | unlicense | rdegges/pelican-minify | """A Pelican plugin which minifies HTML pages."""
from logging import getLogger
from os import walk
from os.path import join
import sys
from htmlmin.minify import html_minify as min
from pelican import signals
# we need save unicode strings to files
if sys.version_info[0] < 3:
import codecs
_open_func_bak ... | Save unicode strings to file
Fix for #1 'ascii' codec can't encode character...
"""A Pelican plugin which minifies HTML pages."""
from logging import getLogger
from os import walk
from os.path import join
from htmlmin.minify import html_minify as min
from pelican import signals
logger = getLogger(__name__)
def ... |
011111f423d8a50fc66a383c0f28c76a9854105a | heat/tests/test_barbican_client.py | heat/tests/test_barbican_client.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
# ... | Add test for barbican client | Add test for barbican client
Change-Id: I9236e62f3259cfd560e3837830191012d107e853
Partial-Bug: #1461967
| Python | apache-2.0 | jasondunsmore/heat,cryptickp/heat,noironetworks/heat,cwolferh/heat-scratch,maestro-hybrid-cloud/heat,noironetworks/heat,rh-s/heat,miguelgrinberg/heat,jasondunsmore/heat,steveb/heat,gonzolino/heat,dragorosson/heat,pratikmallya/heat,srznew/heat,steveb/heat,dims/heat,pratikmallya/heat,dragorosson/heat,cwolferh/heat-scratc... | #
# 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
# ... | Add test for barbican client
Change-Id: I9236e62f3259cfd560e3837830191012d107e853
Partial-Bug: #1461967
| |
d1171195e771b3de4a40c3773d10f5d0837da2b2 | setup.py | setup.py | import os
import sys
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
requirements = ['httplib2', 'argparse', 'prettytable']
if sys.version_info < (2, 6):
requirements.append('simplejson')
setup(
name = "python-keystoneclient... | import os
import sys
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
requirements = ['httplib2', 'argparse', 'prettytable']
if sys.version_info < (2, 6):
requirements.append('simplejson')
setup(
name = "python-keystoneclient... | Adjust version number to match other deliveries | Adjust version number to match other deliveries
Set version from 2.7 to 2012.1 to match the other OpenStack
Keystone deliveries (python-keystoneclient will be released
as part of Keystone 2012.1~e3). Also adjusted the location
of the git repository to match new location. Fixes bug 917656.
Change-Id: I4d8d071e3cdc5665... | Python | apache-2.0 | citrix-openstack-build/python-keystoneclient,Mercador/python-keystoneclient,sdpp/python-keystoneclient,jamielennox/python-keystoneclient,ntt-sic/python-keystoneclient,klmitch/python-keystoneclient,jamielennox/python-keystoneclient,dolph/python-keystoneclient,Mercador/python-keystoneclient,dolph/python-keystoneclient,ja... | import os
import sys
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
requirements = ['httplib2', 'argparse', 'prettytable']
if sys.version_info < (2, 6):
requirements.append('simplejson')
setup(
name = "python-keystoneclient... | Adjust version number to match other deliveries
Set version from 2.7 to 2012.1 to match the other OpenStack
Keystone deliveries (python-keystoneclient will be released
as part of Keystone 2012.1~e3). Also adjusted the location
of the git repository to match new location. Fixes bug 917656.
Change-Id: I4d8d071e3cdc5665... |
2de06cda19c2d50c1362c9babd7c4bce735fb44a | product_configurator_mrp/__manifest__.py | product_configurator_mrp/__manifest__.py | {
'name': 'Product Configurator Manufacturing',
'version': '11.0.1.0.0',
'category': 'Manufacturing',
'summary': 'BOM Support for configurable products',
'author': 'Pledra',
'license': 'AGPL-3',
'website': 'http://www.pledra.com/',
'depends': ['mrp', 'product_configurator'],
"data": ... | {
'name': 'Product Configurator Manufacturing',
'version': '11.0.1.0.0',
'category': 'Manufacturing',
'summary': 'BOM Support for configurable products',
'author': 'Pledra',
'license': 'AGPL-3',
'website': 'http://www.pledra.com/',
'depends': ['mrp', 'product_configurator'],
"data": ... | Set product_configurator_mrp to uninstallable until fixing / refactoring | Set product_configurator_mrp to uninstallable until fixing / refactoring
| Python | agpl-3.0 | pledra/odoo-product-configurator,pledra/odoo-product-configurator,pledra/odoo-product-configurator | {
'name': 'Product Configurator Manufacturing',
'version': '11.0.1.0.0',
'category': 'Manufacturing',
'summary': 'BOM Support for configurable products',
'author': 'Pledra',
'license': 'AGPL-3',
'website': 'http://www.pledra.com/',
'depends': ['mrp', 'product_configurator'],
"data": ... | Set product_configurator_mrp to uninstallable until fixing / refactoring
{
'name': 'Product Configurator Manufacturing',
'version': '11.0.1.0.0',
'category': 'Manufacturing',
'summary': 'BOM Support for configurable products',
'author': 'Pledra',
'license': 'AGPL-3',
'website': 'http://www.... |
e8e00b0bc9c9552858f364526803eb9edcaf52c3 | 01/test_directions.py | 01/test_directions.py | from directions import load_directions, turn, follow_directions
def test_load_directions():
with open("directions.txt") as f:
directions = [direction.strip(',')
for direction
in f.readline().strip().split()]
assert load_directions("directions.txt") == direct... | from directions import load_directions, turn, follow_directions, expand_path
import unittest
class TestDirections(unittest.TestCase):
def test_load_directions(self):
with open("directions.txt") as f:
directions = [direction.strip(',')
for direction
... | Convert to unittest and add test for expand_path. | Convert to unittest and add test for expand_path.
| Python | mit | machinelearningdeveloper/aoc_2016 | from directions import load_directions, turn, follow_directions, expand_path
import unittest
class TestDirections(unittest.TestCase):
def test_load_directions(self):
with open("directions.txt") as f:
directions = [direction.strip(',')
for direction
... | Convert to unittest and add test for expand_path.
from directions import load_directions, turn, follow_directions
def test_load_directions():
with open("directions.txt") as f:
directions = [direction.strip(',')
for direction
in f.readline().strip().split()]
... |
f7be5699265e123866f2e43e3e2920b39495dd80 | tests/test_entities.py | tests/test_entities.py | from __future__ import unicode_literals
from ftfy import fix_text, fix_text_segment
from nose.tools import eq_
def test_entities():
example = '&\n<html>\n&'
eq_(fix_text(example), '&\n<html>\n&')
eq_(fix_text_segment(example), '&\n<html>\n&')
eq_(fix_text(example, fix_entities=True... | Add tests for the fix_entities parameter | Add tests for the fix_entities parameter
| Python | mit | LuminosoInsight/python-ftfy | from __future__ import unicode_literals
from ftfy import fix_text, fix_text_segment
from nose.tools import eq_
def test_entities():
example = '&\n<html>\n&'
eq_(fix_text(example), '&\n<html>\n&')
eq_(fix_text_segment(example), '&\n<html>\n&')
eq_(fix_text(example, fix_entities=True... | Add tests for the fix_entities parameter
| |
be23c953f8f27a8d178022d3ecb44f461100bbc5 | tests/__init__.py | tests/__init__.py | """Tests for running TopoFlow components in CMI."""
import os
def locate_topoflow(cache_dir):
for x in os.listdir(cache_dir):
if x.startswith('topoflow'):
return x
root_dir = '/home/csdms/wmt/topoflow.0'
cache_dir = os.path.join(root_dir, 'cache')
topoflow_dir = locate_topoflow(cache_dir)
ex... | """Tests for running TopoFlow components in CMI."""
import os
def locate_topoflow(cache_dir):
for x in os.listdir(cache_dir):
if x.startswith('topoflow'):
return x
root_dir = '/home/csdms/wmt/topoflow.0'
cache_dir = os.path.join(root_dir, 'cache')
topoflow_dir = locate_topoflow(cache_dir)
ex... | Add path to data directory | Add path to data directory
| Python | mit | mdpiper/topoflow-cmi-testing | """Tests for running TopoFlow components in CMI."""
import os
def locate_topoflow(cache_dir):
for x in os.listdir(cache_dir):
if x.startswith('topoflow'):
return x
root_dir = '/home/csdms/wmt/topoflow.0'
cache_dir = os.path.join(root_dir, 'cache')
topoflow_dir = locate_topoflow(cache_dir)
ex... | Add path to data directory
"""Tests for running TopoFlow components in CMI."""
import os
def locate_topoflow(cache_dir):
for x in os.listdir(cache_dir):
if x.startswith('topoflow'):
return x
root_dir = '/home/csdms/wmt/topoflow.0'
cache_dir = os.path.join(root_dir, 'cache')
topoflow_dir = l... |
4753dffc6a1672dfa99a5a5da8f082d6554bbb8f | http_request_translator/templates/bash_template.py | http_request_translator/templates/bash_template.py | begin_code = """
#!/usr/bin/env bash
curl -s --request """
request_header = """ --header "{header} : {header_value}" """
code_search = " | egrep --color ' {search_string} |$' "
code_simple = "{method} {url} {headers} --include "
proxy_code = "-x {proxy}"
body_code = " --data '{body}' "
| begin_code = """
#!/usr/bin/env bash
curl"""
request_header = """ --header "{header} : {header_value}" """
code_search = " | egrep --color ' {search_string} |$'"
code_simple = " -s --request {method} {url} {headers} --include"
proxy_code = " -x {proxy}"
body_code = " --data '{body}'"
| Fix whitespace in bash script code template | Fix whitespace in bash script code template
Signed-off-by: Arun Sori <e3bf7af6e125f7de61de92cd66a64411bed42bee@gmail.com>
| Python | bsd-3-clause | owtf/http-request-translator,dhruvagarwal/http-request-translator | begin_code = """
#!/usr/bin/env bash
curl"""
request_header = """ --header "{header} : {header_value}" """
code_search = " | egrep --color ' {search_string} |$'"
code_simple = " -s --request {method} {url} {headers} --include"
proxy_code = " -x {proxy}"
body_code = " --data '{body}'"
| Fix whitespace in bash script code template
Signed-off-by: Arun Sori <e3bf7af6e125f7de61de92cd66a64411bed42bee@gmail.com>
begin_code = """
#!/usr/bin/env bash
curl -s --request """
request_header = """ --header "{header} : {header_value}" """
code_search = " | egrep --color ' {search_string} |$' "
code_simple = "{... |
85e77bc7a4706ed1b25d4d53e71ca22beafed411 | sidertests/test_sider.py | sidertests/test_sider.py | import doctest
import os
def test_doctest_types():
from sider import types
assert 0 == doctest.testmod(types)[0]
def test_doctest_datetime():
from sider import datetime
assert 0 == doctest.testmod(datetime)[0]
exttest_count = 0
def test_ext():
from sider.ext import _exttest
assert _extte... | import os
exttest_count = 0
def test_ext():
from sider.ext import _exttest
assert _exttest.ext_loaded == 'yes'
assert exttest_count == 1
from sider import ext
assert ext._exttest is _exttest
try:
import sider.ext._noexttest
except ImportError as e:
assert str(e) == "No mo... | Drop useless tests that invoking doctests | Drop useless tests that invoking doctests
| Python | mit | longfin/sider,dahlia/sider,longfin/sider | import os
exttest_count = 0
def test_ext():
from sider.ext import _exttest
assert _exttest.ext_loaded == 'yes'
assert exttest_count == 1
from sider import ext
assert ext._exttest is _exttest
try:
import sider.ext._noexttest
except ImportError as e:
assert str(e) == "No mo... | Drop useless tests that invoking doctests
import doctest
import os
def test_doctest_types():
from sider import types
assert 0 == doctest.testmod(types)[0]
def test_doctest_datetime():
from sider import datetime
assert 0 == doctest.testmod(datetime)[0]
exttest_count = 0
def test_ext():
from ... |
7ccacd1390e3f3ee86a1d21534db2c775003e432 | writeboards/models.py | writeboards/models.py | from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
writeboard_name = models.CharField(_('writeboard name'), max_length=100)
slug = mod... | from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
"""
Plaintext password field could simply be filled in with a reminder of.
"""
... | Add writeboard specific fields to model | Add writeboard specific fields to model | Python | mit | rizumu/django-paste-organizer | from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
"""
Plaintext password field could simply be filled in with a reminder of.
"""
... | Add writeboard specific fields to model
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
writeboard_name = models.CharField(_('writeboa... |
52e650a9181ce1e8bd8a2c0b1281f81bf6747874 | calvin/actorstore/systemactors/std/ClassicDelay.py | calvin/actorstore/systemactors/std/ClassicDelay.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# 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 ... | Add actor with behavior similar to old-style Delay | Add actor with behavior similar to old-style Delay
| Python | apache-2.0 | EricssonResearch/calvin-base,les69/calvin-base,les69/calvin-base,EricssonResearch/calvin-base,EricssonResearch/calvin-base,les69/calvin-base,EricssonResearch/calvin-base,les69/calvin-base | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# 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 ... | Add actor with behavior similar to old-style Delay
| |
58daf6f2225cdf52079072eee47f23a6d188cfa9 | resync/resource_set.py | resync/resource_set.py | """A set of Resource objects used for Capability List
Indexes and ResourceSync Description documents.
FIXME - what should the ordering be?
"""
class ResourceSet(dict):
"""Implementation of class to store resources in Capability List
Indexes and ResourceSync Description documents.
Key properties of this c... | """A set of Resource objects used for Capability List
Indexes and ResourceSync Description documents.
Ordinging is currently alphanumeric (using sorted(..)) on the
uri which is the key.
"""
class ResourceSet(dict):
"""Implementation of class to store resources in Capability List
Indexes and ResourceSync Desc... | Change comment to indicate choice of alphanum order by uri | Change comment to indicate choice of alphanum order by uri
| Python | apache-2.0 | lindareijnhoudt/resync,resync/resync,lindareijnhoudt/resync,dans-er/resync,dans-er/resync | """A set of Resource objects used for Capability List
Indexes and ResourceSync Description documents.
Ordinging is currently alphanumeric (using sorted(..)) on the
uri which is the key.
"""
class ResourceSet(dict):
"""Implementation of class to store resources in Capability List
Indexes and ResourceSync Desc... | Change comment to indicate choice of alphanum order by uri
"""A set of Resource objects used for Capability List
Indexes and ResourceSync Description documents.
FIXME - what should the ordering be?
"""
class ResourceSet(dict):
"""Implementation of class to store resources in Capability List
Indexes and Resou... |
43291c827d2d7b0a350971b2efa26ca9e1c1e593 | src/sentry/api/endpoints/system_health.py | src/sentry/api/endpoints/system_health.py | from __future__ import absolute_import
import itertools
from rest_framework.response import Response
from sentry import status_checks
from sentry.api.base import Endpoint
from sentry.api.permissions import SuperuserPermission
class SystemHealthEndpoint(Endpoint):
permission_classes = (SuperuserPermission,)
... | from __future__ import absolute_import
import itertools
from hashlib import md5
from rest_framework.response import Response
from sentry import status_checks
from sentry.api.base import Endpoint
from sentry.api.permissions import SuperuserPermission
class SystemHealthEndpoint(Endpoint):
permission_classes = (S... | Add `id` to `SystemHealthEndpoint` response. | Add `id` to `SystemHealthEndpoint` response.
| Python | bsd-3-clause | gencer/sentry,zenefits/sentry,looker/sentry,alexm92/sentry,JackDanger/sentry,zenefits/sentry,alexm92/sentry,ifduyue/sentry,ifduyue/sentry,beeftornado/sentry,fotinakis/sentry,jean/sentry,JamesMura/sentry,BuildingLink/sentry,mvaled/sentry,BuildingLink/sentry,mvaled/sentry,mvaled/sentry,mvaled/sentry,JamesMura/sentry,beef... | from __future__ import absolute_import
import itertools
from hashlib import md5
from rest_framework.response import Response
from sentry import status_checks
from sentry.api.base import Endpoint
from sentry.api.permissions import SuperuserPermission
class SystemHealthEndpoint(Endpoint):
permission_classes = (S... | Add `id` to `SystemHealthEndpoint` response.
from __future__ import absolute_import
import itertools
from rest_framework.response import Response
from sentry import status_checks
from sentry.api.base import Endpoint
from sentry.api.permissions import SuperuserPermission
class SystemHealthEndpoint(Endpoint):
p... |
cba1a165bdfef3c8bd95c0b5864aee811fbc55b3 | myfedora/plugins/apps/tools/profileinfo.py | myfedora/plugins/apps/tools/profileinfo.py | from myfedora.widgets.resourceview import ToolWidget
from fedora.tg.client import BaseClient
from myfedora.lib.app_factory import AppFactory
class ProfileInfoToolApp(AppFactory):
entry_name = "tools.profileinfo"
class ProfileInfoToolWidget(ToolWidget):
template = 'genshi:myfedora.plugins.apps.tools.templates.... | from myfedora.widgets.resourceview import ToolWidget
from fedora.client import BaseClient
from myfedora.lib.app_factory import AppFactory
class ProfileInfoToolApp(AppFactory):
entry_name = "tools.profileinfo"
class ProfileInfoToolWidget(ToolWidget):
template = 'genshi:myfedora.plugins.apps.tools.templates.pro... | Fix a deprecation warning from python-fedora | Fix a deprecation warning from python-fedora
| Python | agpl-3.0 | Fale/fedora-packages,Fale/fedora-packages,fedora-infra/fedora-packages,fedora-infra/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages,fedora-infra/fedora-packages | from myfedora.widgets.resourceview import ToolWidget
from fedora.client import BaseClient
from myfedora.lib.app_factory import AppFactory
class ProfileInfoToolApp(AppFactory):
entry_name = "tools.profileinfo"
class ProfileInfoToolWidget(ToolWidget):
template = 'genshi:myfedora.plugins.apps.tools.templates.pro... | Fix a deprecation warning from python-fedora
from myfedora.widgets.resourceview import ToolWidget
from fedora.tg.client import BaseClient
from myfedora.lib.app_factory import AppFactory
class ProfileInfoToolApp(AppFactory):
entry_name = "tools.profileinfo"
class ProfileInfoToolWidget(ToolWidget):
template = ... |
d81fe16eda36d3a5fa23d163de27bd46f84c4815 | app.py | app.py | from flask import Flask, render_template
import os
app = Flask(__name__)
@app.route('/')
def webprint():
return(render_template('index.html'))
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
| from flask import Flask, render_template
import os
app = Flask(__name__)
@app.route('/')
def webprint():
return 'Hello world!'
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
| Return text message on / | Return text message on /
| Python | mit | fablabjoinville/groselha,fablabjoinville/groselha,fablabjoinville/groselha,fablabjoinville/groselha | from flask import Flask, render_template
import os
app = Flask(__name__)
@app.route('/')
def webprint():
return 'Hello world!'
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
| Return text message on /
from flask import Flask, render_template
import os
app = Flask(__name__)
@app.route('/')
def webprint():
return(render_template('index.html'))
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
584f13955cda8c1b92c1246417881a7a4458155c | account_product_fiscal_classification_test/tests/test_multicompany.py | account_product_fiscal_classification_test/tests/test_multicompany.py | # Copyright (C) 2020 David BEAL @ Akretion
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class MulticompanyTests(TransactionCase):
def setUp(self):
super().setUp()
def test_classif_in_multicompany(self):
prd = self.env.ref(... | FIX prd_classif: set taxes on all companies sharing classif | FIX prd_classif: set taxes on all companies sharing classif
| Python | agpl-3.0 | OCA/account-fiscal-rule,OCA/account-fiscal-rule | # Copyright (C) 2020 David BEAL @ Akretion
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class MulticompanyTests(TransactionCase):
def setUp(self):
super().setUp()
def test_classif_in_multicompany(self):
prd = self.env.ref(... | FIX prd_classif: set taxes on all companies sharing classif
| |
c477427a35a0edaf90f53cf6b9e4cf33d5a4f0cc | tests/test_remote.py | tests/test_remote.py | # Empty test file just for coverage / syntax-checking purposes
# flake8: noqa
import nbdiff.server.remote_server
import nbdiff.server.database
import nbdiff.server.command.AboutUsCommand
import nbdiff.server.command.ComparisonCommand
import nbdiff.server.command.ContactUsCommand
import nbdiff.server.command.DiffComm... | Add empty test file that imports all remote command files for syntax-checking/coverage reporting. | Add empty test file that imports all remote command files for syntax-checking/coverage reporting.
| Python | mit | tarmstrong/nbdiff,tarmstrong/nbdiff,tarmstrong/nbdiff,tarmstrong/nbdiff | # Empty test file just for coverage / syntax-checking purposes
# flake8: noqa
import nbdiff.server.remote_server
import nbdiff.server.database
import nbdiff.server.command.AboutUsCommand
import nbdiff.server.command.ComparisonCommand
import nbdiff.server.command.ContactUsCommand
import nbdiff.server.command.DiffComm... | Add empty test file that imports all remote command files for syntax-checking/coverage reporting.
| |
cd1edf946fcf8b22b5f78f4a1db393b777951527 | website/files/utils.py | website/files/utils.py | from osf.models.base import generate_object_id
def copy_files(src, target_node, parent=None, name=None):
"""Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node to copy files to
:param Folder parent: The parent of to attach th... |
def copy_files(src, target_node, parent=None, name=None):
"""Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node to copy files to
:param Folder parent: The parent of to attach the clone of src to, if applicable
"""
ass... | Use clone() method from BaseModel to copy most recent fileversion | Use clone() method from BaseModel to copy most recent fileversion
| Python | apache-2.0 | adlius/osf.io,felliott/osf.io,HalcyonChimera/osf.io,mattclark/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,mfraezz/osf.io,cslzchen/osf.io,caseyrollins/osf.io,mfraezz/osf.io,saradbowman/osf.io,pattisdr/osf.io,aaxelb/osf.io,aaxelb/osf.io,adlius/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,cslzchen/osf.io,cslzchen/osf.io,case... |
def copy_files(src, target_node, parent=None, name=None):
"""Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node to copy files to
:param Folder parent: The parent of to attach the clone of src to, if applicable
"""
ass... | Use clone() method from BaseModel to copy most recent fileversion
from osf.models.base import generate_object_id
def copy_files(src, target_node, parent=None, name=None):
"""Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node to... |
cd75c139910e8968e5262d0f0f5289119b258f21 | phileo/views.py | phileo/views.py | from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse
from django.utils import simplejson as json
from django.shortcuts import get_object_or_404, redirect
from django.views.decorators.http import require_POST
from phil... | from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse
from django.utils import simplejson as json
from django.shortcuts import get_object_or_404, redirect
from django.views.decorators.http import require_POST
from phil... | Remove user from count query to show likes count for all users for obj | Remove user from count query to show likes count for all users for obj
| Python | mit | pinax/phileo,jacobwegner/phileo,rizumu/pinax-likes,rizumu/pinax-likes,jacobwegner/phileo,pinax/pinax-likes,pinax/phileo | from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse
from django.utils import simplejson as json
from django.shortcuts import get_object_or_404, redirect
from django.views.decorators.http import require_POST
from phil... | Remove user from count query to show likes count for all users for obj
from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse
from django.utils import simplejson as json
from django.shortcuts import get_object_or_404, r... |
d85d1edc769a1d80f8cb4b99824a9277beff4c4c | python/sliding_window.py | python/sliding_window.py | '''
This script showing you how to use a sliding window
'''
from itertools import islice
def sliding_window(a, n, step):
'''
a - sequence
n - width of the window
step - window step
'''
z = (islice(a, i, None, step) for i in range(n))
return zip(*z)
##Example
sliding_window(range(10), 2... | Add a script to do the sliding window efficiently | Add a script to do the sliding window efficiently
| Python | bsd-3-clause | qingkaikong/useful_script,qingkaikong/useful_script,qingkaikong/useful_script,qingkaikong/useful_script,qingkaikong/useful_script | '''
This script showing you how to use a sliding window
'''
from itertools import islice
def sliding_window(a, n, step):
'''
a - sequence
n - width of the window
step - window step
'''
z = (islice(a, i, None, step) for i in range(n))
return zip(*z)
##Example
sliding_window(range(10), 2... | Add a script to do the sliding window efficiently
| |
c6d50c3feed444f8f450c5c140e8470c6897f2bf | societies/models.py | societies/models.py | # -*- coding: utf-8 -*-
from django.db import models
from django_countries.fields import CountryField
class GuitarSociety(models.Model):
"""
Represents a single guitar society.
.. versionadded:: 0.1
"""
#: the name of the society
#: ..versionadded:: 0.1
name = models.CharField(max_lengt... | # -*- coding: utf-8 -*-
from django.db import models
from django_countries.fields import CountryField
class GuitarSociety(models.Model):
"""
Represents a single guitar society.
.. versionadded:: 0.1
"""
#: the name of the society
#: ..versionadded:: 0.1
name = models.CharField(max_lengt... | Make the Guitar Society __str__ Method a bit more Logical | Make the Guitar Society __str__ Method a bit more Logical
| Python | bsd-3-clause | chrisguitarguy/GuitarSocieties.org,chrisguitarguy/GuitarSocieties.org | # -*- coding: utf-8 -*-
from django.db import models
from django_countries.fields import CountryField
class GuitarSociety(models.Model):
"""
Represents a single guitar society.
.. versionadded:: 0.1
"""
#: the name of the society
#: ..versionadded:: 0.1
name = models.CharField(max_lengt... | Make the Guitar Society __str__ Method a bit more Logical
# -*- coding: utf-8 -*-
from django.db import models
from django_countries.fields import CountryField
class GuitarSociety(models.Model):
"""
Represents a single guitar society.
.. versionadded:: 0.1
"""
#: the name of the society
#:... |
cc12728d7160a10f0c182c0cccfde0fd15cadb75 | spicedham/basewrapper.py | spicedham/basewrapper.py |
class BaseWrapper(object):
"""
A base class for backend plugins.
"""
def get_key(self, tag, key, default=None):
"""
Gets the value held by the tag, key composite key. If it doesn't exist,
return default.
"""
raise NotImplementedError()
def get_key_list(sel... |
class BaseWrapper(object):
"""
A base class for backend plugins.
"""
def reset(self, really):
"""
Resets the training data to a blank slate.
"""
if really:
raise NotImplementedError()
def get_key(self, tag, key, default=None):
"""
Gets ... | Add a reset function stub | Add a reset function stub
Also fix a typo.
| Python | mpl-2.0 | mozilla/spicedham,mozilla/spicedham |
class BaseWrapper(object):
"""
A base class for backend plugins.
"""
def reset(self, really):
"""
Resets the training data to a blank slate.
"""
if really:
raise NotImplementedError()
def get_key(self, tag, key, default=None):
"""
Gets ... | Add a reset function stub
Also fix a typo.
class BaseWrapper(object):
"""
A base class for backend plugins.
"""
def get_key(self, tag, key, default=None):
"""
Gets the value held by the tag, key composite key. If it doesn't exist,
return default.
"""
raise Not... |
9260ae587c46f32047dbcfbe1610290282fcdf8c | pymatgen/util/__init__.py | pymatgen/util/__init__.py | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import unicode_literals
"""
The util package implements various utilities that are commonly used by various
packages.
"""
__author__ = "Shyue"
__date__ = "$Jun 6, 2011 7:30:05 AM$"
try:
imp... | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import unicode_literals
"""
The util package implements various utilities that are commonly used by various
packages.
"""
__author__ = "Shyue"
__date__ = "$Jun 6, 2011 7:30:05 AM$"
try:
imp... | Fix spelling in coord_utils import. | Fix spelling in coord_utils import.
Former-commit-id: 03182f09c5e7cc2d7a5ca8b996baa82e4557e7fa [formerly 4011394beda266f4f43120e951b99bdc0470f93e]
Former-commit-id: 78985fde51ef15145a5ff42d8bd9fe05a8890b22 | Python | mit | gpetretto/pymatgen,ndardenne/pymatgen,vorwerkc/pymatgen,xhqu1981/pymatgen,czhengsci/pymatgen,gpetretto/pymatgen,aykol/pymatgen,dongsenfo/pymatgen,blondegeek/pymatgen,gpetretto/pymatgen,mbkumar/pymatgen,richardtran415/pymatgen,gVallverdu/pymatgen,nisse3000/pymatgen,nisse3000/pymatgen,gVallverdu/pymatgen,matk86/pymatgen,... | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import unicode_literals
"""
The util package implements various utilities that are commonly used by various
packages.
"""
__author__ = "Shyue"
__date__ = "$Jun 6, 2011 7:30:05 AM$"
try:
imp... | Fix spelling in coord_utils import.
Former-commit-id: 03182f09c5e7cc2d7a5ca8b996baa82e4557e7fa [formerly 4011394beda266f4f43120e951b99bdc0470f93e]
Former-commit-id: 78985fde51ef15145a5ff42d8bd9fe05a8890b22
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
fr... |
410c47921da205c1628cdff771f3385546edd503 | src/engine/SCons/Platform/darwin.py | src/engine/SCons/Platform/darwin.py | """engine.SCons.Platform.darwin
Platform-specific initialization for Mac OS X systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004 Steven Knight
#
# Permi... | """engine.SCons.Platform.darwin
Platform-specific initialization for Mac OS X systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of char... | Fix __COPYRIGHT__ and __REVISION__ in new Darwin module. | Fix __COPYRIGHT__ and __REVISION__ in new Darwin module.
| Python | mit | Distrotech/scons,Distrotech/scons,Distrotech/scons,Distrotech/scons,Distrotech/scons | """engine.SCons.Platform.darwin
Platform-specific initialization for Mac OS X systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of char... | Fix __COPYRIGHT__ and __REVISION__ in new Darwin module.
"""engine.SCons.Platform.darwin
Platform-specific initialization for Mac OS X systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Co... |
394f5832c6d3ff3efefbc5c21163adcdedd9a9bb | sale_stock_availability/__openerp__.py | sale_stock_availability/__openerp__.py | # -*- coding: utf-8 -*-
{
'name': 'Stock availability in sales order line',
'version': '0.1',
'category': 'Tools',
'description': """
Stock availability in sales order line
======================================
* Add two groups. One for seeing stock on sale orders and other to see only if o... | # -*- coding: utf-8 -*-
{
'name': 'Stock availability in sales order line',
'version': '0.1',
'category': 'Tools',
'description': """
Stock availability in sales order line
======================================
* Add two groups. One for seeing stock on sale orders and other to see only if or not availa... | FIX sale stock availa.. description | FIX sale stock availa.. description
| Python | agpl-3.0 | syci/ingadhoc-odoo-addons,HBEE/odoo-addons,jorsea/odoo-addons,adhoc-dev/odoo-addons,bmya/odoo-addons,bmya/odoo-addons,levkar/odoo-addons,bmya/odoo-addons,dvitme/odoo-addons,ClearCorp/account-financial-tools,jorsea/odoo-addons,sysadminmatmoz/ingadhoc,ingadhoc/account-payment,HBEE/odoo-addons,ingadhoc/stock,adhoc-dev/acc... | # -*- coding: utf-8 -*-
{
'name': 'Stock availability in sales order line',
'version': '0.1',
'category': 'Tools',
'description': """
Stock availability in sales order line
======================================
* Add two groups. One for seeing stock on sale orders and other to see only if or not availa... | FIX sale stock availa.. description
# -*- coding: utf-8 -*-
{
'name': 'Stock availability in sales order line',
'version': '0.1',
'category': 'Tools',
'description': """
Stock availability in sales order line
======================================
* Add two groups. One for seeing stock on s... |
5b0386d0872d4106902655ada78389503c62a95a | yunity/models/relations.py | yunity/models/relations.py | from django.db.models import ForeignKey, DateTimeField, ManyToManyField
from yunity.models.entities import User, Location, Mappable, Message
from yunity.models.utils import BaseModel, MaxLengthCharField
from yunity.utils.decorators import classproperty
class Chat(BaseModel):
participants = ManyToManyField(User)
... | from django.db.models import ForeignKey, DateTimeField, ManyToManyField
from yunity.models.entities import User, Location, Mappable, Message
from yunity.models.utils import BaseModel, MaxLengthCharField
from yunity.utils.decorators import classproperty
class Chat(BaseModel):
participants = ManyToManyField(User)
... | Add some default feedback types for item requests | Add some default feedback types for item requests
| Python | agpl-3.0 | yunity/yunity-core,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/foodsaving-backend | from django.db.models import ForeignKey, DateTimeField, ManyToManyField
from yunity.models.entities import User, Location, Mappable, Message
from yunity.models.utils import BaseModel, MaxLengthCharField
from yunity.utils.decorators import classproperty
class Chat(BaseModel):
participants = ManyToManyField(User)
... | Add some default feedback types for item requests
from django.db.models import ForeignKey, DateTimeField, ManyToManyField
from yunity.models.entities import User, Location, Mappable, Message
from yunity.models.utils import BaseModel, MaxLengthCharField
from yunity.utils.decorators import classproperty
class Chat(Bas... |
e7ad2be6cdb87b84bfa77ff9824f2e9913c17599 | tests/test_cmd.py | tests/test_cmd.py | import base64
import os
from distutils.core import Command
class TestCommand(Command):
description = "Launch all tests under fusion_tables app"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def create_client_secret_file(self):
clie... | import base64
import os
from distutils.core import Command
class TestCommand(Command):
description = "Launch all tests under fusion_tables app"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def create_client_secret_file(self):
clie... | Revert "Fix unit test python3 compatibility." | Revert "Fix unit test python3 compatibility."
This reverts commit 6807e5a5966f1f37f69a54e255a9981918cc8fb6.
| Python | mit | bsvetchine/django-fusion-tables | import base64
import os
from distutils.core import Command
class TestCommand(Command):
description = "Launch all tests under fusion_tables app"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def create_client_secret_file(self):
clie... | Revert "Fix unit test python3 compatibility."
This reverts commit 6807e5a5966f1f37f69a54e255a9981918cc8fb6.
import base64
import os
from distutils.core import Command
class TestCommand(Command):
description = "Launch all tests under fusion_tables app"
user_options = []
def initialize_options(self):
... |
346d6e38e84a5addc5173a331dbc0cc6fa39e754 | corehq/apps/domain/management/commands/fill_last_modified_date.py | corehq/apps/domain/management/commands/fill_last_modified_date.py | from django.core.management.base import BaseCommand
from corehq.apps.domain.models import Domain
from dimagi.utils.couch.database import iter_docs
class Command(BaseCommand):
def _get_domains_without_last_modified_date(self):
docs = iter_docs(Domain.get_db(), [
domain['id']
for d... | from django.core.management.base import BaseCommand
from corehq.apps.domain.models import Domain
from dimagi.utils.couch.database import iter_docs
class Command(BaseCommand):
def _get_domains_without_last_modified_date(self):
docs = iter_docs(Domain.get_db(), [
domain['id']
for d... | Include domains which have last_modified equal to None | Include domains which have last_modified equal to None
| Python | bsd-3-clause | qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq | from django.core.management.base import BaseCommand
from corehq.apps.domain.models import Domain
from dimagi.utils.couch.database import iter_docs
class Command(BaseCommand):
def _get_domains_without_last_modified_date(self):
docs = iter_docs(Domain.get_db(), [
domain['id']
for d... | Include domains which have last_modified equal to None
from django.core.management.base import BaseCommand
from corehq.apps.domain.models import Domain
from dimagi.utils.couch.database import iter_docs
class Command(BaseCommand):
def _get_domains_without_last_modified_date(self):
docs = iter_docs(Domai... |
13d9cf933e49849a3c5343e7bdbf887b9aee6097 | busbus/entity.py | busbus/entity.py | from busbus import util
class LazyEntityProperty(object):
def __init__(self, f, *args, **kwargs):
self.f = f
self.args = args
self.kwargs = kwargs
def __call__(self):
return self.f(*self.args, **self.kwargs)
class BaseEntity(object):
def __init__(self, provider, **kwar... | from busbus import util
class LazyEntityProperty(object):
def __init__(self, f, *args, **kwargs):
self.f = f
self.args = args
self.kwargs = kwargs
def __call__(self):
return self.f(*self.args, **self.kwargs)
class BaseEntity(object):
__repr_attrs__ = ('id',)
def __... | Use an instance variable instead of a non-standard argument to __repr__ | Use an instance variable instead of a non-standard argument to __repr__
| Python | mit | spaceboats/busbus | from busbus import util
class LazyEntityProperty(object):
def __init__(self, f, *args, **kwargs):
self.f = f
self.args = args
self.kwargs = kwargs
def __call__(self):
return self.f(*self.args, **self.kwargs)
class BaseEntity(object):
__repr_attrs__ = ('id',)
def __... | Use an instance variable instead of a non-standard argument to __repr__
from busbus import util
class LazyEntityProperty(object):
def __init__(self, f, *args, **kwargs):
self.f = f
self.args = args
self.kwargs = kwargs
def __call__(self):
return self.f(*self.args, **self.kwa... |
d33a624fa6aedb93ae43ba1d2c0f6a76d90ff4a6 | foldermd5sums.py | foldermd5sums.py | #!/usr/bin/env python
"""Script to read data files in a directory, compute their md5sums, and output
them to a JSON file."""
import json
import os
import sys
import hashlib
def get_md5sums(directory):
md5sums = []
for filename in os.listdir(directory):
md5 = hashlib.md5()
with open(os.path.jo... | #!/usr/bin/env python
"""Script to read data files in a directory, compute their md5sums, and output
them to a JSON file."""
import json
import os
import sys
import hashlib
def get_relative_filepaths(base_directory):
""" Return a list of file paths without the base_directory prefix"""
file_list = []
for ... | Allow directory of files to be indexed | ENH: Allow directory of files to be indexed
In the Data directory, there may be sub-directories of files that need to
be kept separate, but all of them need to be indexed.
| Python | apache-2.0 | zivy/SimpleITK-Notebooks,InsightSoftwareConsortium/SimpleITK-Notebooks,InsightSoftwareConsortium/SimpleITK-Notebooks,zivy/SimpleITK-Notebooks,InsightSoftwareConsortium/SimpleITK-Notebooks,thewtex/SimpleITK-Notebooks,zivy/SimpleITK-Notebooks,thewtex/SimpleITK-Notebooks,thewtex/SimpleITK-Notebooks | #!/usr/bin/env python
"""Script to read data files in a directory, compute their md5sums, and output
them to a JSON file."""
import json
import os
import sys
import hashlib
def get_relative_filepaths(base_directory):
""" Return a list of file paths without the base_directory prefix"""
file_list = []
for ... | ENH: Allow directory of files to be indexed
In the Data directory, there may be sub-directories of files that need to
be kept separate, but all of them need to be indexed.
#!/usr/bin/env python
"""Script to read data files in a directory, compute their md5sums, and output
them to a JSON file."""
import json
import ... |
680679ed2b05bd5131016d13f66f73249e51a102 | tests/utils.py | tests/utils.py | from uuid import uuid4
from valohai_cli.utils import get_random_string
def get_project_data(n_projects):
return {
'results': [
{'id': str(uuid4()), 'name': get_random_string()}
for i in range(n_projects)
],
}
| from uuid import uuid4
from valohai_cli.utils import get_random_string
def get_project_data(n_projects):
return {
'results': [
{'id': str(uuid4()), 'name': get_random_string()}
for i in range(n_projects)
],
}
def make_call_stub(retval=None):
calls = []
def c... | Add generic monkeypatch call stub | Add generic monkeypatch call stub
| Python | mit | valohai/valohai-cli | from uuid import uuid4
from valohai_cli.utils import get_random_string
def get_project_data(n_projects):
return {
'results': [
{'id': str(uuid4()), 'name': get_random_string()}
for i in range(n_projects)
],
}
def make_call_stub(retval=None):
calls = []
def c... | Add generic monkeypatch call stub
from uuid import uuid4
from valohai_cli.utils import get_random_string
def get_project_data(n_projects):
return {
'results': [
{'id': str(uuid4()), 'name': get_random_string()}
for i in range(n_projects)
],
}
|
a6712ce13b0c6e62488adf0ae13fabf986a1b890 | imgsort.py | imgsort.py | #!/usr/bin/env python3
import os
import shutil
from PIL import Image
whitelist = (
(1366, 768),
(1600, 900),
(1680, 1050),
(1920, 1080),
(1920, 1200),
)
def split(directory):
filemap = {dimensions: set() for dimensions in whitelist}
filemap['others'] = set()
makepath = lambda filena... | Add simple script to sort images | Add simple script to sort images
| Python | mit | ranisalt/imgsort | #!/usr/bin/env python3
import os
import shutil
from PIL import Image
whitelist = (
(1366, 768),
(1600, 900),
(1680, 1050),
(1920, 1080),
(1920, 1200),
)
def split(directory):
filemap = {dimensions: set() for dimensions in whitelist}
filemap['others'] = set()
makepath = lambda filena... | Add simple script to sort images
| |
15a5e6c1aca706330147475984848dfc33fd1a9d | common/djangoapps/mitxmako/tests.py | common/djangoapps/mitxmako/tests.py | from django.test import TestCase
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from django.conf import settings
from mitxmako.shortcuts import marketing_link
from mock import patch
class ShortcutsTests(TestCase):
"""
Test the mitxmako shortcuts file
"""
... | from django.test import TestCase
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from django.conf import settings
from mitxmako.shortcuts import marketing_link
from mock import patch
class ShortcutsTests(TestCase):
"""
Test the mitxmako shortcuts file
"""
... | Fix test so that it works with both CMS and LMS settings | Fix test so that it works with both CMS and LMS settings
| Python | agpl-3.0 | nanolearningllc/edx-platform-cypress,jjmiranda/edx-platform,SivilTaram/edx-platform,olexiim/edx-platform,eduNEXT/edx-platform,bdero/edx-platform,olexiim/edx-platform,nanolearningllc/edx-platform-cypress-2,cyanna/edx-platform,rismalrv/edx-platform,don-github/edx-platform,unicri/edx-platform,xuxiao19910803/edx-platform,U... | from django.test import TestCase
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from django.conf import settings
from mitxmako.shortcuts import marketing_link
from mock import patch
class ShortcutsTests(TestCase):
"""
Test the mitxmako shortcuts file
"""
... | Fix test so that it works with both CMS and LMS settings
from django.test import TestCase
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from django.conf import settings
from mitxmako.shortcuts import marketing_link
from mock import patch
class ShortcutsTests(TestCase):
... |
141eb2a647490142adf017d3a755d03ab89ed687 | jrnl/plugins/tag_exporter.py | jrnl/plugins/tag_exporter.py | #!/usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import, unicode_literals
from .text_exporter import TextExporter
from .util import get_tags_count
class TagExporter(TextExporter):
"""This Exporter can convert entries and journals into json."""
names = ["tags"]
extension = "tags"
... | #!/usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import, unicode_literals
from .text_exporter import TextExporter
from .util import get_tags_count
class TagExporter(TextExporter):
"""This Exporter can lists the tags for entries and journals, exported as a plain text file."""
names = ["... | Update `Tag` exporter code documentation. | Update `Tag` exporter code documentation.
| Python | mit | maebert/jrnl,notbalanced/jrnl,philipsd6/jrnl,MinchinWeb/jrnl | #!/usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import, unicode_literals
from .text_exporter import TextExporter
from .util import get_tags_count
class TagExporter(TextExporter):
"""This Exporter can lists the tags for entries and journals, exported as a plain text file."""
names = ["... | Update `Tag` exporter code documentation.
#!/usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import, unicode_literals
from .text_exporter import TextExporter
from .util import get_tags_count
class TagExporter(TextExporter):
"""This Exporter can convert entries and journals into json."""
... |
df784323d0da737755def4015840d118e3c8e595 | nettests/core/http_body_length.py | nettests/core/http_body_length.py | # -*- encoding: utf-8 -*-
#
# :authors: Arturo Filastò
# :licence: see LICENSE
from twisted.internet import defer
from twisted.python import usage
from ooni.templates import httpt
class UsageOptions(usage.Options):
optParameters = [
['url', 'u', None, 'Specify a single URL to test.'],
... | Add test that detects censorship in HTTP pages based on HTTP body length | Add test that detects censorship in HTTP pages based on HTTP body length
| Python | bsd-2-clause | juga0/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,Karthikeyan-kkk/ooni-probe,Karthikeyan-kkk/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,lordappsec/ooni-prob... | # -*- encoding: utf-8 -*-
#
# :authors: Arturo Filastò
# :licence: see LICENSE
from twisted.internet import defer
from twisted.python import usage
from ooni.templates import httpt
class UsageOptions(usage.Options):
optParameters = [
['url', 'u', None, 'Specify a single URL to test.'],
... | Add test that detects censorship in HTTP pages based on HTTP body length
| |
2bde683bcfbdc7149a114abd609a3c91c19cac0f | tagcache/lock.py | tagcache/lock.py | # -*- encoding: utf-8 -*-
import os
import fcntl
class FileLock(object):
def __init__(self, fd):
# the fd is borrowed, so do not close it
self.fd = fd
def acquire(self, write=False, block=False):
try:
lock_flags = fcntl.LOCK_EX if write else fcntl.LOCK_SH
... | # -*- encoding: utf-8 -*-
import os
import fcntl
class FileLock(object):
def __init__(self, fd):
# the fd is borrowed, so do not close it
self.fd = fd
def acquire(self, ex=False, nb=True):
"""
Acquire a lock on the fd.
:param ex (optional): default False, acquire a... | Change parameter names in acquire. Add some doc. | Change parameter names in acquire.
Add some doc.
| Python | mit | huangjunwen/tagcache | # -*- encoding: utf-8 -*-
import os
import fcntl
class FileLock(object):
def __init__(self, fd):
# the fd is borrowed, so do not close it
self.fd = fd
def acquire(self, ex=False, nb=True):
"""
Acquire a lock on the fd.
:param ex (optional): default False, acquire a... | Change parameter names in acquire.
Add some doc.
# -*- encoding: utf-8 -*-
import os
import fcntl
class FileLock(object):
def __init__(self, fd):
# the fd is borrowed, so do not close it
self.fd = fd
def acquire(self, write=False, block=False):
try:
lock_flags = fcnt... |
e8d9dae51dc812e94236d1cc45cf1479d88f02f6 | grokapi/queries.py | grokapi/queries.py | # -*- coding: utf-8 -*-
class Grok:
"""stats.grok.se article statistics."""
def __init__(self, title, site):
self.site = site
self.title = title
def _make_url(self, year, month):
"""Make the URL to the JSON output of stats.grok.se service."""
base_url = "http://stats.gro... | # -*- coding: utf-8 -*-
class Grok(object):
"""stats.grok.se article statistics."""
def __init__(self, title, site):
self.site = site
self.title = title
def _make_url(self, year, month):
"""Make the URL to the JSON output of stats.grok.se service."""
base_url = "http://s... | Make Grok a new-style class inheriting from object | Make Grok a new-style class inheriting from object
| Python | mit | Commonists/Grokapi | # -*- coding: utf-8 -*-
class Grok(object):
"""stats.grok.se article statistics."""
def __init__(self, title, site):
self.site = site
self.title = title
def _make_url(self, year, month):
"""Make the URL to the JSON output of stats.grok.se service."""
base_url = "http://s... | Make Grok a new-style class inheriting from object
# -*- coding: utf-8 -*-
class Grok:
"""stats.grok.se article statistics."""
def __init__(self, title, site):
self.site = site
self.title = title
def _make_url(self, year, month):
"""Make the URL to the JSON output of stats.grok... |
d0ce2b074ffd603c507069d8a5ab1189fad0ca56 | pywikibot/families/wikia_family.py | pywikibot/families/wikia_family.py | # -*- coding: utf-8 -*-
__version__ = '$Id$'
import family
# The Wikia Search family
# user-config.py: usernames['wikia']['wikia'] = 'User name'
class Family(family.Family):
def __init__(self):
family.Family.__init__(self)
self.name = u'wikia'
self.langs = {
u'wikia': None,... | # -*- coding: utf-8 -*-
__version__ = '$Id$'
import family
# The Wikia Search family
# user-config.py: usernames['wikia']['wikia'] = 'User name'
class Family(family.Family):
def __init__(self):
family.Family.__init__(self)
self.name = u'wikia'
self.langs = {
u'wikia': None,... | Update a version number from trunk r9016 | Update a version number from trunk r9016
https://mediawiki.org/wiki/Special:Code/pywikipedia/9040
| Python | mit | VcamX/pywikibot-core,npdoty/pywikibot,npdoty/pywikibot,emijrp/pywikibot-core,darthbhyrava/pywikibot-local,magul/pywikibot-core,magul/pywikibot-core,h4ck3rm1k3/pywikibot-core,trishnaguha/pywikibot-core,xZise/pywikibot-core,valhallasw/pywikibot-core,Darkdadaah/pywikibot-core,icyflame/batman,PersianWikipedia/pywikibot-cor... | # -*- coding: utf-8 -*-
__version__ = '$Id$'
import family
# The Wikia Search family
# user-config.py: usernames['wikia']['wikia'] = 'User name'
class Family(family.Family):
def __init__(self):
family.Family.__init__(self)
self.name = u'wikia'
self.langs = {
u'wikia': None,... | Update a version number from trunk r9016
https://mediawiki.org/wiki/Special:Code/pywikipedia/9040
# -*- coding: utf-8 -*-
__version__ = '$Id$'
import family
# The Wikia Search family
# user-config.py: usernames['wikia']['wikia'] = 'User name'
class Family(family.Family):
def __init__(self):
family.Fa... |
38b4af0b3c1c6105d68ff453d86107758ef9d751 | preconditions.py | preconditions.py | class PreconditionError (TypeError):
pass
def preconditions(*precs):
def decorate(f):
def g(*a, **kw):
return f(*a, **kw)
return g
return decorate
| import inspect
class PreconditionError (TypeError):
pass
def preconditions(*precs):
precinfo = []
for p in precs:
spec = inspect.getargspec(p)
if spec.varargs or spec.keywords:
raise PreconditionError(
'Precondition {!r} must not accept * nor ** args.'.format... | Implement two of the "early" InvalidPreconditionTests which can be checked prior to seeing the wrapping function. | Implement two of the "early" InvalidPreconditionTests which can be checked prior to seeing the wrapping function.
| Python | mit | nejucomo/preconditions | import inspect
class PreconditionError (TypeError):
pass
def preconditions(*precs):
precinfo = []
for p in precs:
spec = inspect.getargspec(p)
if spec.varargs or spec.keywords:
raise PreconditionError(
'Precondition {!r} must not accept * nor ** args.'.format... | Implement two of the "early" InvalidPreconditionTests which can be checked prior to seeing the wrapping function.
class PreconditionError (TypeError):
pass
def preconditions(*precs):
def decorate(f):
def g(*a, **kw):
return f(*a, **kw)
return g
return decorate
|
e2132caf1c677b34eddd679e23983022ec12b5df | watermarker/conf.py | watermarker/conf.py | # -*- coding: utf-8 -*-
import warnings
from django.conf import settings # pylint: disable=W0611
from appconf import AppConf
class WatermarkSettings(AppConf):
QUALITY = 85
OBSCURE_ORIGINAL = True
RANDOM_POSITION_ONCE = True
WATERMARK_PERCENTAGE = 30
class Meta:
prefix = 'watermark'
... | # -*- coding: utf-8 -*-
import warnings
from django.conf import settings # pylint: disable=W0611
from appconf import AppConf
class WatermarkSettings(AppConf):
QUALITY = 85
OBSCURE_ORIGINAL = True
RANDOM_POSITION_ONCE = True
WATERMARK_PERCENTAGE = getattr(settings, 'WATERMARK_PERCENTAGE', 30)
... | Change AppConf class to use settings defined value or default. | Change AppConf class to use settings defined value or default.
| Python | bsd-3-clause | lzanuz/django-watermark,lzanuz/django-watermark | # -*- coding: utf-8 -*-
import warnings
from django.conf import settings # pylint: disable=W0611
from appconf import AppConf
class WatermarkSettings(AppConf):
QUALITY = 85
OBSCURE_ORIGINAL = True
RANDOM_POSITION_ONCE = True
WATERMARK_PERCENTAGE = getattr(settings, 'WATERMARK_PERCENTAGE', 30)
... | Change AppConf class to use settings defined value or default.
# -*- coding: utf-8 -*-
import warnings
from django.conf import settings # pylint: disable=W0611
from appconf import AppConf
class WatermarkSettings(AppConf):
QUALITY = 85
OBSCURE_ORIGINAL = True
RANDOM_POSITION_ONCE = True
WATERMARK_... |
e9cf6bbc5d790dd77fea35ec4875c045cb6f19c3 | thefederation/views.py | thefederation/views.py | import time
from django.shortcuts import redirect
from thefederation.tasks import poll_node
from thefederation.utils import is_valid_hostname
def register_view(request, host):
# TODO rate limit this view per caller ip?
if not is_valid_hostname:
return redirect("/")
if poll_node(host):
# ... | from django.shortcuts import redirect
from thefederation.tasks import poll_node
from thefederation.utils import is_valid_hostname
def register_view(request, host):
# TODO rate limit this view per caller ip?
if not is_valid_hostname:
return redirect("/")
if poll_node(host):
# Success!
... | Fix redirect to node page after registration | Fix redirect to node page after registration
| Python | agpl-3.0 | jaywink/the-federation.info,jaywink/the-federation.info,jaywink/diaspora-hub,jaywink/diaspora-hub,jaywink/diaspora-hub,jaywink/the-federation.info | from django.shortcuts import redirect
from thefederation.tasks import poll_node
from thefederation.utils import is_valid_hostname
def register_view(request, host):
# TODO rate limit this view per caller ip?
if not is_valid_hostname:
return redirect("/")
if poll_node(host):
# Success!
... | Fix redirect to node page after registration
import time
from django.shortcuts import redirect
from thefederation.tasks import poll_node
from thefederation.utils import is_valid_hostname
def register_view(request, host):
# TODO rate limit this view per caller ip?
if not is_valid_hostname:
return re... |
0fa5e9944d573d053633b1ea81497bc20598abee | CodeFights/longestWord.py | CodeFights/longestWord.py | #!/usr/local/bin/python
# Code Fights Longest Word Problem
import re
def longestWord(text):
m = re.findall(r'\b[a-z]+?\b', text, flags=re.I)
return max(m, key=len)
def main():
tests = [
["Ready, steady, go!", "steady"],
["Ready[[[, steady, go!", "steady"],
["ABCd", "ABCd"]
]... | Solve Code Fights longest word problem | Solve Code Fights longest word problem
| Python | mit | HKuz/Test_Code | #!/usr/local/bin/python
# Code Fights Longest Word Problem
import re
def longestWord(text):
m = re.findall(r'\b[a-z]+?\b', text, flags=re.I)
return max(m, key=len)
def main():
tests = [
["Ready, steady, go!", "steady"],
["Ready[[[, steady, go!", "steady"],
["ABCd", "ABCd"]
]... | Solve Code Fights longest word problem
| |
9516621f2b4cfc5b541c3328df95b62111e77463 | app/main/__init__.py | app/main/__init__.py | from flask import Blueprint
main = Blueprint('main', __name__)
from . import errors
from .views import (
crown_hosting, digital_services_framework, g_cloud, login, marketplace, suppliers,
digital_outcomes_and_specialists
)
| from flask import Blueprint
main = Blueprint('main', __name__)
from . import errors
from .views import (
crown_hosting, g_cloud, login, marketplace, suppliers,
digital_outcomes_and_specialists
)
| Delete reference to removed view | Delete reference to removed view
| Python | mit | alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend | from flask import Blueprint
main = Blueprint('main', __name__)
from . import errors
from .views import (
crown_hosting, g_cloud, login, marketplace, suppliers,
digital_outcomes_and_specialists
)
| Delete reference to removed view
from flask import Blueprint
main = Blueprint('main', __name__)
from . import errors
from .views import (
crown_hosting, digital_services_framework, g_cloud, login, marketplace, suppliers,
digital_outcomes_and_specialists
)
|
0115d088061595fe6c6f8589d0599d1b8e970813 | scripts/lwtnn-build-dummy-inputs.py | scripts/lwtnn-build-dummy-inputs.py | #!/usr/bin/env python3
"""Generate fake NN files to test the lightweight classes"""
import argparse
import json
import h5py
import numpy as np
def _run():
args = _get_args()
_build_keras_arch("arch.json")
_build_keras_inputs_file("inputs.json")
_build_keras_weights("weights.h5", verbose=args.verbose)... | Add dummy Keras inputs builder | Add dummy Keras inputs builder
| Python | mit | lwtnn/lwtnn,jwsmithers/lwtnn,jwsmithers/lwtnn,jwsmithers/lwtnn,lwtnn/lwtnn,lwtnn/lwtnn | #!/usr/bin/env python3
"""Generate fake NN files to test the lightweight classes"""
import argparse
import json
import h5py
import numpy as np
def _run():
args = _get_args()
_build_keras_arch("arch.json")
_build_keras_inputs_file("inputs.json")
_build_keras_weights("weights.h5", verbose=args.verbose)... | Add dummy Keras inputs builder
| |
43ab1500719665b44e3b4eca4def9002711c2ee8 | githublist/parser.py | githublist/parser.py | import requests
import collections
API_URL = 'https://api.github.com/users/{}/repos'
def main(user):
return parse(request(user))
def request(user):
return requests.get(url=API_URL.format(user))
def parse(response):
repos = response.json()
data = []
if repos is None:
return None
fo... | import requests
import collections
API_URL = 'https://api.github.com/users/{}/repos?per_page=100'
def main(user):
return parse(request(user))
def request(user):
return requests.get(url=API_URL.format(user))
def parse(response):
repos = response.json()
data = []
if repos is None:
retur... | Update api url for recent 100 instead of default 30 | Update api url for recent 100 instead of default 30
| Python | mit | kshvmdn/github-list,kshvmdn/github-list,kshvmdn/github-list | import requests
import collections
API_URL = 'https://api.github.com/users/{}/repos?per_page=100'
def main(user):
return parse(request(user))
def request(user):
return requests.get(url=API_URL.format(user))
def parse(response):
repos = response.json()
data = []
if repos is None:
retur... | Update api url for recent 100 instead of default 30
import requests
import collections
API_URL = 'https://api.github.com/users/{}/repos'
def main(user):
return parse(request(user))
def request(user):
return requests.get(url=API_URL.format(user))
def parse(response):
repos = response.json()
data ... |
5ff983c1a464fc559cb13addb5316f99379472bf | tests/test_trip.py | tests/test_trip.py | #!/usr/bin/env python
import unittest
from parsemypsa.storage import objects
class TripTestCase(unittest.TestCase):
def setUp(self):
self.trip1 = objects.Trip.create(id=1, 1462731168, 200, 1000, 1, 0, 0)
def test_mileage_calculation(self):
self.trip1.calculate_mileage()
self.assertE... | #!/usr/bin/env python
import unittest
from playhouse.test_utils import test_database
from peewee import *
from parsemypsa.storage import objects
# Data for testing
test_db = SqliteDatabase(':memory:')
model_list = [objects.Alert, objects.VehiculeInformation, objects.Trip]
class TripTestCase(unittest.TestCase):
... | Fix unittests broken after ORM adoption | Fix unittests broken after ORM adoption
| Python | mit | klenje/parsemypsa | #!/usr/bin/env python
import unittest
from playhouse.test_utils import test_database
from peewee import *
from parsemypsa.storage import objects
# Data for testing
test_db = SqliteDatabase(':memory:')
model_list = [objects.Alert, objects.VehiculeInformation, objects.Trip]
class TripTestCase(unittest.TestCase):
... | Fix unittests broken after ORM adoption
#!/usr/bin/env python
import unittest
from parsemypsa.storage import objects
class TripTestCase(unittest.TestCase):
def setUp(self):
self.trip1 = objects.Trip.create(id=1, 1462731168, 200, 1000, 1, 0, 0)
def test_mileage_calculation(self):
self.trip1... |
b76a7c4a60fbe3ea367a14e5fa19283fee062870 | pinboard_linkrot.py | pinboard_linkrot.py | #!/usr/bin/env python
from __future__ import division
import requests
import json
import sys
from requests.exceptions import SSLError, InvalidSchema, ConnectionError
def get_link_status_code(link):
headers = {'User-agent':'Mozilla/5.0'}
try:
r = requests.head(link, headers=headers, allow_redirects=Tru... | #!/usr/bin/env python
from __future__ import division
import requests
import json
import sys
from requests.exceptions import SSLError, InvalidSchema, ConnectionError
def get_link_status_code(link):
headers = {'User-agent':'Mozilla/5.0'}
try:
r = requests.head(link, headers=headers, allow_redirects=Tru... | Return exception details when failing to load link | Return exception details when failing to load link
| Python | mit | edgauthier/pinboard_linkrot | #!/usr/bin/env python
from __future__ import division
import requests
import json
import sys
from requests.exceptions import SSLError, InvalidSchema, ConnectionError
def get_link_status_code(link):
headers = {'User-agent':'Mozilla/5.0'}
try:
r = requests.head(link, headers=headers, allow_redirects=Tru... | Return exception details when failing to load link
#!/usr/bin/env python
from __future__ import division
import requests
import json
import sys
from requests.exceptions import SSLError, InvalidSchema, ConnectionError
def get_link_status_code(link):
headers = {'User-agent':'Mozilla/5.0'}
try:
r = requ... |
2fda06e11c9b536a5771d5b7f4fb31e5c20223a0 | run_jstests.py | run_jstests.py | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Runs DomDistillers jstests.
This uses ChromeDriver (https://sites.google.com/a/chromium.org/chromedriver/) to run the jstests.
This... | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Runs DomDistillers jstests.
This uses ChromeDriver (https://sites.google.com/a/chromium.org/chromedriver/) to run the jstests.
This... | Fix printing of logged non-ascii characters | Fix printing of logged non-ascii characters
webdriver seems to not handle non-ascii characters in the result of an
executed script correctly (python throws an exception when printing the
string). This makes them be printed correctly.
R=mdjones@chromium.org
Review URL: https://codereview.chromium.org/848503003
| Python | apache-2.0 | dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Runs DomDistillers jstests.
This uses ChromeDriver (https://sites.google.com/a/chromium.org/chromedriver/) to run the jstests.
This... | Fix printing of logged non-ascii characters
webdriver seems to not handle non-ascii characters in the result of an
executed script correctly (python throws an exception when printing the
string). This makes them be printed correctly.
R=mdjones@chromium.org
Review URL: https://codereview.chromium.org/848503003
#!/us... |
59066fc1def071aa51a87a6393c8bdf34f081188 | opps/core/__init__.py | opps/core/__init__.py | # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
... | # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
... | Add haystack connections simples engine om opps | Add haystack connections simples engine om opps
| Python | mit | YACOWS/opps,jeanmask/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,opps/opps,opps/opps,YACOWS/opps,YACOWS/opps,opps/opps,williamroot/opps,YACOWS/opps,williamroot/opps,jeanmask/opps | # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
... | Add haystack connections simples engine om opps
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.r... |
724e8303a80f17c83128b5876dbb3d95c106805c | segments/npm_version.py | segments/npm_version.py | import subprocess
def add_npm_version_segment(powerline):
try:
p1 = subprocess.Popen(["npm", "--version"], stdout=subprocess.PIPE)
version = p1.communicate()[0].decode("utf-8").rstrip()
version = "npm " + version
powerline.append(version, 15, 18)
except OSError:
return
| Add segment for npm version | Add segment for npm version
| Python | mit | tswsl1989/powerline-shell,bitIO/powerline-shell,milkbikis/powerline-shell,banga/powerline-shell,b-ryan/powerline-shell,b-ryan/powerline-shell,banga/powerline-shell | import subprocess
def add_npm_version_segment(powerline):
try:
p1 = subprocess.Popen(["npm", "--version"], stdout=subprocess.PIPE)
version = p1.communicate()[0].decode("utf-8").rstrip()
version = "npm " + version
powerline.append(version, 15, 18)
except OSError:
return
| Add segment for npm version
| |
597f586d2cf42f31a0179efc7ac8441f33b3d637 | lib/mysql.py | lib/mysql.py | import pymysql
class MySQL():
def __init__(self, host, user, password, port):
self._host = host
self._user = user
self._password = password
self._conn = pymysql.connect(host=host, port=port,
user=user, passwd=password)
self._cursor = self._conn.cursor... | import pymysql
class MySQL():
def __init__(self, host, user, password, port):
self._host = host
self._user = user
self._password = password
self._port = port
self._conn = pymysql.connect(host=host, port=port,
user=user, passwd=password)
self._... | Define the port variable for reconnection | Define the port variable for reconnection | Python | mit | ImShady/Tubey | import pymysql
class MySQL():
def __init__(self, host, user, password, port):
self._host = host
self._user = user
self._password = password
self._port = port
self._conn = pymysql.connect(host=host, port=port,
user=user, passwd=password)
self._... | Define the port variable for reconnection
import pymysql
class MySQL():
def __init__(self, host, user, password, port):
self._host = host
self._user = user
self._password = password
self._conn = pymysql.connect(host=host, port=port,
user=user, passwd=password... |
26953686515270497cf2361f4a20039603f2f1bd | InvenTree/company/migrations/0018_supplierpart_manufacturer.py | InvenTree/company/migrations/0018_supplierpart_manufacturer.py | # Generated by Django 2.2.10 on 2020-04-13 03:29
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('company', '0017_auto_20200413_0320'),
]
operations = [
migrations.AddField(
model_name='suppli... | Add migration to create a 'manufacturer' field to the SupplierPart model | Add migration to create a 'manufacturer' field to the SupplierPart model
(cherry picked from commit 890e938662ed4aff53ea9399b54a86359d23f23f)
| Python | mit | inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree | # Generated by Django 2.2.10 on 2020-04-13 03:29
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('company', '0017_auto_20200413_0320'),
]
operations = [
migrations.AddField(
model_name='suppli... | Add migration to create a 'manufacturer' field to the SupplierPart model
(cherry picked from commit 890e938662ed4aff53ea9399b54a86359d23f23f)
| |
2fa1e73c44b03ab81e72d14863fd80cff010f0d7 | tests/test_comparisons.py | tests/test_comparisons.py | from itertools import combinations
from unittest import TestCase
from ordering import Ordering
class TestComparisons(TestCase):
def setUp(self) -> None:
self.ordering = Ordering[int]()
self.ordering.insert_start(0)
self.ordering.insert_after(0, 1)
self.ordering.insert_before(0, 2... | Add unit test for complicated comparisons | Add unit test for complicated comparisons
| Python | mit | madman-bob/python-order-maintenance | from itertools import combinations
from unittest import TestCase
from ordering import Ordering
class TestComparisons(TestCase):
def setUp(self) -> None:
self.ordering = Ordering[int]()
self.ordering.insert_start(0)
self.ordering.insert_after(0, 1)
self.ordering.insert_before(0, 2... | Add unit test for complicated comparisons
| |
3965effea3a251d69141e4ef4df6de8a2d5a5089 | shuup_tests/browser/admin/test_menu.py | shuup_tests/browser/admin/test_menu.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import os
import pytest
from shuup.testing.browser_utils import w... | Add browser test for admin menu | Add browser test for admin menu
Refs SH-435
| Python | agpl-3.0 | suutari-ai/shoop,suutari/shoop,suutari/shoop,shoopio/shoop,shoopio/shoop,shoopio/shoop,suutari-ai/shoop,suutari-ai/shoop,suutari/shoop | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import os
import pytest
from shuup.testing.browser_utils import w... | Add browser test for admin menu
Refs SH-435
| |
1a1600b0cd27d5e004be344574901c64cdd6f7a2 | scripts/imgtool/__init__.py | scripts/imgtool/__init__.py | # Copyright 2017 Linaro Limited
#
# 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 writin... | # Copyright 2017-2020 Linaro Limited
#
# 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 w... | Change imgtool version to 1.7.0a1 | Change imgtool version to 1.7.0a1
Signed-off-by: Ihor Slabkyy <5b878c9a28a92b9cb7e9988086921fcb7ae33592@cypress.com>
| Python | apache-2.0 | utzig/mcuboot,tamban01/mcuboot,utzig/mcuboot,runtimeco/mcuboot,runtimeco/mcuboot,runtimeco/mcuboot,tamban01/mcuboot,runtimeco/mcuboot,ATmobica/mcuboot,ATmobica/mcuboot,utzig/mcuboot,tamban01/mcuboot,tamban01/mcuboot,ATmobica/mcuboot,runtimeco/mcuboot,tamban01/mcuboot,utzig/mcuboot,utzig/mcuboot,ATmobica/mcuboot,ATmobic... | # Copyright 2017-2020 Linaro Limited
#
# 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 w... | Change imgtool version to 1.7.0a1
Signed-off-by: Ihor Slabkyy <5b878c9a28a92b9cb7e9988086921fcb7ae33592@cypress.com>
# Copyright 2017 Linaro Limited
#
# 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 Lic... |
b2e26c044e9d5890945e01364d62f814fcd07949 | test/unit/interfaces/test_group_dicom.py | test/unit/interfaces/test_group_dicom.py | import os
from nose.tools import (assert_equal, assert_in, assert_true)
from ...helpers.logging import logger
from qipipe.interfaces import GroupDicom
from ... import ROOT
from ...helpers.logging import logger
# The test fixture.
FIXTURE = os.path.join(ROOT, 'fixtures', 'staging', 'breast', 'BreastChemo3',
... | import os
from nose.tools import (assert_equal, assert_in, assert_true)
from ...helpers.logging import logger
from qipipe.interfaces import GroupDicom
from ... import ROOT
from ...helpers.logging import logger
# The test fixture.
FIXTURE = os.path.join(ROOT, 'fixtures', 'staging', 'breast', 'BreastChemo3',
... | Test the volume rather than series. | Test the volume rather than series.
| Python | bsd-2-clause | ohsu-qin/qipipe | import os
from nose.tools import (assert_equal, assert_in, assert_true)
from ...helpers.logging import logger
from qipipe.interfaces import GroupDicom
from ... import ROOT
from ...helpers.logging import logger
# The test fixture.
FIXTURE = os.path.join(ROOT, 'fixtures', 'staging', 'breast', 'BreastChemo3',
... | Test the volume rather than series.
import os
from nose.tools import (assert_equal, assert_in, assert_true)
from ...helpers.logging import logger
from qipipe.interfaces import GroupDicom
from ... import ROOT
from ...helpers.logging import logger
# The test fixture.
FIXTURE = os.path.join(ROOT, 'fixtures', 'staging', ... |
38eafc8a4a78da04b0260d2bad6a38addb82ee4a | admin_honeypot/migrations/0002_add_field_LoginAttempt_path.py | admin_honeypot/migrations/0002_add_field_LoginAttempt_path.py | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'LoginAttempt.path'
db.add_column('admin_honeypot_loginattempt', 'path',
... | Add South migration for LoginAttempt.path | Add South migration for LoginAttempt.path
| Python | mit | wujuguang/django-admin-honeypot,ajostergaard/django-admin-honeypot,dmpayton/django-admin-honeypot,Samael500/django-admin-honeypot,Samael500/django-admin-honeypot,ajostergaard/django-admin-honeypot,wujuguang/django-admin-honeypot,javierchavez/django-admin-honeypot,javierchavez/django-admin-honeypot,dmpayton/django-admin... | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'LoginAttempt.path'
db.add_column('admin_honeypot_loginattempt', 'path',
... | Add South migration for LoginAttempt.path
| |
d1917d20f3aa26380e1e617f50b380142905d745 | engines/string_template_engine.py | engines/string_template_engine.py | #!/usr/bin/env python
"""Provide the standard Python string.Template engine."""
from __future__ import print_function
from string import Template
from . import Engine
class StringTemplate(Engine):
"""String.Template engine."""
handle = 'string.Template'
def __init__(self, template, tolerant=False, ... | #!/usr/bin/env python
"""Provide the standard Python string.Template engine."""
from __future__ import print_function
from string import Template
from . import Engine
class StringTemplate(Engine):
"""String.Template engine."""
handle = 'string.Template'
def __init__(self, template, tolerant=False, *... | Transform values in string.Template engine before substitution. | Transform values in string.Template engine before substitution.
| Python | mit | blubberdiblub/eztemplate | #!/usr/bin/env python
"""Provide the standard Python string.Template engine."""
from __future__ import print_function
from string import Template
from . import Engine
class StringTemplate(Engine):
"""String.Template engine."""
handle = 'string.Template'
def __init__(self, template, tolerant=False, *... | Transform values in string.Template engine before substitution.
#!/usr/bin/env python
"""Provide the standard Python string.Template engine."""
from __future__ import print_function
from string import Template
from . import Engine
class StringTemplate(Engine):
"""String.Template engine."""
handle = 'st... |
c09b468583c97d7831478119614b231be0d24afa | scripts/generate_input_syntax.py | scripts/generate_input_syntax.py | #!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# this script is actually in the scripts subdirectory, so go up a level
app_path += '/..'
# Set the name of the application here and moose directory relative to the application
app_name = 'f... | #!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# Set the name of the application here and moose directory relative to the application
app_name = 'falcon'
MOOSE_DIR = os.path.abspath(os.path.join(app_path, '..', '..' 'moose'))
FRAMEWORK_... | Update scripts to reflect new MOOSE_DIR definition | Update scripts to reflect new MOOSE_DIR definition
r25009
| Python | lgpl-2.1 | idaholab/falcon,aeslaughter/falcon,idaholab/falcon,aeslaughter/falcon,idaholab/falcon,idaholab/falcon,aeslaughter/falcon | #!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# Set the name of the application here and moose directory relative to the application
app_name = 'falcon'
MOOSE_DIR = os.path.abspath(os.path.join(app_path, '..', '..' 'moose'))
FRAMEWORK_... | Update scripts to reflect new MOOSE_DIR definition
r25009
#!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# this script is actually in the scripts subdirectory, so go up a level
app_path += '/..'
# Set the name of the application here a... |
1d55fe7b1f4f3d70da6867ef7465ac44f8d2da38 | keyring/tests/backends/test_OS_X.py | keyring/tests/backends/test_OS_X.py | import sys
from ..test_backend import BackendBasicTests
from ..py30compat import unittest
from keyring.backends import OS_X
def is_osx_keychain_supported():
return sys.platform in ('mac','darwin')
@unittest.skipUnless(is_osx_keychain_supported(),
"Need OS X")
class OSXKeychainTestCase(Backen... | import sys
from ..test_backend import BackendBasicTests
from ..py30compat import unittest
from keyring.backends import OS_X
def is_osx_keychain_supported():
return sys.platform in ('mac','darwin')
@unittest.skipUnless(is_osx_keychain_supported(),
"Need OS X")
class OSXKeychainTestCase(Backen... | Test passes on OS X | Test passes on OS X
| Python | mit | jaraco/keyring | import sys
from ..test_backend import BackendBasicTests
from ..py30compat import unittest
from keyring.backends import OS_X
def is_osx_keychain_supported():
return sys.platform in ('mac','darwin')
@unittest.skipUnless(is_osx_keychain_supported(),
"Need OS X")
class OSXKeychainTestCase(Backen... | Test passes on OS X
import sys
from ..test_backend import BackendBasicTests
from ..py30compat import unittest
from keyring.backends import OS_X
def is_osx_keychain_supported():
return sys.platform in ('mac','darwin')
@unittest.skipUnless(is_osx_keychain_supported(),
"Need OS X")
class OSXKe... |
f732ab01373e73fe8f707e88f8ba60f4610fc0d4 | polling_stations/apps/data_collection/management/commands/import_denbighshire.py | polling_stations/apps/data_collection/management/commands/import_denbighshire.py | """
Import Denbighshire
"""
from time import sleep
from django.contrib.gis.geos import Point
from data_collection.management.commands import BaseAddressCsvImporter
from data_finder.helpers import geocode
class Command(BaseAddressCsvImporter):
"""
Imports the Polling Station data from Denbighshire
"""
c... | Add import script for Denbighshire | Add import script for Denbighshire
| Python | bsd-3-clause | chris48s/UK-Polling-Stations,andylolz/UK-Polling-Stations,chris48s/UK-Polling-Stations,andylolz/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,andylolz/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations | """
Import Denbighshire
"""
from time import sleep
from django.contrib.gis.geos import Point
from data_collection.management.commands import BaseAddressCsvImporter
from data_finder.helpers import geocode
class Command(BaseAddressCsvImporter):
"""
Imports the Polling Station data from Denbighshire
"""
c... | Add import script for Denbighshire
| |
7226e9ae349eadba10d8f23f81df0b4d70adb6a2 | detectem/plugins/helpers.py | detectem/plugins/helpers.py | def meta_generator(name):
return '//meta[@name="generator" and contains(@content, "{}")]' \
'/@content'.format(name)
| def meta_generator(name):
return '//meta[re:test(@name,"generator","i") and contains(@content, "{}")]' \
'/@content'.format(name)
| Update meta_generator to match case insensitive | Update meta_generator to match case insensitive
| Python | mit | spectresearch/detectem | def meta_generator(name):
return '//meta[re:test(@name,"generator","i") and contains(@content, "{}")]' \
'/@content'.format(name)
| Update meta_generator to match case insensitive
def meta_generator(name):
return '//meta[@name="generator" and contains(@content, "{}")]' \
'/@content'.format(name)
|
bdc0466c63347280fbd8bc8c30fb07f294200194 | client/third_party/idna/__init__.py | client/third_party/idna/__init__.py | # Emulate the bare minimum for idna for the Swarming bot.
# In practice, we do not need it, and it's very large.
def encode(host, uts46):
return unicode(host)
| # Emulate the bare minimum for idna for the Swarming bot.
# In practice, we do not need it, and it's very large.
# See https://pypi.org/project/idna/
from encodings import idna
def encode(host, uts46=False): # pylint: disable=unused-argument
# Used by urllib3
return idna.ToASCII(host)
def decode(host):
# Us... | Change idna stub to use python's default | [client] Change idna stub to use python's default
Fix a regression from 690b8ae29be2ca3b4782fa6ad0e7f2454443c38d which broke
select bots running inside docker.
The new stub is still simpler than https://pypi.org/project/idna/ and lighter
weight but much better than ignoring the "xn-" encoding as this was done
previou... | Python | apache-2.0 | luci/luci-py,luci/luci-py,luci/luci-py,luci/luci-py | # Emulate the bare minimum for idna for the Swarming bot.
# In practice, we do not need it, and it's very large.
# See https://pypi.org/project/idna/
from encodings import idna
def encode(host, uts46=False): # pylint: disable=unused-argument
# Used by urllib3
return idna.ToASCII(host)
def decode(host):
# Us... | [client] Change idna stub to use python's default
Fix a regression from 690b8ae29be2ca3b4782fa6ad0e7f2454443c38d which broke
select bots running inside docker.
The new stub is still simpler than https://pypi.org/project/idna/ and lighter
weight but much better than ignoring the "xn-" encoding as this was done
previou... |
f542b05f9a344c6a39b6ed3b163deddc3086be26 | pybinding/model.py | pybinding/model.py | import _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isin... | import _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
from .system import System as _System
from .hamiltonian import Hamiltonian as _Hamiltonian
from .solver.solver_ex import SolverEx as _Solver
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*... | Annotate return types of Model properties | Annotate return types of Model properties
| Python | bsd-2-clause | MAndelkovic/pybinding,dean0x7d/pybinding,dean0x7d/pybinding,MAndelkovic/pybinding,MAndelkovic/pybinding,dean0x7d/pybinding | import _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
from .system import System as _System
from .hamiltonian import Hamiltonian as _Hamiltonian
from .solver.solver_ex import SolverEx as _Solver
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*... | Annotate return types of Model properties
import _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
... |
a3c768ab90d1354441d90699049f7dd946e683c2 | cleverhans/future/torch/attacks/__init__.py | cleverhans/future/torch/attacks/__init__.py | # pylint: disable=missing-docstring
from cleverhans.future.torch.attacks.fast_gradient_method import fast_gradient_method
from cleverhans.future.torch.attacks.projected_gradient_descent import projected_gradient_descent
from cleverhans.future.torch.attacks.noise import noise
from cleverhans.future.torch.attacks.semanti... | # pylint: disable=missing-docstring
from cleverhans.future.torch.attacks.fast_gradient_method import fast_gradient_method
from cleverhans.future.torch.attacks.projected_gradient_descent import projected_gradient_descent
from cleverhans.future.torch.attacks.noise import noise
from cleverhans.future.torch.attacks.semanti... | Allow spsa to be imported from cleverhans.future.torch.attacks | Allow spsa to be imported from cleverhans.future.torch.attacks
| Python | mit | cleverhans-lab/cleverhans,cleverhans-lab/cleverhans,cleverhans-lab/cleverhans | # pylint: disable=missing-docstring
from cleverhans.future.torch.attacks.fast_gradient_method import fast_gradient_method
from cleverhans.future.torch.attacks.projected_gradient_descent import projected_gradient_descent
from cleverhans.future.torch.attacks.noise import noise
from cleverhans.future.torch.attacks.semanti... | Allow spsa to be imported from cleverhans.future.torch.attacks
# pylint: disable=missing-docstring
from cleverhans.future.torch.attacks.fast_gradient_method import fast_gradient_method
from cleverhans.future.torch.attacks.projected_gradient_descent import projected_gradient_descent
from cleverhans.future.torch.attacks... |
ca7fb88d36b386defab610388761609539e0a9cf | conary/build/capsulerecipe.py | conary/build/capsulerecipe.py | #
# Copyright (c) 2009 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/... | #
# Copyright (c) 2009 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/... | Enable building hybrid capsule/non-capsule packages (CNY-3271) | Enable building hybrid capsule/non-capsule packages (CNY-3271)
| Python | apache-2.0 | fedora-conary/conary,fedora-conary/conary,fedora-conary/conary,fedora-conary/conary,fedora-conary/conary | #
# Copyright (c) 2009 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/... | Enable building hybrid capsule/non-capsule packages (CNY-3271)
#
# Copyright (c) 2009 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the ... |
31f887979d2129bec80311e94b91cf0f77772f26 | zou/app/utils/fs.py | zou/app/utils/fs.py | import os
import shutil
import errno
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def rm_rf(path):
if os.path.exists(path):
shutil.rmtree(path)
| import os
import shutil
import errno
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def rm_rf(path):
if os.path.exists(path):
shutil.rmtree(path)
... | Add a new copy file util function | Add a new copy file util function
| Python | agpl-3.0 | cgwire/zou | import os
import shutil
import errno
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def rm_rf(path):
if os.path.exists(path):
shutil.rmtree(path)
... | Add a new copy file util function
import os
import shutil
import errno
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def rm_rf(path):
if os.path.exists(... |
48d9e6c2d36b7c1beb11f6574624731a88cdccbc | accounts/views.py | accounts/views.py | from django.views.generic import View
from django.shortcuts import render
class MemberProfileView(View):
template_name = 'accounts/profile.html'
def get(self, request):
return render(request, self.template_name) | from django.views.generic import View
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
class MemberProfileView(LoginRequiredMixin, View):
login_url = '/accounts/login/'
redirect_field_name = 'redirect_to'
template_name = 'accounts/profile.html'
def get(sel... | Add login required mixin to user profile | Add login required mixin to user profile
| Python | mit | davidjrichardson/uwcs-zarya,davidjrichardson/uwcs-zarya | from django.views.generic import View
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
class MemberProfileView(LoginRequiredMixin, View):
login_url = '/accounts/login/'
redirect_field_name = 'redirect_to'
template_name = 'accounts/profile.html'
def get(sel... | Add login required mixin to user profile
from django.views.generic import View
from django.shortcuts import render
class MemberProfileView(View):
template_name = 'accounts/profile.html'
def get(self, request):
return render(request, self.template_name) |
ab9cd172641176c2ae8fdb0ec20d48e45499436e | django_extensions/management/technical_response.py | django_extensions/management/technical_response.py | # -*- coding: utf-8 -*-
import six
def null_technical_500_response(request, exc_type, exc_value, tb, status_code=500):
six.reraise(exc_type, exc_value, tb)
| # -*- coding: utf-8 -*-
import six
from django.core.handlers.wsgi import WSGIHandler
wsgi_tb = None
def null_technical_500_response(request, exc_type, exc_value, tb, status_code=500):
"""Function to override django.views.debug.technical_500_response.
Django's convert_exception_to_response wrapper is called ... | Reduce reraise pollution in runserver_plus traceback page | Reduce reraise pollution in runserver_plus traceback page
| Python | mit | django-extensions/django-extensions,django-extensions/django-extensions,django-extensions/django-extensions | # -*- coding: utf-8 -*-
import six
from django.core.handlers.wsgi import WSGIHandler
wsgi_tb = None
def null_technical_500_response(request, exc_type, exc_value, tb, status_code=500):
"""Function to override django.views.debug.technical_500_response.
Django's convert_exception_to_response wrapper is called ... | Reduce reraise pollution in runserver_plus traceback page
# -*- coding: utf-8 -*-
import six
def null_technical_500_response(request, exc_type, exc_value, tb, status_code=500):
six.reraise(exc_type, exc_value, tb)
|
9c9a33869747223952b4a999a5a14354ffb3e540 | contrib/examples/actions/pythonactions/forloop_parse_github_repos.py | contrib/examples/actions/pythonactions/forloop_parse_github_repos.py | from st2actions.runners.pythonrunner import Action
from bs4 import BeautifulSoup
class ParseGithubRepos(Action):
def run(self, content):
try:
soup = BeautifulSoup(content, 'html.parser')
repo_list = soup.find_all("h3")
output = {}
for each_item in repo_list:
repo_half_url = each_i... | from st2actions.runners.pythonrunner import Action
from bs4 import BeautifulSoup
class ParseGithubRepos(Action):
def run(self, content):
try:
soup = BeautifulSoup(content, 'html.parser')
repo_list = soup.find_all("h3")
output = {}
for each_item in repo_list:
repo_half_url = each_i... | Throw exception instead of returning false. | Throw exception instead of returning false.
| Python | apache-2.0 | StackStorm/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,StackStorm/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2,nzlosh/st2,nzlosh/st2,StackStorm/st2 | from st2actions.runners.pythonrunner import Action
from bs4 import BeautifulSoup
class ParseGithubRepos(Action):
def run(self, content):
try:
soup = BeautifulSoup(content, 'html.parser')
repo_list = soup.find_all("h3")
output = {}
for each_item in repo_list:
repo_half_url = each_i... | Throw exception instead of returning false.
from st2actions.runners.pythonrunner import Action
from bs4 import BeautifulSoup
class ParseGithubRepos(Action):
def run(self, content):
try:
soup = BeautifulSoup(content, 'html.parser')
repo_list = soup.find_all("h3")
output = {}
for each_item... |
07ae4af01043887d584e3024d7d7e0aa093c85f4 | intercom.py | intercom.py | import configparser
import time
import RPi.GPIO as GPIO
from client import MumbleClient
class InterCom:
def __init__(self):
config = configparser.ConfigParser()
config.read('intercom.ini')
self.mumble_client = MumbleClient(config['mumbleclient'])
self.exit = False
self.sen... | import configparser
import time
import RPi.GPIO as GPIO
from client import MumbleClient
class InterCom:
def __init__(self):
config = configparser.ConfigParser()
config.read('intercom.ini')
self.mumble_client = MumbleClient(config['mumbleclient'])
self.exit = False
if conf... | Add clearing if not recording and remove useless member | Add clearing if not recording and remove useless member
| Python | mit | pkronstrom/intercom | import configparser
import time
import RPi.GPIO as GPIO
from client import MumbleClient
class InterCom:
def __init__(self):
config = configparser.ConfigParser()
config.read('intercom.ini')
self.mumble_client = MumbleClient(config['mumbleclient'])
self.exit = False
if conf... | Add clearing if not recording and remove useless member
import configparser
import time
import RPi.GPIO as GPIO
from client import MumbleClient
class InterCom:
def __init__(self):
config = configparser.ConfigParser()
config.read('intercom.ini')
self.mumble_client = MumbleClient(config['m... |
6924b1326b664e405f926c36753192603204034e | salt/modules/nfs.py | salt/modules/nfs.py | '''
Module for managing NFS.
'''
# Import python libs
import logging
import salt.utils
log = logging.getLogger(__name__)
def __virtual__():
'''
Only work on posix-like systems
'''
# Disable on these platorms, specific service modules exist:
disable = [
'Windows',
]
if not sa... | '''
Module for managing NFS.
'''
# Import python libs
import logging
import salt.utils
log = logging.getLogger(__name__)
def __virtual__():
'''
Only work on posix-like systems
'''
# Disable on these platorms, specific service modules exist:
disable = [
'Windows',
]
if not sa... | Add multiple permissions to a single export | Add multiple permissions to a single export
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | '''
Module for managing NFS.
'''
# Import python libs
import logging
import salt.utils
log = logging.getLogger(__name__)
def __virtual__():
'''
Only work on posix-like systems
'''
# Disable on these platorms, specific service modules exist:
disable = [
'Windows',
]
if not sa... | Add multiple permissions to a single export
'''
Module for managing NFS.
'''
# Import python libs
import logging
import salt.utils
log = logging.getLogger(__name__)
def __virtual__():
'''
Only work on posix-like systems
'''
# Disable on these platorms, specific service modules exist:
disable =... |
ad7d39c472130e7f06c30d06a5aed465d2e5ab2c | linter.py | linter.py | from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
cmd = ('cppcheck', '--template={file}:{line}: {severity}: {message}', '--inline-suppr', '--quiet', '${args}', '${file}')
regex = (
r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\d+):)?\s+'
r'((?P<error>error)|(?P<warning>war... | from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
cmd = (
'cppcheck',
'--template={file}:{line}: {severity}: {message}',
'--inline-suppr',
'--quiet',
'${args}',
'${file}'
)
regex = (
r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\... | Reformat cmd to go under 120 character limit | Reformat cmd to go under 120 character limit | Python | mit | SublimeLinter/SublimeLinter-cppcheck | from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
cmd = (
'cppcheck',
'--template={file}:{line}: {severity}: {message}',
'--inline-suppr',
'--quiet',
'${args}',
'${file}'
)
regex = (
r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\... | Reformat cmd to go under 120 character limit
from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
cmd = ('cppcheck', '--template={file}:{line}: {severity}: {message}', '--inline-suppr', '--quiet', '${args}', '${file}')
regex = (
r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\d+):)?\s+... |
211eefa9e607e16ad04e3617c2de1156697417e2 | tests/test_apps.py | tests/test_apps.py | from unittest import TestCase
from clean_fields.apps import CleanFieldsConfig
class CleanFieldsConfigTestCase(TestCase):
def test_name_class_attr(self):
self.assertEqual(CleanFieldsConfig.name, 'clean_fields')
| Add unit tests for AppConfig | Add unit tests for AppConfig
Oh, that sweet, sweet 100% coverage. Aw yiss.
| Python | mit | lamarmeigs/django-clean-fields | from unittest import TestCase
from clean_fields.apps import CleanFieldsConfig
class CleanFieldsConfigTestCase(TestCase):
def test_name_class_attr(self):
self.assertEqual(CleanFieldsConfig.name, 'clean_fields')
| Add unit tests for AppConfig
Oh, that sweet, sweet 100% coverage. Aw yiss.
| |
de9c5235d379fcebbfc801fb23c3b9aa2f1fe4e8 | benchmark/datasets/musicbrainz/extract-random-queries.py | benchmark/datasets/musicbrainz/extract-random-queries.py | #!/usr/bin/env python
"""
Script to extract and then generate random queries for fuzzy searching.
Usage:
./extract-random-queries.py <infile> <outfile>
"""
import os
from random import choice, randint, random
import string
from subprocess import call
import sys
from tempfile import mkstemp
__author__ = "Uwe L. K... | #!/usr/bin/env python
"""
Script to extract and then generate random queries for fuzzy searching.
Usage:
./extract-random-queries.py <infile> <outfile>
"""
import codecs
import os
from random import choice, randint, random
import string
from subprocess import call
import sys
from tempfile import mkstemp
__author... | Fix query extractor UTF-8 handling | Fix query extractor UTF-8 handling | Python | mit | xhochy/libfuzzymatch,xhochy/libfuzzymatch | #!/usr/bin/env python
"""
Script to extract and then generate random queries for fuzzy searching.
Usage:
./extract-random-queries.py <infile> <outfile>
"""
import codecs
import os
from random import choice, randint, random
import string
from subprocess import call
import sys
from tempfile import mkstemp
__author... | Fix query extractor UTF-8 handling
#!/usr/bin/env python
"""
Script to extract and then generate random queries for fuzzy searching.
Usage:
./extract-random-queries.py <infile> <outfile>
"""
import os
from random import choice, randint, random
import string
from subprocess import call
import sys
from tempfile imp... |
6ed04d735641a42103f7626fafc8570f04b6b1dc | quiet.py | quiet.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import webbrowser
from Foundation import NSBundle
import rumps
import modules.google_calendar
#rumps.debug_mode(True) # turn on command line logging information for development - default is off
def about(sender):
webbrowser.open("https://github.com/hiroshi/quiet")
if... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import webbrowser
from Foundation import NSBundle
import rumps
import modules.google_calendar
#rumps.debug_mode(True) # turn on command line logging information for development - default is off
def about(sender):
webbrowser.open("https://github.com/hiroshi/quiet/wiki"... | Change about link to github wiki | Change about link to github wiki
| Python | mit | hiroshi/quiet | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import webbrowser
from Foundation import NSBundle
import rumps
import modules.google_calendar
#rumps.debug_mode(True) # turn on command line logging information for development - default is off
def about(sender):
webbrowser.open("https://github.com/hiroshi/quiet/wiki"... | Change about link to github wiki
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import webbrowser
from Foundation import NSBundle
import rumps
import modules.google_calendar
#rumps.debug_mode(True) # turn on command line logging information for development - default is off
def about(sender):
webbrowser.open("http... |
ba93ea71b87c95f4d52c85ae652496ebfb012e1f | pupa/importers/memberships.py | pupa/importers/memberships.py | from .base import BaseImporter
class MembershipImporter(BaseImporter):
_type = 'membership'
def __init__(self, jurisdiction_id, person_importer, org_importer):
super(MembershipImporter, self).__init__(jurisdiction_id)
self.person_importer = person_importer
self.org_importer = org_impo... | from .base import BaseImporter
class MembershipImporter(BaseImporter):
_type = 'membership'
def __init__(self, jurisdiction_id, person_importer, org_importer):
super(MembershipImporter, self).__init__(jurisdiction_id)
self.person_importer = person_importer
self.org_importer = org_impo... | Add unmatched_legislator to the spec | Add unmatched_legislator to the spec
| Python | bsd-3-clause | datamade/pupa,datamade/pupa,rshorey/pupa,mileswwatkins/pupa,rshorey/pupa,mileswwatkins/pupa,opencivicdata/pupa,influence-usa/pupa,influence-usa/pupa,opencivicdata/pupa | from .base import BaseImporter
class MembershipImporter(BaseImporter):
_type = 'membership'
def __init__(self, jurisdiction_id, person_importer, org_importer):
super(MembershipImporter, self).__init__(jurisdiction_id)
self.person_importer = person_importer
self.org_importer = org_impo... | Add unmatched_legislator to the spec
from .base import BaseImporter
class MembershipImporter(BaseImporter):
_type = 'membership'
def __init__(self, jurisdiction_id, person_importer, org_importer):
super(MembershipImporter, self).__init__(jurisdiction_id)
self.person_importer = person_importe... |
1e980277f53d12686264b8ce816e65ffea16a2dd | examples/basic.py | examples/basic.py | from simpleflow import (
activity,
Workflow,
)
@activity.with_attributes(task_list='quickstart')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart')
def double(x):
return x * 2
class BasicWorkflow(Workflow):
name = 'basic'
version = 'example'
def run(self,... | import time
from simpleflow import (
activity,
Workflow,
)
@activity.with_attributes(task_list='quickstart')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart')
def double(x):
return x * 2
@activity.with_attributes(task_list='quickstart', version='example')
def delay(... | Update example: add a delay task | Update example: add a delay task
| Python | mit | botify-labs/simpleflow,botify-labs/simpleflow | import time
from simpleflow import (
activity,
Workflow,
)
@activity.with_attributes(task_list='quickstart')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart')
def double(x):
return x * 2
@activity.with_attributes(task_list='quickstart', version='example')
def delay(... | Update example: add a delay task
from simpleflow import (
activity,
Workflow,
)
@activity.with_attributes(task_list='quickstart')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart')
def double(x):
return x * 2
class BasicWorkflow(Workflow):
name = 'basic'
vers... |
4a43bc36f0f3a413b222f2cb1fac316240168aa2 | LPC.py | LPC.py | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 27 22:01:37 2016
@author: ORCHISAMA
"""
#calculate LPC coefficients from sound file
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
def autocorr(x):
n = len(x)
variance = np.var(x)
x = x - np.mean(x)
r = np.correlate(x... | Add program to calculate Linear Prediction Coefficients | Add program to calculate Linear Prediction Coefficients
| Python | mit | orchidas/Speaker-Recognition | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 27 22:01:37 2016
@author: ORCHISAMA
"""
#calculate LPC coefficients from sound file
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
def autocorr(x):
n = len(x)
variance = np.var(x)
x = x - np.mean(x)
r = np.correlate(x... | Add program to calculate Linear Prediction Coefficients
| |
16144d2edf80d634182e1ff185dc4f39e467871d | st2common/tests/unit/test_util_payload.py | st2common/tests/unit/test_util_payload.py | # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Licen... | Add tests for new payload module | Add tests for new payload module
| Python | apache-2.0 | nzlosh/st2,nzlosh/st2,Plexxi/st2,nzlosh/st2,StackStorm/st2,StackStorm/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,StackStorm/st2 | # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Licen... | Add tests for new payload module
| |
c977bef31fd36356f3a131d1f25250640c61f4b7 | dojango/__init__.py | dojango/__init__.py | VERSION = (0, 5, 5, 'final', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
if VERSION[3] != 'final':
version = '%s %... | VERSION = (0, 5, 6, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
if VERSION[3] != 'final':
version = '%s %... | Mark dojango as 0.5.6 alpha | Mark dojango as 0.5.6 alpha
| Python | bsd-3-clause | ofirr/dojango,ricard33/dojango,ofirr/dojango,ricard33/dojango,ofirr/dojango,william-gr/dojango,william-gr/dojango,ricard33/dojango,klipstein/dojango,william-gr/dojango,klipstein/dojango | VERSION = (0, 5, 6, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
if VERSION[3] != 'final':
version = '%s %... | Mark dojango as 0.5.6 alpha
VERSION = (0, 5, 5, 'final', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
if VERSION[3] != 'final'... |
2a4d78be3df2d068431fe007b6f2d73956dc23d4 | sitecontent/urls.py | sitecontent/urls.py | from django.conf.urls import patterns, url
from sitecontent import views
urlpatterns = patterns('',
url("^rss/(?P<format>.*)$",
"sitecontent.views.blog_post_feed_richtext_filters", name="blog_post_feed_richtext_filters"),
)
| from django.conf.urls import patterns, url
from sitecontent import views
urlpatterns = patterns('',
url("^feeds/(?P<format>.*)$",
"sitecontent.views.blog_post_feed_richtext_filters", name="blog_post_feed_richtext_filters"),
)
| Use feeds instead of rss | Use feeds instead of rss
| Python | mit | vjousse/viserlalune,vjousse/viserlalune,vjousse/viserlalune,vjousse/viserlalune | from django.conf.urls import patterns, url
from sitecontent import views
urlpatterns = patterns('',
url("^feeds/(?P<format>.*)$",
"sitecontent.views.blog_post_feed_richtext_filters", name="blog_post_feed_richtext_filters"),
)
| Use feeds instead of rss
from django.conf.urls import patterns, url
from sitecontent import views
urlpatterns = patterns('',
url("^rss/(?P<format>.*)$",
"sitecontent.views.blog_post_feed_richtext_filters", name="blog_post_feed_richtext_filters"),
)
|
a9c8d3331451deaaa6b156d73df951021705fd71 | setup.py | setup.py | import setuptools
REQUIREMENTS = [
"docopt==0.6.1",
"feedparser==5.1.3",
"jabberbot==0.15",
"xmpppy==0.5.0rc1",
]
if __name__ == "__main__":
setuptools.setup(
name="dudebot",
version="0.0.6",
author="Sujay Mansingh",
author_email="sujay.mansingh@gmail.com",
... | import setuptools
REQUIREMENTS = [
"docopt==0.6.1",
"feedparser==5.1.3",
"jabberbot==0.15",
"xmpppy==0.5.0rc1",
]
if __name__ == "__main__":
setuptools.setup(
name="dudebot",
version="0.0.6",
author="Sujay Mansingh",
author_email="sujay.mansingh@gmail.com",
... | Use a placeholder string instead of a README. | Use a placeholder string instead of a README.
Until I work out why README.rst isn't being included, use this.
| Python | bsd-2-clause | sujaymansingh/dudebot | import setuptools
REQUIREMENTS = [
"docopt==0.6.1",
"feedparser==5.1.3",
"jabberbot==0.15",
"xmpppy==0.5.0rc1",
]
if __name__ == "__main__":
setuptools.setup(
name="dudebot",
version="0.0.6",
author="Sujay Mansingh",
author_email="sujay.mansingh@gmail.com",
... | Use a placeholder string instead of a README.
Until I work out why README.rst isn't being included, use this.
import setuptools
REQUIREMENTS = [
"docopt==0.6.1",
"feedparser==5.1.3",
"jabberbot==0.15",
"xmpppy==0.5.0rc1",
]
if __name__ == "__main__":
setuptools.setup(
name="dudebot",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.