commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
4bd6ed79562435c3e2ef96472f6990109c482117 | deen/constants.py | deen/constants.py | import sys
__version__ = '0.9.1'
ENCODINGS = ['Base64',
'Base64 URL',
'Base32',
'Hex',
'URL',
'HTML',
'Rot13',
'UTF8',
'UTF16']
COMPRESSIONS = ['Gzip',
'Bz2']
HASHS = ['MD5',
'SHA1',
... | import sys
__version__ = '0.9.2'
ENCODINGS = ['Base64',
'Base64 URL',
'Base32',
'Hex',
'URL',
'HTML',
'Rot13',
'UTF8',
'UTF16']
COMPRESSIONS = ['Gzip',
'Bz2']
HASHS = ['MD5',
'SHA1',
... | Add X509 support only when pyOpenSSL is installed | Add X509 support only when pyOpenSSL is installed
| Python | apache-2.0 | takeshixx/deen,takeshixx/deen |
ff06ce55d0856cff774bdec5f0e872e093216bce | diffs/__init__.py | diffs/__init__.py | from __future__ import absolute_import, unicode_literals
from django.apps import apps as django_apps
from .signals import connect
__version__ = '0.0.1'
default_app_config = 'diffs.apps.DiffLogConfig'
klasses_to_connect = []
def register(klass):
"""
Decorator function that registers a class to record diffs... | from __future__ import absolute_import, unicode_literals
from .signals import connect
__version__ = '0.0.1'
default_app_config = 'diffs.apps.DiffLogConfig'
klasses_to_connect = []
def register(klass):
"""
Decorator function that registers a class to record diffs.
@register
class ExampleModel(model... | Reorganize imports to be later | Reorganize imports to be later
| Python | mit | linuxlewis/django-diffs |
a1c8326b9e520a9f262360ef97e2d5651c2e973e | inventory.py | inventory.py | from flask import Flask, render_template, url_for, redirect
from peewee import *
app = Flask(__name__)
database = SqliteDatabase('developmentData.db')
#class Device(Model):
@app.route('/')
def index():
# http://flask.pocoo.org/snippets/15/
return render_template('inventory.html', inventoryData="", deviceLogData="... | from flask import Flask, render_template, url_for, redirect
from peewee import *
#from datetime import date
app = Flask(__name__)
# http://docs.peewee-orm.com/en/latest/peewee/quickstart.html
database = SqliteDatabase('developmentData.db')
#class Device(Model):
@app.route('/')
def index():
# http://flask.pocoo.org/... | Add comments for references later | Add comments for references later
| Python | mit | lcdi/Inventory,lcdi/Inventory,lcdi/Inventory,lcdi/Inventory |
6a246c46f5adadc12fe4034c2b25e79196c3c831 | bake/load.py | bake/load.py | # load.py
# loads and formats bp files
import re
import os
import os.path
def load(iterator):
"""
Loads lines from an iterator and does line parsing
1 Handles line continuation
2 Handles include statements
3 Handle comments at start of line
"""
lines = []
for l in iterator:
# Handle... | # load.py
# loads and formats bp files
import re
import os
import os.path
def load(iterator):
"""
Loads lines from an iterator and does line parsing
1 Handles line continuation
2 Handles include statements
3 Handle comments at start of line
"""
lines = []
for l in iterator:
# Handle... | Allow for user-specified newline breaks in values | Allow for user-specified newline breaks in values
| Python | mit | AlexSzatmary/bake |
1abe172a31805d26a02b4c57d940c9afcc60ce78 | etcd3/__init__.py | etcd3/__init__.py | from __future__ import absolute_import
__author__ = 'Louis Taylor'
__email__ = 'louis@kragniz.eu'
__version__ = '0.1.0'
__all__ = ['Etcd3Client', 'client']
import grpc
from etcd3.etcdrpc import rpc_pb2 as etcdrpc
import etcd3.exceptions as exceptions
class Etcd3Client(object):
def __init__(self):
self... | from __future__ import absolute_import
__author__ = 'Louis Taylor'
__email__ = 'louis@kragniz.eu'
__version__ = '0.1.0'
__all__ = ['Etcd3Client', 'client']
import grpc
from etcd3.etcdrpc import rpc_pb2 as etcdrpc
import etcd3.exceptions as exceptions
class Etcd3Client(object):
def __init__(self, host='localho... | Add host and port parameters | Add host and port parameters
| Python | apache-2.0 | kragniz/python-etcd3 |
83d4c5b9b1f7ed9b75ae04464423b7ca4b5d627d | nova/db/sqlalchemy/migrate_repo/versions/037_add_config_drive_to_instances.py | nova/db/sqlalchemy/migrate_repo/versions/037_add_config_drive_to_instances.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
#
# 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
#
... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
#
# 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
#
... | Fix config_drive migration, per Matt Dietz. | Fix config_drive migration, per Matt Dietz. | Python | apache-2.0 | plumgrid/plumgrid-nova,adelina-t/nova,houshengbo/nova_vmware_compute_driver,cyx1231st/nova,redhat-openstack/nova,noironetworks/nova,jeffrey4l/nova,Stavitsky/nova,zaina/nova,CloudServer/nova,openstack/nova,sridevikoushik31/nova,eonpatapon/nova,usc-isi/extra-specs,shail2810/nova,sridevikoushik31/nova,russellb/nova,bclau/... |
4c69afe07533c37c3780b653d343e795cc515c5c | tests/test_examples.py | tests/test_examples.py | # -*- coding: utf8 - *-
from __future__ import absolute_import, print_function, unicode_literals
import examples.basic_usage
import examples.dataset
import examples.variant_ts_difficulties
import examples.variants
def test_dataset(unihan_options):
examples.dataset.run()
def test_variants(unihan_options):
e... | # -*- coding: utf8 - *-
from __future__ import absolute_import, print_function, unicode_literals
import examples.basic_usage
import examples.dataset
import examples.variant_ts_difficulties
import examples.variants
def test_dataset(unihan_options):
examples.dataset.run()
def test_variants(unihan_options):
e... | Add stdout tests for basic usage example | Add stdout tests for basic usage example
| Python | mit | cihai/cihai,cihai/cihai-python,cihai/cihai |
a64221bbf3ebc2c1be24c82870f1f233bac10cd4 | app_v2/client.py | app_v2/client.py | #!/usr/bin/env python3
import socket
import atexit
import pygame
from message import Message
PRECISION = 3
host = "localhost"
port = 9999
# create a socket object and connect to specified host/port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
def close_socket():
s.close()
d... | #!/usr/bin/env python3
import socket
import atexit
import pygame
from message import Message
PRECISION = 3
host = "192.168.0.1"
port = 9999
# create a socket object and connect to specified host/port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
def close_socket():
s.close()
... | Update host to use Pi’s static address | Update host to use Pi’s static address
| Python | mit | thelonious/g2x,gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x |
f6313e28bbf00d65d6a4635b5377f9ad06548de6 | appengine_config.py | appengine_config.py | # Copyright 2013 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Configures appstats.
https://developers.google.com/appengine/docs/python/tools/appengineconfig
"""
# Enable appstats and optionally cost calculation... | # Copyright 2013 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Configures appstats.
https://developers.google.com/appengine/docs/python/tools/appengineconfig
"""
# The app engine headers are located locally, so ... | Enable app stats on '-dev' instance. | Enable app stats on '-dev' instance.
This will also enable them on local dev server as well since default app name
in app.yaml is 'isolateserver-dev'.
R=maruel@chromium.org
Review URL: https://codereview.appspot.com/13457054
| Python | apache-2.0 | luci/luci-py,luci/luci-py,madecoste/swarming,luci/luci-py,pombreda/swarming,madecoste/swarming,madecoste/swarming,pombreda/swarming,pombreda/swarming,luci/luci-py,pombreda/swarming,madecoste/swarming |
1316e3ab69fe3e08de6d6f08a04ce0f4bd94dc04 | examples/completion.py | examples/completion.py | import gtk
from kiwi.ui.widgets.entry import Entry
entry = Entry()
entry.set_completion_strings(['apa', 'apapa', 'apbla',
'apppa', 'aaspa'])
win = gtk.Window()
win.connect('delete-event', gtk.main_quit)
win.add(entry)
win.show_all()
gtk.main()
| # encoding: iso-8859-1
import gtk
from kiwi.ui.widgets.entry import Entry
def on_entry_activate(entry):
print 'You selected:', entry.get_text().encode('latin1')
gtk.main_quit()
entry = Entry()
entry.connect('activate', on_entry_activate)
entry.set_completion_strings(['Belo Horizonte',
... | Extend example to include non-ASCII characters | Extend example to include non-ASCII characters | Python | lgpl-2.1 | stoq/kiwi |
5b892de6093de62615e327a805948b76ce806cb4 | protoplot-test/test_options_resolving.py | protoplot-test/test_options_resolving.py | import unittest
from protoplot.engine.item import Item
from protoplot.engine.item_container import ItemContainer
class Series(Item):
pass
Series.options.register("color", True)
Series.options.register("lineWidth", False)
Series.options.register("lineStyle", False)
class TestOptionsResolving(unittest.TestCase):... | import unittest
from protoplot.engine.item import Item
from protoplot.engine.item_container import ItemContainer
# class Series(Item):
# pass
#
# Series.options.register("color", True)
# Series.options.register("lineWidth", False)
# Series.options.register("lineStyle", False)
class TestOptionsResolving(unittes... | Disable code made for old engine model | Disable code made for old engine model
| Python | agpl-3.0 | deffi/protoplot |
5d7a70d2d5e5934d1804d7aac69fd6c79d2ac9a7 | src/waldur_core/logging/migrations/0008_drop_sec_group_rules_pulling_events.py | src/waldur_core/logging/migrations/0008_drop_sec_group_rules_pulling_events.py | from django.db import migrations
def drop_events(apps, schema_editor):
Event = apps.get_model('logging', 'Event')
Event.objects.filter(event_type='openstack_security_group_rule_pulled').delete()
class Migration(migrations.Migration):
dependencies = [
('logging', '0007_drop_alerts'),
]
... | from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('logging', '0007_drop_alerts'),
]
# Run SQL instead of Run Python is used to avoid OOM error
# See also: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.delet... | Fix migration script to avoid OOM error. | Fix migration script to avoid OOM error.
| Python | mit | opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind |
49e89bee4a7c5e241402766072ae60697c136ca6 | guild/__init__.py | guild/__init__.py | import os
import subprocess
__version__ = "0.1.0-1"
def _try_init_git_attrs():
try:
_init_git_commit()
except (OSError, subprocess.CalledProcessError):
pass
else:
try:
_init_git_status()
except (OSError, subprocess.CalledProcessError):
pass
def _ini... | import os
import subprocess
__version__ = "0.1.0-1"
def _try_init_git_attrs():
try:
_init_git_commit()
except (OSError, subprocess.CalledProcessError):
pass
else:
try:
_init_git_status()
except (OSError, subprocess.CalledProcessError):
pass
def _ini... | Fix to git status info | Fix to git status info
| Python | apache-2.0 | guildai/guild,guildai/guild,guildai/guild,guildai/guild |
f90467edaf02ae66cdfd01a34f7e03f20073c12d | tests/__init__.py | tests/__init__.py | # tests.__init__
import os
import os.path
import shutil
import tempfile
import yvs.shared as yvs
from mock import patch
yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs')
yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json')
os.mkdir(yvs.ALFRED_DATA_DIR)
def mock_open(path, mode):
... | # tests.__init__
import os
import os.path
import shutil
import tempfile
import yvs.shared as yvs
from mock import patch
yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs')
yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json')
def mock_open(path, mode):
if path.endswith('preference... | Create Alfred data dir on test setup | Create Alfred data dir on test setup
| Python | mit | caleb531/youversion-suggest,caleb531/youversion-suggest |
587cfa978eb2d2d6708061016836710ca7e3057b | scrapple/utils/exceptions.py | scrapple/utils/exceptions.py | """
scrapple.utils.exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~
Functions related to handling exceptions in the input arguments
"""
import re
class InvalidType(ValueError):
"""Exception class for invalid type in arguments."""
pass
class InvalidSelector(ValueError):
"""Exception class for invalid in arguments."""
pass
... | """
scrapple.utils.exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~
Functions related to handling exceptions in the input arguments
"""
import re
class InvalidType(ValueError):
"""Exception class for invalid type in arguments."""
pass
class InvalidSelector(ValueError):
"""Exception class for invalid in arguments."""
pass
... | Add custom error class 'InvalidOutputType' | Add custom error class 'InvalidOutputType'
| Python | mit | AlexMathew/scrapple,AlexMathew/scrapple,scrappleapp/scrapple,scrappleapp/scrapple,AlexMathew/scrapple |
cefbcda91d6f9d5a0fce97c7b72844f8dcb8d8cf | tests/conftest.py | tests/conftest.py | import pytest
from .fixtures import *
def pytest_addoption(parser):
parser.addoption("--runslow", action="store_true", help="run slow tests")
def pytest_runtest_setup(item):
if "slow" in item.keywords and not item.config.getoption("--runslow"):
pytest.skip("need --runslow option to run")
| import pytest
import os.path
from functools import lru_cache
from django.conf import settings
from .fixtures import *
def pytest_addoption(parser):
parser.addoption("--runslow", action="store_true", help="run slow tests")
def pytest_runtest_setup(item):
if "slow" in item.keywords and not item.config.getop... | Load tags sql on connection is created on tests. | Load tags sql on connection is created on tests.
| Python | agpl-3.0 | seanchen/taiga-back,obimod/taiga-back,frt-arch/taiga-back,CoolCloud/taiga-back,EvgeneOskin/taiga-back,rajiteh/taiga-back,bdang2012/taiga-back-casting,dayatz/taiga-back,astronaut1712/taiga-back,gauravjns/taiga-back,dayatz/taiga-back,forging2012/taiga-back,bdang2012/taiga-back-casting,dycodedev/taiga-back,taigaio/taiga-b... |
5fd879dbd5278d54a6659eb060f959af36556e1e | tests/test_usb.py | tests/test_usb.py | import unittest
from openxc.sources import UsbDataSource, DataSourceError
class UsbDataSourceTests(unittest.TestCase):
def setUp(self):
super(UsbDataSourceTests, self).setUp()
def test_create(self):
def callback(message):
pass
try:
UsbDataSource(callback)
... | import unittest
from openxc.sources import UsbDataSource, DataSourceError
class UsbDataSourceTests(unittest.TestCase):
def setUp(self):
super(UsbDataSourceTests, self).setUp()
def test_create(self):
def callback(message):
pass
| Disable trivial USB test case to get suite running on CI. | Disable trivial USB test case to get suite running on CI.
| Python | bsd-3-clause | openxc/openxc-python,openxc/openxc-python,openxc/openxc-python |
c191101ff26a9931c8aeb92bc6ff68f7a0baf95a | wordbridge/mappings.py | wordbridge/mappings.py | from wordbridge.html import HtmlBuilder
html = HtmlBuilder()
def top_level_element(tag_name):
return TopLevelElement(tag_name)
class TopLevelElement(object):
def __init__(self, tag_name):
self._tag_name = tag_name
def start(self, html_stack):
html_stack.open_element(self._tag_name)
... | from wordbridge.html import HtmlBuilder
html = HtmlBuilder()
def top_level_element(tag_name):
return Style(
on_start=_sequence(_clear_stack, _open_element(tag_name)),
on_end=_clear_stack
)
def _clear_stack(html_stack):
while html_stack.current_element() is not None:
html_stack.clo... | Build up style from composable functions | Build up style from composable functions
| Python | bsd-2-clause | mwilliamson/wordbridge |
6c9fa6a8d82a57b51e963c453fece5f445b3a3ba | spicedham/split_tokenizer.py | spicedham/split_tokenizer.py | from re import split
from spicedham.tokenizer import BaseTokenizer
class SplitTokenizer(BaseTokenizer):
"""
Split the text on punctuation and newlines, lowercase everything, and
filter the empty strings
"""
def tokenize(self, text):
text = split('[ ,.?!\n\r]', text)
is_not_blan... | from re import split
from spicedham.tokenizer import BaseTokenizer
class SplitTokenizer(BaseTokenizer):
"""
Split the text on punctuation and newlines, lowercase everything, and
filter the empty strings
"""
def tokenize(self, text):
text = split('[ ,.?!\n\r]', text)
text = [tok... | Make mapping & filtering into a list comprehension | Make mapping & filtering into a list comprehension
| Python | mpl-2.0 | mozilla/spicedham,mozilla/spicedham |
66f467c64a0dbfcbb81d9edc74e506c076aac439 | onadata/apps/logger/migrations/0006_add-index-to-instance-uuid_and_xform_uuid.py | onadata/apps/logger/migrations/0006_add-index-to-instance-uuid_and_xform_uuid.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('logger', '0005_instance_xml_hash'),
]
# This custom migration must be run on Postgres 9.5+.
# Because some servers already have ... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('logger', '0005_instance_xml_hash'),
]
# Because some servers already have these modifications applied by Django South migration,
... | Remove incorrect remark about Postgres 9.5 | Remove incorrect remark about Postgres 9.5
| Python | bsd-2-clause | kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat |
ee3b11a7a15535ffe52a6bdd493819fbd76b2300 | vroom/graphics.py | vroom/graphics.py | import pygame
class Graphic:
car_color = (255, 50, 50)
car_width = 3
road_color = (255, 255, 255)
road_width = 6
draw_methods = {
'Car': 'draw_car',
'Road': 'draw_road',
}
def __init__(self, surface):
self.surface = surface
def draw(self, obj):
object_... | import pygame
class Graphic:
car_color = (255, 50, 50)
car_width = 3
road_color = (255, 255, 255)
road_width = 6
draw_methods = {
'Car': 'draw_car',
'Road': 'draw_road',
}
def __init__(self, surface):
self.surface = surface
def draw(self, obj):
object_... | Make color easier to read | Make color easier to read
| Python | mit | thibault/vroom |
27e14d057aad81f4686ed3def25cfffc8156fd4c | scp-slots.py | scp-slots.py | #!/usr/bin/python
import re
import sys
from bs4 import BeautifulSoup
from urllib.request import urlopen
SCP_SERIES_REGEX = re.compile(r'/scp-[0-9]{3,4}')
def count_slots(url):
with urlopen(url) as response:
data = response.read()
empty_slots = 0
total_slots = 0
scps = set()
soup = Beau... | #!/usr/bin/python
import re
import sys
from bs4 import BeautifulSoup
from urllib.request import urlopen
SCP_SERIES_REGEX = re.compile(r'/scp-[0-9]{3,4}')
def count_slots(url):
with urlopen(url) as response:
data = response.read()
empty_slots = 0
total_slots = 0
scps = set()
soup = Beau... | Add support for Series I. | Add support for Series I.
| Python | mit | ammongit/scripts,ammongit/scripts,ammongit/scripts,ammongit/scripts |
76784dc06bc1d7fedb7e2e85f87fc4a2c2a489fc | chainer/functions/reshape.py | chainer/functions/reshape.py | from chainer import function
class Reshape(function.Function):
"""Reshapes an input array without copy."""
def __init__(self, shape):
self.shape = shape
def forward(self, x):
return x[0].reshape(self.shape),
def backward(self, x, gy):
return gy[0].reshape(x[0].shape),
def... | import numpy
from chainer import function
from chainer.utils import type_check
class Reshape(function.Function):
"""Reshapes an input array without copy."""
def __init__(self, shape):
self.shape = shape
def check_type_forward(self, in_type):
type_check.expect(in_type.size() == 1)
... | Add typecheck for Reshape function | Add typecheck for Reshape function
| Python | mit | muupan/chainer,niboshi/chainer,AlpacaDB/chainer,ktnyt/chainer,keisuke-umezawa/chainer,ytoyama/yans_chainer_hackathon,elviswf/chainer,wkentaro/chainer,jfsantos/chainer,chainer/chainer,ikasumi/chainer,hvy/chainer,okuta/chainer,bayerj/chainer,tigerneil/chainer,okuta/chainer,cupy/cupy,muupan/chainer,sinhrks/chainer,anaruse... |
df8c19fe4679aa0d4fff90a15efcf4183a8ec8c1 | api/v2/serializers/details/image_version.py | api/v2/serializers/details/image_version.py | from core.models import ApplicationVersion as ImageVersion
from rest_framework import serializers
from api.v2.serializers.summaries import LicenseSerializer
from api.v2.serializers.summaries import ImageVersionSummarySerializer
from api.v2.serializers.fields import ProviderMachineRelatedField
class ImageVersionSerial... | from core.models import ApplicationVersion as ImageVersion
from rest_framework import serializers
from api.v2.serializers.summaries import (
LicenseSerializer,
UserSummarySerializer,
IdentitySummarySerializer,
ImageVersionSummarySerializer)
from api.v2.serializers.fields import ProviderM... | Add 'user' and 'identity' attributes to the ImageVersion Details Serializer | Add 'user' and 'identity' attributes to the ImageVersion Details Serializer
| Python | apache-2.0 | CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend |
06dd856ce57193f34395f8ee6e7c7d3030356609 | tests/test_single.py | tests/test_single.py | import json
from fixtures import PostSerializer
def test_single(post):
data = PostSerializer().to_json(post)
assert json.loads(data) == {'posts': [{'id': 1, 'title': 'My title'}]}
def test_meta(post):
data = PostSerializer().to_json(post, meta={'key': 'value'})
assert json.loads(data)['meta']['ke... | import json
from fixtures import PostSerializer
def test_single(post):
data = PostSerializer().to_json(post)
assert json.loads(data) == {'posts': [{'id': 1, 'title': 'My title'}]}
def test_multiple(post_factory):
post = post_factory(id=1, title='A title')
another_post = post_factory(id=2, title='A... | Add test for multiple resources | Add test for multiple resources
| Python | mit | kalasjocke/hyp |
0a628ed81ca11fc4175b480aad9a136b8a4fe1c2 | constantsgen/pythonwriter.py | constantsgen/pythonwriter.py | class PythonWriter:
def __init__(self, constants):
self.constants = constants
def write(self, out):
out.write("# This file was generated by generate_constants.\n\n")
out.write("from enum import Enum, unique\n\n")
for name, enum in self.constants.enum_values.items():
... | class PythonWriter:
def __init__(self, constants):
self.constants = constants
def write(self, out):
out.write("# This file was generated by generate_constants.\n\n")
out.write("from enum import Enum, unique\n\n")
for name, enum in self.constants.enum_values.items():
... | Add PEP8 whitespace around Enums | Add PEP8 whitespace around Enums
| Python | bsd-3-clause | barracudanetworks/constantsgen,barracudanetworks/constantsgen,barracudanetworks/constantsgen |
640e0d0c9ec58c534f4d08962dd558e87401abb2 | problem_4/solution.py | problem_4/solution.py | def is_palindrome_number(n): return n == n[::-1]
largest_number = 0
for x in xrange(100, 999):
for y in xrange(100, 999):
v = x * y
if v > largest_number:
if is_palindrome_number(str(v)):
largest_number = v
print largest_number
| import time
def is_palindrome_number(n): return n == n[::-1]
def largest_palindrome_from_the_product_of_three_digit_numbers():
largest_number = 0
for x in xrange(100, 999):
for y in xrange(100, 999):
v = x * y
if v > largest_number:
if is_palindrome_number(str(v)... | Add timing for python implementation of problem 4 | Add timing for python implementation of problem 4
| Python | mit | mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler |
619033bc8daf3b8f5faafa95b04c06d98c39969f | stack/vpc.py | stack/vpc.py | from troposphere import (
Ref,
)
from troposphere.ec2 import (
InternetGateway,
Route,
RouteTable,
VPC,
VPCGatewayAttachment,
)
from .template import template
vpc = VPC(
"Vpc",
template=template,
CidrBlock="10.0.0.0/16",
)
# Allow outgoing to outside VPC
internet_gateway = Inte... | from troposphere import (
GetAtt,
Ref,
)
from troposphere.ec2 import (
EIP,
InternetGateway,
NatGateway,
Route,
RouteTable,
Subnet,
SubnetRouteTableAssociation,
VPC,
VPCGatewayAttachment,
)
from .template import template
vpc = VPC(
"Vpc",
template=template,
Ci... | Add a public subnet that holds a `NAT` gateway | Add a public subnet that holds a `NAT` gateway
| Python | mit | caktus/aws-web-stacks,tobiasmcnulty/aws-container-basics |
26e16c6229f12ca75c4bbf224eb9d1cf3b250b9c | rock/utils.py | rock/utils.py | import StringIO
import os
from rock.exceptions import ConfigError
ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split()
class Shell(object):
def __init__(self):
self.stdin = StringIO.StringIO()
def __enter__(self):
return self
def __exit__(self, type, value, traceback):... | import StringIO
import os
from rock.exceptions import ConfigError
ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split()
def isexecutable(path):
return os.path.isfile(path) and os.access(path, os.X_OK)
class Shell(object):
def __init__(self):
self.stdin = StringIO.StringIO()
de... | Split isexecutable into its own function | Split isexecutable into its own function
| Python | mit | silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock |
6c564ebe538d2723cc5f9397e09e5945796a257e | pyelevator/message.py | pyelevator/message.py | import msgpack
import logging
from .constants import FAILURE_STATUS
class MessageFormatError(Exception):
pass
class Request(object):
"""Handler objects for frontend->backend objects messages"""
def __new__(cls, *args, **kwargs):
content = {
'DB_UID': kwargs.pop('db_uid'),
... | import msgpack
import logging
from .constants import FAILURE_STATUS
class MessageFormatError(Exception):
pass
class Request(object):
"""Handler objects for frontend->backend objects messages"""
def __new__(cls, *args, **kwargs):
content = {
'DB_UID': kwargs.pop('db_uid'),
... | Fix : Range of len(1) have to be a tuple of tuples | Fix : Range of len(1) have to be a tuple of tuples
| Python | mit | oleiade/py-elevator |
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 |
1599bc03b0a1cd202836479fba2406457a17f118 | user_map/tests/urls.py | user_map/tests/urls.py | from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^user-map/', include('user_map.urls', namespace='user_map'))
)
| from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^user-map/', include('user_map.urls', namespace='user_map')),
url(r'^login/$',
'django.contrib.auth.views.login',
{'template_name': 'admin/login.html'},
name='my_login',
),
)
| Add login url for testing. | Add login url for testing.
| Python | lgpl-2.1 | akbargumbira/django-user-map,akbargumbira/django-user-map,akbargumbira/django-user-map,akbargumbira/django-user-map |
2a9c213c02abbabeddbf2a699fd6caf5e18bf6dd | utils/word_checking.py | utils/word_checking.py | from __future__ import unicode_literals
import re
from collections import Counter
def check_for_flag_words(message, words_array):
cnt = Counter()
delims = '!"#$%&()*+,./:;<=>?@[\\]^_`{|}~\t\n\x0b\x0c\r '
pattern = r"[{}]".format(delims)
message_array = re.split(pattern, message.lower())
for word... | from __future__ import unicode_literals
import re
from collections import Counter
def check_for_flag_words(message, words_array):
cnt = Counter()
delims = '!"#$%&()*+,./:;<=>?@[\\]^_`{|}~\t\n\x0b\x0c\r '
pattern = r"[{}]".format(delims)
message_array = re.split(pattern, message.lower())
for word... | Remove numbers from the word to check for. | Remove numbers from the word to check for.
| Python | apache-2.0 | jkvoorhis/cheeseburger_backpack_bot |
186cd6148bba29baebad0dfcdbe57cd393bf1777 | report/report_util.py | report/report_util.py | def compare_ledger_types(account, data, orm):
# TODO alternate_ledger
return True
account_ledgers = [ledger.id for ledger in account.ledger_types]
selected_ledger = int(data['form']['ledger_type'])
# Store in data to avoid recomputing.
if 'ledger_type_all' not in data:
data['ledger_typ... | def compare_ledger_types(account, data, orm):
account_ledgers = [ledger.id for ledger in account.ledger_types]
selected_ledgers = data['form']['ledger_types']
# Store in data to avoid recomputing.
if 'ledger_type_all' not in data:
ledger_A = orm.pool.get('alternate_ledger.ledger_type').search(
... | Make the ledger type selector work | Make the ledger type selector work
| Python | agpl-3.0 | xcgd/account_report_webkit,xcgd/account_report_webkit,lithint/account_report_webkit,lithint/account_report_webkit |
a7b1bc006c23f534820fe06dea2da3b6553b64df | shcol/config.py | shcol/config.py | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke
# Released under the Simplified BSD license
# (see LICENSE file for details).
"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read durin... | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke
# Released under the Simplified BSD license
# (see LICENSE file for details).
"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read durin... | Use environment variable to detect Windows systems. | Use environment variable to detect Windows systems.
| Python | bsd-2-clause | seblin/shcol |
19c46fd57e04a026c6e52e1be9ba265a82d651f1 | walletname/__init__.py | walletname/__init__.py | __author__ = 'mdavid'
import json
import re
import requests
from blockexplorer.settings import WNS_URL_BASE
WALLET_NAME_RE = re.compile('^([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$')
TIMEOUT_IN_SECONDS = 20
def is_valid_wallet_name(string):
return WALLET_NAME_RE.match(string)
def lookup_wallet_name(wallet_name, curre... | __author__ = 'mdavid'
import json
import re
import requests
from blockexplorer.settings import WNS_URL_BASE
WALLET_NAME_RE = re.compile('^([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$')
TIMEOUT_IN_SECONDS = 20
def is_valid_wallet_name(string):
return WALLET_NAME_RE.match(string)
def lookup_wallet_name(wallet_name, curre... | Add try/except block around lookup in lookup_wallet_name function | Add try/except block around lookup in lookup_wallet_name function
| Python | apache-2.0 | ychaim/explorer,blockcypher/explorer,blockcypher/explorer,ychaim/explorer,ychaim/explorer,blockcypher/explorer |
74faea73440c4ff8b94493d5864e23e3fae7a53f | core/observables/file.py | core/observables/file.py | from __future__ import unicode_literals
from mongoengine import *
from core.observables import Observable
from core.observables import Hash
class File(Observable):
value = StringField(verbose_name="SHA256 hash")
mime_type = StringField(verbose_name="MIME type")
hashes = DictField(verbose_name="Hashes"... | from __future__ import unicode_literals
from flask import url_for
from flask_mongoengine.wtf import model_form
from mongoengine import *
from core.observables import Observable
from core.database import StringListField
class File(Observable):
value = StringField(verbose_name="Value")
mime_type = StringFie... | Clean up File edit view | Clean up File edit view
| Python | apache-2.0 | yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti |
724d7235e546fb79009800700fd74328f8171b8c | src/etc/tidy.py | src/etc/tidy.py | #!/usr/bin/python
import sys, fileinput, subprocess
err=0
cols=78
try:
result=subprocess.check_output([ "git", "config", "core.autocrlf" ])
autocrlf=result.strip() == b"true"
except CalledProcessError:
autocrlf=False
def report_err(s):
global err
print("%s:%d: %s" % (fileinput.filename(), filein... | #!/usr/bin/python
import sys, fileinput
err=0
cols=78
def report_err(s):
global err
print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s))
err=1
for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")):
if line.find('\t') != -1 and fileinput.filename().find("Makefile") =... | Revert "Don't complain about \r when core.autocrlf is on in Git" | Revert "Don't complain about \r when core.autocrlf is on in Git"
This reverts commit 828afaa2fa4cc9e3e53bda0ae3073abfcfa151ca.
| Python | apache-2.0 | SiegeLord/rust,gifnksm/rust,kwantam/rust,defuz/rust,aidancully/rust,avdi/rust,sae-bom/rust,erickt/rust,pelmers/rust,avdi/rust,pythonesque/rust,Ryman/rust,carols10cents/rust,robertg/rust,aepsil0n/rust,kwantam/rust,jbclements/rust,aepsil0n/rust,kmcallister/rust,mihneadb/rust,andars/rust,pczarn/rust,pczarn/rust,krzysz00/r... |
2805eb26865d7a12cbc0e6f7a71dbd99ba49224e | gem/templatetags/gem_tags.py | gem/templatetags/gem_tags.py | from django.template import Library
from django.conf import settings
register = Library()
@register.simple_tag()
def get_site_static_prefix():
return settings.SITE_STATIC_PREFIX
@register.filter('fieldtype')
def fieldtype(field):
return field.field.widget.__class__.__name__
@register.filter(name='smarttr... | from django.template import Library
from django.conf import settings
from gem.models import GemSettings
register = Library()
@register.simple_tag()
def get_site_static_prefix():
return settings.SITE_STATIC_PREFIX
@register.filter()
def get_bbm_app_id(request):
return GemSettings.for_site(request.site).bbm... | Create GEM filter to get BBM App ID | Create GEM filter to get BBM App ID
| Python | bsd-2-clause | praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem |
062a2e41e6e605dad4d8a8dc23abaa50f8348595 | start_server.py | start_server.py | #!/usr/bin/env python3
# tsuserver3, an Attorney Online server
#
# Copyright (C) 2016 argoneus <argoneuscze@gmail.com>
#
# This program 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 ... | #!/usr/bin/env python3
# tsuserver3, an Attorney Online server
#
# Copyright (C) 2016 argoneus <argoneuscze@gmail.com>
#
# This program 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 ... | Use ModuleNotFoundError instead of ImportError | Use ModuleNotFoundError instead of ImportError
| Python | agpl-3.0 | Attorney-Online-Engineering-Task-Force/tsuserver3,Mariomagistr/tsuserver3 |
5cf839df99a03299215db7c2f6d9a78ac724c155 | src/rinoh/language/__init__.py | src/rinoh/language/__init__.py | # This file is part of rinohtype, the Python document preparation system.
#
# Copyright (c) Brecht Machiels.
#
# Use of this source code is subject to the terms of the GNU Affero General
# Public License v3. See the LICENSE file or http://www.gnu.org/licenses/.
from .cls import Language
from .en import EN
from .fr i... | # This file is part of rinohtype, the Python document preparation system.
#
# Copyright (c) Brecht Machiels.
#
# Use of this source code is subject to the terms of the GNU Affero General
# Public License v3. See the LICENSE file or http://www.gnu.org/licenses/.
from .cls import Language
from .en import EN
from .fr i... | Fix the rendering of language instance docstrings | Fix the rendering of language instance docstrings
| Python | agpl-3.0 | brechtm/rinohtype,brechtm/rinohtype,brechtm/rinohtype |
502ef2c155aeaed7a2b9a2e4ad0471f34ef3790f | app/utils/utilities.py | app/utils/utilities.py | from re import search
from flask import g
from flask_restplus import abort
from flask_httpauth import HTTPBasicAuth
from app.models.user import User
from instance.config import Config
auth = HTTPBasicAuth() | from re import search
from flask import g
from flask_restplus import abort
from flask_httpauth import HTTPBasicAuth
from app.models.user import User
from instance.config import Config
auth = HTTPBasicAuth()
def validate_email(email):
''' Method to check that a valid email is provided '''
email_re = r"(^[a-zA-Z0... | Add validate_email and verify_token methods Methods to be used to: - check that a valid email is provided - check the token authenticity | Add validate_email and verify_token methods
Methods to be used to:
- check that a valid email is provided
- check the token authenticity
| Python | mit | Elbertbiggs360/buckelist-api |
099545e7a68ef82af8e8db15dc21746553143310 | statictemplate/management/commands/statictemplate.py | statictemplate/management/commands/statictemplate.py | # -*- coding: utf-8 -*-
from contextlib import contextmanager
from django.conf import settings
try:
from django.conf.urls.defaults import patterns, url, include
except ImportError:
from django.conf.urls import patterns, url, include # pragma: no cover
from django.core.management.base import BaseCommand
from dj... | # -*- coding: utf-8 -*-
from contextlib import contextmanager
from django.conf import settings
try:
from django.conf.urls.defaults import patterns, url, include
except ImportError:
from django.conf.urls import patterns, url, include # pragma: no cover
from django.core.management.base import BaseCommand
from dj... | Add verbose error for a meddling middleware | Add verbose error for a meddling middleware
| Python | bsd-3-clause | ojii/django-statictemplate,bdon/django-statictemplate,yakky/django-statictemplate |
b528b2cf4379369da8277a0a1c904267b5c7cf6f | Lib/test/test_atexit.py | Lib/test/test_atexit.py | # Test the atexit module.
from test_support import TESTFN, vereq
import atexit
import os
input = """\
import atexit
def handler1():
print "handler1"
def handler2(*args, **kargs):
print "handler2", args, kargs
atexit.register(handler1)
atexit.register(handler2)
atexit.register(handler2, 7, kw="abc")
"""
fna... | # Test the atexit module.
from test_support import TESTFN, vereq
import atexit
import os
import sys
input = """\
import atexit
def handler1():
print "handler1"
def handler2(*args, **kargs):
print "handler2", args, kargs
atexit.register(handler1)
atexit.register(handler2)
atexit.register(handler2, 7, kw="abc... | Use sys.executable to run Python, as suggested by Neal Norwitz. | Use sys.executable to run Python, as suggested by Neal Norwitz.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
4409823a5611d0f426ca09541d7e9dc982bc8c9f | asyncqlio/utils.py | asyncqlio/utils.py | """
Miscellaneous utilities used throughout the library.
"""
import collections.abc
class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator):
"""
Transforms an `__iter__` method into an `__aiter__` method.
"""
def __init__(self, iterator: collections.abc.Iterator):
self._it ... | """
Miscellaneous utilities used throughout the library.
"""
import collections.abc
class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator):
"""
Transforms an `__iter__` method into an `__aiter__` method.
"""
def __init__(self, iterator: collections.abc.Iterator):
self._it ... | Raise StopAsyncIteration instead of StopAsyncIteration in aiter wrapper. | Raise StopAsyncIteration instead of StopAsyncIteration in aiter wrapper.
| Python | mit | SunDwarf/asyncqlio |
f1cf2d2e9cbdd4182a5a755b5958e499fc9d9585 | gcloud_expenses/views.py | gcloud_expenses/views.py | from pyramid.renderers import get_renderer
from pyramid.view import view_config
from . import get_report_info
from . import list_employees
from . import list_reports
def get_main_template(request):
main_template = get_renderer('templates/main.pt')
return main_template.implementation()
@view_config(route_nam... | from pyramid.renderers import get_renderer
from pyramid.view import view_config
from . import get_report_info
from . import list_employees
from . import list_reports
def get_main_template(request):
main_template = get_renderer('templates/main.pt')
return main_template.implementation()
@view_config(route_nam... | Improve status display for reports. | Improve status display for reports.
| Python | apache-2.0 | GoogleCloudPlatform/google-cloud-python-expenses-demo,GoogleCloudPlatform/google-cloud-python-expenses-demo |
737e2877cfad9ea801641b72094633a7c0178a44 | UM/Settings/__init__.py | UM/Settings/__init__.py | # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from .SettingDefinition import SettingDefinition
from .SettingInstance import SettingInstance
from .DefinitionContainer import DefinitionContainer
from .InstanceContainer import InstanceContainer
from .ContainerStack i... | # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from .ContainerRegistry import ContainerRegistry
from .SettingDefinition import SettingDefinition
from .SettingInstance import SettingInstance
from .DefinitionContainer import DefinitionContainer
from .InstanceContaine... | Add ContainerRegistry to the exposed classes of UM.Settings | Add ContainerRegistry to the exposed classes of UM.Settings
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium |
243bb615c579c0598a2f2be5791d3d5092dcd556 | invoice/tasks.py | invoice/tasks.py | # -*- encoding: utf-8 -*-
import logging
from celery import shared_task
from django.utils import timezone
from invoice.models import InvoiceUser
from mail.service import queue_mail_message
from mail.tasks import process_mail
from .report import time_summary
logger = logging.getLogger(__name__)
@shared_task
def ma... | # -*- encoding: utf-8 -*-
import logging
from celery import shared_task
from django.utils import timezone
from invoice.models import InvoiceUser
from mail.service import queue_mail_message
from mail.tasks import process_mail
from .report import time_summary
logger = logging.getLogger(__name__)
@shared_task
def ma... | Remove HTML table (our mail cannot send HTML) | Remove HTML table (our mail cannot send HTML)
| Python | apache-2.0 | pkimber/invoice,pkimber/invoice,pkimber/invoice |
5e5f5c8bfb5b61bd87ff4e55004e80c0e7edf408 | ikea-ota-download.py | ikea-ota-download.py | #!/usr/bin/env python
"""
Snipped to download current IKEA ZLL OTA files into ~/otau
compatible with python 3.
"""
import os
import json
try:
from urllib.request import urlopen, urlretrieve
except ImportError:
from urllib2 import urlopen
from urllib import urlretrieve
f = urlopen("http://fw.ota.homesmart.ikea.net... | #!/usr/bin/env python
"""
Snipped to download current IKEA ZLL OTA files into ~/otau
compatible with python 3.
"""
import os
import json
try:
from urllib.request import urlopen, urlretrieve
except ImportError:
from urllib2 import urlopen
from urllib import urlretrieve
f = urlopen("http://fw.ota.homesmart.ikea.net... | Update json.loads line for python 3.5 | Update json.loads line for python 3.5
Running the script inside a docker container with python 3.5 throws an "TypeError: the JSON object must be str, not 'bytes'".
Fixed it by decoding downloaded json to utf-8 | Python | bsd-3-clause | dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin |
208081800ab7e6217ec0f88e76c2dffd32187db1 | whyp/shell.py | whyp/shell.py | import os
from pysyte.types.paths import path
def value(key):
"""A value from the shell environment, defaults to empty string
>>> value('SHELL') is not None
True
"""
try:
return os.environ[key]
except KeyError:
return ''
def paths(name=None):
"""A list of paths in the ... | import os
from pysyte.types.paths import path
def value(key):
"""A value from the shell environment, defaults to empty string
>>> value('SHELL') is not None
True
"""
try:
return os.environ[key]
except KeyError:
return ''
def paths(name=None):
"""A list of paths in the ... | Allow for missing directories in $PATH | Allow for missing directories in $PATH
| Python | mit | jalanb/what,jalanb/what |
c727f8382237c177d508d5113a7e3b8ca8ea7066 | fasta/graphs.py | fasta/graphs.py | # Internal modules #
from plumbing.graphs import Graph
from plumbing.autopaths import FilePath
# Third party modules #
from matplotlib import pyplot
# Constants #
__all__ = ['LengthDist']
################################################################################
class LengthDist(Graph):
"""The length distr... | # Internal modules #
from plumbing.graphs import Graph
from plumbing.autopaths import FilePath
# Third party modules #
from matplotlib import pyplot
# Constants #
__all__ = ['LengthDist']
################################################################################
class LengthDist(Graph):
"""The length distr... | Return graph object after ploting | Return graph object after ploting
| Python | mit | xapple/fasta |
1851190543d24d6f4c26a5d7a3a04f56aeba511d | sheldon/exceptions.py | sheldon/exceptions.py | # -*- coding: utf-8 -*-
"""
@author: Lises team
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
""" | # -*- coding: utf-8 -*-
"""
@author: Lises team
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.utils import logger
def catch_plugin_errors(plugin_call_function):
"""
Catch all plugin exceptions and log it
:param plugin_call_function: function with calling... | Create decorator for catching plugin errors | Create decorator for catching plugin errors
| Python | mit | lises/sheldon |
301fd00ea31346126d78696c50ac9daf1b76a428 | classifier.py | classifier.py | import training_data
import re
import math
class Classifier:
def classify(self,text,prior=0.5,c=10e-6):
""" Remove a pontuacao do texto """
words = re.findall(r"[\w']+",text)
"""words = text.split()"""
data = training_data.TrainingData()
spamLikehood = math.log(1)
hamLikehood = math.log(1)
for word in ... | import re
import math
class Classifier:
def classify(self,text,trainingData,prior=0.5,c=10e-6):
""" Remove a pontuacao do texto """
words = re.findall(r"[\w']+",text)
"""words = text.split()"""
likehood = math.log(1)
for word in words:
""" Calculo do likehood """
if word in trainingData:
likehood... | Change so that we can use with any data | Change so that we can use with any data
| Python | mit | anishihara/SpamFilter |
bc083087cd7aadbf11fba9a8d1312bde3b7a2a27 | osgtest/library/mysql.py | osgtest/library/mysql.py | import os
from osgtest.library import core
from osgtest.library import service
def name():
if core.el_release() < 7:
return 'mysql'
else:
return 'mariadb'
def daemon_name():
if core.el_release() < 7:
return 'mysqld'
else:
return 'mariadb'
def init_script():
return... | import os
import re
from osgtest.library import core
from osgtest.library import service
def name():
if core.el_release() < 7:
return 'mysql'
else:
return 'mariadb'
def daemon_name():
if core.el_release() < 7:
return 'mysqld'
else:
return 'mariadb'
def init_script():
... | Add several useful MySQL functions | Add several useful MySQL functions
Functions useful for examining and manipulating MySQL databases:
- execute() -- execute one or more MySQL statements (as a single string),
optionally on a specific database. Returns the same thing as core.system()
- check_execute() -- same as execute(), but checks return code and
... | Python | apache-2.0 | efajardo/osg-test,efajardo/osg-test |
4cd0d2a947bbfa9ba830c4dc543b1688ecf2e54f | produceEports.py | produceEports.py | #!/usr/bin/env python
from app.views.export import write_all_measurements_csv
import tempfile
import os
f = open("app/static/exports/AllMeasurements_inprogress.csv", "w")
try:
write_all_measurements_csv(f)
finally:
f.close
os.rename("app/static/exports/AllMeasurements_inprogress.csv", "app/static/exports/Al... | #!/usr/bin/env python
from app.views.export import write_all_measurements_csv
import tempfile
import os
f = open("{}/app/static/exports/AllMeasurements_inprogress.csv".format(os.path.dirname(os.path.realpath(__file__))), "w")
try:
write_all_measurements_csv(f)
finally:
f.close
os.rename("app/static/exports/... | Add application directory to export directory | Add application directory to export directory
| Python | mit | rabramley/telomere,rabramley/telomere,rabramley/telomere |
4072f8ec6e1908d6e84859c8a0bd6c96562ea5cc | parts/plugins/x-shell.py | parts/plugins/x-shell.py | import snapcraft
class ShellPlugin(snapcraft.BasePlugin):
@classmethod
def schema(cls):
schema = super().schema()
schema['required'] = []
schema['properties']['shell'] = {
'type': 'string',
'default': '/bin/sh',
}
schema['required'].append('shell')
schema['properties']['shell-flags'] = {
'typ... | import snapcraft
class ShellPlugin(snapcraft.BasePlugin):
@classmethod
def schema(cls):
schema = super().schema()
schema['required'] = []
schema['properties']['shell'] = {
'type': 'string',
'default': '/bin/sh',
}
schema['required'].append('shell')
schema['properties']['shell-flags'] = {
'typ... | Add "SNAPDIR" and simple vim modeline | Add "SNAPDIR" and simple vim modeline
| Python | mit | infosiftr/snap-docker,docker-snap/docker,docker-snap/docker |
338672c4f79fe01b4801346594bcd0d95a925e75 | python-prefix.py | python-prefix.py | #!/usr/bin/env python
import sys
import os.path
import site
def main():
'''\
Check if the given prefix is included in sys.path for the given
python version; if not find an alternate valid prefix. Print the
result to standard out.
'''
if len(sys.argv) != 3:
msg = 'usage: %s <prefix> <p... | #!/usr/bin/env python
import sys
import os.path
import site
def main():
'''\
Check if the given prefix is included in sys.path for the given
python version; if not find an alternate valid prefix. Print the
result to standard out.
'''
if len(sys.argv) != 3:
msg = 'usage: %s <prefix> <p... | Fix typo in previous commit. | Fix typo in previous commit. | Python | bsd-2-clause | D3f0/coreemu,abn/coreemu,cudadog/coreemu,cudadog/coreemu,abn/coreemu,D3f0/coreemu,abn/coreemu,D3f0/coreemu,eiginn/coreemu,eiginn/coreemu,cudadog/coreemu,eiginn/coreemu |
f035ca424504a37e350fd009e973b89ba7e00670 | desertbot/datastore.py | desertbot/datastore.py | import json
import os
class DataStore(object):
def __init__(self, storagePath="desertbot_data.json"):
self.storagePath = storagePath
self.data = {}
self.load()
def load(self):
if not os.path.exists(self.storagePath):
with open(os.path.join("desertbot", "datastore_d... | import json
import os
class DataStore(object):
def __init__(self, storagePath="desertbot_data.json"):
self.storagePath = storagePath
self.data = {}
self.load()
def load(self):
if not os.path.exists(self.storagePath):
with open(os.path.join("desertbot", "datastore_d... | Load data from defaults if defaults has keys that data doesn't. | Load data from defaults if defaults has keys that data doesn't.
| Python | mit | DesertBot/DesertBot |
bbb12dd60222ae617e5ed70d37c0ea3d350b9f3a | satsound/views.py | satsound/views.py | from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .forms import *
from .models import *
@login_required
def index(request):
return render(request, 'satsound/index.html')
@login_required... | from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .forms import *
from .models import *
@login_required
def index(request):
return render(request, 'satsound/index.html')
@login_required... | Create new satellite from spacetrack if satellite audio upload is for a nonexistent satellite | Create new satellite from spacetrack if satellite audio upload is for a nonexistent satellite
| Python | mit | saanobhaai/apman,saanobhaai/apman |
a967b62c5f11b35ac3b31d64975ea62471be8295 | script_helpers.py | script_helpers.py | """A set of functions to standardize some options for python scripts."""
def setup_parser_help(parser, additional_docs=None):
"""
Set formatting for parser to raw and add docstring to help output
Parameters
----------
parser : `ArgumentParser`
The parser to be modified.
additional_d... | """A set of functions to standardize some options for python scripts."""
def setup_parser_help(parser, additional_docs=None):
"""
Set formatting for parser to raw and add docstring to help output
Parameters
----------
parser : `ArgumentParser`
The parser to be modified.
additional_d... | Add destination directory to default arguments for scripts | Add destination directory to default arguments for scripts
| Python | bsd-3-clause | mwcraig/msumastro |
1d828dfdb77cf69ce88386c3bb98036d851a891a | data_structures/linked_list.py | data_structures/linked_list.py | class Node(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
def __repr__(self):
return '{val}'.format(val=self.val)
class LinkedList(object):
def __init__(self, iterable=()):
self._current = None
self.head = None
self.length = 0
... | class Node(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
def __repr__(self):
return '{val}'.format(val=self.val)
class LinkedList(object):
def __init__(self, iterable=()):
self._current = None
self.head = None
self.length = 0
... | Add methods to linked list. | Add methods to linked list.
| Python | mit | sjschmidt44/python_data_structures |
46ab82bf387b6f7d13abc94bacb16b76bc292080 | util/cron/verify_config_names.py | util/cron/verify_config_names.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Ensure filenames for test-*.bash scripts match the config name registered
inside them.
"""
from __future__ import print_function
import sys
for line in sys.stdin.readlines():
filename, content = line.split(':', 1)
config_name = content.split('"')[1]
expe... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Ensure filenames for test-*.bash scripts match the config name registered
inside them.
"""
from __future__ import print_function
import os.path
import re
import sys
for line in sys.stdin.readlines():
filename, content = line.split(':', 1)
filename_parts = os... | Update config name verify script to work with the .bat files. | Update config name verify script to work with the .bat files.
| Python | apache-2.0 | chizarlicious/chapel,CoryMcCartan/chapel,chizarlicious/chapel,CoryMcCartan/chapel,hildeth/chapel,CoryMcCartan/chapel,chizarlicious/chapel,CoryMcCartan/chapel,hildeth/chapel,hildeth/chapel,chizarlicious/chapel,hildeth/chapel,CoryMcCartan/chapel,hildeth/chapel,CoryMcCartan/chapel,chizarlicious/chapel,chizarlicious/chapel... |
637953efa1f71b123bb28c8404b79219a6bd6b3e | fablab-businessplan.py | fablab-businessplan.py | # -*- encoding: utf-8 -*-
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: MIT
#
import xlsxwriter
# Create the file
workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx')
# Create the worksheets
expenses = workbook.add_worksheet('Expenses')
activities = workbook.add_worksheet... | # -*- encoding: utf-8 -*-
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: MIT
#
import xlsxwriter
# Create document -------------------------------------------------------------
# Create the file
workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx')
# Create the worksheets
... | Add structure and first styles | Add structure and first styles
| Python | mit | openp2pdesign/FabLab-BusinessPlan |
54691f9be052e5564ca0e5c6a503e641ea3142e1 | keras/layers/normalization.py | keras/layers/normalization.py | from ..layers.core import Layer
from ..utils.theano_utils import shared_zeros
from .. import initializations
class BatchNormalization(Layer):
'''
Reference:
Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift
http://arxiv.org/pdf/1502.03... | from ..layers.core import Layer
from ..utils.theano_utils import shared_zeros
from .. import initializations
import theano.tensor as T
class BatchNormalization(Layer):
'''
Reference:
Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift
h... | Add modes to BatchNormalization, fix BN issues | Add modes to BatchNormalization, fix BN issues | Python | mit | yingzha/keras,imcomking/Convolutional-GRU-keras-extension-,jayhetee/keras,why11002526/keras,marchick209/keras,relh/keras,mikekestemont/keras,florentchandelier/keras,jbolinge/keras,tencrance/keras,meanmee/keras,kuza55/keras,nehz/keras,keras-team/keras,EderSantana/keras,kemaswill/keras,abayowbo/keras,dhruvparamhans/keras... |
3b30a036f9f9fb861c0ed1711b5bd967756a072d | flask_cors/__init__.py | flask_cors/__init__.py | # -*- coding: utf-8 -*-
"""
flask_cors
~~~~
Flask-CORS is a simple extension to Flask allowing you to support cross
origin resource sharing (CORS) using a simple decorator.
:copyright: (c) 2014 by Cory Dolphin.
:license: MIT, see LICENSE for more details.
"""
from .decorator import cross_origin... | # -*- coding: utf-8 -*-
"""
flask_cors
~~~~
Flask-CORS is a simple extension to Flask allowing you to support cross
origin resource sharing (CORS) using a simple decorator.
:copyright: (c) 2014 by Cory Dolphin.
:license: MIT, see LICENSE for more details.
"""
from .decorator import cross_origin... | Disable logging for flask_cors by default | Disable logging for flask_cors by default
| Python | mit | corydolphin/flask-cors,ashleysommer/sanic-cors |
3699cc594d9a4f02d24308cb41b8757124616f78 | boltiot/requesting.py | boltiot/requesting.py | from boltiot.urls import url
import requests
def request_from(url, *kwargs):
try:
response = str(requests.get(url.format(*kwargs)).text)
return response
except requests.exceptions.ConnectionError as err:
return str({"success":"0", "message":"A Connection error occurred"})
except req... | from boltiot.urls import url
import requests
def request_from(url, *kwargs):
try:
response = str(requests.get(url.format(*kwargs)).text)
return response
except requests.exceptions.ConnectionError as err:
return str({"success":"0", "message":"A Connection error occurred"})
except req... | Add ERROR: keyword in error message return | Add ERROR: keyword in error message return
| Python | mit | Inventrom/bolt-api-python |
7feb7eeba7e591f7a0c1cbf3b72efb099bd9f644 | hijack/urls.py | hijack/urls.py | from compat import patterns, url
from django.conf import settings
urlpatterns = patterns('hijack.views',
url(r'^release-hijack/$', 'release_hijack', name='release_hijack'),
)
if getattr(settings, "HIJACK_NOTIFY_ADMIN", False):
urlpatterns += patterns('hijack.views',
url(r'^disable-hijack-warning/$', '... | from compat import patterns, url
from django.conf import settings
urlpatterns = patterns('hijack.views',
url(r'^release-hijack/$', 'release_hijack', name='release_hijack'),
)
if getattr(settings, "HIJACK_NOTIFY_ADMIN", False):
urlpatterns += patterns('hijack.views',
url(r'^disable-hijack-warning/$', '... | Use a more liberal/naive approach to regex checking for an email | Use a more liberal/naive approach to regex checking for an email
The problem with the old method is that it does not support
- Internationalized TLDs, domains or users, such as .xn--4gbrim domains
- Geographic TLDs, such as .europe
- ICANN-era TLDs, such as .audio and .clothing
The new regex still matches <anything>@... | Python | mit | arteria/django-hijack,arteria/django-hijack,arteria/django-hijack |
5f6ba1b3a1f2798df1e17d2c29785f04939bd847 | src/test/testlexer.py | src/test/testlexer.py |
from cStringIO import StringIO
from nose.tools import *
from parse import EeyoreLexer
def _lex( string ):
return list( EeyoreLexer.Lexer( StringIO( string ) ) )
def _assert_token( token, ( text, tp ) ):
assert_equal( token.getText(), text )
assert_equal( token.getType(), tp )
def test_hello_world():
... |
from cStringIO import StringIO
from nose.tools import *
from parse import EeyoreLexer
def _lex( string ):
return list( EeyoreLexer.Lexer( StringIO( string ) ) )
def _assert_token( token, text, tp, line = None, col = None ):
assert_equal( token.getText(), text )
assert_equal( token.getType(), tp )
if... | Test line numbers in lexer tests. | Test line numbers in lexer tests.
| Python | mit | andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper |
ebe7e1012ddc1286d61de5c5a565aff9cd4faedf | stdnum/jp/__init__.py | stdnum/jp/__init__.py | # __init__.py - collection of Japanese numbers
# coding: utf-8
#
# Copyright (C) 2019 Alan Hettinger
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License,... | # __init__.py - collection of Japanese numbers
# coding: utf-8
#
# Copyright (C) 2019 Alan Hettinger
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License,... | Add missing vat alias for Japan | Add missing vat alias for Japan
| Python | lgpl-2.1 | arthurdejong/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum |
e0308672543d0bbe8309351c9d63732d0d0e3e30 | steel/fields/mixin.py | steel/fields/mixin.py | from gettext import gettext as _
class Fixed:
_("A mixin that ensures the presence of a predetermined value")
def __init__(self, value, *args, **kwargs):
self.value = value
super(Fixed, self).__init__(*args, **kwargs)
def encode(self, value):
# Always encode the fixed value
... | from gettext import gettext as _
class Fixed:
_("A mixin that ensures the presence of a predetermined value")
def __init__(self, value, *args, **kwargs):
self.value = value
# Pass the value in as a default as well, to make
# sure it goes through when no value was supplied
sup... | Include fixed values as defaults | Include fixed values as defaults
I'm not a big fan of this approach, but it avoids a good bit of code duplication
| Python | bsd-3-clause | gulopine/steel-experiment |
a287c1e7a6e96a2a2143e9270a5f9b2ec295022e | fireplace/cards/removed/all.py | fireplace/cards/removed/all.py | """
Cards removed from the game
"""
from ..utils import *
# Adrenaline Rush
class NEW1_006:
action = drawCard
combo = drawCards(2)
# Bolstered (Bloodsail Corsair)
class NEW1_025e:
Health = 1
| """
Cards removed from the game
"""
from ..utils import *
# Dagger Mastery
class CS2_083:
def action(self):
if self.hero.weapon:
self.hero.weapon.buff("CS2_083e")
else:
self.hero.summon("CS2_082")
class CS2_083e:
Atk = 1
# Adrenaline Rush
class NEW1_006:
action = drawCard
combo = drawCards(2)
# Bo... | Implement the old Dagger Mastery | Implement the old Dagger Mastery
| Python | agpl-3.0 | Ragowit/fireplace,beheh/fireplace,NightKev/fireplace,liujimj/fireplace,amw2104/fireplace,butozerca/fireplace,oftc-ftw/fireplace,jleclanche/fireplace,liujimj/fireplace,butozerca/fireplace,oftc-ftw/fireplace,smallnamespace/fireplace,Meerkov/fireplace,smallnamespace/fireplace,amw2104/fireplace,Ragowit/fireplace,Meerkov/fi... |
2d94532e316e9ad563b3b7506d47cfd78ca7f689 | tests/test_cattery.py | tests/test_cattery.py | import pytest
from catinabox import cattery
###########################################################################
# add_cats
###########################################################################
def test__add_cats__succeeds():
c = cattery.Cattery()
c.add_cats(["Fluffy", "Snookums"])
assert c... | import pytest
from catinabox import cattery
###########################################################################
# fixtures
###########################################################################
@pytest.fixture
def c():
return cattery.Cattery()
#####################################################... | Add fixtures to cattery tests | Step_5: Add fixtures to cattery tests
Add a fixture to remove initialisation of the cattery in every test.
Signed-off-by: Meghan Halton <3ef2199560b9c9d063f7146fc0f2e3c408894741@gmail.com>
| Python | mit | indexOutOfBound5/catinabox |
2ecdd2feb18ef23610e55242b70b64ce0d6f6fe9 | src/sentry/app.py | src/sentry/app.py | """
sentry.app
~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from sentry.conf import settings
from sentry.utils.imports import import_string
from threading import local
class State(local):
request = None
def get_buffer(p... | """
sentry.app
~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from sentry.conf import settings
from sentry.utils.imports import import_string
from threading import local
class State(local):
request = None
def get_buffer(p... | Raise an import error when import_string fails on get_buffer | Raise an import error when import_string fails on get_buffer
| Python | bsd-3-clause | mvaled/sentry,llonchj/sentry,argonemyth/sentry,songyi199111/sentry,1tush/sentry,fotinakis/sentry,BayanGroup/sentry,alexm92/sentry,NickPresta/sentry,fotinakis/sentry,jokey2k/sentry,looker/sentry,fuziontech/sentry,imankulov/sentry,felixbuenemann/sentry,boneyao/sentry,Kryz/sentry,drcapulet/sentry,rdio/sentry,SilentCircle/... |
80de36ddbe4e2eb2e0d00d5910ab8c199d1a6edb | gom_server/char_attr/router.py | gom_server/char_attr/router.py | from rest_framework import routers, serializers, viewsets
import models
# Serializers define the API representation.
class AttributeSerializer(serializers.ModelSerializer):
class Meta:
model = models.Attribute
class AttributeTypeSerializer(serializers.ModelSerializer):
attributes = AttributeSerializer(many... | from rest_framework import routers, serializers, viewsets
import models
# Serializers define the API representation.
class AttributeSerializer(serializers.ModelSerializer):
class Meta:
model = models.Attribute
class AttributeTypeSerializer(serializers.ModelSerializer):
attributes = AttributeSerializer(many... | Add api end point /api-detail/ | Add api end point /api-detail/
| Python | bsd-2-clause | jhogg41/gm-o-matic,jhogg41/gm-o-matic,jhogg41/gm-o-matic |
6611641fec2342fa8dcfdbf12d74558df65ed2eb | isserviceup/services/heroku.py | isserviceup/services/heroku.py | import requests
from isserviceup.services.models.service import Service, Status
class Heroku(Service):
name = 'Heroku'
status_url = 'https://status.heroku.com/'
icon_url = '/images/icons/heroku.png'
def get_status(self):
r = requests.get('https://status.heroku.com/api/v3/current-status')
... | import requests
from isserviceup.services.models.service import Service, Status
class Heroku(Service):
name = 'Heroku'
status_url = 'https://status.heroku.com/'
icon_url = '/images/icons/heroku.png'
def get_status(self):
r = requests.get('https://status.heroku.com/api/v3/current-status')
... | Raise exception for unexpected status | Raise exception for unexpected status
| Python | apache-2.0 | marcopaz/is-service-up,marcopaz/is-service-up,marcopaz/is-service-up |
fcddaececf4d30fa8588f72812338e551efea056 | oscar/apps/wishlists/forms.py | oscar/apps/wishlists/forms.py | # -*- coding: utf-8 -*-
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory, fields_for_model
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args,... | # -*- coding: utf-8 -*-
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory, fields_for_model
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args,... | Use bootstrap input styles to shrink quantity field width | Use bootstrap input styles to shrink quantity field width
| Python | bsd-3-clause | faratro/django-oscar,vovanbo/django-oscar,ademuk/django-oscar,jinnykoo/wuyisj.com,kapt/django-oscar,eddiep1101/django-oscar,itbabu/django-oscar,nfletton/django-oscar,jlmadurga/django-oscar,solarissmoke/django-oscar,jinnykoo/wuyisj.com,MatthewWilkes/django-oscar,mexeniz/django-oscar,jinnykoo/wuyisj,michaelkuty/django-os... |
903030fc0a0d545e652337d543c6167e2bb192b1 | pyaggr3g470r/duplicate.py | pyaggr3g470r/duplicate.py | #! /usr/bin/env python
#-*- coding: utf-8 -*-
import itertools
import utils
def compare_documents(feed):
"""
Compare a list of documents by pair.
"""
duplicates = []
for pair in itertools.combinations(feed.articles, 2):
if pair[0].content != "" and pair[0].content == pair[1].content:
... | #! /usr/bin/env python
#-*- coding: utf-8 -*-
import itertools
import utils
def compare_documents(feed):
"""
Compare a list of documents by pair.
"""
duplicates = []
for pair in itertools.combinations(feed.articles, 2):
if pair[0].content != "" and \
(utils.clear_string(pair[0... | Test the equality of the contents and of the titles. | Test the equality of the contents and of the titles.
| Python | agpl-3.0 | JARR-aggregator/JARR,jaesivsm/JARR,JARR-aggregator/JARR,cedricbonhomme/pyAggr3g470r,JARR/JARR,jaesivsm/pyAggr3g470r,JARR/JARR,jaesivsm/pyAggr3g470r,JARR-aggregator/JARR,jaesivsm/pyAggr3g470r,cedricbonhomme/pyAggr3g470r,JARR/JARR,cedricbonhomme/pyAggr3g470r,cedricbonhomme/pyAggr3g470r,jaesivsm/pyAggr3g470r,jaesivsm/JARR... |
a5dd30e38e58c08d67a2f831e2ae3cbc4a288337 | diary/admin.py | diary/admin.py | from django.contrib import admin
from diary.models import DiaryItem, EventLocation, ImageItem
class DiaryAdmin(admin.ModelAdmin):
list_display = ('title', 'start_date', 'start_time', 'author', 'location')
# Register your models here.
admin.site.register(DiaryItem, DiaryAdmin)
admin.site.register(EventLocation)
admi... | from django.contrib import admin
from diary.models import DiaryItem, EventLocation, ImageItem
class DiaryAdmin(admin.ModelAdmin):
list_display = ('title', 'start_date', 'start_time', 'author', 'location')
exclude = ('author',)
def save_model(self, request, obj, form, change):
if obj.pk is None:
... | Set author automatically for diary items | Set author automatically for diary items
| Python | mit | DevLoL/devlol.at,DevLoL/devlol.at,DevLoL/devlol.at,DevLoL/devlol.at |
27a7e589ec3f5b29d99cede4af66780509ab6973 | foursquare/tests/test_photos.py | foursquare/tests/test_photos.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# (c) 2013 Mike Lewis
import logging; log = logging.getLogger(__name__)
from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase
import os
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata')
class PhotosEndpointTestCase(BaseAuthenti... | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# (c) 2013 Mike Lewis
import logging; log = logging.getLogger(__name__)
from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase
import os
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata')
class PhotosEndpointTestCase(BaseAuthenti... | Make test compatible with Python 2.6. | Make test compatible with Python 2.6.
| Python | mit | mLewisLogic/foursquare,mLewisLogic/foursquare |
a5ceaa6401c53fc99a85ef69ee1357996877e141 | ocradmin/core/tests/testutils.py | ocradmin/core/tests/testutils.py | """
Functions for performing test setup/teardown etc.
"""
import os
MODELDIR = "etc/defaultmodels"
def symlink_model_fixtures():
"""
Create symlinks between the files referenced in the OcrModel
fixtures and our default model files. Need to do this because
they get deleted again at test teardown.
... | """
Functions for performing test setup/teardown etc.
"""
import os
MODELDIR = "etc/defaultmodels"
def symlink_model_fixtures():
"""
Create symlinks between the files referenced in the OcrModel
fixtures and our default model files. Need to do this because
they get deleted again at test teardown.
... | Add a function to symlink reference_page files into existance | Add a function to symlink reference_page files into existance
| Python | apache-2.0 | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium |
c79bec872f1bd9158d202cade39d5e2351688c22 | src/hireme/server.py | src/hireme/server.py | # -*- coding: utf-8 -*-
from tasks import task1, task2
import flask
def index():
return flask.render_template('index.html', title='index')
def app_factory():
app = flask.Flask(import_name=__package__)
app.add_url_rule('/', 'index', index)
app.add_url_rule('/task1', 'task1', task1.solve)
app.add... | # -*- coding: utf-8 -*-
from tasks import task1, task2
import flask
def index():
return flask.render_template('index.html', title='index')
def app_factory():
app = flask.Flask(import_name=__package__)
app.add_url_rule('/', 'index', index)
app.add_url_rule('/task1', 'task1', task1.solve, methods=['G... | Allow POST as well as GET | Allow POST as well as GET
| Python | bsd-2-clause | cutoffthetop/hireme |
9ea7e49e11c3e05b86b9eeaffd416285c9a2551a | pushhub/models.py | pushhub/models.py | from persistent.mapping import PersistentMapping
class Root(PersistentMapping):
__parent__ = __name__ = None
def appmaker(zodb_root):
if not 'app_root' in zodb_root:
app_root = Root()
zodb_root['app_root'] = app_root
import transaction
transaction.commit()
return zodb_roo... | from persistent.mapping import PersistentMapping
from .subsciber import Subscribers
from .topic import Topics
class Root(PersistentMapping):
__parent__ = __name__ = None
def appmaker(zodb_root):
if not 'app_root' in zodb_root:
app_root = Root()
zodb_root['app_root'] = app_root
impor... | Add folder set up to the ZODB on app creation. | Add folder set up to the ZODB on app creation.
| Python | bsd-3-clause | ucla/PushHubCore |
d788375843d42d1de3c0143064e905a932394e30 | library/tests/test_factories.py | library/tests/test_factories.py | import pytest
from .factories import BookFactory, BookSpecimenFactory
pytestmark = pytest.mark.django_db
def test_it_should_create_a_default_book_from_factory():
book = BookFactory()
assert book.pk is not None
assert unicode(book)
def test_it_should_override_book_fields_passed_to_factory():
book =... | import pytest
from .factories import BookFactory, BookSpecimenFactory
pytestmark = pytest.mark.django_db
def test_it_should_create_a_default_book_from_factory():
book = BookFactory()
assert book.pk is not None
assert unicode(book)
def test_it_should_override_book_fields_passed_to_factory():
book =... | Test that BookSpecimenFactory also creates the related book | Test that BookSpecimenFactory also creates the related book
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,Lcaracol/ideasbox.lan,ideascube/ideascube,Lcaracol/ideasbox.lan,Lcaracol/ideasbox.lan,ideascube/ideascube |
972eaa90d4ffad7f4e74792e2bdc4917e5eb7c3a | puffin/core/compose.py | puffin/core/compose.py | from .applications import get_application_domain, get_application_name
from .machine import get_env_vars
from .. import app
from subprocess import Popen, STDOUT, PIPE
from os import environ
from os.path import join
def init():
pass
def compose_start(machine, user, application, **environment):
compose_run(ma... | from .applications import get_application_domain, get_application_name
from .machine import get_env_vars
from .. import app
from subprocess import Popen, STDOUT, PIPE
from os import environ
from os.path import join
def init():
pass
def compose_start(machine, user, application, **environment):
compose_run(ma... | Add dummy Let's Encrypt email | Add dummy Let's Encrypt email
| Python | agpl-3.0 | loomchild/jenca-puffin,loomchild/puffin,puffinrocks/puffin,loomchild/puffin,loomchild/puffin,puffinrocks/puffin,loomchild/puffin,loomchild/puffin,loomchild/jenca-puffin |
a292f2978f07839af07a8963a51fd48b046f0c73 | website/addons/mendeley/settings/__init__.py | website/addons/mendeley/settings/__init__.py | import logging
from .defaults import * # noqa
try:
from .local import * # noqa
except ImportError as error:
logging.warn('No local.py settings file found')
| import logging
from .defaults import * # noqa
logger = logging.getLogger(__name__)
try:
from .local import * # noqa
except ImportError as error:
logger.warn('No local.py settings file found')
| Use namespaces logger in mendeley settings | Use namespaces logger in mendeley settings
h/t Arpita for catching this
[skip ci]
| Python | apache-2.0 | brianjgeiger/osf.io,Johnetordoff/osf.io,samchrisinger/osf.io,KAsante95/osf.io,crcresearch/osf.io,arpitar/osf.io,danielneis/osf.io,cslzchen/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,asanfilippo7/osf.io,kwierman/osf.io,SSJohns/osf.io,GageGaskins/osf.io,GageGaskins/osf.io,danielneis/osf.io,brandonPurvis/osf.io,emetsger/o... |
a5ff4c247030559c83a06976fcda062c0c42d810 | django_fixmystreet/fixmystreet/tests/__init__.py | django_fixmystreet/fixmystreet/tests/__init__.py | import shutil
import os
from django.core.files.storage import default_storage
from django.test import TestCase
class SampleFilesTestCase(TestCase):
fixtures = ['sample']
@classmethod
def setUpClass(cls):
default_storage.location = 'media' # force using source media folder to avoid real data erasi... | import shutil
import os
from django.core.files.storage import default_storage
from django.test import TestCase
class SampleFilesTestCase(TestCase):
fixtures = ['sample']
@classmethod
def setUpClass(cls):
default_storage.location = 'media' # force using source media folder to avoid real data erasi... | Fix unit test fixtures files | Fix unit test fixtures files
| Python | agpl-3.0 | IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet |
faa4125dd8c491eb360ccfea5609a0dabb3cccda | fluent/apps.py | fluent/apps.py |
try:
# Configure a generator if the user is using model_mommy
from model_mommy import generators
def gen_translatablecontent(max_length):
from fluent.fields import TranslatableContent
return TranslatableContent(text=generators.gen_string(max_length))
gen_translatablecontent.required ... |
try:
# Configure a generator if the user is using model_mommy
from model_mommy import generators
def gen_translatablecontent(max_length):
from fluent.fields import TranslatableContent
return TranslatableContent(text=generators.gen_string(max_length))
gen_translatablecontent.required ... | Add missing name to the AppConfig | Add missing name to the AppConfig
| Python | mit | potatolondon/fluent-2.0,potatolondon/fluent-2.0 |
8812341b705e6cec98b2708d0a1481d769f5f476 | salt/runners/config.py | salt/runners/config.py | # -*- coding: utf-8 -*-
'''
This runner is designed to mirror the execution module config.py, but for
master settings
'''
from __future__ import absolute_import
from __future__ import print_function
import salt.utils
def get(key, default='', delimiter=':'):
'''
Retrieve master config options, with optional n... | # -*- coding: utf-8 -*-
'''
This runner is designed to mirror the execution module config.py, but for
master settings
'''
from __future__ import absolute_import
from __future__ import print_function
import salt.utils
import salt.utils.sdb
def get(key, default='', delimiter=':'):
'''
Retrieve master config op... | Add sdb support, and also properly return the default | Add sdb support, and also properly return the default
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
4e9c0cb3cd0d74ce008f0279bc6e9ec353c03fee | senlin_dashboard/api/utils.py | senlin_dashboard/api/utils.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Use entities.reverse() rather sorted(.., reverse=True) | Use entities.reverse() rather sorted(.., reverse=True)
Change-Id: I33ee5b078e3d27a45bd159be0f0b241c20792f92
| Python | apache-2.0 | openstack/senlin-dashboard,stackforge/senlin-dashboard,stackforge/senlin-dashboard,openstack/senlin-dashboard,stackforge/senlin-dashboard,openstack/senlin-dashboard,openstack/senlin-dashboard |
5812aae9059ede1a3cb19be9033ebc435d5ebb94 | scripts/create_user.py | scripts/create_user.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#==============================================================================
# Script for creating MySQL user
#==============================================================================
import os
import sys
import mysql.connector
from mysql.connector import errorco... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#==============================================================================
# Script for creating MySQL user
#==============================================================================
import os
import sys
import mysql.connector
from mysql.connector import errorco... | Fix MySQL command executing (MySQL commit). | scripts: Fix MySQL command executing (MySQL commit).
| Python | mit | alberand/tserver,alberand/tserver,alberand/tserver,alberand/tserver |
d187a8434c9d64171f76efa3055bdc06afbc8981 | scripts/pystart.py | scripts/pystart.py | import os,sys,re
from time import sleep
from pprint import pprint
home = os.path.expanduser('~')
from math import log,ceil
def clog2(num):
return int(ceil(log(num,2)))
if (sys.version_info > (3, 0)):
# Python 3 code in this block
exec(open(home+'/homedir/scripts/hexecho.py').read())
else:
# Python 2 code in thi... | import os,sys,re
from time import sleep
from pprint import pprint
home = os.path.expanduser('~')
from math import log,ceil
sys.ps1 = '\001\033[96m\002>>> \001\033[0m\002'
sys.ps2 = '\001\033[96m\002... \001\033[0m\002'
def clog2(num):
return int(ceil(log(num,2)))
if (sys.version_info > (3, 0)):
# Python 3 code in t... | Add color to python prompt | Add color to python prompt
| Python | mit | jdanders/homedir,jdanders/homedir,jdanders/homedir,jdanders/homedir |
d8b13dcb884046ee43d54fcf27f1bbfd0ff3263a | sentrylogs/parsers/__init__.py | sentrylogs/parsers/__init__.py | """
Log file parsers provided by Sentry Logs
"""
import tailer # same functionality as UNIX tail in python
from ..helpers import send_message
class Parser(object):
"""Abstract base class for any parser"""
def __init__(self, filepath):
self.filepath = filepath
self.logger = self.__doc__.stri... | """
Log file parsers provided by Sentry Logs
"""
import tailer # same functionality as UNIX tail in python
from ..helpers import send_message
try:
(FileNotFoundError, PermissionError)
except NameError: # Python 2.7
FileNotFoundError = IOError # pylint: disable=redefined-builtin
PermissionError = IOErro... | Handle FileNotFound and Permission errors gracefully | Handle FileNotFound and Permission errors gracefully
| Python | bsd-3-clause | bittner/sentrylogs,mdgart/sentrylogs |
a7e87621b3223e0c4df9d417129fcb7da545c629 | integration/integration.py | integration/integration.py | # Python Packages
import random
# External Packages
import numpy as np
def sin_theta_sum(variables):
theta = 0
for var in variables:
theta += var
return np.sin(theta)
def gen_random_list(count, rmin, rmax):
variables = []
for i in range(count):
value = np.rand... | # Python Packages
import random
# External Packages
import numpy as np
def sin_theta_sum(theta):
return np.sin(theta)
def gen_random_value(count, rmin, rmax):
value = 0
for i in range(count):
value += np.random.uniform(rmin, rmax)
# test_range(rmin, rmax, value)
retu... | Add preliminary function to execute monte-carlo approximation. | Add preliminary function to execute monte-carlo approximation.
Adjust functions, remove some generality for speed. Implement monte-carlo
for the exercise case with initial config. No error calculation or
execution for varied N yet. Initial tests with N = 10^7 give a
value of ~537.1 and take ~1.20min.
| Python | mit | lemming52/white_knight |
bfd8ac40bed4535a91bfd645cbe80b47c827a8de | librarian/embeds/mathml.py | librarian/embeds/mathml.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from lxml import etree
import six
from librarian import get_resource
from . import TreeEmbed, create_embed, downgrades_to
class MathML(TreeEmbed):
@downgrades_to('application/x-latex')
def to_latex(self):
xslt = etree.parse(get_resource(... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from lxml import etree
import six
from librarian import get_resource
from . import TreeEmbed, create_embed, downgrades_to
class MathML(TreeEmbed):
@downgrades_to('application/x-latex')
def to_latex(self):
"""
>>> print(MathML(etr... | Fix XML entities left from MathML. | Fix XML entities left from MathML.
| Python | agpl-3.0 | fnp/librarian,fnp/librarian |
ac55f6936551a0927b25aa520ab49649a6b4a904 | plugins/basic_info_plugin.py | plugins/basic_info_plugin.py | import string
import textwrap
from veryprettytable import VeryPrettyTable
from plugins import BasePlugin
__author__ = 'peter'
class BasicInfoPlugin(BasePlugin):
short_description = 'Basic info:'
default = True
description = textwrap.dedent('''\
This plugin provides some basic info about the string... | import string
import textwrap
from veryprettytable import VeryPrettyTable
from plugins import BasePlugin
__author__ = 'peter'
class BasicInfoPlugin(BasePlugin):
short_description = 'Basic info:'
default = True
description = textwrap.dedent('''\
This plugin provides some basic info about the string... | Put basic info in one table | Put basic info in one table
| Python | mit | Sakartu/stringinfo |
aa69ae87a947ee17d72d7881dc61a5091772ff6c | pythainlp/segment/pyicu.py | pythainlp/segment/pyicu.py | from __future__ import absolute_import,print_function
from itertools import groupby
import PyICU
import six
# ตัดคำภาษาไทย
def segment(txt):
"""รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU"""
bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th"))
bd.setText(six.u(txt))
bre... | from __future__ import absolute_import,print_function
from itertools import groupby
import PyICU
# ตัดคำภาษาไทย
def segment(txt):
"""รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU"""
bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th"))
bd.setText(six.u(txt))
breaks = list(... | Revert "fix bug import six" | Revert "fix bug import six"
This reverts commit a80c1d7c80d68f72d435dbb7ac5c48a6114716fb.
| Python | apache-2.0 | PyThaiNLP/pythainlp |
cbea20e07807df21645c0edd52ccfdef2c5f72f1 | modules/dispatcher.py | modules/dispatcher.py | from os import unlink
from configobj import ConfigObj
from tests.ch_mock import Twitter
def Dispatch(channels, msgFile):
msgConfig = ConfigObj(msgFile)
Topic = msgConfig['Topic']
To_Email = msgConfig['To_Email']
Message = msgConfig['Message']
unlink(msgFile)
reply = {}
for channel in chann... | from os import unlink
from configobj import ConfigObj
from twitter import Twitter
def Dispatch(channels, msgFile):
msgConfig = ConfigObj(msgFile)
Topic = msgConfig['Topic']
To_Email = msgConfig['To_Email']
Message = msgConfig['Message']
unlink(msgFile)
reply = {}
for channel in channels:
... | Replace mock Twitter channel with actual channel | Replace mock Twitter channel with actual channel
| Python | mit | alfie-max/Publish |
8cfa861107ae9ed829561300baeab74e7d0dd0f3 | mysite/urls.py | mysite/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
from candidates.views import (ConstituencyPostcodeFinderView,
ConstituencyDetailView, CandidacyView, CandidacyDeleteView, NewPersonView)
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', ConstituencyPostcodeFinderV... | from django.conf.urls import patterns, include, url
from django.contrib import admin
from candidates.views import (ConstituencyPostcodeFinderView,
ConstituencyDetailView, CandidacyView, CandidacyDeleteView, NewPersonView)
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', ConstituencyPostcodeFinderV... | Add a separate endpoint for posting postcode lookups to | Add a separate endpoint for posting postcode lookups to
| Python | agpl-3.0 | mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,openstate/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,openstate/yournextrepresentative,openst... |
61253510bc859ec1695484d11cbadcd92ad4b107 | tests/test_misc.py | tests/test_misc.py | import mistune
from unittest import TestCase
class TestMiscCases(TestCase):
def test_none(self):
self.assertEqual(mistune.html(None), '')
def test_before_parse_hooks(self):
def _add_name(md, s, state):
state['name'] = 'test'
return s, state
md = mistune.create_markdown()
... | import mistune
from unittest import TestCase
class TestMiscCases(TestCase):
def test_none(self):
self.assertEqual(mistune.html(None), '')
def test_before_parse_hooks(self):
def _add_name(md, s, state):
state['name'] = 'test'
return s, state
md = mistune.create_... | Add test for allow harmful protocols | Add test for allow harmful protocols
| Python | bsd-3-clause | lepture/mistune |
ff14a65284603e27cff9628cd8eec0c4cfd8e81d | pale/arguments/url.py | pale/arguments/url.py | from __future__ import absolute_import
import string
import urlparse
from pale.arguments.string import StringArgument
from pale.errors import ArgumentError
class URLArgument(StringArgument):
def validate_url(self, original_string):
"""Returns the original string if it was valid, raises an argument
... | from __future__ import absolute_import
import string
import urlparse
from pale.arguments.string import StringArgument
from pale.errors import ArgumentError
class URLArgument(StringArgument):
path_only = False
def validate_url(self, original_string):
"""Returns the original string if it was valid, r... | Add path_only support to URLArgument | Add path_only support to URLArgument
| Python | mit | Loudr/pale |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.