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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dc755e07516e1cbbcd01f01e8be59abf8f1a6329 | humfrey/update/management/commands/update_dataset.py | humfrey/update/management/commands/update_dataset.py | import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.update.longliving.updater import Updater
class Command(BaseCommand):
def handle(self, *args, **options):
config_file... | import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.update.longliving.updater import Updater
class Command(BaseCommand):
def handle(self, *args, **options):
config_file... | Update trigger can now be specified on the command line as the second argument, and the module can now be run as a script. | Update trigger can now be specified on the command line as the second argument, and the module can now be run as a script.
| Python | bsd-3-clause | ox-it/humfrey,ox-it/humfrey,ox-it/humfrey | import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.update.longliving.updater import Updater
class Command(BaseCommand):
def handle(self, *args, **options):
config_file... | Update trigger can now be specified on the command line as the second argument, and the module can now be run as a script.
import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.updat... |
dbc7ad0dad6161d19f65bbf186d84d23628cfd16 | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', ... | Add entry point for the CLI script | Add entry point for the CLI script
| Python | mit | jcollado/pic2map,jcollado/pic2map,jcollado/pic2map | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', ... | Add entry point for the CLI script
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_fi... |
08ea2c257780f23cec5dfb923e80966fdf9c5ac8 | IPython/zmq/zmqshell.py | IPython/zmq/zmqshell.py | import sys
from subprocess import Popen, PIPE
from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
class ZMQInteractiveShell(InteractiveShell):
"""A subclass of InteractiveShell for ZMQ."""
def system(self, cmd):
cmd = self.var_expand(cmd, depth=2)
p = Popen(cmd, sh... | import sys
from subprocess import Popen, PIPE
from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
class ZMQInteractiveShell(InteractiveShell):
"""A subclass of InteractiveShell for ZMQ."""
def system(self, cmd):
cmd = self.var_expand(cmd, depth=2)
sys.stdout.flush(... | Add flushing to stdout/stderr in system calls. | Add flushing to stdout/stderr in system calls.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | import sys
from subprocess import Popen, PIPE
from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
class ZMQInteractiveShell(InteractiveShell):
"""A subclass of InteractiveShell for ZMQ."""
def system(self, cmd):
cmd = self.var_expand(cmd, depth=2)
sys.stdout.flush(... | Add flushing to stdout/stderr in system calls.
import sys
from subprocess import Popen, PIPE
from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
class ZMQInteractiveShell(InteractiveShell):
"""A subclass of InteractiveShell for ZMQ."""
def system(self, cmd):
cmd = self.va... |
7dbdae4cbf8e4d78f84c2b8163cd62c7935d3890 | bandicoot/tests/generate_regressions.py | bandicoot/tests/generate_regressions.py | import bandicoot as bc
from os.path import dirname, abspath, join
if __name__ == '__main__':
empty_user = bc.User()
empty_user.attributes['empty'] = True
empty_path = join(dirname(abspath(__file__)), 'samples/empty_user.json')
bc.io.to_json(bc.utils.all(empty_user, summary='extended', flatten=True), em... | Add a simple command to generate automatic regressions | Add a simple command to generate automatic regressions
| Python | mit | ulfaslak/bandicoot,yvesalexandre/bandicoot,econandrew/bandicoot,econandrew/bandicoot,yvesalexandre/bandicoot,econandrew/bandicoot,ulfaslak/bandicoot,yvesalexandre/bandicoot,ulfaslak/bandicoot | import bandicoot as bc
from os.path import dirname, abspath, join
if __name__ == '__main__':
empty_user = bc.User()
empty_user.attributes['empty'] = True
empty_path = join(dirname(abspath(__file__)), 'samples/empty_user.json')
bc.io.to_json(bc.utils.all(empty_user, summary='extended', flatten=True), em... | Add a simple command to generate automatic regressions
| |
5c447d46a8a62407549650ada98131968ace9921 | spyc/scheduler.py | spyc/scheduler.py | from spyc.graph import Vertex, find_cycle, topological_sort
class Scheduler(object):
def __init__(self):
self.specs = {}
def ensure(self, spec):
"""Require that ``spec`` is satisfied."""
if spec.key() in self.specs:
self.specs[spec.key()].data.merge(spec)
else:
... | from spyc.graph import Vertex, find_cycle, topological_sort
class CircularDependency(Exception):
pass
class Scheduler(object):
def __init__(self):
self.specs = {}
def ensure(self, spec):
"""Require that ``spec`` is satisfied."""
if spec.key() in self.specs:
self.spe... | Raise a more useful error for circular deps. | Raise a more useful error for circular deps.
| Python | lgpl-2.1 | zenhack/spyc | from spyc.graph import Vertex, find_cycle, topological_sort
class CircularDependency(Exception):
pass
class Scheduler(object):
def __init__(self):
self.specs = {}
def ensure(self, spec):
"""Require that ``spec`` is satisfied."""
if spec.key() in self.specs:
self.spe... | Raise a more useful error for circular deps.
from spyc.graph import Vertex, find_cycle, topological_sort
class Scheduler(object):
def __init__(self):
self.specs = {}
def ensure(self, spec):
"""Require that ``spec`` is satisfied."""
if spec.key() in self.specs:
self.specs... |
fb7e771646946637824b06eaf6d21b8c1b2be164 | main.py | main.py | # -*- coding: utf-8 -*-
'''
url-shortener
==============
An application for generating and storing shorter aliases for
requested urls. Uses `spam-lists`__ to prevent generating a short url
for an address recognized as spam, or to warn a user a pre-existing
short alias has a target that has been later recognized as spa... | # -*- coding: utf-8 -*-
'''
url-shortener
==============
An application for generating and storing shorter aliases for
requested urls. Uses `spam-lists`__ to prevent generating a short url
for an address recognized as spam, or to warn a user a pre-existing
short alias has a target that has been later recognized as spa... | Make application use log file if its name is not None | Make application use log file if its name is not None
| Python | mit | piotr-rusin/url-shortener,piotr-rusin/url-shortener | # -*- coding: utf-8 -*-
'''
url-shortener
==============
An application for generating and storing shorter aliases for
requested urls. Uses `spam-lists`__ to prevent generating a short url
for an address recognized as spam, or to warn a user a pre-existing
short alias has a target that has been later recognized as spa... | Make application use log file if its name is not None
# -*- coding: utf-8 -*-
'''
url-shortener
==============
An application for generating and storing shorter aliases for
requested urls. Uses `spam-lists`__ to prevent generating a short url
for an address recognized as spam, or to warn a user a pre-existing
short a... |
9704602f26b4a9aab15caf00795d283c5f6e4ae4 | src/fiona/tool.py | src/fiona/tool.py | # The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='sto... | # The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='sto... | Change record output to strict GeoJSON. | Change record output to strict GeoJSON.
Meaning features in a FeatureCollection.
| Python | bsd-3-clause | rbuffat/Fiona,Toblerity/Fiona,sgillies/Fiona,johanvdw/Fiona,perrygeo/Fiona,Toblerity/Fiona,perrygeo/Fiona,rbuffat/Fiona | # The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='sto... | Change record output to strict GeoJSON.
Meaning features in a FeatureCollection.
# The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or ... |
cd62369097feba54172c0048c4ef0ec0713be6d3 | linter.py | linter.py |
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports the Bemlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Bemlint(NodeLinter):
"""Provides an ... |
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports the Bemlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Bemlint(NodeLinter):
"""Provides an ... | Fix compatibility for SublimeLinter 4.12.0 | Fix compatibility for SublimeLinter 4.12.0
Signed-off-by: Jack Cherng <159f0f32a62cc912ca55f89bb5e06807cf019bc7@gmail.com>
| Python | mit | DesTincT/SublimeLinter-contrib-bemlint |
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports the Bemlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Bemlint(NodeLinter):
"""Provides an ... | Fix compatibility for SublimeLinter 4.12.0
Signed-off-by: Jack Cherng <159f0f32a62cc912ca55f89bb5e06807cf019bc7@gmail.com>
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports t... |
20f7b0296f0e7139a69f94ca8c80c9ad1b73c011 | tests/test_package.py | tests/test_package.py | import argparse
import mock
import os
import tempfile
import unittest
import shutil
import re
import sys
from dogen.plugins.repo import Repo
from dogen.generator import Generator
class TestPackage(unittest.TestCase):
def setUp(self):
self.workdir = tempfile.mkdtemp(prefix='test_repo_plugin')
self.... | Add a test for package generation | Add a test for package generation
| Python | mit | jboss-dockerfiles/dogen,goldmann/dogen,jboss-container-images/concreate,jboss-container-images/concreate,goldmann/dogen,goldmann/dogen,jboss-container-images/concreate,jboss-dockerfiles/dogen,jboss-dockerfiles/dogen | import argparse
import mock
import os
import tempfile
import unittest
import shutil
import re
import sys
from dogen.plugins.repo import Repo
from dogen.generator import Generator
class TestPackage(unittest.TestCase):
def setUp(self):
self.workdir = tempfile.mkdtemp(prefix='test_repo_plugin')
self.... | Add a test for package generation
| |
460580ff585fa76cebc5e2e9cb1d49550db9f68d | components/item_lock.py | components/item_lock.py | from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag):
item_model = ItemModel(self... | from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
from superdesk.utc import utcnow
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag):
... | Set timestamp on item lock operation | Set timestamp on item lock operation
| Python | agpl-3.0 | akintolga/superdesk,superdesk/superdesk-ntb,verifiedpixel/superdesk,Aca-jov/superdesk,amagdas/superdesk,hlmnrmr/superdesk,verifiedpixel/superdesk,pavlovicnemanja/superdesk,ioanpocol/superdesk-ntb,liveblog/superdesk,marwoodandrew/superdesk-aap,sivakuna-aap/superdesk,mugurrus/superdesk,akintolga/superdesk-aap,pavlovicnem... | from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
from superdesk.utc import utcnow
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag):
... | Set timestamp on item lock operation
from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag... |
08300895dc8d2abb740dd71b027e9acda8bb84dd | chatterbot/ext/django_chatterbot/views.py | chatterbot/ext/django_chatterbot/views.py | from django.views.generic import View
from django.http import JsonResponse
from django.conf import settings
class ChatterBotView(View):
def post(self, request, *args, **kwargs):
input_statement = request.POST.get('text')
response_data = settings.CHATTERBOT.get_response(input_statement)
... | from django.views.generic import View
from django.http import JsonResponse
from django.conf import settings
from chatterbot import ChatBot
class ChatterBotView(View):
chatterbot = ChatBot(
settings.CHATTERBOT['NAME'],
storage_adapter='chatterbot.adapters.storage.DjangoStorageAdapter',
inp... | Initialize ChatterBot in django view module instead of settings. | Initialize ChatterBot in django view module instead of settings.
| Python | bsd-3-clause | Reinaesaya/OUIRL-ChatBot,Reinaesaya/OUIRL-ChatBot,vkosuri/ChatterBot,davizucon/ChatterBot,gunthercox/ChatterBot,maclogan/VirtualPenPal,Gustavo6046/ChatterBot | from django.views.generic import View
from django.http import JsonResponse
from django.conf import settings
from chatterbot import ChatBot
class ChatterBotView(View):
chatterbot = ChatBot(
settings.CHATTERBOT['NAME'],
storage_adapter='chatterbot.adapters.storage.DjangoStorageAdapter',
inp... | Initialize ChatterBot in django view module instead of settings.
from django.views.generic import View
from django.http import JsonResponse
from django.conf import settings
class ChatterBotView(View):
def post(self, request, *args, **kwargs):
input_statement = request.POST.get('text')
response_... |
6425c20b536e8952b062ccb8b470ea615ebc0fa2 | conman/routes/migrations/0002_simplify_route_slug_help_text.py | conman/routes/migrations/0002_simplify_route_slug_help_text.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('routes', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='route',
name='slug',
... | Add missing migration to routes app | Add missing migration to routes app
| Python | bsd-2-clause | meshy/django-conman,Ian-Foote/django-conman,meshy/django-conman | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('routes', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='route',
name='slug',
... | Add missing migration to routes app
| |
44b311eade20016f613311a98d666b2463826ad1 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
... | from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
... | Update requests requirement from <2.21,>=2.4.2 to >=2.4.2,<2.22 | Update requests requirement from <2.21,>=2.4.2 to >=2.4.2,<2.22
Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version.
- [Release notes](https://github.com/requests/requests/releases)
- [Changelog](https://github.com/requests/requests/blob/master/HISTORY.md)
- [Commi... | Python | apache-2.0 | zooniverse/panoptes-python-client | from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
... | Update requests requirement from <2.21,>=2.4.2 to >=2.4.2,<2.22
Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version.
- [Release notes](https://github.com/requests/requests/releases)
- [Changelog](https://github.com/requests/requests/blob/master/HISTORY.md)
- [Commi... |
5e2111a5ccc0bcbe7b9af4fec09b9b46eb03ebd3 | GenNowPlayingMovieID.py | GenNowPlayingMovieID.py | #!/usr/bin/python
#coding: utf-8
import requests
import re
if __name__=="__main__":
page = requests.get('https://movie.douban.com/nowplaying/beijing/')
content=page.text.encode("utf-8")
pattern=re.compile(r'(?<=id=")\d+(?="\n)')
result=pattern.findall(content)
for iterm in result:
print iterm
| #!/usr/bin/python
#coding: utf-8
import requests
import re
import time
from time import gmtime, strftime
class GenNowPlayingID(object):
"""docstring for ClassName"""
def __init__(self):
#super(ClassName, self).__init__()
# self.arg = arg
pass
def GenNowPlayingIdList(self):
page = requests.get('https://movi... | Write the nowplaying movie id to file | Write the nowplaying movie id to file
| Python | apache-2.0 | ModernKings/MKMovieCenter,ModernKings/MKMovieCenter,ModernKings/MKMovieCenter | #!/usr/bin/python
#coding: utf-8
import requests
import re
import time
from time import gmtime, strftime
class GenNowPlayingID(object):
"""docstring for ClassName"""
def __init__(self):
#super(ClassName, self).__init__()
# self.arg = arg
pass
def GenNowPlayingIdList(self):
page = requests.get('https://movi... | Write the nowplaying movie id to file
#!/usr/bin/python
#coding: utf-8
import requests
import re
if __name__=="__main__":
page = requests.get('https://movie.douban.com/nowplaying/beijing/')
content=page.text.encode("utf-8")
pattern=re.compile(r'(?<=id=")\d+(?="\n)')
result=pattern.findall(content)
for iterm in re... |
631665a8aeee54d5094480ddf4140a61dce4a960 | ostinato/blog/apps.py | ostinato/blog/apps.py | from django.apps import AppConfig
class OstinatoBlogConfig(AppConfig):
name = 'ostinato.blog'
label = 'ost_blog'
verbose_name = 'Ostinato Blog Engine'
| from django.apps import AppConfig
class OstinatoBlogConfig(AppConfig):
name = 'ostinato.blog'
label = 'ostinato_blog'
verbose_name = 'Ostinato Blog Engine'
| Correct app label of ostinato_blog | Correct app label of ostinato_blog
| Python | mit | andrewebdev/django-ostinato,andrewebdev/django-ostinato,andrewebdev/django-ostinato | from django.apps import AppConfig
class OstinatoBlogConfig(AppConfig):
name = 'ostinato.blog'
label = 'ostinato_blog'
verbose_name = 'Ostinato Blog Engine'
| Correct app label of ostinato_blog
from django.apps import AppConfig
class OstinatoBlogConfig(AppConfig):
name = 'ostinato.blog'
label = 'ost_blog'
verbose_name = 'Ostinato Blog Engine'
|
a7ba6ece76e768e642a6ed264791e3987f7c7629 | apps/user_app/forms.py | apps/user_app/forms.py | from django import forms
from django.core import validators
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class RegistrationForm(UserCreationForm):
username = forms.CharField(label='username',
max_length=30,
required=True,) #validators=[self.isValidU... | from django import forms
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
def isValidUserName(username):
try:
User.objects.get(username=username)
except User.DoesNotExist:
return
raise ValidationError('The usern... | Implement validation to the username field. | Implement validation to the username field.
| Python | mit | pedrolinhares/po-po-modoro,pedrolinhares/po-po-modoro | from django import forms
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
def isValidUserName(username):
try:
User.objects.get(username=username)
except User.DoesNotExist:
return
raise ValidationError('The usern... | Implement validation to the username field.
from django import forms
from django.core import validators
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class RegistrationForm(UserCreationForm):
username = forms.CharField(label='username',
max_length=30,
... |
b0dbd7029f003538ddef9f3a5f8035f8691bf4d7 | shuup/core/utils/shops.py | shuup/core/utils/shops.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from shuup.core.models import Shop
def get_shop_from_host(host):... | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from shuup.core.models import Shop
def get_shop_from_host(host):... | Make handle ports better when choosing shop | Make handle ports better when choosing shop
Refs EE-235
| Python | agpl-3.0 | shoopio/shoop,shoopio/shoop,shoopio/shoop | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from shuup.core.models import Shop
def get_shop_from_host(host):... | Make handle ports better when choosing shop
Refs EE-235
# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from shu... |
5945b27aa6b5ae43470738dd6638ffa4617f7be1 | poradnia/users/migrations/0014_auto_20170317_1927.py | poradnia/users/migrations/0014_auto_20170317_1927.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-17 18:27
from __future__ import unicode_literals
import django.contrib.auth.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0013_profile_event_reminder_time'),
]
... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-17 18:27
from __future__ import unicode_literals
from django.db import migrations, models
try:
import django.contrib.auth.validators
extra_kwargs = {'validators': [django.contrib.auth.validators.ASCIIUsernameValidator()]}
except ImportError:
e... | Fix backward compatibility of migrations | Fix backward compatibility of migrations
| Python | mit | watchdogpolska/poradnia,rwakulszowa/poradnia,rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-17 18:27
from __future__ import unicode_literals
from django.db import migrations, models
try:
import django.contrib.auth.validators
extra_kwargs = {'validators': [django.contrib.auth.validators.ASCIIUsernameValidator()]}
except ImportError:
e... | Fix backward compatibility of migrations
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-17 18:27
from __future__ import unicode_literals
import django.contrib.auth.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '001... |
2f26197d10a1c7cfc010074576c7e1a2c2a31e78 | data_structures/bitorrent/torrent.py | data_structures/bitorrent/torrent.py | import hashlib
import urllib
import bencode
class Torrent(object):
def __init__(self, path):
self.encoded = self._get_meta(path)
self.decoded = bencode.bdecode(self.encoded)
def _get_meta(self, path):
with open(path) as f:
return f.read()
@property
def hash(self):
info_hash = hashlib... | import hashlib
import urllib
import bencode
class Torrent(object):
def __init__(self, path):
self.encoded = self._get_meta(path)
self.decoded = bencode.bdecode(self.encoded)
def _get_meta(self, path):
with open(path) as f:
return f.read()
def __getitem__(self, item):
return self.decode... | Use __getitem__ to improve readbility | Use __getitem__ to improve readbility
| Python | apache-2.0 | vtemian/university_projects,vtemian/university_projects,vtemian/university_projects | import hashlib
import urllib
import bencode
class Torrent(object):
def __init__(self, path):
self.encoded = self._get_meta(path)
self.decoded = bencode.bdecode(self.encoded)
def _get_meta(self, path):
with open(path) as f:
return f.read()
def __getitem__(self, item):
return self.decode... | Use __getitem__ to improve readbility
import hashlib
import urllib
import bencode
class Torrent(object):
def __init__(self, path):
self.encoded = self._get_meta(path)
self.decoded = bencode.bdecode(self.encoded)
def _get_meta(self, path):
with open(path) as f:
return f.read()
@property
... |
3e6f835a88183182b6ebba25c61666735a69fc81 | tests/vaultshell.py | tests/vaultshell.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
class VaultShellTests(unittest.TestCase):
def test_basic(self):
print "test basic. Pass"
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import vault_shell.vault_commandhelper as VaultHelper
class VaultShellTests(unittest.TestCase):
def test_basic(self):
print "test basic. Pass"
vaulthelper = VaultHelper.VaultCommandHelper()
self.failUnless(vaulthelper is not Non... | Add more tests for the vault commandhelper | Add more tests for the vault commandhelper
| Python | apache-2.0 | bdastur/vault-shell | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import vault_shell.vault_commandhelper as VaultHelper
class VaultShellTests(unittest.TestCase):
def test_basic(self):
print "test basic. Pass"
vaulthelper = VaultHelper.VaultCommandHelper()
self.failUnless(vaulthelper is not Non... | Add more tests for the vault commandhelper
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
class VaultShellTests(unittest.TestCase):
def test_basic(self):
print "test basic. Pass"
|
8605b07f2f5951f8a0b85d3d77baa1758723fb64 | auth0/v2/authentication/users.py | auth0/v2/authentication/users.py | from .base import AuthenticationBase
class Users(AuthenticationBase):
def __init__(self, domain):
self.domain = domain
def userinfo(self, access_token):
return self.get(
url='https://%s/userinfo' % self.domain,
headers={'Authorization': 'Bearer %s' % access_token}
... | from .base import AuthenticationBase
class Users(AuthenticationBase):
"""Userinfo related endpoints.
Args:
domain (str): Your auth0 domain (e.g: username.auth0.com)
"""
def __init__(self, domain):
self.domain = domain
def userinfo(self, access_token):
"""Returns the us... | Add docstrings to Users class | Add docstrings to Users class
| Python | mit | auth0/auth0-python,auth0/auth0-python | from .base import AuthenticationBase
class Users(AuthenticationBase):
"""Userinfo related endpoints.
Args:
domain (str): Your auth0 domain (e.g: username.auth0.com)
"""
def __init__(self, domain):
self.domain = domain
def userinfo(self, access_token):
"""Returns the us... | Add docstrings to Users class
from .base import AuthenticationBase
class Users(AuthenticationBase):
def __init__(self, domain):
self.domain = domain
def userinfo(self, access_token):
return self.get(
url='https://%s/userinfo' % self.domain,
headers={'Authorization': ... |
c7e65db27da59ddf221d1720362434581ef30311 | test/unit/locale/test_locale.py | test/unit/locale/test_locale.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
import unittest
try:
from subprocess import check_output
except ImportError:
from subprocess import Popen, PIPE, CalledProcessError
def check_output(*popenargs, **kwargs):
"""Lifted from python 2.7 stdlib."""
if 'stdout' in kwargs:
... | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
import unittest
import string
import sys
try:
from subprocess import check_output
except ImportError:
from subprocess import Popen, PIPE, CalledProcessError
def check_output(*popenargs, **kwargs):
"""Lifted from python 2.7 stdlib."""
i... | Make test_translations test our tree | Make test_translations test our tree
In order to run the correct classes, Python test framework adjusts
sys.path. However, these changes are not propagated to subprocesses.
Therefore, the test actually tries to test installed Swift, not
the one in which it is running.
The usual suggestion is to run "python setup.py d... | Python | apache-2.0 | swiftstack/swift,rackerlabs/swift,zackmdavis/swift,williamthegrey/swift,eatbyte/Swift,matthewoliver/swift,Seagate/swift,anishnarang/gswift,clayg/swift,shibaniahegde/OpenStak_swift,openstack/swift,prashanthpai/swift,matthewoliver/swift,psachin/swift,nadeemsyed/swift,AfonsoFGarcia/swift,prashanthpai/swift,smerritt/swift,... | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
import unittest
import string
import sys
try:
from subprocess import check_output
except ImportError:
from subprocess import Popen, PIPE, CalledProcessError
def check_output(*popenargs, **kwargs):
"""Lifted from python 2.7 stdlib."""
i... | Make test_translations test our tree
In order to run the correct classes, Python test framework adjusts
sys.path. However, these changes are not propagated to subprocesses.
Therefore, the test actually tries to test installed Swift, not
the one in which it is running.
The usual suggestion is to run "python setup.py d... |
73a9ba740d446e19c0428ffc29bf5bb5b033d7fe | PynamoDB/persistence_engine.py | PynamoDB/persistence_engine.py | """
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Pytho... | """
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Pytho... | Remove use of timestamped value. | Remove use of timestamped value.
Thought it was dumb/inelegant to have a Value() object floating around
with value and timestamp . Instead, now all messages are sent around
as json dicts.
The request enters the system as json, flows through to an endpoint
where it becomes a reply message, then flows back to the clie... | Python | mit | samuelwu90/PynamoDB | """
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Pytho... | Remove use of timestamped value.
Thought it was dumb/inelegant to have a Value() object floating around
with value and timestamp . Instead, now all messages are sent around
as json dicts.
The request enters the system as json, flows through to an endpoint
where it becomes a reply message, then flows back to the clie... |
85f8bb3e46c5c79af6ba1e246ad5938642feadcc | test/test_i18n.py | test/test_i18n.py | # -*- coding: utf8 -*-
###
# Copyright (c) 2012, Valentin Lorentz
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# ... | Add unit tests for i18n. | Add unit tests for i18n.
| Python | bsd-3-clause | Ban3/Limnoria,Ban3/Limnoria,ProgVal/Limnoria-test,ProgVal/Limnoria-test | # -*- coding: utf8 -*-
###
# Copyright (c) 2012, Valentin Lorentz
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# ... | Add unit tests for i18n.
| |
c28127941ed88fdedc084c6227da3b921a5e15ab | jsk_apc2015_common/scripts/test_bof_object_recognition.py | jsk_apc2015_common/scripts/test_bof_object_recognition.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import cPickle as pickle
import gzip
import sys
import cv2
from imagesift import get_sift_keypoints
import numpy as np
from sklearn.datasets import load_files
from sklearn.metrics import accuracy_score, classification_report
from sklearn.preprocessing impo... | Add bof object recognition test script | [jsk_2015_apc_common] Add bof object recognition test script
| Python | bsd-3-clause | pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import cPickle as pickle
import gzip
import sys
import cv2
from imagesift import get_sift_keypoints
import numpy as np
from sklearn.datasets import load_files
from sklearn.metrics import accuracy_score, classification_report
from sklearn.preprocessing impo... | [jsk_2015_apc_common] Add bof object recognition test script
| |
a9c6e045631103fe8508fd1b60d6076c05092fe1 | tests/examples/customnode/nodes.py | tests/examples/customnode/nodes.py | from viewflow.activation import AbstractGateActivation, Activation
from viewflow.flow import base
from viewflow.token import Token
class DynamicSplitActivation(AbstractGateActivation):
def calculate_next(self):
self._split_count = self.flow_task._task_count_callback(self.process)
@Activation.status.s... | from viewflow.activation import AbstractGateActivation
from viewflow.flow import base
from viewflow.token import Token
class DynamicSplitActivation(AbstractGateActivation):
def calculate_next(self):
self._split_count = self.flow_task._task_count_callback(self.process)
def activate_next(self):
... | Add undo to custom node sample | Add undo to custom node sample
| Python | agpl-3.0 | ribeiro-ucl/viewflow,codingjoe/viewflow,pombredanne/viewflow,pombredanne/viewflow,codingjoe/viewflow,codingjoe/viewflow,viewflow/viewflow,viewflow/viewflow,ribeiro-ucl/viewflow,viewflow/viewflow,ribeiro-ucl/viewflow | from viewflow.activation import AbstractGateActivation
from viewflow.flow import base
from viewflow.token import Token
class DynamicSplitActivation(AbstractGateActivation):
def calculate_next(self):
self._split_count = self.flow_task._task_count_callback(self.process)
def activate_next(self):
... | Add undo to custom node sample
from viewflow.activation import AbstractGateActivation, Activation
from viewflow.flow import base
from viewflow.token import Token
class DynamicSplitActivation(AbstractGateActivation):
def calculate_next(self):
self._split_count = self.flow_task._task_count_callback(self.pr... |
75a8d2ed6a3fa03ca132388182b1e7876fb6413e | setup.py | setup.py | #!/usr/bin/env python
from __future__ import unicode_literals
from setuptools import setup, find_packages
install_requires = [
"Jinja2",
"boto>=2.36.0",
"flask",
"httpretty==0.8.10",
"requests",
"xmltodict",
"six",
"werkzeug",
"sure",
"freezegun"
]
extras_require = {
# No b... | #!/usr/bin/env python
from __future__ import unicode_literals
from setuptools import setup, find_packages
install_requires = [
"Jinja2",
"boto>=2.36.0",
"flask",
"httpretty==0.8.10",
"requests",
"xmltodict",
"six",
"werkzeug",
"sure",
"freezegun"
]
extras_require = {
# No b... | Revert "Bumping the version reflecting the bugfix" | Revert "Bumping the version reflecting the bugfix"
This reverts commit 7f3daf4755aff19d04acf865df39f7d188655b15.
| Python | apache-2.0 | okomestudio/moto,spulec/moto,spulec/moto,heddle317/moto,Affirm/moto,okomestudio/moto,whummer/moto,2rs2ts/moto,Affirm/moto,ZuluPro/moto,rocky4570/moto,Brett55/moto,spulec/moto,gjtempleton/moto,2rs2ts/moto,okomestudio/moto,2rs2ts/moto,gjtempleton/moto,Brett55/moto,heddle317/moto,botify-labs/moto,spulec/moto,2rs2ts/moto,h... | #!/usr/bin/env python
from __future__ import unicode_literals
from setuptools import setup, find_packages
install_requires = [
"Jinja2",
"boto>=2.36.0",
"flask",
"httpretty==0.8.10",
"requests",
"xmltodict",
"six",
"werkzeug",
"sure",
"freezegun"
]
extras_require = {
# No b... | Revert "Bumping the version reflecting the bugfix"
This reverts commit 7f3daf4755aff19d04acf865df39f7d188655b15.
#!/usr/bin/env python
from __future__ import unicode_literals
from setuptools import setup, find_packages
install_requires = [
"Jinja2",
"boto>=2.36.0",
"flask",
"httpretty==0.8.10",
"... |
681cc0a4160373fe82de59946b52e0e21611af84 | linkLister.py | linkLister.py | import requests
import re
url = raw_input("Enter URL with http or https prefix : " )
print url
website= requests.get(url)
html = website.text
print html
linklist = re.findall('"((http|ftp)s?://.*?)"',html)
print linklist
for link in linklist:
print link[0]
| Print out all links on a page | Print out all links on a page
| Python | mit | NilanjanaLodh/PyScripts,NilanjanaLodh/PyScripts | import requests
import re
url = raw_input("Enter URL with http or https prefix : " )
print url
website= requests.get(url)
html = website.text
print html
linklist = re.findall('"((http|ftp)s?://.*?)"',html)
print linklist
for link in linklist:
print link[0]
| Print out all links on a page
| |
52610add5ae887dcbc06f1435fdff34f182d78c9 | go/campaigns/forms.py | go/campaigns/forms.py | from django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('C', 'Conversation'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceField(label="Which kind of campaign ... | from django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('D', 'Dialogue'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceField(label="Which kind of campaign woul... | Use dialogue terminology in menu | Use dialogue terminology in menu
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | from django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('D', 'Dialogue'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceField(label="Which kind of campaign woul... | Use dialogue terminology in menu
from django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('C', 'Conversation'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceFi... |
fd47b9235a95146fc0ccbaf10f4b5c2c217fe401 | libsrc/test/TestXdmfPythonArray.py | libsrc/test/TestXdmfPythonArray.py | import Xdmf
from Xdmf import *
if __name__ == '__main__':
array = Xdmf.XdmfArray()
array.SetNumberType(Xdmf.XDMF_INT64_TYPE)
assert(array.GetNumberType() == Xdmf.XDMF_INT64_TYPE)
array.SetShapeFromString("3 3")
assert(array.GetShapeAsString() == "3 3")
assert(array.GetNumberOfElements() == 9... | Add Xdmf Python Test that writes values to an XdmfArray | ENH: Add Xdmf Python Test that writes values to an XdmfArray
| Python | bsd-3-clause | cjh1/Xdmf2,cjh1/Xdmf2,cjh1/Xdmf2 | import Xdmf
from Xdmf import *
if __name__ == '__main__':
array = Xdmf.XdmfArray()
array.SetNumberType(Xdmf.XDMF_INT64_TYPE)
assert(array.GetNumberType() == Xdmf.XDMF_INT64_TYPE)
array.SetShapeFromString("3 3")
assert(array.GetShapeAsString() == "3 3")
assert(array.GetNumberOfElements() == 9... | ENH: Add Xdmf Python Test that writes values to an XdmfArray
| |
00922099d6abb03a0dbcca19781eb586d367eab0 | skimage/measure/__init__.py | skimage/measure/__init__.py | from .find_contours import find_contours
from ._regionprops import regionprops
from .find_contours import find_contours
from ._structural_similarity import ssim
| from .find_contours import find_contours
from ._regionprops import regionprops
from ._structural_similarity import ssim
| Remove double import of find contours. | BUG: Remove double import of find contours.
| Python | bsd-3-clause | robintw/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,ajaybhat/scikit-image,rjeli/scikit-image,SamHames/scikit-image,chintak/scikit-image,ofgulban/scikit-image,SamHames/scikit-image,dpshelio/scikit-image,chintak/scikit-image,rjeli/scikit-image,oew1v07/scikit-image,almarklein/scikit-image,pratapvardha... | from .find_contours import find_contours
from ._regionprops import regionprops
from ._structural_similarity import ssim
| BUG: Remove double import of find contours.
from .find_contours import find_contours
from ._regionprops import regionprops
from .find_contours import find_contours
from ._structural_similarity import ssim
|
57a58893a2ba94b174b06e7f5f63478dff1e879e | providers/popularity/netflix.py | providers/popularity/netflix.py | from providers.popularity.provider import PopularityProvider
from utils.torrent_util import remove_bad_torrent_matches, torrent_to_movie
IDENTIFIER = "netflix"
class Provider(PopularityProvider):
def get_popular(self):
country = "se"
url = f"https://www.finder.com/{country}/netflix-movies"
... | Add provider for (Swedish) Netflix. | Add provider for (Swedish) Netflix.
Change "country" inside the provider for the movies available in a different country.
| Python | mit | EmilStenstrom/nephele | from providers.popularity.provider import PopularityProvider
from utils.torrent_util import remove_bad_torrent_matches, torrent_to_movie
IDENTIFIER = "netflix"
class Provider(PopularityProvider):
def get_popular(self):
country = "se"
url = f"https://www.finder.com/{country}/netflix-movies"
... | Add provider for (Swedish) Netflix.
Change "country" inside the provider for the movies available in a different country.
| |
318ebb141ebb50010964821145811aa36e46877f | temba/flows/migrations/0030_auto_20150825_1406.py | temba/flows/migrations/0030_auto_20150825_1406.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('flows', '0029_populate_run_modified_on'),
]
operations = [
migrations.AlterField(
model_name='flowrun',
... | Make modified_on and org no longer be nullable | Make modified_on and org no longer be nullable
| Python | agpl-3.0 | tsotetsi/textily-web,reyrodrigues/EU-SMS,praekelt/rapidpro,pulilab/rapidpro,ewheeler/rapidpro,ewheeler/rapidpro,ewheeler/rapidpro,ewheeler/rapidpro,reyrodrigues/EU-SMS,reyrodrigues/EU-SMS,tsotetsi/textily-web,tsotetsi/textily-web,pulilab/rapidpro,praekelt/rapidpro,tsotetsi/textily-web,pulilab/rapidpro,pulilab/rapidpro,... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('flows', '0029_populate_run_modified_on'),
]
operations = [
migrations.AlterField(
model_name='flowrun',
... | Make modified_on and org no longer be nullable
| |
cd2b628ca118ffae8090004e845e399110aada21 | disk/datadog_checks/disk/__init__.py | disk/datadog_checks/disk/__init__.py | # (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from .disk import Disk
__all__ = ['Disk']
| # (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from .__about__ import __version__
from .disk import Disk
all = [
'__version__', 'Disk'
]
| Allow Agent to properly pull version info | [Disk] Allow Agent to properly pull version info | Python | bsd-3-clause | DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core | # (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from .__about__ import __version__
from .disk import Disk
all = [
'__version__', 'Disk'
]
| [Disk] Allow Agent to properly pull version info
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from .disk import Disk
__all__ = ['Disk']
|
7629afde2627457b4f4b19e1542a87e695c1837d | tests/events/test_models.py | tests/events/test_models.py | """Unit tests for events models."""
import datetime
from app.events.factories import EventFactory
from app.events.models import Event
def test_event_factory(db): # noqa: D103
# GIVEN an empty database
assert Event.objects.count() == 0
# WHEN saving a new event instance to the database
EventFactory.... | """Unit tests for events models."""
import datetime
from app.events.factories import EventFactory
from app.events.models import Event
def test_event_factory(db): # noqa: D103
# GIVEN an empty database
assert Event.objects.count() == 0
# WHEN saving a new event instance to the database
EventFactory.... | Make sure slug gets updated on date change | Make sure slug gets updated on date change
| Python | mit | FlowFX/reggae-cdmx,FlowFX/reggae-cdmx | """Unit tests for events models."""
import datetime
from app.events.factories import EventFactory
from app.events.models import Event
def test_event_factory(db): # noqa: D103
# GIVEN an empty database
assert Event.objects.count() == 0
# WHEN saving a new event instance to the database
EventFactory.... | Make sure slug gets updated on date change
"""Unit tests for events models."""
import datetime
from app.events.factories import EventFactory
from app.events.models import Event
def test_event_factory(db): # noqa: D103
# GIVEN an empty database
assert Event.objects.count() == 0
# WHEN saving a new even... |
479f1792aabc9220a489445979b48781a8cf7ff9 | tests/pytests/unit/states/test_influxdb_continuous_query.py | tests/pytests/unit/states/test_influxdb_continuous_query.py | import pytest
import salt.modules.influxdbmod as influx_mod
import salt.states.influxdb_continuous_query as influx
from tests.support.mock import create_autospec, patch
@pytest.fixture
def configure_loader_modules():
return {influx: {"__salt__": {}, "__opts__": {"test": False}}}
@pytest.mark.xfail
@pytest.mark... | Add tests for influxdb create_continuous_query | Add tests for influxdb create_continuous_query
Currently marked as xfail, since we'll pull the existing changes into
here.
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | import pytest
import salt.modules.influxdbmod as influx_mod
import salt.states.influxdb_continuous_query as influx
from tests.support.mock import create_autospec, patch
@pytest.fixture
def configure_loader_modules():
return {influx: {"__salt__": {}, "__opts__": {"test": False}}}
@pytest.mark.xfail
@pytest.mark... | Add tests for influxdb create_continuous_query
Currently marked as xfail, since we'll pull the existing changes into
here.
| |
3c30166378d37c812cecb505a3d9023b079d24be | app/__init__.py | app/__init__.py | # Gevent needed for sockets
from gevent import monkey
monkey.patch_all()
# Imports
import os
from flask import Flask, render_template
from flask_socketio import SocketIO
import boto3
# Configure app
socketio = SocketIO()
app = Flask(__name__)
app.config.from_object(os.environ["APP_SETTINGS"])
import nltk
try:
nl... | # Gevent needed for sockets
from gevent import monkey
monkey.patch_all()
# Imports
import os
from flask import Flask, render_template
from flask_socketio import SocketIO
import boto3
# Configure app
socketio = SocketIO()
app = Flask(__name__)
app.config.from_object(os.environ["APP_SETTINGS"])
import nltk
nltk.downlo... | Fix stupid nltk data download thing | Fix stupid nltk data download thing
| Python | mit | PapaCharlie/SteamyReviews,PapaCharlie/SteamyReviews,PapaCharlie/SteamyReviews,PapaCharlie/SteamyReviews | # Gevent needed for sockets
from gevent import monkey
monkey.patch_all()
# Imports
import os
from flask import Flask, render_template
from flask_socketio import SocketIO
import boto3
# Configure app
socketio = SocketIO()
app = Flask(__name__)
app.config.from_object(os.environ["APP_SETTINGS"])
import nltk
nltk.downlo... | Fix stupid nltk data download thing
# Gevent needed for sockets
from gevent import monkey
monkey.patch_all()
# Imports
import os
from flask import Flask, render_template
from flask_socketio import SocketIO
import boto3
# Configure app
socketio = SocketIO()
app = Flask(__name__)
app.config.from_object(os.environ["APP... |
1046157fa2e062f12123e110c82851c2484216be | gallery_plugins/plugin_gfycat.py | gallery_plugins/plugin_gfycat.py | import re
try:
import urllib.request as urllib
except:
import urllib # Python 2
def title(source):
gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1]
link = 'https://gfycat.com/cajax/get/' + gfyId
respond = urllib.urlopen(link).read()
username = re.findall(r'\"userName\":\"(.+?)\... | import re
try:
import urllib.request as urllib
except:
import urllib # Python 2
def title(source):
gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1]
link = 'https://gfycat.com/cajax/get/' + gfyId
respond = urllib.urlopen(link).read().decode("utf8")
username = re.findall(r'\"user... | Update gfycat plugin for python3 support | Update gfycat plugin for python3 support
| Python | mit | regosen/gallery_get | import re
try:
import urllib.request as urllib
except:
import urllib # Python 2
def title(source):
gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1]
link = 'https://gfycat.com/cajax/get/' + gfyId
respond = urllib.urlopen(link).read().decode("utf8")
username = re.findall(r'\"user... | Update gfycat plugin for python3 support
import re
try:
import urllib.request as urllib
except:
import urllib # Python 2
def title(source):
gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1]
link = 'https://gfycat.com/cajax/get/' + gfyId
respond = urllib.urlopen(link).read()
use... |
389d7e5d131188d5b8a3f9111d9a6a7a96ce8af8 | dmoj/executors/ICK.py | dmoj/executors/ICK.py | from .base_executor import CompiledExecutor
class Executor(CompiledExecutor):
ext = '.i'
name = 'ICK'
command = 'ick'
test_program = '''\
PLEASE DO ,1 <- #1
DO .4 <- #0
DO .5 <- #0
DO COME FROM (30)
DO WRITE IN ,1
DO .1 <- ,1SUB#1
DO (10) NEXT
... | from .base_executor import CompiledExecutor
class Executor(CompiledExecutor):
ext = '.i'
name = 'ICK'
command = 'ick'
test_program = '''\
PLEASE DO ,1 <- #1
DO .4 <- #0
DO .5 <- #0
DO COME FROM (30)
DO WRITE IN ,1
DO .1 <- ,1SUB#1
DO (10) NEXT
... | Make Intercal executor not fail to start at times. | Make Intercal executor not fail to start at times.
| Python | agpl-3.0 | DMOJ/judge,DMOJ/judge,DMOJ/judge | from .base_executor import CompiledExecutor
class Executor(CompiledExecutor):
ext = '.i'
name = 'ICK'
command = 'ick'
test_program = '''\
PLEASE DO ,1 <- #1
DO .4 <- #0
DO .5 <- #0
DO COME FROM (30)
DO WRITE IN ,1
DO .1 <- ,1SUB#1
DO (10) NEXT
... | Make Intercal executor not fail to start at times.
from .base_executor import CompiledExecutor
class Executor(CompiledExecutor):
ext = '.i'
name = 'ICK'
command = 'ick'
test_program = '''\
PLEASE DO ,1 <- #1
DO .4 <- #0
DO .5 <- #0
DO COME FROM (30)
DO WRITE IN... |
4dc2d5710f5f34a0611c8d38a84ee3c5ecf79463 | uliweb/contrib/rbac/tags.py | uliweb/contrib/rbac/tags.py | from uliweb.core.template import BaseBlockNode
from uliweb import functions
class PermissionNode(BaseBlockNode):
def __init__(self, name='', content=None):
super(PermissionNode, self).__init__(name, content)
self.nodes = ['if functions.has_permission(request.user, "%s"):\n' % self.name]
... | from uliweb.core.template import BaseBlockNode
from uliweb import functions
class PermissionNode(BaseBlockNode):
def __init__(self, name='', content=None):
super(PermissionNode, self).__init__(name, content)
self.nodes = ['if functions.has_permission(request.user, %s):\n' % self.name]
... | Change role and permission tag parameter format, no need "" | Change role and permission tag parameter format, no need ""
| Python | bsd-2-clause | wwfifi/uliweb,wwfifi/uliweb,wwfifi/uliweb,limodou/uliweb,limodou/uliweb,wwfifi/uliweb,limodou/uliweb,limodou/uliweb | from uliweb.core.template import BaseBlockNode
from uliweb import functions
class PermissionNode(BaseBlockNode):
def __init__(self, name='', content=None):
super(PermissionNode, self).__init__(name, content)
self.nodes = ['if functions.has_permission(request.user, %s):\n' % self.name]
... | Change role and permission tag parameter format, no need ""
from uliweb.core.template import BaseBlockNode
from uliweb import functions
class PermissionNode(BaseBlockNode):
def __init__(self, name='', content=None):
super(PermissionNode, self).__init__(name, content)
self.nodes = ['if functions.ha... |
415e34fb913feaf623320827fb7680ee56c9d335 | gunicorn.conf.py | gunicorn.conf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
bind = '127.0.0.1:8001'
workers = 6
proc_name = 'lastuser'
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
bind = '127.0.0.1:8002'
workers = 6
proc_name = 'lastuser'
| Use a different port for lastuser | Use a different port for lastuser
| Python | bsd-2-clause | hasgeek/lastuser,hasgeek/lastuser,sindhus/lastuser,hasgeek/lastuser,sindhus/lastuser,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/lastuser,sindhus/lastuser,sindhus/lastuser,sindhus/lastuser,hasgeek/funnel,hasgeek/lastuser | #!/usr/bin/env python
# -*- coding: utf-8 -*-
bind = '127.0.0.1:8002'
workers = 6
proc_name = 'lastuser'
| Use a different port for lastuser
#!/usr/bin/env python
# -*- coding: utf-8 -*-
bind = '127.0.0.1:8001'
workers = 6
proc_name = 'lastuser'
|
dd31ff9372f587cf2fd7e634f3c6886fa9beedc0 | examples/pywapi-example.py | examples/pywapi-example.py | #!/usr/bin/env python
import pywapi
weather_com_result = pywapi.get_weather_from_weather_com('10001')
yahoo_result = pywapi.get_weather_from_yahoo('10001')
noaa_result = pywapi.get_weather_from_noaa('KJFK')
print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + ... | #!/usr/bin/env python
import pywapi
weather_com_result = pywapi.get_weather_from_weather_com('10001')
yahoo_result = pywapi.get_weather_from_yahoo('10001')
noaa_result = pywapi.get_weather_from_noaa('KJFK')
print "Weather.com says: It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weathe... | Fix error in example script | Fix error in example script | Python | mit | kheuton/python-weather-api | #!/usr/bin/env python
import pywapi
weather_com_result = pywapi.get_weather_from_weather_com('10001')
yahoo_result = pywapi.get_weather_from_yahoo('10001')
noaa_result = pywapi.get_weather_from_noaa('KJFK')
print "Weather.com says: It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weathe... | Fix error in example script
#!/usr/bin/env python
import pywapi
weather_com_result = pywapi.get_weather_from_weather_com('10001')
yahoo_result = pywapi.get_weather_from_yahoo('10001')
noaa_result = pywapi.get_weather_from_noaa('KJFK')
print "Weather.com says: It is " + string.lower(weather_com_result['current_condit... |
97e60ffa741bafbd34bcee18d0dce9f323b0132a | project/settings/prod.py | project/settings/prod.py | # Local
from .base import *
# Heroku Settings
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
ALLOWED_HOSTS = [
'.barberscore.com',
'.herokuapp.com',
]
DATABASES['default']['TEST'] = {
'NAME': DATABASES['default']['NAME'],
}
# Email
EMAIL_HOST = 'smtp.sendgrid.ne... | # Local
from .base import *
# Heroku Settings
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
ALLOWED_HOSTS = [
'testserver',
'.barberscore.com',
'.herokuapp.com',
]
DATABASES['default']['TEST'] = {
'NAME': DATABASES['default']['NAME'],
}
# Email
EMAIL_HOST =... | TEst adding test server to allowed hosts | TEst adding test server to allowed hosts
| Python | bsd-2-clause | dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore-django | # Local
from .base import *
# Heroku Settings
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
ALLOWED_HOSTS = [
'testserver',
'.barberscore.com',
'.herokuapp.com',
]
DATABASES['default']['TEST'] = {
'NAME': DATABASES['default']['NAME'],
}
# Email
EMAIL_HOST =... | TEst adding test server to allowed hosts
# Local
from .base import *
# Heroku Settings
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
ALLOWED_HOSTS = [
'.barberscore.com',
'.herokuapp.com',
]
DATABASES['default']['TEST'] = {
'NAME': DATABASES['default']['NAME'],
... |
1e10fa30998f63359ddd26d9804bd32a837c2cab | armstrong/esi/tests/_utils.py | armstrong/esi/tests/_utils.py | from django.conf import settings
from django.test import TestCase as DjangoTestCase
import fudge
class TestCase(DjangoTestCase):
def setUp(self):
self._original_settings = settings
def tearDown(self):
settings = self._original_settings
| from django.conf import settings
from django.http import HttpRequest
from django.test import TestCase as DjangoTestCase
import fudge
def with_fake_request(func):
def inner(self, *args, **kwargs):
request = fudge.Fake(HttpRequest)
fudge.clear_calls()
result = func(self, request, *args, **kw... | Add in a decorator for generating fake request objects for test cases | Add in a decorator for generating fake request objects for test cases
| Python | bsd-3-clause | armstrong/armstrong.esi | from django.conf import settings
from django.http import HttpRequest
from django.test import TestCase as DjangoTestCase
import fudge
def with_fake_request(func):
def inner(self, *args, **kwargs):
request = fudge.Fake(HttpRequest)
fudge.clear_calls()
result = func(self, request, *args, **kw... | Add in a decorator for generating fake request objects for test cases
from django.conf import settings
from django.test import TestCase as DjangoTestCase
import fudge
class TestCase(DjangoTestCase):
def setUp(self):
self._original_settings = settings
def tearDown(self):
settings = self._origi... |
6d15230f46c22226f6a2e84ac41fc39e6c5c190b | linode/objects/linode/backup.py | linode/objects/linode/backup.py | from .. import DerivedBase, Property, Base
class Backup(DerivedBase):
api_name = 'backups'
api_endpoint = '/linode/instances/{linode_id}/backups/{id}'
derived_url_path = 'backups'
parent_id_name='linode_id'
properties = {
'id': Property(identifier=True),
'create_dt': Property(is_da... | from .. import DerivedBase, Property, Base
class Backup(DerivedBase):
api_name = 'backups'
api_endpoint = '/linode/instances/{linode_id}/backups/{id}'
derived_url_path = 'backups'
parent_id_name='linode_id'
properties = {
'id': Property(identifier=True),
'created': Property(is_date... | Fix datetime fields in Backup and SupportTicket | Fix datetime fields in Backup and SupportTicket
This closes #23.
| Python | bsd-3-clause | linode/python-linode-api,jo-tez/python-linode-api | from .. import DerivedBase, Property, Base
class Backup(DerivedBase):
api_name = 'backups'
api_endpoint = '/linode/instances/{linode_id}/backups/{id}'
derived_url_path = 'backups'
parent_id_name='linode_id'
properties = {
'id': Property(identifier=True),
'created': Property(is_date... | Fix datetime fields in Backup and SupportTicket
This closes #23.
from .. import DerivedBase, Property, Base
class Backup(DerivedBase):
api_name = 'backups'
api_endpoint = '/linode/instances/{linode_id}/backups/{id}'
derived_url_path = 'backups'
parent_id_name='linode_id'
properties = {
'... |
1663cb8557de85b1f3ccf5822fa01758e679ccd7 | TestScript/multi_client.py | TestScript/multi_client.py | # -*- coding: utf-8 -*-
__author__ = 'sm9'
import asyncore, socket
import string, random
import struct, time
HOST = '192.168.0.11'
PORT = 9001
PKT_CS_LOGIN = 1
PKT_SC_LOGIN = 2
PKT_CS_CHAT = 3
PKT_SC_CHAT = 4
def str_generator(size=128, chars=string.ascii_uppercase + string.digits):
return... | Test script for the stress test | *added: Test script for the stress test | Python | mit | zrma/EasyGameServer,zeliard/EasyGameServer,zeliard/EasyGameServer,zrma/EasyGameServer,Lt-Red/EasyGameServer,Lt-Red/EasyGameServer | # -*- coding: utf-8 -*-
__author__ = 'sm9'
import asyncore, socket
import string, random
import struct, time
HOST = '192.168.0.11'
PORT = 9001
PKT_CS_LOGIN = 1
PKT_SC_LOGIN = 2
PKT_CS_CHAT = 3
PKT_SC_CHAT = 4
def str_generator(size=128, chars=string.ascii_uppercase + string.digits):
return... | *added: Test script for the stress test
| |
2c7adc6fd0a53db44951eccb8f5db3b45e4a4653 | setup.py | setup.py | from setuptools import setup
setup(
name='jinjer',
version='0.1',
packages=['jinjer'],
package_dir={'': 'src'},
url='https://github.com/andrematheus/jinjer',
license='BSD',
author='André Roque Matheus',
author_email='amatheus@ligandoospontos.com.br',
description='Tool to render Jinj... | from setuptools import setup
setup(
name='jinjer',
version='0.2',
packages=['jinjer'],
package_dir={'': 'src'},
url='https://github.com/andrematheus/jinjer',
license='BSD',
author='André Roque Matheus',
author_email='amatheus@ligandoospontos.com.br',
description='Tool to render Jinj... | Correct requires to force installation. | Correct requires to force installation.
| Python | mit | andrematheus/jinjer | from setuptools import setup
setup(
name='jinjer',
version='0.2',
packages=['jinjer'],
package_dir={'': 'src'},
url='https://github.com/andrematheus/jinjer',
license='BSD',
author='André Roque Matheus',
author_email='amatheus@ligandoospontos.com.br',
description='Tool to render Jinj... | Correct requires to force installation.
from setuptools import setup
setup(
name='jinjer',
version='0.1',
packages=['jinjer'],
package_dir={'': 'src'},
url='https://github.com/andrematheus/jinjer',
license='BSD',
author='André Roque Matheus',
author_email='amatheus@ligandoospontos.com.... |
e6f19cc58f32b855fc1f71086dac0ad56b697ed3 | opps/articles/urls.py | opps/articles/urls.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
from django.conf.urls import patterns, url
from .views import OppsDetail, OppsList, Search
urlpatterns = patterns(
'',
url(r'^$', OppsList.as_view(), name='home'),
url(r'^search/', Search(), name='search'),
url(r'^(?P<channel__long_slug>[\w//-]+)/(?P<sl... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from django.views.decorators.cache import cache_page
from .views import OppsDetail, OppsList, Search
urlpatterns = patterns(
'',
url(r'^$', cache_page(60 * 2)(OppsList.as_view()), name='home'),
url(r'^search/', Searc... | Add cache on article page (via url) | Add cache on article page (via url)
| Python | mit | opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,williamroot/opps,williamroot/opps | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from django.views.decorators.cache import cache_page
from .views import OppsDetail, OppsList, Search
urlpatterns = patterns(
'',
url(r'^$', cache_page(60 * 2)(OppsList.as_view()), name='home'),
url(r'^search/', Searc... | Add cache on article page (via url)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
from django.conf.urls import patterns, url
from .views import OppsDetail, OppsList, Search
urlpatterns = patterns(
'',
url(r'^$', OppsList.as_view(), name='home'),
url(r'^search/', Search(), name='search'),
url(r'^(?... |
030e558b3b52900b8fa2cea9a92c055de3ec5b44 | corehq/apps/domain/management/commands/migrate_domain_countries.py | corehq/apps/domain/management/commands/migrate_domain_countries.py | from django.core.management.base import LabelCommand
from django_countries.countries import COUNTRIES
from corehq.apps.domain.models import Domain
class Command(LabelCommand):
help = "Migrates old django domain countries from string to list. Sept 2014."
args = ""
label = ""
def handle(self, *args, **o... | Add management command to migrate countries to list | Add management command to migrate countries to list
| Python | bsd-3-clause | puttarajubr/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq | from django.core.management.base import LabelCommand
from django_countries.countries import COUNTRIES
from corehq.apps.domain.models import Domain
class Command(LabelCommand):
help = "Migrates old django domain countries from string to list. Sept 2014."
args = ""
label = ""
def handle(self, *args, **o... | Add management command to migrate countries to list
| |
8d53a7478a139770d9ffb241ec2985123c403845 | bookmarks/bookmarks/models.py | bookmarks/bookmarks/models.py | from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.dispatch import receiver
from django.conf import settings
from taggit.managers import TaggableManager
import requests
class Bookmark(models.Model):
title = models.CharField(max_length=200, blank=T... | from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.dispatch import receiver
from django.conf import settings
from taggit.managers import TaggableManager
import requests
class Bookmark(models.Model):
title = models.CharField(max_length=200, blank=T... | Remove attachment and use slack link unfurling | Remove attachment and use slack link unfurling
| Python | mit | tom-henderson/bookmarks,tom-henderson/bookmarks,tom-henderson/bookmarks | from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.dispatch import receiver
from django.conf import settings
from taggit.managers import TaggableManager
import requests
class Bookmark(models.Model):
title = models.CharField(max_length=200, blank=T... | Remove attachment and use slack link unfurling
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.dispatch import receiver
from django.conf import settings
from taggit.managers import TaggableManager
import requests
class Bookmark(models.Model):
... |
aca1b138350434c9afb08f31164269cd58de1d2d | YouKnowShit/CheckFile.py | YouKnowShit/CheckFile.py | import os
import sys
(dir, filename) = os.path.split(os.path.abspath(sys.argv[0]))
print(dir)
filenames = os.listdir(dir)
for file in filenames:
print(file)
print('*****************************************************')
updir = os.path.abspath('..')
print(updir)
filenames = os.listdir(updir)
for file in filenames... | import os
import sys
(dir, filename) = os.path.split(os.path.abspath(sys.argv[0]))
print(dir)
filenames = os.listdir(dir)
for file in filenames:
print(file)
print()
print()
print()
print('*****************************************************')
updir = os.path.abspath('..')
print(updir)
filenames = os.listdir(updi... | Add a level of uper directory | Add a level of uper directory
| Python | mit | jiangtianyu2009/PiSoftCake | import os
import sys
(dir, filename) = os.path.split(os.path.abspath(sys.argv[0]))
print(dir)
filenames = os.listdir(dir)
for file in filenames:
print(file)
print()
print()
print()
print('*****************************************************')
updir = os.path.abspath('..')
print(updir)
filenames = os.listdir(updi... | Add a level of uper directory
import os
import sys
(dir, filename) = os.path.split(os.path.abspath(sys.argv[0]))
print(dir)
filenames = os.listdir(dir)
for file in filenames:
print(file)
print('*****************************************************')
updir = os.path.abspath('..')
print(updir)
filenames = os.listd... |
6ca79d2ce16f8745c8d58c3dea20174931820ef3 | api/models.py | api/models.py | from flask import current_app
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, BadSignature, SignatureExpired)
from datetime import datetime
from api import db
class User(db.Model):
id = db.Column(db.Inte... | Add User object to model | Add User object to model
| Python | mit | EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list | from flask import current_app
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, BadSignature, SignatureExpired)
from datetime import datetime
from api import db
class User(db.Model):
id = db.Column(db.Inte... | Add User object to model
| |
7383343f7fb77c74455a50490ad2886fcf36bbd5 | dlstats/fetchers/test_ecb.py | dlstats/fetchers/test_ecb.py | import unittest
import mongomock
import ulstats
from dlstats.fetchers._skeleton import (Skeleton, Category, Series, BulkSeries,
Dataset, Provider)
import datetime
from bson import ObjectId
#class CategoriesTestCase(unittest.TestCase):
#if __name__ == '__main__':
# unittest.ma... | Comment test for the moment | Comment test for the moment
| Python | agpl-3.0 | Widukind/dlstats,mmalter/dlstats,mmalter/dlstats,MichelJuillard/dlstats,MichelJuillard/dlstats,MichelJuillard/dlstats,mmalter/dlstats,Widukind/dlstats | import unittest
import mongomock
import ulstats
from dlstats.fetchers._skeleton import (Skeleton, Category, Series, BulkSeries,
Dataset, Provider)
import datetime
from bson import ObjectId
#class CategoriesTestCase(unittest.TestCase):
#if __name__ == '__main__':
# unittest.ma... | Comment test for the moment
| |
df68b821807d25d204f43d7b1805da6c25f42b43 | src/lib/pagination.py | src/lib/pagination.py | from collections import OrderedDict
from django.utils.translation import ugettext_lazy as _
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class LegacyPaginator(PageNumberPagination):
"""
A legacy paginator that mocks the one from Eve Python
"""
... | from collections import OrderedDict
from django.utils.translation import ugettext_lazy as _
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class LegacyPaginator(PageNumberPagination):
"""
A legacy paginator that mocks the one from Eve Python
"""
... | Set a maximum to the number of elements that may be requested | Set a maximum to the number of elements that may be requested
| Python | agpl-3.0 | lafranceinsoumise/api-django,lafranceinsoumise/api-django,lafranceinsoumise/api-django,lafranceinsoumise/api-django | from collections import OrderedDict
from django.utils.translation import ugettext_lazy as _
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class LegacyPaginator(PageNumberPagination):
"""
A legacy paginator that mocks the one from Eve Python
"""
... | Set a maximum to the number of elements that may be requested
from collections import OrderedDict
from django.utils.translation import ugettext_lazy as _
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class LegacyPaginator(PageNumberPagination):
"""
A ... |
74f82029223cc541beab98d7026abb1ec992be40 | createTodoFile.py | createTodoFile.py | """createTodoFile.py: Creates an todo file with title name as current date"""
import time
import os.path
def createfile():
# My-File--2009-12-31--23-59-59.txt
date = time.strftime("%d-%m-%Y")
filename = "GOALS--" + date + ".todo"
if not os.path.exists(filename):
with open(filename, "a") as my... | """createTodoFile.py: Creates an todo file with title name as current date"""
import os.path
import time
def createfile():
# My-File--2009-12-31--23-59-59.txt
date = time.strftime("%d-%m-%Y")
filename = "GOALS--" + date + ".todo"
if not os.path.exists(filename):
with open(filename, "a") as my... | Add created file to sublime | feat: Add created file to sublime
| Python | mit | prajesh-ananthan/Tools | """createTodoFile.py: Creates an todo file with title name as current date"""
import os.path
import time
def createfile():
# My-File--2009-12-31--23-59-59.txt
date = time.strftime("%d-%m-%Y")
filename = "GOALS--" + date + ".todo"
if not os.path.exists(filename):
with open(filename, "a") as my... | feat: Add created file to sublime
"""createTodoFile.py: Creates an todo file with title name as current date"""
import time
import os.path
def createfile():
# My-File--2009-12-31--23-59-59.txt
date = time.strftime("%d-%m-%Y")
filename = "GOALS--" + date + ".todo"
if not os.path.exists(filename):
... |
b6389de5f531fa49e911b344cbaea29599260c82 | src/tests/test_cleanup_marathon_orphaned_containers.py | src/tests/test_cleanup_marathon_orphaned_containers.py | #!/usr/bin/env python
import cleanup_marathon_orphaned_images
# These should be left running
mesos_deployed_old = {
'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
'Names': ['/nonmesos-undeployed-old', ],
}
# These sho... | #!/usr/bin/env python
import cleanup_marathon_orphaned_images
# These should be left running
mesos_deployed_old = {
'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
'Names': ['/nonmesos-undeployed-old', ],
}
# These sho... | Clarify intent and fail fast | Clarify intent and fail fast
| Python | apache-2.0 | Yelp/paasta,somic/paasta,gstarnberger/paasta,somic/paasta,gstarnberger/paasta,Yelp/paasta | #!/usr/bin/env python
import cleanup_marathon_orphaned_images
# These should be left running
mesos_deployed_old = {
'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
'Names': ['/nonmesos-undeployed-old', ],
}
# These sho... | Clarify intent and fail fast
#!/usr/bin/env python
import cleanup_marathon_orphaned_images
# These should be left running
mesos_deployed_old = {
'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
'Names': ['/nonmesos-und... |
3460a627b535a55eedefb7ec5a37fe068f3d7abd | tests/fixtures/postgres.py | tests/fixtures/postgres.py | import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_en... | Add fixtures for connecting to Postgres test database | Add fixtures for connecting to Postgres test database
| Python | mit | igboyes/virtool,igboyes/virtool,virtool/virtool,virtool/virtool | import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_en... | Add fixtures for connecting to Postgres test database
| |
55b7b07986590c4ab519fcda3c973c87ad23596b | flask_admin/model/typefmt.py | flask_admin/model/typefmt.py | from jinja2 import Markup
def null_formatter(value):
"""
Return `NULL` as the string for `None` value
:param value:
Value to check
"""
return Markup('<i>NULL</i>')
def empty_formatter(value):
"""
Return empty string for `None` value
:param value:
... | from jinja2 import Markup
def null_formatter(value):
"""
Return `NULL` as the string for `None` value
:param value:
Value to check
"""
return Markup('<i>NULL</i>')
def empty_formatter(value):
"""
Return empty string for `None` value
:param value:
... | Add extra type formatter for `list` type | Add extra type formatter for `list` type
| Python | bsd-3-clause | mrjoes/flask-admin,janusnic/flask-admin,Kha/flask-admin,wuxiangfeng/flask-admin,litnimax/flask-admin,HermasT/flask-admin,quokkaproject/flask-admin,Kha/flask-admin,flabe81/flask-admin,porduna/flask-admin,Junnplus/flask-admin,ibushong/test-repo,janusnic/flask-admin,jschneier/flask-admin,closeio/flask-admin,chase-seibert/... | from jinja2 import Markup
def null_formatter(value):
"""
Return `NULL` as the string for `None` value
:param value:
Value to check
"""
return Markup('<i>NULL</i>')
def empty_formatter(value):
"""
Return empty string for `None` value
:param value:
... | Add extra type formatter for `list` type
from jinja2 import Markup
def null_formatter(value):
"""
Return `NULL` as the string for `None` value
:param value:
Value to check
"""
return Markup('<i>NULL</i>')
def empty_formatter(value):
"""
Return empty string for `... |
707a6016a3023fe423ede53db707c55273b0f6d0 | oauth2_provider/backends.py | oauth2_provider/backends.py | from django.contrib.auth import get_user_model
from .oauth2_backends import get_oauthlib_core
UserModel = get_user_model()
OAuthLibCore = get_oauthlib_core()
class OAuth2Backend(object):
"""
Authenticate against an OAuth2 access token
"""
def authenticate(self, **credentials):
request = cr... | from django.contrib.auth import get_user_model
from .oauth2_backends import get_oauthlib_core
UserModel = get_user_model()
OAuthLibCore = get_oauthlib_core()
class OAuth2Backend(object):
"""
Authenticate against an OAuth2 access token
"""
def authenticate(self, **credentials):
request = cr... | Use the OAuthLibCore object defined at the module level. | Use the OAuthLibCore object defined at the module level.
| Python | bsd-2-clause | bleib1dj/django-oauth-toolkit,StepicOrg/django-oauth-toolkit,JensTimmerman/django-oauth-toolkit,JensTimmerman/django-oauth-toolkit,StepicOrg/django-oauth-toolkit,DeskConnect/django-oauth-toolkit,bleib1dj/django-oauth-toolkit,DeskConnect/django-oauth-toolkit | from django.contrib.auth import get_user_model
from .oauth2_backends import get_oauthlib_core
UserModel = get_user_model()
OAuthLibCore = get_oauthlib_core()
class OAuth2Backend(object):
"""
Authenticate against an OAuth2 access token
"""
def authenticate(self, **credentials):
request = cr... | Use the OAuthLibCore object defined at the module level.
from django.contrib.auth import get_user_model
from .oauth2_backends import get_oauthlib_core
UserModel = get_user_model()
OAuthLibCore = get_oauthlib_core()
class OAuth2Backend(object):
"""
Authenticate against an OAuth2 access token
"""
d... |
f0c374eba55cdeb56bf3526ea0da041556f6ffe2 | tests/test_yamlmod.py | tests/test_yamlmod.py | import os
import sys
from nose.tools import *
def setup_yamlmod():
import yamlmod
reload(yamlmod)
def teardown_yamlmod():
import yamlmod
for hook in sys.meta_path:
if isinstance(hook, yamlmod.YamlImportHook):
sys.meta_path.remove(hook)
break
@with_setup(setup_yamlmod, teardown_yamlmod)
def test_import_... | import os
import sys
from nose.tools import *
try:
from importlib import reload
except ImportError:
pass
def setup_yamlmod():
import yamlmod
reload(yamlmod)
def teardown_yamlmod():
import yamlmod
for hook in sys.meta_path:
if isinstance(hook, yamlmod.YamlImportHook):
sys.meta_path.remove(hook)
break
... | Fix tests on python 3 | Fix tests on python 3
| Python | mit | sciyoshi/yamlmod | import os
import sys
from nose.tools import *
try:
from importlib import reload
except ImportError:
pass
def setup_yamlmod():
import yamlmod
reload(yamlmod)
def teardown_yamlmod():
import yamlmod
for hook in sys.meta_path:
if isinstance(hook, yamlmod.YamlImportHook):
sys.meta_path.remove(hook)
break
... | Fix tests on python 3
import os
import sys
from nose.tools import *
def setup_yamlmod():
import yamlmod
reload(yamlmod)
def teardown_yamlmod():
import yamlmod
for hook in sys.meta_path:
if isinstance(hook, yamlmod.YamlImportHook):
sys.meta_path.remove(hook)
break
@with_setup(setup_yamlmod, teardown_ya... |
356dd5294280db3334f86354202f0d68881254b9 | joerd/check.py | joerd/check.py | import zipfile
import tarfile
import shutil
import tempfile
from osgeo import gdal
def is_zip(tmp):
"""
Returns True if the NamedTemporaryFile given as the argument appears to be
a well-formed Zip file.
"""
try:
zip_file = zipfile.ZipFile(tmp.name, 'r')
test_result = zip_file.test... | import zipfile
import tarfile
import shutil
import tempfile
from osgeo import gdal
def is_zip(tmp):
"""
Returns True if the NamedTemporaryFile given as the argument appears to be
a well-formed Zip file.
"""
try:
zip_file = zipfile.ZipFile(tmp.name, 'r')
test_result = zip_file.test... | Return verifier function, not None. Also reset the temporary file to the beginning before verifying it. | Return verifier function, not None. Also reset the temporary file to the beginning before verifying it.
| Python | mit | mapzen/joerd,tilezen/joerd | import zipfile
import tarfile
import shutil
import tempfile
from osgeo import gdal
def is_zip(tmp):
"""
Returns True if the NamedTemporaryFile given as the argument appears to be
a well-formed Zip file.
"""
try:
zip_file = zipfile.ZipFile(tmp.name, 'r')
test_result = zip_file.test... | Return verifier function, not None. Also reset the temporary file to the beginning before verifying it.
import zipfile
import tarfile
import shutil
import tempfile
from osgeo import gdal
def is_zip(tmp):
"""
Returns True if the NamedTemporaryFile given as the argument appears to be
a well-formed Zip file... |
6cd640eb09d674afaff1c96e69322705a843dde9 | src/commands/user/user.py | src/commands/user/user.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
User command...
"""
import grp
class User(object):
"""Something, something, something darkside...."""
def __init__(self, settingsInstance, commandInstance, cmdName, *args):
super(User, self).__init__()
self.settingsInstance = settingsInstanc... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
User command...
"""
import grp
class User(object):
"""Something, something, something darkside...."""
def __init__(self, settingsInstance, commandInstance, cmdName, *args):
super(User, self).__init__()
self.settingsInstance = settingsInstanc... | Test if you can return the channel. | Test if you can return the channel.
| Python | bsd-3-clause | Tehnix/PyIRCb | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
User command...
"""
import grp
class User(object):
"""Something, something, something darkside...."""
def __init__(self, settingsInstance, commandInstance, cmdName, *args):
super(User, self).__init__()
self.settingsInstance = settingsInstanc... | Test if you can return the channel.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
User command...
"""
import grp
class User(object):
"""Something, something, something darkside...."""
def __init__(self, settingsInstance, commandInstance, cmdName, *args):
super(User, self).__init__()
se... |
daf6468079e7ff3e00550db0f3a16bc109184027 | osgtest/tests/test_49_jobs.py | osgtest/tests/test_49_jobs.py | #pylint: disable=C0301
#pylint: disable=C0111
#pylint: disable=R0201
#pylint: disable=R0904
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.osgunittest as osgunittest
class TestCleanupJobs(osgunittest.OSGTestCase):
"""Clean any configuration we touched for running ... | #pylint: disable=C0301
#pylint: disable=C0111
#pylint: disable=R0201
#pylint: disable=R0904
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.osgunittest as osgunittest
class TestCleanupJobs(osgunittest.OSGTestCase):
"""Clean any configuration we touched for running ... | Drop job env backup cleanup dependence on osg-configure | Drop job env backup cleanup dependence on osg-configure
We already dropped the creation of the job env files in 840ea8
| Python | apache-2.0 | efajardo/osg-test,efajardo/osg-test | #pylint: disable=C0301
#pylint: disable=C0111
#pylint: disable=R0201
#pylint: disable=R0904
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.osgunittest as osgunittest
class TestCleanupJobs(osgunittest.OSGTestCase):
"""Clean any configuration we touched for running ... | Drop job env backup cleanup dependence on osg-configure
We already dropped the creation of the job env files in 840ea8
#pylint: disable=C0301
#pylint: disable=C0111
#pylint: disable=R0201
#pylint: disable=R0904
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.osgunitte... |
ba063bd052284571ab6e51b0fcebe238c415071f | setup.py | setup.py | import os
import sys
import setuptools
from keystoneclient.openstack.common import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
requires = setup.parse_requirements()
depend_links = setup.parse_dependency_links()
tests_require = setup.parse_requirements(['tools/test-r... | import os
import sys
import setuptools
from keystoneclient.openstack.common import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
requires = setup.parse_requirements()
depend_links = setup.parse_dependency_links()
tests_require = setup.parse_requirements(['tools/test-r... | Add OpenStack trove classifier for PyPI | Add OpenStack trove classifier for PyPI
Add trove classifier to have the client listed among the
other OpenStack-related projets on PyPI.
Change-Id: I1ddae8d1272a2b1c5e4c666c9aa4e4a274431415
Signed-off-by: Doug Hellmann <8c845c26a3868dadec615703cd974244eb2ac6d1@dreamhost.com>
| Python | apache-2.0 | jamielennox/keystoneauth,sileht/keystoneauth,citrix-openstack-build/keystoneauth | import os
import sys
import setuptools
from keystoneclient.openstack.common import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
requires = setup.parse_requirements()
depend_links = setup.parse_dependency_links()
tests_require = setup.parse_requirements(['tools/test-r... | Add OpenStack trove classifier for PyPI
Add trove classifier to have the client listed among the
other OpenStack-related projets on PyPI.
Change-Id: I1ddae8d1272a2b1c5e4c666c9aa4e4a274431415
Signed-off-by: Doug Hellmann <8c845c26a3868dadec615703cd974244eb2ac6d1@dreamhost.com>
import os
import sys
import setuptools
... |
c0633bc60dda6b81e623795f2c65a1eb0ba5933d | blinkytape/blinkyplayer.py | blinkytape/blinkyplayer.py | import time
class BlinkyPlayer(object):
FOREVER = -1
def __init__(self, blinkytape):
self._blinkytape = blinkytape
def play(self, animation, num_cycles = FOREVER):
finished = self._make_finished_predicate(animation, num_cycles)
animation.begin()
while not finished():
... | import time
class BlinkyPlayer(object):
FOREVER = -1
def __init__(self, blinkytape):
self._blinkytape = blinkytape
def play(self, animation, num_cycles = FOREVER):
finished = self._finished_predicate(animation, num_cycles)
animation.begin()
while not finished():
... | Clean up BlinkyPlayer a little | Clean up BlinkyPlayer a little
| Python | mit | jonspeicher/blinkyfun | import time
class BlinkyPlayer(object):
FOREVER = -1
def __init__(self, blinkytape):
self._blinkytape = blinkytape
def play(self, animation, num_cycles = FOREVER):
finished = self._finished_predicate(animation, num_cycles)
animation.begin()
while not finished():
... | Clean up BlinkyPlayer a little
import time
class BlinkyPlayer(object):
FOREVER = -1
def __init__(self, blinkytape):
self._blinkytape = blinkytape
def play(self, animation, num_cycles = FOREVER):
finished = self._make_finished_predicate(animation, num_cycles)
animation.begin()
... |
b32f4955665b8618a9623f6898a15d4da40dc58e | dxtbx/command_line/print_header.py | dxtbx/command_line/print_header.py | def print_header():
import sys
from dxtbx.format.Registry import Registry
# this will do the lookup for every frame - this is strictly not needed
# if all frames are from the same instrument
for arg in sys.argv[1:]:
format = Registry.find(arg)
i = format(arg)
print 'Bea... | def print_header():
import sys
from dxtbx.format.Registry import Registry
# this will do the lookup for every frame - this is strictly not needed
# if all frames are from the same instrument
for arg in sys.argv[1:]:
format = Registry.find(arg)
print 'Using header reader: %s' % ... | Print the Format class used | Print the Format class used | Python | bsd-3-clause | dials/dials,dials/dials,dials/dials,dials/dials,dials/dials | def print_header():
import sys
from dxtbx.format.Registry import Registry
# this will do the lookup for every frame - this is strictly not needed
# if all frames are from the same instrument
for arg in sys.argv[1:]:
format = Registry.find(arg)
print 'Using header reader: %s' % ... | Print the Format class used
def print_header():
import sys
from dxtbx.format.Registry import Registry
# this will do the lookup for every frame - this is strictly not needed
# if all frames are from the same instrument
for arg in sys.argv[1:]:
format = Registry.find(arg)
i = fo... |
cb9b1a2163f960e34721f74bad30622fda71e43b | packages/Python/lldbsuite/test/lang/objc/modules-cache/TestClangModulesCache.py | packages/Python/lldbsuite/test/lang/objc/modules-cache/TestClangModulesCache.py | """Test that the clang modules cache directory can be controlled."""
from __future__ import print_function
import unittest2
import os
import time
import platform
import shutil
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class ObjCMo... | """Test that the clang modules cache directory can be controlled."""
from __future__ import print_function
import unittest2
import os
import time
import platform
import shutil
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class ObjCMo... | Mark ObjC testcase as skipUnlessDarwin and fix a typo in test function. | Mark ObjC testcase as skipUnlessDarwin and fix a typo in test function.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@326640 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb | """Test that the clang modules cache directory can be controlled."""
from __future__ import print_function
import unittest2
import os
import time
import platform
import shutil
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class ObjCMo... | Mark ObjC testcase as skipUnlessDarwin and fix a typo in test function.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@326640 91177308-0d34-0410-b5e6-96231b3b80d8
"""Test that the clang modules cache directory can be controlled."""
from __future__ import print_function
import unittest2
import os
import time
... |
60a10e8fbfd40197db8226f0791c7064c80fe370 | run.py | run.py | import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
args = parser.parse_args()
if not any(vars(args).values()):
parser.print_help()
elif args.run:
os.system("ENVIRONMENT=development python server.py"... | import sys
import os
import argparse
import shutil
from efselab import build
parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
parser.add_argument('--update', action="store_true")
args = parser.parse_args()
if not any(vars(args).... | Add new update command that updates efselab dependencies. | Add new update command that updates efselab dependencies.
Former-commit-id: 6cfed1b9af9c0bbf34b7e58e3aa8ac3bada85aa7 | Python | mit | EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger | import sys
import os
import argparse
import shutil
from efselab import build
parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
parser.add_argument('--update', action="store_true")
args = parser.parse_args()
if not any(vars(args).... | Add new update command that updates efselab dependencies.
Former-commit-id: 6cfed1b9af9c0bbf34b7e58e3aa8ac3bada85aa7
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
args = parser.parse_args()
if not an... |
0ba671698bf4e268ae3f17e11078a5eb669a174c | indico/modules/events/roles/__init__.py | indico/modules/events/roles/__init__.py | # This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | # This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | Move roles menu item into a submenu | Move roles menu item into a submenu
- 'organization' for conferences
- 'advanced' for other event types
| Python | mit | mic4ael/indico,indico/indico,mic4ael/indico,pferreir/indico,DirkHoffmann/indico,OmeGak/indico,pferreir/indico,OmeGak/indico,DirkHoffmann/indico,indico/indico,mvidalgarcia/indico,ThiefMaster/indico,indico/indico,OmeGak/indico,ThiefMaster/indico,DirkHoffmann/indico,DirkHoffmann/indico,mvidalgarcia/indico,ThiefMaster/indi... | # This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | Move roles menu item into a submenu
- 'organization' for conferences
- 'advanced' for other event types
# This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU Gener... |
ea4746f6b809c0c3b2a6931bc863121c07ee2c9a | lib/plugins/method/__init__.py | lib/plugins/method/__init__.py | from yapsy.IPlugin import IPlugin
from lib.methods import BaseMethod
class IMethodPlugin(BaseMethod, IPlugin):
def __init__(self):
pass
def setNameAndFactory(self, name, factory):
self.methodName = name
self.factory = factory
| from yapsy.IPlugin import IPlugin
from lib.methods import BaseMethod
class IMethodPlugin(BaseMethod, IPlugin):
def __init__(self):
pass
def setNameAndFactory(self, name, factory):
self.methodName = name
self.factory = factory
@staticmethod
def supports(methodName):
raise NotImplementedError
| Make supports method throw NotImplementedError so that methods failing to implement it does not fail silently | Make supports method throw NotImplementedError so that methods failing to implement it does not fail silently
| Python | mit | factorial-io/fabalicious,factorial-io/fabalicious | from yapsy.IPlugin import IPlugin
from lib.methods import BaseMethod
class IMethodPlugin(BaseMethod, IPlugin):
def __init__(self):
pass
def setNameAndFactory(self, name, factory):
self.methodName = name
self.factory = factory
@staticmethod
def supports(methodName):
raise NotImplementedError
| Make supports method throw NotImplementedError so that methods failing to implement it does not fail silently
from yapsy.IPlugin import IPlugin
from lib.methods import BaseMethod
class IMethodPlugin(BaseMethod, IPlugin):
def __init__(self):
pass
def setNameAndFactory(self, name, factory):
self.methodNam... |
f4026b34f97c4e42a2229d47e778fbe09b351eb1 | tools/tabulate_events.py | tools/tabulate_events.py | #!/usr/bin/env python
# note: must be invoked from the top-level sts directory
import time
import argparse
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from sts.replay_event import *
from sts.dataplane_traces.trace import Trace
from sts.input_traces.log_parser import parse
fro... | Add simple tool for tabulating classes of event types for readability | Add simple tool for tabulating classes of event types for readability
| Python | apache-2.0 | jmiserez/sts,jmiserez/sts,ucb-sts/sts,ucb-sts/sts | #!/usr/bin/env python
# note: must be invoked from the top-level sts directory
import time
import argparse
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from sts.replay_event import *
from sts.dataplane_traces.trace import Trace
from sts.input_traces.log_parser import parse
fro... | Add simple tool for tabulating classes of event types for readability
| |
143e76eaf220e5200150653627642dc2bc3a645e | examples/network_correlations.py | examples/network_correlations.py | """
Cortical networks correlation matrix
====================================
"""
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(context="paper", font="monospace")
df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0)
corrmat = df.corr()
f, ax = plt.subplots(figsize=(12, 9))
sns.heatm... | Add correlation matrix heatmap example | Add correlation matrix heatmap example
| Python | bsd-3-clause | oesteban/seaborn,gef756/seaborn,arokem/seaborn,anntzer/seaborn,drewokane/seaborn,ischwabacher/seaborn,phobson/seaborn,ebothmann/seaborn,cwu2011/seaborn,sinhrks/seaborn,q1ang/seaborn,aashish24/seaborn,ashhher3/seaborn,dimarkov/seaborn,lypzln/seaborn,mwaskom/seaborn,JWarmenhoven/seaborn,olgabot/seaborn,dotsdl/seaborn,luk... | """
Cortical networks correlation matrix
====================================
"""
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(context="paper", font="monospace")
df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0)
corrmat = df.corr()
f, ax = plt.subplots(figsize=(12, 9))
sns.heatm... | Add correlation matrix heatmap example
| |
c5b73be1bf0f0edd05c4743c2449bee568d01c76 | setup.py | setup.py | from distutils.core import setup
from turbasen import VERSION
name = 'turbasen'
setup(
name=name,
packages=[name],
version=VERSION,
description='Client for Nasjonal Turbase REST API',
author='Ali Kaafarani',
author_email='ali.kaafarani@turistforeningen.no',
url='https://github.com/Turbase... | from distutils.core import setup
from os import path
from turbasen import VERSION
name = 'turbasen'
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name=name,
packages=[name],
version=VERSION,
descript... | Add long description from README | Add long description from README
| Python | mit | Turbasen/turbasen.py | from distutils.core import setup
from os import path
from turbasen import VERSION
name = 'turbasen'
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name=name,
packages=[name],
version=VERSION,
descript... | Add long description from README
from distutils.core import setup
from turbasen import VERSION
name = 'turbasen'
setup(
name=name,
packages=[name],
version=VERSION,
description='Client for Nasjonal Turbase REST API',
author='Ali Kaafarani',
author_email='ali.kaafarani@turistforeningen.no',
... |
fc2a3635a37cd1dcfc2ea8705e2cae37b083b6a2 | lintcode/Easy/181_Flip_Bits.py | lintcode/Easy/181_Flip_Bits.py | class Solution:
"""
@param a, b: Two integer
return: An integer
"""
def bitSwapRequired(self, a, b):
# write your code here
return bin((a^b) & 0xffffffff).count('1')
| Add solution to lintcode problem 181 | Add solution to lintcode problem 181
| Python | mit | Rhadow/leetcode,Rhadow/leetcode,Rhadow/leetcode,Rhadow/leetcode | class Solution:
"""
@param a, b: Two integer
return: An integer
"""
def bitSwapRequired(self, a, b):
# write your code here
return bin((a^b) & 0xffffffff).count('1')
| Add solution to lintcode problem 181
| |
699a2d8d97d8c526f9fb269245d5fb593d47d3ca | rasa/nlu/tokenizers/__init__.py | rasa/nlu/tokenizers/__init__.py | class Tokenizer:
pass
class Token:
def __init__(self, text, offset, data=None):
self.offset = offset
self.text = text
self.end = offset + len(text)
self.data = data if data else {}
def set(self, prop, info):
self.data[prop] = info
def get(self, prop, default=N... | import functools
class Tokenizer:
pass
@functools.total_ordering
class Token:
def __init__(self, text, offset, data=None):
self.offset = offset
self.text = text
self.end = offset + len(text)
self.data = data if data else {}
def set(self, prop, info):
self.data[pr... | Fix to make sanitize_examples() be able to sort tokens | Fix to make sanitize_examples() be able to sort tokens
| Python | apache-2.0 | RasaHQ/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu | import functools
class Tokenizer:
pass
@functools.total_ordering
class Token:
def __init__(self, text, offset, data=None):
self.offset = offset
self.text = text
self.end = offset + len(text)
self.data = data if data else {}
def set(self, prop, info):
self.data[pr... | Fix to make sanitize_examples() be able to sort tokens
class Tokenizer:
pass
class Token:
def __init__(self, text, offset, data=None):
self.offset = offset
self.text = text
self.end = offset + len(text)
self.data = data if data else {}
def set(self, prop, info):
s... |
58cd27f4daa921a63d0a80c31f5ff1bf73cb1992 | lintcode/Medium/040_Implement_Queue_by_Two_Stacks.py | lintcode/Medium/040_Implement_Queue_by_Two_Stacks.py | class MyQueue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, element):
# write your code here
self.stack1.append(element)
def top(self):
# write your code here
# return the top element
return self.stack1[0]
def pop(self):... | Add solution to lintcode question 40 | Add solution to lintcode question 40
| Python | mit | Rhadow/leetcode,Rhadow/leetcode,Rhadow/leetcode,Rhadow/leetcode | class MyQueue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, element):
# write your code here
self.stack1.append(element)
def top(self):
# write your code here
# return the top element
return self.stack1[0]
def pop(self):... | Add solution to lintcode question 40
| |
7adab964e523ec6af96acbea0fa7f30efef78dc8 | examples/tracing/strlen_hist.py | examples/tracing/strlen_hist.py | #!/usr/bin/python
#
# strlen_hist.py Histogram of system-wide strlen return values
#
# A basic example of using uprobes along with a histogram to show
# distributions.
#
# Runs until ctrl-c is pressed.
#
# Copyright (c) PLUMgrid, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# Example outp... | Add uprobe strlen histogram example | Add uprobe strlen histogram example
This example traces all calls to libc's strlen(). The program is attached as a
retprobe, therefore giving access to the resulting string length. The value is
kept in a log2 histogram that is printed to console once per second.
Example:
```
$ sudo ./strlen_hist.py
22:12:51
strl... | Python | apache-2.0 | romain-intel/bcc,tuxology/bcc,brendangregg/bcc,mcaleavya/bcc,zaafar/bcc,romain-intel/bcc,tuxology/bcc,shodoco/bcc,shodoco/bcc,iovisor/bcc,iovisor/bcc,mkacik/bcc,mcaleavya/bcc,mkacik/bcc,iovisor/bcc,mcaleavya/bcc,mcaleavya/bcc,mkacik/bcc,mcaleavya/bcc,shodoco/bcc,brendangregg/bcc,brendangregg/bcc,zaafar/bcc,tuxology/bcc... | #!/usr/bin/python
#
# strlen_hist.py Histogram of system-wide strlen return values
#
# A basic example of using uprobes along with a histogram to show
# distributions.
#
# Runs until ctrl-c is pressed.
#
# Copyright (c) PLUMgrid, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# Example outp... | Add uprobe strlen histogram example
This example traces all calls to libc's strlen(). The program is attached as a
retprobe, therefore giving access to the resulting string length. The value is
kept in a log2 histogram that is printed to console once per second.
Example:
```
$ sudo ./strlen_hist.py
22:12:51
strl... | |
3c0f8899521465fcb2d4685b6e6e6e3e61c0eabc | kitchen/dashboard/graphs.py | kitchen/dashboard/graphs.py | """Facility to render node graphs using pydot"""
import os
import pydot
from kitchen.settings import STATIC_ROOT, REPO
def generate_node_map(nodes):
"""Generates a graphviz nodemap"""
graph = pydot.Dot(graph_type='digraph')
graph_nodes = {}
# Create nodes
for node in nodes:
label = node['... | """Facility to render node graphs using pydot"""
import os
import pydot
from kitchen.settings import STATIC_ROOT, REPO
def generate_node_map(nodes):
"""Generates a graphviz nodemap"""
graph = pydot.Dot(graph_type='digraph')
graph_nodes = {}
# Create nodes
for node in nodes:
label = node['... | Change to "ask for forgiveness", as the 'client_roles' condition could get too complicated | Change to "ask for forgiveness", as the 'client_roles' condition could get too complicated
| Python | apache-2.0 | edelight/kitchen,edelight/kitchen,edelight/kitchen,edelight/kitchen | """Facility to render node graphs using pydot"""
import os
import pydot
from kitchen.settings import STATIC_ROOT, REPO
def generate_node_map(nodes):
"""Generates a graphviz nodemap"""
graph = pydot.Dot(graph_type='digraph')
graph_nodes = {}
# Create nodes
for node in nodes:
label = node['... | Change to "ask for forgiveness", as the 'client_roles' condition could get too complicated
"""Facility to render node graphs using pydot"""
import os
import pydot
from kitchen.settings import STATIC_ROOT, REPO
def generate_node_map(nodes):
"""Generates a graphviz nodemap"""
graph = pydot.Dot(graph_type='dig... |
30d70f30b24454affaf56299a014e577089dc885 | tools/telemetry/catapult_base/__init__.py | tools/telemetry/catapult_base/__init__.py | # Copyright 2015 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.
# All files in this directory should be moved to catapult/base/ after moving
# to the new repo.
| Add catapult_base folder to tools/telemetry to make the refactor easier. | Add catapult_base folder to tools/telemetry to make the refactor easier.
This will make some of the refactoring more obvious and easy to review, as
well as making the needed reafctoring after moving to the catapult repo easier.
BUG=473414
Review URL: https://codereview.chromium.org/1168263002
Cr-Commit-Position: 97... | Python | bsd-3-clause | axinging/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium... | # Copyright 2015 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.
# All files in this directory should be moved to catapult/base/ after moving
# to the new repo.
| Add catapult_base folder to tools/telemetry to make the refactor easier.
This will make some of the refactoring more obvious and easy to review, as
well as making the needed reafctoring after moving to the catapult repo easier.
BUG=473414
Review URL: https://codereview.chromium.org/1168263002
Cr-Commit-Position: 97... | |
62494cd7125d498d8de058ab3ebe556cd9686f6e | calvin/runtime/north/plugins/coders/messages/msgpack_coder.py | calvin/runtime/north/plugins/coders/messages/msgpack_coder.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 ... | # -*- 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 ... | Use umsgpack package for msgpack coder | coder/msgpack: Use umsgpack package for msgpack coder
| Python | apache-2.0 | EricssonResearch/calvin-base,EricssonResearch/calvin-base,EricssonResearch/calvin-base,EricssonResearch/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 ... | coder/msgpack: Use umsgpack package for msgpack coder
# -*- 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/... |
4514c5c5644796413c01f6132b3b6afece73ce01 | txircd/modules/cmode_s.py | txircd/modules/cmode_s.py | from txircd.modbase import Mode
class SecretMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
cdata = data["cdata"]
if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
data["cdata"] = {}
# other +s stuff is hiding in other modules.
cla... | from txircd.modbase import Mode
class SecretMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
cdata = data["cdata"]
if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
data["cdata"].clear()
# other +s stuff is hiding in other modules.
... | Make +s actually definitely clear the cdata dictionary | Make +s actually definitely clear the cdata dictionary
| Python | bsd-3-clause | ElementalAlchemist/txircd,Heufneutje/txircd,DesertBus/txircd | from txircd.modbase import Mode
class SecretMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
cdata = data["cdata"]
if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
data["cdata"].clear()
# other +s stuff is hiding in other modules.
... | Make +s actually definitely clear the cdata dictionary
from txircd.modbase import Mode
class SecretMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
cdata = data["cdata"]
if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
data["cdata"]... |
9406ed1d55151bb47760947c54c2bd29fcc1d3a3 | knowledge_repo/converters/md.py | knowledge_repo/converters/md.py | from ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text
class MdConverter(KnowledgePostConverter):
_registry_keys = [MD]
def from_file(self, filename):
self.kp_write(read_text(filename))
| from ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text
class MdConverter(KnowledgePostConverter):
_registry_keys = [MD]
def from_file(self, filename):
self.kp_write(read_text(filename))
| Fix a lint required empty lines issue | Fix a lint required empty lines issue
| Python | apache-2.0 | airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo | from ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text
class MdConverter(KnowledgePostConverter):
_registry_keys = [MD]
def from_file(self, filename):
self.kp_write(read_text(filename))
| Fix a lint required empty lines issue
from ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text
class MdConverter(KnowledgePostConverter):
_registry_keys = [MD]
def from_file(self, filename):
self.kp_write(read_text(filename))
|
27ee2752a71ee415154c40e1978edb9d5221a331 | IPython/lib/tests/test_deepreload.py | IPython/lib/tests/test_deepreload.py | """Test suite for the deepreload module."""
from IPython.testing import decorators as dec
from IPython.lib.deepreload import reload as dreload
@dec.skipif_not_numpy
def test_deepreload_numpy():
import numpy
exclude = [
# Standard exclusions:
'sys', 'os.path', '__builtin__', '__main__',
... | # -*- coding: utf-8 -*-
"""Test suite for the deepreload module."""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from IPython.testing import decorators as dec
from IPython.lib.deepreload import r... | Reformat test to a standard style. | Reformat test to a standard style.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | # -*- coding: utf-8 -*-
"""Test suite for the deepreload module."""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from IPython.testing import decorators as dec
from IPython.lib.deepreload import r... | Reformat test to a standard style.
"""Test suite for the deepreload module."""
from IPython.testing import decorators as dec
from IPython.lib.deepreload import reload as dreload
@dec.skipif_not_numpy
def test_deepreload_numpy():
import numpy
exclude = [
# Standard exclusions:
'sys', 'os.path'... |
cfaaf421bb9627f1741a9ef4074517fd5daaec86 | wsgi/setup.py | wsgi/setup.py |
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen("gunicorn hello:app -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.com... |
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen('gunicorn hello:app --worker-class="egg:meinheld#gunicorn_worker" -b 0.0.0.0:8080 -w '
+ str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subproces... | Use meinheld worker (same as other Python Frameworks) | wsgi: Use meinheld worker (same as other Python Frameworks)
| Python | bsd-3-clause | torhve/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,denkab/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,grob/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,jetty-project/FrameworkBenchmark... |
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen('gunicorn hello:app --worker-class="egg:meinheld#gunicorn_worker" -b 0.0.0.0:8080 -w '
+ str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subproces... | wsgi: Use meinheld worker (same as other Python Frameworks)
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen("gunicorn hello:app -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subprocess.Po... |
6f75300037254f51f1512a271bf7850a4bc0a8f8 | djangospam/cookie/urls.py | djangospam/cookie/urls.py | # -*- coding: utf-8 -*-
"""URL for setting SPAM value to the `djangospam.cookie` cookie.
You must also add `(r"^somewhere/", include("djangospam.cookie.urls")`
to your url patterns (usually in your root urls.conf; `somewhere`
may be any path, except the one used for true posts).
"""
from django.conf.urls.defaults impo... | # -*- coding: utf-8 -*-
"""URL for setting SPAM value to the `djangospam.cookie` cookie.
You must also add `(r"^somewhere/", include("djangospam.cookie.urls")`
to your url patterns (usually in your root urls.conf; `somewhere`
may be any path, except the one used for true posts).
"""
try:
from django.conf.urls impo... | Add support for Django 1.4 and up | Add support for Django 1.4 and up
* Module django.conf.urls.defaults has been moved to django.conf.urls in
version 1.4.
Commit references issue #3.
| Python | bsd-2-clause | leandroarndt/djangospam,leandroarndt/djangospam | # -*- coding: utf-8 -*-
"""URL for setting SPAM value to the `djangospam.cookie` cookie.
You must also add `(r"^somewhere/", include("djangospam.cookie.urls")`
to your url patterns (usually in your root urls.conf; `somewhere`
may be any path, except the one used for true posts).
"""
try:
from django.conf.urls impo... | Add support for Django 1.4 and up
* Module django.conf.urls.defaults has been moved to django.conf.urls in
version 1.4.
Commit references issue #3.
# -*- coding: utf-8 -*-
"""URL for setting SPAM value to the `djangospam.cookie` cookie.
You must also add `(r"^somewhere/", include("djangospam.cookie.urls")`
to your u... |
f2fd224b5e3c8cb4a919e082c47c603d4469a564 | jacquard/buckets/tests/test_bucket.py | jacquard/buckets/tests/test_bucket.py | import pytest
from jacquard.odm import Session
from jacquard.buckets import Bucket
from jacquard.buckets.constants import NUM_BUCKETS
@pytest.mark.parametrize('divisor', (
2,
3,
4,
5,
6,
10,
100,
))
def test_divisible(divisor):
assert NUM_BUCKETS % divisor == 0
def test_at_least_thr... | import pytest
from jacquard.odm import Session
from jacquard.buckets import Bucket
from jacquard.buckets.constants import NUM_BUCKETS
@pytest.mark.parametrize('divisor', (
2,
3,
4,
5,
6,
10,
100,
))
def test_divisible(divisor):
assert NUM_BUCKETS % divisor == 0
def test_at_least_thr... | Use an explicit test here | Use an explicit test here
| Python | mit | prophile/jacquard,prophile/jacquard | import pytest
from jacquard.odm import Session
from jacquard.buckets import Bucket
from jacquard.buckets.constants import NUM_BUCKETS
@pytest.mark.parametrize('divisor', (
2,
3,
4,
5,
6,
10,
100,
))
def test_divisible(divisor):
assert NUM_BUCKETS % divisor == 0
def test_at_least_thr... | Use an explicit test here
import pytest
from jacquard.odm import Session
from jacquard.buckets import Bucket
from jacquard.buckets.constants import NUM_BUCKETS
@pytest.mark.parametrize('divisor', (
2,
3,
4,
5,
6,
10,
100,
))
def test_divisible(divisor):
assert NUM_BUCKETS % divisor =... |
0f0e0e91db679f18ad9dc7568047b76e447ac589 | stock_inventory_chatter/__openerp__.py | stock_inventory_chatter/__openerp__.py | # -*- coding: utf-8 -*-
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
# (http://www.eficent.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
'name': 'Stock Inventory Chatter',
'version': '9.0.1.0.0',
'author': "Eficent, "
"Odoo Community Assoc... | # -*- coding: utf-8 -*-
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
# Copyright 2018 initOS GmbH
# (http://www.eficent.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
'name': 'Stock Inventory Chatter',
'version': '8.0.1.0.0',
'author': "Eficent, "
... | Change of the module version | Change of the module version
| Python | agpl-3.0 | kmee/stock-logistics-warehouse,acsone/stock-logistics-warehouse,open-synergy/stock-logistics-warehouse | # -*- coding: utf-8 -*-
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
# Copyright 2018 initOS GmbH
# (http://www.eficent.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
'name': 'Stock Inventory Chatter',
'version': '8.0.1.0.0',
'author': "Eficent, "
... | Change of the module version
# -*- coding: utf-8 -*-
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
# (http://www.eficent.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
'name': 'Stock Inventory Chatter',
'version': '9.0.1.0.0',
'author': "Eficent, "
... |
9dee48fb0964b12780f57cef26c5b84072448232 | ds/api/serializer/app.py | ds/api/serializer/app.py | from __future__ import absolute_import
from ds.models import App
from .base import Serializer
from .manager import add
@add(App)
class AppSerializer(Serializer):
def serialize(self, item, attrs):
return {
'id': str(item.id),
'name': item.name,
}
| from __future__ import absolute_import
from ds.models import App
from .base import Serializer
from .manager import add
@add(App)
class AppSerializer(Serializer):
def serialize(self, item, attrs):
return {
'id': str(item.id),
'name': item.name,
'provider': item.provide... | Add provider information to App | Add provider information to App
| Python | apache-2.0 | jkimbo/freight,rshk/freight,jkimbo/freight,getsentry/freight,jkimbo/freight,rshk/freight,klynton/freight,rshk/freight,getsentry/freight,klynton/freight,getsentry/freight,rshk/freight,klynton/freight,getsentry/freight,getsentry/freight,jkimbo/freight,klynton/freight | from __future__ import absolute_import
from ds.models import App
from .base import Serializer
from .manager import add
@add(App)
class AppSerializer(Serializer):
def serialize(self, item, attrs):
return {
'id': str(item.id),
'name': item.name,
'provider': item.provide... | Add provider information to App
from __future__ import absolute_import
from ds.models import App
from .base import Serializer
from .manager import add
@add(App)
class AppSerializer(Serializer):
def serialize(self, item, attrs):
return {
'id': str(item.id),
'name': item.name,
... |
56cd2b9804718caeb8728c3b01fb6f0bc0f2d0d4 | setup.py | setup.py | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.8',
packages=['todoist', 'todoist.managers'],
author='Doist Team'... | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.9',
packages=['todoist', 'todoist.managers'],
author='Doist Team'... | Update the PyPI version to 7.0.9. | Update the PyPI version to 7.0.9.
| Python | mit | Doist/todoist-python | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.9',
packages=['todoist', 'todoist.managers'],
author='Doist Team'... | Update the PyPI version to 7.0.9.
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.8',
packages=['todoist', 'todoist.... |
531d11ea10064fdbbad85b482bcdf075529c977d | tests/test_utils.py | tests/test_utils.py | import unittest
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "..\\"))
from app import create_app, db
from app.utils import get_or_create
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self... | Add test case for get_or_create util | Add test case for get_or_create util
| Python | mit | Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary | import unittest
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "..\\"))
from app import create_app, db
from app.utils import get_or_create
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self... | Add test case for get_or_create util
| |
d8295756e73cb096acd5e3ef7e2b076b8b871c31 | apps/domain/src/main/routes/general/routes.py | apps/domain/src/main/routes/general/routes.py | from .blueprint import root_blueprint as root_route
from ...core.node import node
# syft absolute
from syft.core.common.message import SignedImmediateSyftMessageWithReply
from syft.core.common.message import SignedImmediateSyftMessageWithoutReply
from syft.core.common.serde.deserialize import _deserialize
from flask ... | from .blueprint import root_blueprint as root_route
from ...core.node import node
# syft absolute
from syft.core.common.message import SignedImmediateSyftMessageWithReply
from syft.core.common.message import SignedImmediateSyftMessageWithoutReply
from syft.core.common.serde.deserialize import _deserialize
from flask ... | Update /users/login endpoint to return serialized metadata | Update /users/login endpoint to return serialized metadata
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | from .blueprint import root_blueprint as root_route
from ...core.node import node
# syft absolute
from syft.core.common.message import SignedImmediateSyftMessageWithReply
from syft.core.common.message import SignedImmediateSyftMessageWithoutReply
from syft.core.common.serde.deserialize import _deserialize
from flask ... | Update /users/login endpoint to return serialized metadata
from .blueprint import root_blueprint as root_route
from ...core.node import node
# syft absolute
from syft.core.common.message import SignedImmediateSyftMessageWithReply
from syft.core.common.message import SignedImmediateSyftMessageWithoutReply
from syft.co... |
f76a766f7be4936d34dc14e65a0f1fd974055b20 | fireplace/cards/tgt/paladin.py | fireplace/cards/tgt/paladin.py | from ..utils import *
##
# Minions
# Murloc Knight
class AT_076:
inspire = Summon(CONTROLLER, RandomMurloc())
# Eadric the Pure
class AT_081:
play = Buff(ALL_MINIONS, "AT_081e")
##
# Spells
# Seal of Champions
class AT_074:
play = Buff(TARGET, "AT_074e2")
##
# Secrets
# Competitive Spirit
class A... | from ..utils import *
##
# Minions
# Murloc Knight
class AT_076:
inspire = Summon(CONTROLLER, RandomMurloc())
# Eadric the Pure
class AT_081:
play = Buff(ENEMY_MINIONS, "AT_081e")
##
# Spells
# Seal of Champions
class AT_074:
play = Buff(TARGET, "AT_074e2")
##
# Secrets
# Competitive Spirit
class AT_073:
... | Fix Eadric the Pure's target selection | Fix Eadric the Pure's target selection
| Python | agpl-3.0 | liujimj/fireplace,beheh/fireplace,NightKev/fireplace,smallnamespace/fireplace,jleclanche/fireplace,amw2104/fireplace,oftc-ftw/fireplace,Meerkov/fireplace,Ragowit/fireplace,amw2104/fireplace,oftc-ftw/fireplace,Ragowit/fireplace,liujimj/fireplace,Meerkov/fireplace,smallnamespace/fireplace | from ..utils import *
##
# Minions
# Murloc Knight
class AT_076:
inspire = Summon(CONTROLLER, RandomMurloc())
# Eadric the Pure
class AT_081:
play = Buff(ENEMY_MINIONS, "AT_081e")
##
# Spells
# Seal of Champions
class AT_074:
play = Buff(TARGET, "AT_074e2")
##
# Secrets
# Competitive Spirit
class AT_073:
... | Fix Eadric the Pure's target selection
from ..utils import *
##
# Minions
# Murloc Knight
class AT_076:
inspire = Summon(CONTROLLER, RandomMurloc())
# Eadric the Pure
class AT_081:
play = Buff(ALL_MINIONS, "AT_081e")
##
# Spells
# Seal of Champions
class AT_074:
play = Buff(TARGET, "AT_074e2")
##... |
74ceceb6ccdb3b205a72aa6ca75b833c66eb659c | HearthStone2/copy_data.py | HearthStone2/copy_data.py | #! /usr/bin/python
# -*- coding: utf-8 -*-
"""Copy data from the given zip file to the project."""
import argparse
import fnmatch
import os
import time
import zipfile
__author__ = 'fyabc'
DataDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'MyHearthStone')
DataFilePattern = '*/resources/*'
def main... | Add a script to copy data files conveniently. | Add a script to copy data files conveniently.
| Python | mit | fyabc/MiniGames | #! /usr/bin/python
# -*- coding: utf-8 -*-
"""Copy data from the given zip file to the project."""
import argparse
import fnmatch
import os
import time
import zipfile
__author__ = 'fyabc'
DataDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'MyHearthStone')
DataFilePattern = '*/resources/*'
def main... | Add a script to copy data files conveniently.
| |
29e6e77b03569d39e484b47efd3b8230f30ee195 | eduid_signup/db.py | eduid_signup/db.py | import pymongo
from eduid_signup.compat import urlparse
DEFAULT_MONGODB_HOST = 'localhost'
DEFAULT_MONGODB_PORT = 27017
DEFAULT_MONGODB_NAME = 'eduid'
DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST,
DEFAULT_MONGODB_PORT,
... | import pymongo
DEFAULT_MONGODB_HOST = 'localhost'
DEFAULT_MONGODB_PORT = 27017
DEFAULT_MONGODB_NAME = 'eduid'
DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST,
DEFAULT_MONGODB_PORT,
DEFAULT_MONGODB_NAME)
cla... | Allow Mongo connections to Mongo Replicaset Cluster | Allow Mongo connections to Mongo Replicaset Cluster
| Python | bsd-3-clause | SUNET/eduid-signup,SUNET/eduid-signup,SUNET/eduid-signup | import pymongo
DEFAULT_MONGODB_HOST = 'localhost'
DEFAULT_MONGODB_PORT = 27017
DEFAULT_MONGODB_NAME = 'eduid'
DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST,
DEFAULT_MONGODB_PORT,
DEFAULT_MONGODB_NAME)
cla... | Allow Mongo connections to Mongo Replicaset Cluster
import pymongo
from eduid_signup.compat import urlparse
DEFAULT_MONGODB_HOST = 'localhost'
DEFAULT_MONGODB_PORT = 27017
DEFAULT_MONGODB_NAME = 'eduid'
DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST,
... |
ae463e9f27bd1266125d0d3d94dd88171df997d2 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='straight.plugin',
version='1.0',
description='A simple namespaced plugin facility',
author='Calvin Spealman',
author_email='ironfroggy@gmail.com',
url='https://github.com/ironfroggy/straight.plugin',
packages=['stra... | #!/usr/bin/env python
from distutils.core import setup
setup(name='straight.plugin',
version='1.1.1',
description='A simple namespaced plugin facility',
author='Calvin Spealman',
author_email='ironfroggy@gmail.com',
url='https://github.com/ironfroggy/straight.plugin',
packages=['st... | Mark version 1.1.1 with license. | Mark version 1.1.1 with license.
| Python | mit | ironfroggy/straight.plugin,pombredanne/straight.plugin | #!/usr/bin/env python
from distutils.core import setup
setup(name='straight.plugin',
version='1.1.1',
description='A simple namespaced plugin facility',
author='Calvin Spealman',
author_email='ironfroggy@gmail.com',
url='https://github.com/ironfroggy/straight.plugin',
packages=['st... | Mark version 1.1.1 with license.
#!/usr/bin/env python
from distutils.core import setup
setup(name='straight.plugin',
version='1.0',
description='A simple namespaced plugin facility',
author='Calvin Spealman',
author_email='ironfroggy@gmail.com',
url='https://github.com/ironfroggy/strai... |
2e9472e4989985ebdb770c193856a02616a3d8e4 | 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 | 0xPoly/ooni-probe,juga0/ooni-probe,kdmurray91/ooni-probe,hackerberry/ooni-probe,lordappsec/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,juga0/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni... | 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... |
29519614965e6629debcd2d08fd1fe2e0debe08f | test/test_paramval.py | test/test_paramval.py | import logging
import luigi
import sciluigi as sl
import os
import time
import unittest
log = logging.getLogger('sciluigi-interface')
log.setLevel(logging.WARNING)
class IntParamTask(sl.Task):
an_int_param = luigi.IntParameter()
def out_int_val(self):
return sl.TargetInfo(self, '/tmp/intparamtask_in... | Add test for non-string (integer) parameter value | Add test for non-string (integer) parameter value
| Python | mit | pharmbio/sciluigi,pharmbio/sciluigi,samuell/sciluigi | import logging
import luigi
import sciluigi as sl
import os
import time
import unittest
log = logging.getLogger('sciluigi-interface')
log.setLevel(logging.WARNING)
class IntParamTask(sl.Task):
an_int_param = luigi.IntParameter()
def out_int_val(self):
return sl.TargetInfo(self, '/tmp/intparamtask_in... | Add test for non-string (integer) parameter value
| |
e40c295967e8d0b1a190c173dedebefe9eb89462 | Python/66_PlusOne.py | Python/66_PlusOne.py | class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits[len(digits)-1] += 1
if digits[len(digits)-1] < 10:
return digits
for i in xrange(len(digits)-1,0,-1):
if digits[i] == 10:
di... | Add solution for 66 Plus One. | Add solution for 66 Plus One.
| Python | mit | comicxmz001/LeetCode,comicxmz001/LeetCode | class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits[len(digits)-1] += 1
if digits[len(digits)-1] < 10:
return digits
for i in xrange(len(digits)-1,0,-1):
if digits[i] == 10:
di... | Add solution for 66 Plus One.
| |
81215120afffe54b17be3f38bbc2ac292452c0c4 | addons/mail/models/ir_attachment.py | addons/mail/models/ir_attachment.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class IrAttachment(models.Model):
_inherit = 'ir.attachment'
@api.multi
def _post_add_create(self):
""" Overrides behaviour when the attachment is created throu... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class IrAttachment(models.Model):
_inherit = 'ir.attachment'
@api.multi
def _post_add_create(self):
""" Overrides behaviour when the attachment is created throu... | Revert "[FIX] mail: remove attachment as main at unlink" | Revert "[FIX] mail: remove attachment as main at unlink"
This reverts commit abc45b1
Since by default the ondelete attribute of a many2one is `set null`,
this was completely unnecessary to begin with.
Bug caused by this commit:
Unlink a record that has some attachments.
The unlink first removes the record, then its r... | Python | agpl-3.0 | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class IrAttachment(models.Model):
_inherit = 'ir.attachment'
@api.multi
def _post_add_create(self):
""" Overrides behaviour when the attachment is created throu... | Revert "[FIX] mail: remove attachment as main at unlink"
This reverts commit abc45b1
Since by default the ondelete attribute of a many2one is `set null`,
this was completely unnecessary to begin with.
Bug caused by this commit:
Unlink a record that has some attachments.
The unlink first removes the record, then its r... |
a581253c6daee875855ac1677717eb1cf464e704 | froide/publicbody/migrations/0021_proposedpublicbody.py | froide/publicbody/migrations/0021_proposedpublicbody.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-07-19 10:35
from __future__ import unicode_literals
from django.db import migrations
import froide.publicbody.models
class Migration(migrations.Migration):
dependencies = [
('publicbody', '0020_foilaw_requires_signature'),
]
operatio... | Add proposed publicbody proxy model migration | Add proposed publicbody proxy model migration | Python | mit | fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-07-19 10:35
from __future__ import unicode_literals
from django.db import migrations
import froide.publicbody.models
class Migration(migrations.Migration):
dependencies = [
('publicbody', '0020_foilaw_requires_signature'),
]
operatio... | Add proposed publicbody proxy model migration
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.