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 |
|---|---|---|---|---|---|---|---|---|---|
bf6d4c4622b9a0161fad3b03422747fb16faf5de | setup.py | setup.py | from distutils.core import setup
setup(
name='BitstampClient',
version='0.1',
packages=['bitstamp'],
url='',
license='MIT',
author='Kamil Madac',
author_email='kamil.madac@gmail.com',
description='Bitstamp API python implementation',
requires=['requests']
)
| from distutils.core import setup
setup(
name='bitstamp-python-client',
version='0.1',
packages=['bitstamp'],
url='',
license='MIT',
author='Kamil Madac',
author_email='kamil.madac@gmail.com',
description='Bitstamp API python implementation',
requires=['requests']
)
| Rename because of clash with original package. | Rename because of clash with original package.
| Python | mit | nederhoed/bitstamp-python-client |
434bc5554dcd8b2f2bf4a3b4a1d1991746e86b78 | setup.py | setup.py | from distutils.core import setup
setup(
name = 'pybenchmark',
packages = ['pybenchmark'], # this must be the same as the name above
version = '0.0.5',
description = 'A benchmark utility used in performance tests.',
author = 'Eugene Duboviy',
author_email = 'eugene.dubovoy@gmail.com',
url = 'https://github... | from distutils.core import setup
setup(
name = 'pybenchmark',
packages = ['pybenchmark'], # this must be the same as the name above
version = '0.0.6',
description = 'A benchmark utility used in performance tests.',
author = 'Eugene Duboviy',
author_email = 'eugene.dubovoy@gmail.com',
url = 'https://github... | Fix long description; Add new PyPI release version | Fix long description; Add new PyPI release version
| Python | mit | duboviy/pybenchmark |
d9f2ab870c3226d932f7d31aed2c255495573051 | src/xii/need/need_guestfs.py | src/xii/need/need_guestfs.py | from abc import ABCMeta, abstractmethod
import guestfs
from xii import util
class NeedGuestFS():
__metaclass__ = ABCMeta
@abstractmethod
def get_tmp_volume_path(self):
pass
def guest(self):
def _start_guestfs():
path = self.get_tmp_volume_path()
guest = gues... | from abc import ABCMeta, abstractmethod
import guestfs
from xii import util, error
class NeedGuestFS():
__metaclass__ = ABCMeta
@abstractmethod
def get_tmp_volume_path(self):
pass
def guest(self):
def _start_guestfs():
try:
path = self.get_tmp_volume_pat... | Add error handling to guestfs initializer | Add error handling to guestfs initializer
| Python | apache-2.0 | xii/xii,xii/xii |
8182657154b86cf65c515af3537e369818051ff5 | tests/test_config.py | tests/test_config.py | # -*- coding: utf-8 -*-
import unittest
from .utils import all_available_methods, get_config_path
from noterator import Noterator
from noterator.config import ConfigurationError
class TestConfigValidation(unittest.TestCase):
def test_valid_config(self):
noterator = Noterator(
method=all_ava... | # -*- coding: utf-8 -*-
import unittest
from .utils import all_available_methods, get_config_path
from noterator import Noterator
from noterator.config import ConfigurationError
class TestConfigValidation(unittest.TestCase):
def test_valid_config(self):
noterator = Noterator(
method=all_ava... | Make sure config is empty if a bad path is given | Make sure config is empty if a bad path is given
| Python | mit | jimr/noterator |
d5217075d20c9b707dba191f4e7efdc9f66dcfaa | am_workout_assistant.py | am_workout_assistant.py | #!/usr/bin/env python
from telegram import Telegram
from message_checker import MessageHandler
from data_updater import DataUpdater
# init telegram bot
bot = Telegram()
ok = bot.init()
if not ok:
print("ERROR (bot init): {}".format(bot.get_messages()))
exit(1)
# init message checker
msg_checker = MessageHandl... | #!/usr/bin/env python
from telegram import Telegram
from message_checker import MessageHandler
from data_updater import DataUpdater
# init telegram bot
bot = Telegram()
ok = bot.init()
if not ok:
print("ERROR (bot init): {}".format(bot.get_messages()))
exit(1)
# init message checker
msg_checker = MessageHandl... | Return summary for the day on success | Return summary for the day on success
This implements #2
| Python | mit | amaslenn/AMWorkoutAssist |
e9387e0f0bf7e0fc7e656ebc1a181a3667718a56 | lc0118_pascal_triangle.py | lc0118_pascal_triangle.py | """Leetcode 118. Pascal's Triangle
Easy
URL: https://leetcode.com/problems/pascals-triangle/
Given a non-negative integer numRows, generate the first numRows of
Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly
above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
... | """Leetcode 118. Pascal's Triangle
Easy
URL: https://leetcode.com/problems/pascals-triangle/
Given a non-negative integer numRows, generate the first numRows of
Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly
above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
... | Add comments & revise space complexity | Add comments & revise space complexity
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
4c7e4e629d154424acf5590a3c65c7e4d30c5aff | tests/test_person.py | tests/test_person.py | from unittest import TestCase
class PersonTestCase(TestCase):
def test_get_groups(self):
pass | from unittest import TestCase
from address_book import Person
class PersonTestCase(TestCase):
def test_get_groups(self):
pass
def test_add_address(self):
basic_address = ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'],
person = Person(
'John'... | Test the ability to add some address to the person | Test the ability to add some address to the person
| Python | mit | dizpers/python-address-book-assignment |
3f06897115896c9aff2ee15d2cf6214809390199 | moviealert/forms.py | moviealert/forms.py | from django import forms
from django.conf import settings
from moviealert.base.widgets import CalendarWidget
from .models import TaskList, RegionData
class MovieForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MovieForm, self).__init__(*args, **kwargs)
self.fields['movie_date'] =... | from django import forms
from django.conf import settings
from moviealert.base.widgets import CalendarWidget
from .models import TaskList, RegionData
class MovieForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MovieForm, self).__init__(*args, **kwargs)
self.fields['movie_date'] =... | Disable entry of cities outside of database. | Disable entry of cities outside of database.
Add a try-except to prevent entry of city name which is not in the database. | Python | mit | iAmMrinal0/django_moviealert,iAmMrinal0/django_moviealert,iAmMrinal0/django_moviealert |
a5f4700349f19d50d0fbf25bab9c927f2e1b477a | examples/build.py | examples/build.py | #!/usr/bin/python
from fabricate import *
programs = ['create', 'read', 'update', 'delete', 'filter', 'nearest']
def build():
for program in programs:
sources = [program, 'clustergis']
compile(sources)
link(sources, program)
def compile(sources):
for source in sources:
run('mpicc -Wall -O3 `geos-config --... | #!/usr/bin/python
from fabricate import *
programs = ['create', 'read', 'update', 'delete', 'filter', 'nearest']
def build():
for program in programs:
sources = [program, '../src/clustergis']
compile(sources)
link(sources, program)
def compile(sources):
for source in sources:
run('mpicc -Wall -O3 -I../src... | Build script for examples now works | Build script for examples now works
| Python | mit | nathankerr/clusterGIS,nathankerr/clusterGIS |
bd2c87809d98fe89064bd7e8c7cc69c567095d00 | taipan/objective/__init__.py | taipan/objective/__init__.py | """
Object-oriented programming utilities.
"""
import inspect
from taipan._compat import IS_PY26, IS_PY3
from taipan.functional import ensure_callable
from taipan.strings import is_string
__all__ = ['is_internal', 'is_magic']
def is_internal(member):
"""Checks whether given class/instance member, or its name, ... | """
Object-oriented programming utilities.
"""
import inspect
from taipan.functional import ensure_callable
from taipan.strings import is_string
__all__ = ['is_internal', 'is_magic']
def is_internal(member):
"""Checks whether given class/instance member, or its name, is internal."""
name = _get_member_name... | Fix a bug in .objective utility function | Fix a bug in .objective utility function
| Python | bsd-2-clause | Xion/taipan |
d74c82d31071d80c5433fce0ebc46a1145b00d7e | bin/burgers.py | bin/burgers.py | from wenohj.solver import Solver
import numpy as np
import matplotlib.pyplot as plt
def get_alpha(x, t, u, u_x_plus, u_x_minus):
max = np.zeros_like(x)
for i in range(len(x)):
if np.abs(u_x_plus[i] + 1.0) > np.abs(u_x_minus[i] + 1.0):
max[i] = np.abs(u_x_plus[i] + 1.0)
else:
... | from wenohj.solver import Solver
import numpy as np
import matplotlib.pyplot as plt
def get_alpha(x, t, u, u_x_plus, u_x_minus):
f1 = np.abs(u_x_plus + 1.0)
f2 = np.abs(u_x_minus + 1.0)
return np.maximum(f1, f2)
def flux(x, t, u, u_x):
return (u_x + 1)**2 / 2.0
lb = -1.0
rb = 1.0
ncells = 320
T = ... | Refactor get_alpha() to make it faster | Refactor get_alpha() to make it faster
Computations of alpha using for loop are very slow. I switch to usage
of element-wise numpy functions to make get_alpha() function faster.
| Python | bsd-3-clause | kabanovdmitry/weno-hamilton-jacobi,dmitry-kabanov/weno-hamilton-jacobi |
0e20a568ae10982f4886b546553c1caa41042faa | picoCTF-shell/shell_manager/problem_repo.py | picoCTF-shell/shell_manager/problem_repo.py | """
Problem repository management for the shell manager.
"""
import spur, gzip
from shutil import copy2
from os.path import join
def local_update(repo_path, deb_paths=[]):
"""
Updates a local deb repository by copying debs and running scanpackages.
Args:
repo_path: the path to the local reposito... | """
Problem repository management for the shell manager.
"""
import spur, gzip
from shutil import copy2
from os.path import join
def update_repo(args):
"""
Main entrypoint for repo update operations.
"""
if args.repo_type == "local":
local_update(args.repository, args.package_paths)
else... | Update repo entrypoint and remote_update stub. | Update repo entrypoint and remote_update stub.
| Python | mit | royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF |
7daed119551dfc259a0eda0224ac2a6b701c5c14 | app/main/services/process_request_json.py | app/main/services/process_request_json.py | import six
from .query_builder import FILTER_FIELDS, TEXT_FIELDS
from .conversions import strip_and_lowercase
def process_values_for_matching(request_json, key):
values = request_json[key]
if isinstance(values, list):
return [strip_and_lowercase(value) for value in values]
elif isinstance(values... | import six
from .query_builder import FILTER_FIELDS, TEXT_FIELDS
from .conversions import strip_and_lowercase
FILTER_FIELDS_SET = set(FILTER_FIELDS)
TEXT_FIELDS_SET = set(TEXT_FIELDS)
def process_values_for_matching(values):
if isinstance(values, list):
return [strip_and_lowercase(value) for value in va... | Drop any unknown request fields when converting into index document | Drop any unknown request fields when converting into index document
Previously, convert_request_json_into_index_json relied on the request
being sent through the dmutils.apiclient, which dropped any fields that
aren't supposed to be indexed. This means that dmutils contains a copy
of the filter and text fields lists.
... | Python | mit | RichardKnop/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api |
1f6bec9df04e2717a347796080ed6bfcc9638f25 | qipipe/staging/sarcoma_config.py | qipipe/staging/sarcoma_config.py | import os
import ConfigParser
_CFG_FILE = os.path.join(os.path.dirname(__file__), '..', '..', 'conf', 'sarcoma.cfg')
_CONFIG = ConfigParser()
_CONFIG.read(_CFG_FILE)
def sarcoma_location(pt_id):
return _CONFIG.get('Tumor Location', pt_id)
| import os
import io
from ConfigParser import ConfigParser as Config
_CFG_FILE = os.path.join(os.path.dirname(__file__), '..', '..', 'conf', 'sarcoma.cfg')
def sarcoma_location(pt_id):
return sarcoma_config().get('Tumor Location', pt_id)
def sarcoma_config():
if not hasattr(sarcoma_config, 'instance'):
... | Move the singleton to a method attribute. | Move the singleton to a method attribute.
| Python | bsd-2-clause | ohsu-qin/qipipe |
266aadbde72c6d9fa9f26a5060f9aa6e86184015 | app/timetables/admin.py | app/timetables/admin.py | from django.contrib import admin
from .models import *
admin.site.register(Weekday)
admin.site.register(Meal)
admin.site.register(MealOption)
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish)
admin.site.register(Admin)
| from django.contrib import admin
from . import models
admin.site.register(models.Weekday)
admin.site.register(models.Meal)
admin.site.register(models.MealOption)
admin.site.register(models.Course)
admin.site.register(models.Timetable)
admin.site.register(models.Dish)
admin.site.register(models.Admin)
| Change module import to pass flake8 tests | Change module import to pass flake8 tests
| Python | mit | teamtaverna/core |
630c823706e28e66306828d6c3001b6e3773ce90 | ui/players/models.py | ui/players/models.py | from django.db import models
from django.contrib.auth.models import User
class Player(models.Model):
user = models.OneToOneField(User)
class Avatar(models.Model):
player = models.ForeignKey(User)
code = models.TextField() | from django.db import models
from django.contrib.auth.models import User
class Player(models.Model):
user = models.OneToOneField(User)
code = models.TextField()
class Avatar(models.Model):
player = models.ForeignKey(User)
| Move code into player (if only for now) | Move code into player (if only for now)
| Python | agpl-3.0 | Spycho/aimmo,Spycho/aimmo,Spycho/aimmo,Spycho/aimmo |
26dbfe6033eadfd3eb3df40387599e1a2c541296 | board.py | board.py | import numpy
"""
Board represents a four in a row game board.
Author: Isaac Arvestad
"""
class Board:
"""
Initializes the game with a certain number of rows
and columns.
"""
def __init__(self, rows, columns):
self.rows = rows
self.columns = columns
self.boardMatrix = numpy.... | import numpy
"""
Board represents a four in a row game board.
Author: Isaac Arvestad
"""
class Board:
"""
Initializes the game with a certain number of rows
and columns.
"""
def __init__(self, rows, columns):
self.rows = rows
self.columns = columns
self.boardMatrix = numpy.... | Fix bug of not stopping algorithm in time. | Fix bug of not stopping algorithm in time.
| Python | mit | isaacarvestad/four-in-a-row |
fdcfe40cd388a6f53db22af44fcfa10d7901f490 | reviewboard/attachments/admin.py | reviewboard/attachments/admin.py | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from reviewboard.attachments.models import FileAttachment
from reviewboard.reviews.models import FileAttachmentComment
class FileAttachmentAdmin(admin.ModelAdmin):
list_display = ('file', 'caption', 'mimetype',
... | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from reviewboard.attachments.models import FileAttachment
from reviewboard.reviews.models import FileAttachmentComment
class FileAttachmentAdmin(admin.ModelAdmin):
list_display = ('file', 'caption', 'mimetype',
... | Fix another broken file attachment field. | Fix another broken file attachment field.
There was one more admin field for file attachments that was using an old
name. Now fixed.
| Python | mit | chazy/reviewboard,custode/reviewboard,sgallagher/reviewboard,beol/reviewboard,Khan/reviewboard,chipx86/reviewboard,1tush/reviewboard,sgallagher/reviewboard,brennie/reviewboard,davidt/reviewboard,Khan/reviewboard,atagar/ReviewBoard,Khan/reviewboard,reviewboard/reviewboard,chazy/reviewboard,1tush/reviewboard,custode/revi... |
018a5151939a96aa8a9f82e3562dc8c2691d2672 | src/app.py | src/app.py | '''
The main app
'''
from flask import Flask
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
return 'A work in progress, check back later'
@app.route('/add', methods=['POST'])
def add_reminder():
return 'Use this method to POST new reminders to the database'
@app.route('/show',... | '''
The main app
'''
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
return 'A work in progress, check back later'
@app.route('/add', methods=['POST'])
def add_reminder():
return render_template('input.html')
@app.route('/show', methods=... | Return HTML templates using render_template | Return HTML templates using render_template
| Python | bsd-2-clause | ambidextrousTx/RPostIt |
aa86dfda0b92ac99c86053db7fb43bd8cecccc83 | kpi/interfaces/sync_backend_media.py | kpi/interfaces/sync_backend_media.py | # coding: utf-8
class SyncBackendMediaInterface:
"""
This interface defines required properties and methods
of objects passed to deployment back-end class on media synchronization.
"""
@property
def backend_data_value(self):
raise NotImplementedError('This property should be implement... | # coding: utf-8
from kpi.exceptions import AbstractMethodError, AbstractPropertyError
class SyncBackendMediaInterface:
"""
This interface defines required properties and methods
of objects passed to deployment back-end class on media synchronization.
"""
@property
def backend_data_value(self... | Use new exceptions: AbstractMethodError, AbstractPropertyError | Use new exceptions: AbstractMethodError, AbstractPropertyError
| Python | agpl-3.0 | kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi |
fbd168ae6a2b2733bec9ffa1eec4c56fbfdbc97b | modoboa/admin/migrations/0002_migrate_from_modoboa_admin.py | modoboa/admin/migrations/0002_migrate_from_modoboa_admin.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def rename_and_clean(apps, schema_editor):
"""Rename old content types if necessary, remove permissions."""
ContentType = apps.get_model("contenttypes", "ContentType")
for ct in ContentType.objects.fi... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def rename_and_clean(apps, schema_editor):
"""Rename old content types if necessary, remove permissions."""
ContentType = apps.get_model("contenttypes", "ContentType")
for ct in ContentType.objects.fi... | Handle the fresh install case. | Handle the fresh install case.
| Python | isc | modoboa/modoboa,bearstech/modoboa,carragom/modoboa,carragom/modoboa,tonioo/modoboa,bearstech/modoboa,bearstech/modoboa,bearstech/modoboa,tonioo/modoboa,carragom/modoboa,modoboa/modoboa,tonioo/modoboa,modoboa/modoboa,modoboa/modoboa |
a9711705a8c122bf7e7f1edbf9b640c3be5f8510 | integration-test/552-water-boundary-sort-key.py | integration-test/552-water-boundary-sort-key.py | # from https://github.com/mapzen/vector-datasource/issues/552
assert_has_feature(
19, 83900, 202617, "water",
{"kind": "ocean", "boundary": True, "sort_rank": 205})
| # from https://github.com/mapzen/vector-datasource/issues/552
assert_has_feature(
16, 10487, 25327, "water",
{"kind": "ocean", "boundary": True, "sort_rank": 205})
| Update water boundary sort key test zooms | Update water boundary sort key test zooms
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource |
c04a0bbe56e97a96df28f8505f6601df0c638f71 | src/blackred/__init__.py | src/blackred/__init__.py | """
Copyright 2015 Juergen Edelbluth
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, softwa... | """
Copyright 2015 Juergen Edelbluth
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, softwa... | Make the flake8 test pass | Make the flake8 test pass
The import in the `__init__.py` should not be reported by flake8. The warning itself is OK, but not for this file. | Python | apache-2.0 | edelbluth/blackred,edelbluth/blackred |
89f9b30bf3539d947fc066e5ab2845cf78e45ab5 | test/test_07_user_thermal.py | test/test_07_user_thermal.py | class TestUserThermal:
def test_can_download_audio(self, helper):
device = helper.given_new_device(self, 'cacophonator')
recording = device.has_recording()
print("\nA user should be able to download the recording")
helper.admin_user().can_download_correct_recording(recording)
d... | class TestUserThermal:
def test_can_download_recording(self, helper):
device = helper.given_new_device(self, 'cacophonator-download')
recording = device.has_recording()
print("\nA user should be able to download the recording")
helper.admin_user().can_download_correct_recording(reco... | Use unique device names in tests & correct a test name | Use unique device names in tests & correct a test name
| Python | agpl-3.0 | TheCacophonyProject/Full_Noise |
cd44bcde10332d2e8fa092a1df1c4383b5718660 | imager/imagerprofile/handlers.py | imager/imagerprofile/handlers.py | from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from imagerprofile.models import ImagerProfile
@receiver(post_save, sender=User)
def add_profile(sender, instance, **kwargs):
if kwargs['created']:
new_profile = ImagerProfile(us... | from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from imagerprofile.models import ImagerProfile
@receiver(post_save, sender=User)
def add_profile(sender, **kwargs):
if kwargs['created']:
obj = kwargs.get('instance')
new... | Fix instance handling in profile handler | Fix instance handling in profile handler
| Python | mit | nbeck90/django-imager,nbeck90/django-imager |
2512ff39651d55c2c17ad1b4e05a0fc5d0bee415 | indra/tests/test_chebi_client.py | indra/tests/test_chebi_client.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from indra.databases import chebi_client
from indra.util import unicode_strs
from nose.plugins.attrib import attr
def test_read_chebi_to_pubchem():
(ctop, ptoc) = chebi_client._read_chebi_to_pubchem()
asser... | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from indra.databases import chebi_client
from indra.util import unicode_strs
from nose.plugins.attrib import attr
def test_read_chebi_to_pubchem():
(ctop, ptoc) = chebi_client._read_chebi_to_pubchem()
asser... | Fix ChEBI to Pubchem mapping test | Fix ChEBI to Pubchem mapping test
| Python | bsd-2-clause | johnbachman/indra,johnbachman/belpy,sorgerlab/indra,bgyori/indra,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,sorgerlab/belpy,bgyori/indra,johnbachman/indra,sorgerlab/belpy,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,bgyori/indra,pvtodorov/indra,johnbachman/indra,pvtodorov/indra,sorgerlab/indra |
37baf4b9929b7d894cdb090bb4874d7a782a2c38 | solvent/run.py | solvent/run.py | import subprocess
import logging
def run(command, cwd=None):
try:
return subprocess.check_output(
command, cwd=cwd, stderr=subprocess.STDOUT,
stdin=open("/dev/null"), close_fds=True)
except subprocess.CalledProcessError as e:
logging.error("Failed command '%s' output:\n... | import subprocess
import logging
import os
def fix_env_in_case_of_invalid_locale_name(env):
"""See https://github.com/ros-drivers/hokuyo_node/issues/3"""
env["LC_ALL"] = "C"
def run(command, cwd=None):
env = os.environ.copy()
fix_env_in_case_of_invalid_locale_name(env)
try:
return subpro... | Fix env var for osmosis when locale name is invalid | Fix env var for osmosis when locale name is invalid
See https://github.com/ros-drivers/hokuyo_node/issues/3
| Python | apache-2.0 | Stratoscale/solvent,Stratoscale/solvent |
41d8311ac83cc97e0f02800089c47b5ce4630e8e | solumclient/builder/v1/client.py | solumclient/builder/v1/client.py | # Copyright 2014 - Noorul Islam K M
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | # Copyright 2014 - Noorul Islam K M
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | Set the service_type for the builder | Set the service_type for the builder
If we don't do this we can't lookup the endpoint.
Change-Id: I7eae87afc9e4d9ef9dd4f5877b71a4ebe299df0a
| Python | apache-2.0 | rackerlabs/arborlabs_client,stackforge/python-solumclient,openstack/python-solumclient,rackerlabs/arborlabs_client,stackforge/python-solumclient,ed-/python-solumclient,ed-/python-solumclient |
8a8b152566b92cfe0ccbc379b9871da795cd4b5b | keystoneclient/hacking/checks.py | keystoneclient/hacking/checks.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Change hacking check to verify all oslo imports | Change hacking check to verify all oslo imports
The hacking check was verifying that specific oslo imports
weren't using the oslo-namespaced package. Since all the oslo
libraries used by keystoneclient are now changed to use the
new package name the hacking check can be simplified.
bp drop-namespace-packages
Change-... | Python | apache-2.0 | jamielennox/keystoneauth,citrix-openstack-build/keystoneauth,sileht/keystoneauth |
90bd31e43b403efa7d52ee480e89ef29235218c7 | spelling_ja.py | spelling_ja.py | # -*- coding: utf-8 -*-
"""Japanese rules and tables for the spellnum module"""
RULES = """
1x = 十{x}
ab = {a}十{b}
1xx = {100}{x}
axx = {a}{100}{x}
axxx = {a}千{x}
(a)xxxx = {a}{x}
"""
NUMBERS = {
0: '零',
1: '一',
2: '二',
3: '三',
4: '四',
5: '五',
6: '六',
7: '七',
8: '八',
9: '九',
... | # -*- coding: utf-8 -*-
"""Japanese rules and tables for the spellnum module"""
RULES = """
1x = 十{x}
ab = {a}十{b}
1xx = {100}{x}
axx = {a}{100}{x}
axxx = {a}千{x}
(a)xxxx = {a}{x}
"""
NUMBERS = {
0: '零',
1: '一',
2: '二',
3: '三',
4: '四',
5: '五',
6: '六',
7: '七',
8: '八',
9: '九',
... | Add META with 'order_separator' key to Japanese spelling | Add META with 'order_separator' key to Japanese spelling
This is required due to a change in how separators are loaded
in spellnum.py. | Python | mit | alco/numspell,alco/numspell |
6ff9e206f8bdc150b5b0562dd4a07e0e4f80a93f | enthought/traits/ui/editors/date_editor.py | enthought/traits/ui/editors/date_editor.py | #------------------------------------------------------------------------------
#
# Copyright (c) 2008, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions... | #------------------------------------------------------------------------------
#
# Copyright (c) 2008, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions... | Add type info in comment. | Add type info in comment.
| Python | bsd-3-clause | burnpanck/traits,burnpanck/traits |
4d86aff88c4085dc9adfc80adb8d5f07d74d89cf | parse.py | parse.py | from PIL import Image
import sys
import pyocr
import pyocr.builders
image_loc = ' '.join(sys.argv[1:])
tools = pyocr.get_available_tools()
if len(tools) == 0:
print("Error: No OCR tool found")
sys.exit(1)
# should be 'Tesseract (sh)'
tool = tools[0]
orig_image = Image.open(image_loc)
# crop to only the se... | from PIL import Image
import sys
import pyocr
import pyocr.builders
image_loc = ' '.join(sys.argv[1:])
if not len(image_loc):
print('Please provide a Project Euler badge png to parse.')
print('As an example, to parse `test.png`, run the program like this:')
print('python3 parse.py test.png')
sys.exit... | Add help message when no path is given | Add help message when no path is given
| Python | bsd-2-clause | iandioch/euler-foiler |
e0270d78dff4b3e58726465ef464a82ce00738a3 | utility.py | utility.py | #!/usr/bin/env python3
from datetime import datetime
#our timestamping function, accurate to milliseconds
#(remove [:-3] to display microseconds)
def get_time():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
def rd_print(log, *args, **kwargs):
print(get_time(), *args, **kwargs)
if log:
... | #!/usr/bin/env python3
from datetime import datetime
#our timestamping function, accurate to milliseconds
#(remove [:-3] to display microseconds)
def get_time():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
def rd_print(log, *args, **kwargs):
print(get_time(), *args, **kwargs)
if log:
... | Make rd_print() compatibile with Python 3.4. | Make rd_print() compatibile with Python 3.4.
| Python | bsd-2-clause | tdaede/rd_tool,tdaede/rd_tool |
21f234aa20a1315f2106218a402ab230e2d1a1a9 | scripts/prepared_json_to_fasta.py | scripts/prepared_json_to_fasta.py | """
Convert a prepared JSON file from augur into a FASTA file.
"""
import argparse
import Bio
import json
import logging
import pandas as pd
import sys
sys.path.append('..')
from base.sequences_process import sequence_set
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Convert a prepare... | """
Convert a prepared JSON file from augur into a FASTA file.
"""
import argparse
import Bio
import json
import logging
import pandas as pd
import sys
sys.path.append('..')
from base.sequences_process import sequence_set
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Convert a prepare... | Fix bugs in conversion of prepared JSONs to FASTA and metadata | Fix bugs in conversion of prepared JSONs to FASTA and metadata
Specifically, omit reference sequences when the prepared JSON explicitly states
that they should not be included and rename any column named "num_date" to
prevent conflicts with TreeTime in modular augur.
| Python | agpl-3.0 | nextstrain/augur,blab/nextstrain-augur,nextstrain/augur,nextstrain/augur |
6994a94f55380c7a0eafeaab28fe42bc29db8e4d | modder/utils/desktop_notification.py | modder/utils/desktop_notification.py | # coding: utf-8
import platform
if platform.system() == 'Darwin':
from Foundation import NSUserNotificationDefaultSoundName
import objc
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
def desktop_notify(text, titl... | # coding: utf-8
import os.path
import platform
import sys
if getattr(sys, 'frozen', False):
desktop_icon = os.path.abspath(
os.path.join(
os.path.dirname(sys.executable), 'resources', 'icons8-Module-128.png'
)
)
else:
desktop_icon = os.path.abspath(
os.path.join(
... | Add icon for desktop notifications | Add icon for desktop notifications
| Python | mit | JokerQyou/Modder2 |
1de828cf54ec0e87bdf1db4d7d4abf1b822eab68 | pytips/models.py | pytips/models.py | # -*- coding: utf-8 -*-
"""Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
clas... | # -*- coding: utf-8 -*-
"""Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
clas... | Add `publication_date` property to `Tip` model. | Add `publication_date` property to `Tip` model.
BEFORE: We had a column in the DB, but no property on the model object.
AFTER: We have that property in the model.
| Python | isc | gthank/pytips,gthank/pytips,gthank/pytips,gthank/pytips |
180d8d721d321609f18eed9f44d59d32f474dc13 | project_fish/whats_fresh/tests/test_products_model.py | project_fish/whats_fresh/tests/test_products_model.py | from django.test import TestCase
from django.conf import settings
from phonenumber_field.modelfields import PhoneNumberField
from whats_fresh.models import *
from django.contrib.gis.db import models
import os
import time
import sys
import datetime
class ProductTestCase(TestCase):
def setUp(self):
self.e... | from django.test import TestCase
from django.conf import settings
from phonenumber_field.modelfields import PhoneNumberField
from whats_fresh.models import *
from django.contrib.gis.db import models
import os
import time
import sys
import datetime
class ProductTestCase(TestCase):
def setUp(self):
self.e... | Use ForeignKey for foreign keys and NullBooleanField in tests | Use ForeignKey for foreign keys and NullBooleanField in tests
| Python | apache-2.0 | osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api |
11e2535f75fbfc294361b6dba3ae51cae158fd59 | migrations/versions/849170064430_.py | migrations/versions/849170064430_.py | """add enqueue_job column to smtpserver table
Revision ID: 849170064430
Revises: a63df077051a
Create Date: 2018-11-22 10:04:00.330101
"""
# revision identifiers, used by Alembic.
revision = '849170064430'
down_revision = 'a63df077051a'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_colum... | """add enqueue_job column to smtpserver table
Revision ID: 849170064430
Revises: a63df077051a
Create Date: 2018-11-22 10:04:00.330101
"""
# revision identifiers, used by Alembic.
revision = '849170064430'
down_revision = 'a63df077051a'
from alembic import op
import sqlalchemy as sa
def upgrade():
try:
... | Add try-except block to queue migration script | Add try-except block to queue migration script
| Python | agpl-3.0 | privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea |
62e73be09289c9334c6833c205ba8580945bbafc | swh/web/ui/tests/views/test_main.py | swh/web/ui/tests/views/test_main.py | # Copyright (C) 2016 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU Affero General Public License version 3, or any later version
# See top-level LICENSE file for more information
from nose.tools import istest
from .. import test_app
class Main... | # Copyright (C) 2016 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU Affero General Public License version 3, or any later version
# See top-level LICENSE file for more information
from nose.tools import istest
from .. import test_app
class Main... | Comment out test on /about/ | api: Comment out test on /about/
Related fb0bf65356aa6a6fd6cfb6e29122e1f45925d21c
| Python | agpl-3.0 | SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui |
ee1deb28a2c32b7e35a2132542edd69f3c785c9c | django/projects/mysite/run-gevent.py | django/projects/mysite/run-gevent.py | #!/usr/bin/env python
# Import gevent monkey and patch everything
from gevent import monkey
monkey.patch_all(httplib=True)
# Import the rest
from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp
from django.core.management import setup_environ
from gevent.wsgi import WSGIServer
import sys
import settings... | #!/usr/bin/env python
# Import gevent monkey and patch everything
from gevent import monkey
monkey.patch_all()
# Import the rest
from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp
from django.core.management import setup_environ
from gevent.wsgi import WSGIServer
import sys
import settings
setup_envi... | Fix httplib monkey patching problem with Gevent >= 1.0 | Fix httplib monkey patching problem with Gevent >= 1.0
From v1.0 on, Gevent doesn't support monkey patching of httplib anymore.
CATMAID's example script to run a Gevent WSGI server, however, was still
expecting this to be possible. This commit fixes this.
Thanks to Mikhail Kandel for reporting.
| Python | agpl-3.0 | fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,htem/CATMAID |
d5122206fe5c8e0d60fd19f08a64962577be931e | manage.py | manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
if 'test' in sys.argv and '--tag=pkg' in sys.argv:
settings = 'tola.settings.test_pkg'
os.environ['DJANGO_SETTINGS_MODULE'] = settings
elif 'test':
settings = 'tola.settings.test'
os.environ['DJANGO_SETTINGS_M... | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
if 'test' in sys.argv and '--tag=pkg' in sys.argv:
settings = 'tola.settings.test_pkg'
os.environ['DJANGO_SETTINGS_MODULE'] = settings
elif 'test' in sys.argv:
settings = 'tola.settings.test'
os.environ['DJANG... | Fix bug running always with test config in dev | Fix bug running always with test config in dev
| Python | apache-2.0 | toladata/TolaActivity,toladata/TolaActivity,toladata/TolaActivity,toladata/TolaActivity |
b3702552ab83b7910b7972512253a829bbc56488 | osgtest/tests/test_838_xrootd_tpc.py | osgtest/tests/test_838_xrootd_tpc.py | import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.service as service
import osgtest.library.osgunittest as osgunittest
class TestStopXrootdTPC(osgunittest.OSGTestCase):
@core.elrelease(7,8)
def test_01_stop_xrootd(self):
if core.state['xrootd.tpc.backups-e... | import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.service as service
import osgtest.library.osgunittest as osgunittest
class TestStopXrootdTPC(osgunittest.OSGTestCase):
@core.elrelease(7,8)
def setUp(self):
core.skip_ok_unless_installed("xrootd",
... | Add xrootd and non-el6 check for xrootd-tpc cleanup too | Add xrootd and non-el6 check for xrootd-tpc cleanup too
| Python | apache-2.0 | efajardo/osg-test,efajardo/osg-test |
ff19e1e6028ab53f20740845b4317782a0d088cc | static_html_generation/tests/layers_interpretations_tests.py | static_html_generation/tests/layers_interpretations_tests.py | from layers.interpretations import InterpretationsLayer
from unittest import TestCase
class InterpretationsLayerTest(TestCase):
def test_apply_layer(self):
return # @todo refactor this test to use the new format
layer = {
"200-2-b": [{
"reference": "200-Interp... | from layers.interpretations import InterpretationsLayer
from mock import Mock, patch
from unittest import TestCase
class InterpretationsLayerTest(TestCase):
@patch('layers.interpretations.api_reader')
def test_apply_layer_extra_fields(self, api_reader):
layer = {
"200-2-b-3-i": [{
... | Test for the new fields | Test for the new fields
| Python | cc0-1.0 | EricSchles/regulations-site,tadhg-ohiggins/regulations-site,ascott1/regulations-site,adderall/regulations-site,jeremiak/regulations-site,adderall/regulations-site,jeremiak/regulations-site,ascott1/regulations-site,willbarton/regulations-site,adderall/regulations-site,EricSchles/regulations-site,ascott1/regulations-site... |
8c480f7b566047655d45cf675d9d803c15e6d19d | Lib/ctypes/test/test_unaligned_structures.py | Lib/ctypes/test/test_unaligned_structures.py | import sys, unittest
from ctypes import *
structures = []
byteswapped_structures = []
if sys.byteorder == "little":
SwappedStructure = BigEndianStructure
else:
SwappedStructure = LittleEndianStructure
for typ in [c_short, c_int, c_long, c_longlong,
c_float, c_double,
c_... | import sys, unittest
from ctypes import *
structures = []
byteswapped_structures = []
if sys.byteorder == "little":
SwappedStructure = BigEndianStructure
else:
SwappedStructure = LittleEndianStructure
for typ in [c_short, c_int, c_long, c_longlong,
c_float, c_double,
c_ushort, c_uint... | Add missing SVN eol-style property to text files. | Add missing SVN eol-style property to text files.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
ffee056415e7d1d1bcd0bb0a1c42a506ab0cd6af | mozcal/admin/forms.py | mozcal/admin/forms.py | from django.forms import ModelForm
from mozcal.events.models import Event, Space
class EventForm(ModelForm):
class Meta:
model = Event
class SpaceForm(ModelForm):
class Meta:
model = Space
| from django.forms import ModelForm
from mozcal.events.models import Event, Space
class EventForm(ModelForm):
class Meta:
model = Event
fields = ['title', 'space', 'start', 'end', 'areas', 'description', 'details']
class SpaceForm(ModelForm):
class Meta:
model = Space
fields = ['name', 'address'... | Add fields properties to all form Meta classes | Add fields properties to all form Meta classes
| Python | bsd-3-clause | ppapadeas/wprevents,yvan-sraka/wprevents,yvan-sraka/wprevents,yvan-sraka/wprevents,ppapadeas/wprevents,yvan-sraka/wprevents,ppapadeas/wprevents |
039d7bc7f19add23670fc387b3091293d2ed94ce | parser.py | parser.py | #!/usr/bin/env python
from config import MongoSource
from manager import PluginManager
from log import LogDocGenerator
def main():
# 1. load all plugins
plugin_manager = PluginManager()
# 2. get one or more mongodb collection
ms = MongoSource()
collection = ms.get_collection("net-test", "ename_... | #!/usr/bin/env python
from config import MongoSource
from manager import PluginManager
from log import LogDocGenerator
import datetime
def main():
# 1. load all plugins
plugin_manager = PluginManager()
# 2. get one or more mongodb collection
ms = MongoSource()
collection = ms.get_collection("ne... | Add example for query datetime range | Add example for query datetime range
| Python | apache-2.0 | keepzero/fluent-mongo-parser |
4961967ab70fc33361954314553613fe6e8b4851 | pyV2S.py | pyV2S.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
from file_manager.vhdl_reader import Vhdl_reader
from decorator.pdfdrawer import PdfDrawer
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
filename = str(sys.argv[1])
reader = Vhdl_reader(filename)
drawe... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
from file_manager.vhdl_reader import Vhdl_reader
from decorator.pdfdrawer import PdfDrawer
import sys
try:
filename = str(sys.argv[1])
except:
filename = "datas/test_files/demo.vhd"
reader = Vhdl_reader(filename)
drawer = PdfDrawer("%s.pdf" % reader.entity.name... | Add a demo mode : if no vhdl file is given the demo one is used datas/test_files/demo.vhd | Add a demo mode :
if no vhdl file is given the demo one is used
datas/test_files/demo.vhd
| Python | bsd-2-clause | LaurentCabaret/pyVhdl2Sch,LaurentCabaret/pyVhdl2Sch |
04923693f30dc2eb41a0b2e406645a1dea29b4c7 | setup.py | setup.py | from distutils.core import setup
setup(
name='Flask-Roots',
version='0.0.1',
description='Lightweight personal git server.',
url='http://github.com/mikeboers/Flask-Roots',
packages=['flask_roots'],
author='Mike Boers',
author_email='flask-roots@mikeboers.com',
license='BSD-3',... | from distutils.core import setup
setup(
name='Flask-Roots',
version='0.0.1',
description='Lightweight personal git server.',
url='http://github.com/mikeboers/Flask-Roots',
packages=['flask_roots'],
author='Mike Boers',
author_email='flask-roots@mikeboers.com',
license='BSD-3',... | Tidy up the installation process a little | Tidy up the installation process a little
| Python | bsd-3-clause | mikeboers/Flask-Roots,mikeboers/Flask-Roots |
5caa22112a11f2cabdacd8302536580012a2bf98 | setup.py | setup.py | from distutils.core import setup
from pexpect import __version__
setup (name='pexpect',
version=__version__,
py_modules=['pxssh', 'fdpexpect', 'FSM', 'screen', 'ANSI'],
packages=['pexpect'],
description='Pexpect allows easy control of interactive console applications.',
author='Noah Spurrier; Thom... | from distutils.core import setup
from pexpect import __version__
setup (name='pexpect',
version=__version__,
py_modules=['pxssh', 'fdpexpect', 'FSM', 'screen', 'ANSI'],
packages=['pexpect'],
description='Pexpect allows easy control of interactive console applications.',
author='Noah Spurrier; Thom... | Fix Trove classifiers to allow PyPI upload | Fix Trove classifiers to allow PyPI upload
| Python | isc | dongguangming/pexpect,crdoconnor/pexpect,nodish/pexpect,dongguangming/pexpect,blink1073/pexpect,Depado/pexpect,quatanium/pexpect,nodish/pexpect,bangi123/pexpect,bangi123/pexpect,Wakeupbuddy/pexpect,Wakeupbuddy/pexpect,nodish/pexpect,crdoconnor/pexpect,bangi123/pexpect,quatanium/pexpect,Depado/pexpect,crdoconnor/pexpect... |
792e073317f75f4b9a687c4a647a2b7f9f5656c1 | test_project/runtests.py | test_project/runtests.py | #This file mainly exists to allow python setup.py test to work.
import os, sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_project.settings'
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
from django.test.utils import get_runner
from django.conf import settings
def runtests():
test_runner = ... | #This file mainly exists to allow python setup.py test to work.
import os, sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_project.settings'
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
from django.test.utils import get_runner
from django.conf import settings
def runtests():
test_runner = ... | Fix the running of tests. Wonder if this is a django regression. | Fix the running of tests. Wonder if this is a django regression.
| Python | mit | ericholscher/django-test-utils,frac/django-test-utils,ericholscher/django-test-utils,acdha/django-test-utils,frac/django-test-utils,acdha/django-test-utils |
12d021a546a8af3ceccfc0a705d03c9cb8dbdba3 | flocker/route/functional/__init__.py | flocker/route/functional/__init__.py | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Tests for :py:mod:`flocker.route`.
"""
| # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Tests for :py:mod:`flocker.route`.
"""
from eliot.twisted import redirectLogsForTrial
redirectLogsForTrial()
del redirectLogsForTrial
| Send eliot logs to trial output. | Send eliot logs to trial output.
| Python | apache-2.0 | w4ngyi/flocker,AndyHuu/flocker,jml/flocker,beni55/flocker,achanda/flocker,1d4Nf6/flocker,AndyHuu/flocker,jml/flocker,Azulinho/flocker,agonzalezro/flocker,LaynePeng/flocker,adamtheturtle/flocker,adamtheturtle/flocker,wallnerryan/flocker-profiles,agonzalezro/flocker,1d4Nf6/flocker,beni55/flocker,Azulinho/flocker,hackday-... |
1731bb581eff4cb62100863cea23af81cd8f2ef5 | tests/e2e/client/main.py | tests/e2e/client/main.py | import argparse
import sys
import requests
def main(url):
requests.get(url + 'refresh')
response = requests.get(url + 'test')
print(response.text)
if response.status_code != 200:
sys.exit(1)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('url')
... | import argparse
import sys
import requests
def main(url):
response = requests.get(url + 'refresh')
if response.status_code != 200:
print(response.status_code)
print(response.headers)
print(response.text)
sys.exit(1)
response = requests.get(url + 'test')
print(respons... | Add error checking and more verbose error messages. | Add error checking and more verbose error messages.
| Python | apache-2.0 | GoogleCloudPlatform/python-compat-runtime,GoogleCloudPlatform/python-compat-runtime,GoogleCloudPlatform/python-compat-runtime,GoogleCloudPlatform/python-compat-runtime,GoogleCloudPlatform/python-compat-runtime |
01eb74ebca81f79ab829073f163b028d3e98f055 | setup.py | setup.py | '''
cd dropbox/codes/check_forbidden
py -3.4 setup.py py2exe
Libraries used:
import tkinter
import tkinter.filedialog
import csv
import os
import re
from time import sleep
import zipfile
'''
from distutils.core import setup
import py2exe
setup(
console=[{'author': 'Shun Sakurai',
... | '''
cd dropbox/codes/check_forbidden
py -3.4 setup.py py2exe
Libraries used:
import tkinter
import tkinter.filedialog
import csv
import os
import re
from time import sleep
import zipfile
'''
from distutils.core import setup
import py2exe
setup(
console=[{'author': 'Shun Sakurai',
... | Change the application name to 'Check Forbidden' | Change the application name to 'Check Forbidden'
| Python | mit | ShunSakurai/check_forbidden,ShunSakurai/check_forbidden |
6c3c379d414a0c9bfde81ff8daa0e1d40aa7a658 | setup.py | setup.py | from distutils.core import setup
import traitscli
setup(
name='traitscli',
version=traitscli.__version__,
py_modules=['traitscli'],
author=traitscli.__author__,
author_email='aka.tkf@gmail.com',
url='https://github.com/tkf/traitscli',
license=traitscli.__license__,
description='traitsc... | from distutils.core import setup
import traitscli
setup(
name='traitscli',
version=traitscli.__version__,
py_modules=['traitscli'],
author=traitscli.__author__,
author_email='aka.tkf@gmail.com',
url='https://github.com/tkf/traitscli',
license=traitscli.__license__,
description='traitsc... | Add argparse to install_requires for Python 2.6 | Add argparse to install_requires for Python 2.6
| Python | bsd-3-clause | tkf/traitscli,tkf/traitscli |
259555775c098153b1715f85561309b42e29ee7d | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
from avena import avena
_classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Progra... | #!/usr/bin/env python
from distutils.core import setup
from avena import avena
_classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Progra... | Install the script with the library. | Install the script with the library.
| Python | isc | eliteraspberries/avena |
6db55e993cb4a93aeede2cd9aff244e2c517fa06 | setup.py | setup.py | from distutils.core import setup
setup(
name='firebase-token-generator',
version='1.2',
author='Greg Soltis',
author_email='greg@firebase.com',
py_modules=['firebase_token_generator'],
license='LICENSE',
url='https://github.com/firebase/PyFirebaseTokenGenerator',
description='A utility ... | from distutils.core import setup
setup(
name='firebase-token-generator',
version='1.2',
author='Greg Soltis',
author_email='greg@firebase.com',
py_modules=['firebase_token_generator'],
license='LICENSE',
url='https://github.com/firebase/firebase-token-generator-python',
description='A u... | Fix repo URL after rename | Fix repo URL after rename
| Python | mit | googlearchive/firebase-token-generator-python |
f764b52558cb02b8e31b9695a724e4c4e80872dd | iscc_bench/readers/__init__.py | iscc_bench/readers/__init__.py | # -*- coding: utf-8 -*-
from iscc_bench.readers.bxbooks import bxbooks
from iscc_bench.readers.dnbrdf import dnbrdf
from iscc_bench.readers.harvard import harvard
from iscc_bench.readers.openlibrary import openlibrary
from iscc_bench.readers.libgen import libgen
ALL_READERS = (bxbooks, dnbrdf, harvard, openlibrary, ... | # -*- coding: utf-8 -*-
from iscc_bench.readers.bxbooks import bxbooks
from iscc_bench.readers.dnbrdf import dnbrdf
from iscc_bench.readers.harvard import harvard
from iscc_bench.readers.openlibrary import openlibrary
from iscc_bench.readers.libgen import libgen
from iscc_bench.readers.caltech101 import caltech_101
fr... | Add image readers to package scope | Add image readers to package scope
| Python | bsd-2-clause | coblo/isccbench |
711c992a89f9a6118d2b274e2a526be62e670a92 | examples/flask_server.py | examples/flask_server.py | from flask import Flask, request # type: ignore
from jsonrpcserver import method, dispatch, Result, Success
app = Flask(__name__)
@method
def ping() -> Result:
return Success("pong")
@app.route("/", methods=["POST"])
def index() -> str:
return dispatch(request.get_data().decode())
if __name__ == "__main... | from flask import Flask, Response, request # type: ignore
from jsonrpcserver import Result, Success, dispatch, method
app = Flask(__name__)
@method
def ping() -> Result:
return Success("pong")
@app.route("/", methods=["POST"])
def index() -> str:
return Response(
dispatch(request.get_data().decode... | Set content-type in flask example | Set content-type in flask example
| Python | mit | bcb/jsonrpcserver |
8d01e536f0d3ce3332b3538155f0a5dd11cef16d | csv2ofx/mappings/gls.py | csv2ofx/mappings/gls.py | # coding: utf-8
from __future__ import absolute_import
from operator import itemgetter
mapping = {
'has_header': True,
'currency': 'EUR',
'delimiter': ';',
'bank': 'GLS Bank',
'account': itemgetter('Kontonummer'),
# Chop up the dotted German date format and put it in ridiculous M/D/Y order
... | # coding: utf-8
from __future__ import absolute_import
from operator import itemgetter
mapping = {
'has_header': True,
'currency': 'EUR',
'delimiter': ';',
'bank': 'GLS Bank',
'account': itemgetter('Kontonummer'),
# Chop up the dotted German date format and put it in ridiculous M/D/Y order
... | Add comment about python2.7 specific code. | Add comment about python2.7 specific code.
| Python | mit | reubano/csv2ofx,reubano/csv2ofx |
cfb995b21cbeac74b7ae80980ccd299c613d00db | ctypeslib/test/stdio.py | ctypeslib/test/stdio.py | import os
from ctypeslib.dynamic_module import include
from ctypes import *
import logging
logging.basicConfig(level=logging.INFO)
if os.name == "nt":
_libc = CDLL("msvcrt")
else:
_libc = CDLL(None)
include("""\
#include <stdio.h>
#ifdef _MSC_VER
# include <fcntl.h>
#else
# include <sys/fcntl.h>
#endif
"""... | import os
from ctypeslib.dynamic_module import include
from ctypes import *
if os.name == "nt":
_libc = CDLL("msvcrt")
else:
_libc = CDLL(None)
include("""\
#include <stdio.h>
#ifdef _MSC_VER
# include <fcntl.h>
#else
# include <sys/fcntl.h>
#endif
""",
persist=False)
| Remove the logging setup call. | Remove the logging setup call.
git-svn-id: ac2c3632cb6543e7ab5fafd132c7fe15057a1882@52678 6015fed2-1504-0410-9fe1-9d1591cc4771
| Python | mit | luzfcb/ctypeslib,trolldbois/ctypeslib,trolldbois/ctypeslib,luzfcb/ctypeslib,luzfcb/ctypeslib,trolldbois/ctypeslib |
7a7e824b63c4498ee12c59a6af459e6fe8639003 | server.py | server.py | import bottle
import waitress
import controller
import breathe
from pytz import timezone
from apscheduler.schedulers.background import BackgroundScheduler
bottle_app = bottle.app()
scheduler = BackgroundScheduler()
scheduler.configure(timezone=timezone('US/Pacific'))
breather = breathe.Breathe()
my_controller = contro... | import bottle
from cso_parser import CsoParser
import waitress
from pytz import timezone
from apscheduler.schedulers.background import BackgroundScheduler
from breathe import Breathe
from controller import Controller
bottle_app = bottle.app()
scheduler = BackgroundScheduler()
scheduler.configure(timezone=timezone('US/... | Add scheduled cso_job method - Retrieves the CSO status and updates the breathe rate | Add scheduled cso_job method
- Retrieves the CSO status and updates the breathe rate
| Python | mit | tipsqueal/duwamish-lighthouse,tipsqueal/duwamish-lighthouse,illumenati/duwamish-lighthouse,illumenati/duwamish-lighthouse |
6382a5d47f720d62c596a9f7dd24f6d0aa9dff55 | plugins/invitejoiner/invitejoiner.py | plugins/invitejoiner/invitejoiner.py |
import plugin
from twisted.python import log
class Invitejoiner(plugin.Plugin):
def __init__(self):
plugin.Plugin.__init__(self, "Invitejoiner")
def invited(self, server_id, channel):
log.msg("Invited to: ", channel)
self.join(server_id, channel)
Invitejoiner.run()
|
import plugin
from twisted.python import log
class Invitejoiner(plugin.Plugin):
def __init__(self):
plugin.Plugin.__init__(self, "Invitejoiner")
def invited(self, server_id, channel):
log.msg("Invited to: ", channel)
self.join(server_id, channel)
if __name__ == "__main__":
sys.... | Fix starting the Invitejoiner plugin | Fix starting the Invitejoiner plugin
| Python | mit | Tigge/platinumshrimp |
0f4c1b69753450802c1e8a438544b41cf705e92a | backend/api_access/main.py | backend/api_access/main.py | import pandas as pd
import geonames as gn
#Enter csv path
path = "/Users/larshelin/Documents/PycharmProjects/CEP/nyc-taxi/backend/parser/trips_shortend.csv"
#Open Dataframe
df = pd.read_csv(path)
for i in range(0,10):
# Get Latitude and Longitude
lat = df.ix[i]['pickup_latitude']
long = df.ix[i]['pickup_... | import pandas as pd
import geonames as gn
#Enter csv path
path = "/Users/larshelin/Documents/PycharmProjects/CEP/nyc-taxi/backend/parser/trips_shortend.csv"
#Open Dataframe
df = pd.read_csv(path)
for i in range(0,10):
# Get Latitude and Longitude
lat = df.ix[i]['pickup_latitude']
long = df.ix[i]['pickup_... | Change the way data is printed | Change the way data is printed
| Python | mit | nikha1/nyc-taxi,nikha1/nyc-taxi,nikha1/nyc-taxi |
91e8878764fd9914d56b01da7b8bbbbb37258a20 | tests.py | tests.py | #!/usr/bin/python -O
import sqlite3
from parser import SQLITE3_DB_NAME
from random import randint, randrange
def main():
""" Ouputs a random clue (with game ID) from 10 random games for checking. """
sql = sqlite3.connect(SQLITE3_DB_NAME)
# list of random game id numbers
gids = [randint(1, 3790) for i in xran... | #!/usr/bin/python -O
# -*- coding: utf-8 -*-
import sqlite3
from parser import SQLITE3_DB_NAME
from random import randint, randrange
def main():
""" Ouputs a random clue (with game ID) from 10 random games for checking. """
sql = sqlite3.connect(SQLITE3_DB_NAME)
# list of random game id numbers
gids = [randin... | Test script to UTF-8 and output category. | Test script to UTF-8 and output category.
| Python | mit | dangoldin/jeopardy-parser,dangoldin/jeopardy-parser,whymarrh/jeopardy-parser |
fcffabef406cd0d983e4754c58c76760f0204357 | pywikibot/families/commons_family.py | pywikibot/families/commons_family.py | # -*- coding: utf-8 -*-
__version__ = '$Id$'
from pywikibot import family
# The Wikimedia Commons family
class Family(family.WikimediaFamily):
def __init__(self):
super(Family, self).__init__()
self.name = 'commons'
self.langs = {
'commons': 'commons.wikimedia.org',
... | # -*- coding: utf-8 -*-
__version__ = '$Id$'
from pywikibot import family
# The Wikimedia Commons family
class Family(family.WikimediaFamily):
def __init__(self):
super(Family, self).__init__()
self.name = 'commons'
self.langs = {
'commons': 'commons.wikimedia.org',
... | Enable Wikidata for Wikimedia Commons | Enable Wikidata for Wikimedia Commons
Change-Id: Ibc8734f65dcd97dc7af9674efe8655fe01dc61d3
| Python | mit | smalyshev/pywikibot-core,Darkdadaah/pywikibot-core,npdoty/pywikibot,jayvdb/pywikibot-core,magul/pywikibot-core,VcamX/pywikibot-core,h4ck3rm1k3/pywikibot-core,wikimedia/pywikibot-core,hasteur/g13bot_tools_new,darthbhyrava/pywikibot-local,wikimedia/pywikibot-core,hasteur/g13bot_tools_new,Darkdadaah/pywikibot-core,emijrp/... |
73d444c234ddb734ac14b688f6542750ea09de78 | api/init/graphqlapi/routes.py | api/init/graphqlapi/routes.py | from graphqlapi.proxy import proxy_request
from graphqlapi.interceptor import RequestException
from flask_restplus import Resource, fields, Namespace, Api
from docker.errors import APIError
from flask import request, jsonify, make_response
def register_graphql(namespace: Namespace, api: Api):
"""Method used to re... | from docker.errors import APIError
from flask import request, jsonify, make_response
from flask_restplus import Resource, fields, Namespace, Api
from graphqlapi.exceptions import RequestException
from graphqlapi.proxy import proxy_request
def register_graphql(namespace: Namespace, api: Api):
"""Method used to reg... | Reorder imports in alphabetical order | Reorder imports in alphabetical order
| Python | apache-2.0 | alexisrolland/data-quality,alexisrolland/data-quality,alexisrolland/data-quality,alexisrolland/data-quality |
d88c2b8c99c57a434209741a65bdb2751415ec3f | setuptools/command/install_scripts.py | setuptools/command/install_scripts.py | from distutils.command.install_scripts import install_scripts \
as _install_scripts
from easy_install import get_script_args
from pkg_resources import Distribution, PathMetadata, ensure_directory
import os
from distutils import log
class install_scripts(_install_scripts):
"""Do normal script install, plus an... | from distutils.command.install_scripts import install_scripts \
as _install_scripts
from easy_install import get_script_args
from pkg_resources import Distribution, PathMetadata, ensure_directory
import os
from distutils import log
class install_scripts(_install_scripts):
"""Do normal script install, plus any... | Fix "legacy mode" trying to install scripts when there are none. | Fix "legacy mode" trying to install scripts when there are none.
--HG--
branch : setuptools
extra : convert_revision : svn%3A6015fed2-1504-0410-9fe1-9d1591cc4771/sandbox/trunk/setuptools%4041777
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools |
56236454f252ab8feee461c49c26b9eee70a7e09 | vpython/_vector_import_helper.py | vpython/_vector_import_helper.py | import platform
try:
if platform.python_implementation() == 'PyPy':
from .vector import * # use pure python vector for PyPy
else:
from .cyvector import *
v = vector(0,0,0)
except:
from .vector import *
# synonyms in GlowScript
vec = vector
| import platform
try:
if platform.python_implementation() == 'PyPy':
from .vector import * # use pure python vector for PyPy
else:
from .cyvector import *
v = vector(0,0,0)
except:
from .vector import *
# Remove platform from the namespace now that we are done with it
del platfor... | Delete platform so that it doesn't end up in the user's namespace | Delete platform so that it doesn't end up in the user's namespace
| Python | mit | BruceSherwood/vpython-jupyter,mwcraig/vpython-jupyter,BruceSherwood/vpython-jupyter,mwcraig/vpython-jupyter,mwcraig/vpython-jupyter,mwcraig/vpython-jupyter,BruceSherwood/vpython-jupyter,BruceSherwood/vpython-jupyter |
8c4059b9467b586ba54e387c9cf7f134a71aaba8 | utils.py | utils.py | import os
from google.appengine.api import apiproxy_stub_map
from google.appengine.api.app_identity import get_application_id
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
def appid():
if have_appserver:
return get_application_id()
else:
try:
from .boot... | import os
from google.appengine.api import apiproxy_stub_map
from google.appengine.api.app_identity import get_application_id
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if not have_appserver:
from .boot import PROJECT_DIR
from google.appengine.tools import dev_appserver
app... | Fix a bug introduced in the last commit | Fix a bug introduced in the last commit
| Python | bsd-3-clause | potatolondon/djangoappengine-1-4,potatolondon/djangoappengine-1-4 |
7558ffc73ebb6300e186fe508497a32acbc0c5ae | src/pythonic/test_primes.py | src/pythonic/test_primes.py | import pytest
import itertools
from main import Primes, Sieve
def test_sieve_limit():
limit = 10000
with Sieve(limit) as s:
assert s.upper_bound() >= limit
def test_upper_bound_exception():
limit = 10
with Sieve(limit) as s:
with pytest.raises(IndexError):
s.is_prime(101)... | import pytest
import itertools
from main import Primes, Sieve
def test_sieve_limit():
limit = 10000
with Sieve(limit) as s:
assert s.upper_bound() >= limit
def test_checking_above_upper_bound_is_an_error():
limit = 10
with Sieve(limit) as s:
with pytest.raises(IndexError):
... | Reword guard test on upper bounds | Reword guard test on upper bounds
| Python | cc0-1.0 | Michael-F-Bryan/rust-ffi-guide,Michael-F-Bryan/rust-ffi-guide,Michael-F-Bryan/rust-ffi-guide |
8036a12794f61192dbd8639c84395d8cbb31fb31 | axes_login_actions/signals.py | axes_login_actions/signals.py | # -*- coding: utf-8 -*-
from axes.models import AccessAttempt
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.importlib import import_module
DEFAULT_ACTION = 'axes_login_actions.actions.email.notify'
ACTIONS = getattr(settings, 'A... | # -*- coding: utf-8 -*-
from axes.models import AccessAttempt
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from importlib import import_module
DEFAULT_ACTION = 'axes_login_actions.actions.email.notify'
ACTIONS = getattr(settings, 'AXES_LOGIN_ACT... | Use importlib from Python instead from Django | Use importlib from Python instead from Django
| Python | bsd-3-clause | eht16/django-axes-login-actions |
8e4f09592d6b4d681a62026b56dca29abeed88d7 | backend/scripts/ddirdenorm.py | backend/scripts/ddirdenorm.py | #!/usr/bin/env python
import rethinkdb as r
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
(options, args) = parser.parse_args()
conn = r.connect('localhost', int(op... | #!/usr/bin/env python
import rethinkdb as r
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
(options, args) = parser.parse_args()
conn = r.connect('localhost', int(op... | Handle non-existent files in the database. | Handle non-existent files in the database.
| Python | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org |
e2fdee671e23fe06cc191b4940f611369c9e90b5 | waterfall_wall/models.py | waterfall_wall/models.py | # This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free ... | # This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free ... | Fix model id to auto increment | Fix model id to auto increment
| Python | mit | carlcarl/rcard,carlcarl/rcard |
fd95be0137f23643d99e49b2acdaf28a73e0ae43 | read_FVCOM_results.py | read_FVCOM_results.py | from netCDF4 import Dataset, MFDataset
def readFVCOM(file, varList, noisy=False):
"""
Read in the FVCOM results file and spit out numpy arrays for
each of the variables.
"""
rootgrp = Dataset(file, 'r')
mfdata = MFDataset(file)
if noisy:
print "File format: " + rootgrp.file_format... |
def readFVCOM(file, varList, noisy=False):
"""
Read in the FVCOM results file and spit out numpy arrays for
each of the variables.
"""
from netCDF4 import Dataset, MFDataset
rootgrp = Dataset(file, 'r')
mfdata = MFDataset(file)
if noisy:
print "File format: " + rootgrp.file_f... | Add function to extract surface elevation from a 2D array of surface elevations | Add function to extract surface elevation from a 2D array of surface elevations
| Python | mit | pwcazenave/PyFVCOM |
e3833d0c8352fa33e6b77200310edfdb96b2cd5a | chipy_org/libs/social_auth_pipelines.py | chipy_org/libs/social_auth_pipelines.py | from django.utils.translation import ugettext
from django.contrib.auth.models import User
from social_auth.backends.pipeline.user import create_user as social_auth_create_user
from social_auth.exceptions import AuthAlreadyAssociated
def create_user(backend, details, response, uid, username, user = None, is_new = Fals... | from django.utils.translation import ugettext
from django.contrib.auth.models import User
from social_auth.backends.pipeline.user import create_user as social_auth_create_user
from social_auth.exceptions import AuthAlreadyAssociated
def create_user(backend, details, response, uid, username, user=None, is_new=False, ... | Return the user in the pipeline if the backend is google oauth2 | Return the user in the pipeline if the backend is google oauth2
| Python | mit | bharathelangovan/chipy.org,brianray/chipy.org,chicagopython/chipy.org,agfor/chipy.org,tanyaschlusser/chipy.org,bharathelangovan/chipy.org,agfor/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,brianray/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,brianray/chipy.org,agfor/chipy.org,chicagopython/... |
46972788b2f4c3b3ac79e2d2fb9b8dd6a3834148 | src/yunohost/utils/error.py | src/yunohost/utils/error.py | # -*- coding: utf-8 -*-
""" License
Copyright (C) 2018 YUNOHOST.ORG
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) a... | # -*- coding: utf-8 -*-
""" License
Copyright (C) 2018 YUNOHOST.ORG
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) a... | Add comment about the motivation behind YunohostError | Add comment about the motivation behind YunohostError | Python | agpl-3.0 | YunoHost/yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost |
b2f5e71e15eec47efd1b8faed97ec614b78deaf6 | test/test_stream.py | test/test_stream.py | import pynmea2
from tempfile import TemporaryFile
def test_stream():
data = "$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000*6D\n"
sr = pynmea2.NMEAStreamReader()
assert len(sr.next('')) == 0
assert len(sr.next(data)) == 1
assert len(sr.next(data)) == 1
sr =... | from __future__ import print_function
import pynmea2
from tempfile import TemporaryFile
def test_stream():
data = "$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000*6D\n"
sr = pynmea2.NMEAStreamReader()
assert len(sr.next('')) == 0
assert len(sr.next(data)) == 1
ass... | Add compatibility with Python 3.3. | Add compatibility with Python 3.3.
| Python | mit | Knio/pynmea2,adamfazzari/pynmea2,ampledata/pynmea2,silentquasar/pynmea2,lobocv/pynmea2 |
6c73fd3ca1c6459a3a8987a2a5c77b0247eda128 | tests/test_users.py | tests/test_users.py | import pytest
from mock import patch, Mock
from spanky.lib import users
class TestCreateUsers(object):
def setup(self):
self.conf = [
{'username': 'foo'},
{'username': 'bar'},
]
self.user_init = users.UserInit(self.conf)
def test_build(self):
self.us... | import pytest
from mock import patch, Mock
from spanky.lib import users
class TestCreateUsers(object):
def setup(self):
self.conf = [
{'username': 'foo'},
{'username': 'bar'},
]
self.user_init = users.UserInit(self.conf)
def test_build(self):
self.us... | Create a test asserting the useradd command | Create a test asserting the useradd command
| Python | bsd-3-clause | pglbutt/spanky,pglbutt/spanky,pglbutt/spanky |
409722f0e075385e05a77513f6dbd9c3b540bfac | txpoloniex/const.py | txpoloniex/const.py | """
Constant values for the Poloniex API
"""
PUBLIC_API = 'https://poloniex.com/public'
PRIVATE_API = 'https://poloniex.com/tradingApi'
PUBLIC_COMMANDS = [
'returnTicker',
'return24hVolume',
'returnOrderBook',
'returnTradeHistory',
'returnChartData',
'returnCurrencies',
'returnLoanOrders',... | """
Constant values for the Poloniex API
"""
PUBLIC_API = 'https://poloniex.com/public'
PRIVATE_API = 'https://poloniex.com/tradingApi'
PUBLIC_COMMANDS = [
'returnTicker',
'return24hVolume',
'returnOrderBook',
'returnTradeHistory',
'returnChartData',
'returnCurrencies',
'returnLoanOrders',... | Add DATE_FORMAT for parsing any datetime strings | Add DATE_FORMAT for parsing any datetime strings
Poloniex seems to use a fixed output format for datetime strings
| Python | apache-2.0 | congruency/txpoloniex |
74f8b419083189ba666459888d1427193c38873e | netdisco/discoverables/apple_tv.py | netdisco/discoverables/apple_tv.py | """Discover Apple TV media players."""
from . import MDNSDiscoverable
# pylint: disable=too-few-public-methods
class Discoverable(MDNSDiscoverable):
"""Add support for Apple TV devices."""
def __init__(self, nd):
super(Discoverable, self).__init__(nd, '_appletv-v2._tcp.local.')
def info_from_ent... | """Discover Apple TV media players."""
import ipaddress
from . import MDNSDiscoverable
# pylint: disable=too-few-public-methods
class Discoverable(MDNSDiscoverable):
"""Add support for Apple TV devices."""
def __init__(self, nd):
super(Discoverable, self).__init__(nd, '_appletv-v2._tcp.local.')
... | Add missing host field to Apple TV | Add missing host field to Apple TV
| Python | mit | brburns/netdisco,balloob/netdisco |
2f074527b1c1a776d944aa4f487b2f35b388db28 | cities_light/tests/test_unicode_decode_error.py | cities_light/tests/test_unicode_decode_error.py | from __future__ import unicode_literals
import os
import mock
from django import test
from django.core.management import call_command
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
FIXTURE_DIR = os.path.abspath(os.path.join(BASE_DIR, 'tests', 'fixtures'))
def mock_source(setting, short_name): # noqa
re... | from __future__ import unicode_literals
import os
import mock
from django import test
from django.core.management import call_command
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
FIXTURE_DIR = os.path.abspath(os.path.join(BASE_DIR, 'tests', 'fixtures'))
def mock_source(setting, short_name): # noqa
re... | Patch settings from inside the command module | Patch settings from inside the command module
| Python | mit | greenday2/django-cities-light,yourlabs/django-cities-light,max-arnold/django-cities-light,KevinGrahamFoster/django-cities-light,max-arnold/django-cities-light |
4486fba6dd75dab67c25221653f2384455eda9be | tests/test_sorting_and_searching/test_binary_search.py | tests/test_sorting_and_searching/test_binary_search.py | import unittest
from sorting_and_searching import binary_search_recursive
class BinarySearchTestCase(unittest.TestCase):
'''
Unit tests for binary search
'''
def setUp(self):
self.example_1 = [2, 3, 4, 10, 40]
def test_binary_search_recursive(self):
result = binary_search_recurs... | import unittest
from aids.sorting_and_searching.binary_search import binary_search_recursive, binary_search_iterative
class BinarySearchTestCase(unittest.TestCase):
'''
Unit tests for binary search
'''
def setUp(self):
self.example_1 = [2, 3, 4, 10, 40]
def test_binary_search_recursive(... | Add unit tests for binary search recursive and iterative | Add unit tests for binary search recursive and iterative
| Python | mit | ueg1990/aids |
92204c154ab964d02faade72642a395356f1fa9b | aorun/losses.py | aorun/losses.py | import torch
def mean_squared_error(true, pred):
return torch.mean((true - pred)**2)
def binary_crossentropy(true, pred, eps=1e-9):
p1 = true * torch.log(pred + eps)
p2 = (1 - true) * torch.log(1 - pred + eps)
return torch.mean(-(p1 + p2))
def categorical_crossentropy(true, pred, eps=1e-9):
re... | import torch
def mean_squared_error(true, pred):
return ((true - pred)**2).mean()
def binary_crossentropy(true, pred, eps=1e-9):
p1 = true * torch.log(pred + eps)
p2 = (1 - true) * torch.log(1 - pred + eps)
return torch.mean(-(p1 + p2))
def categorical_crossentropy(true, pred, eps=1e-9):
retur... | Change error message to loss | Change error message to loss
| Python | mit | ramon-oliveira/aorun |
36950cf9cffd5083408bc257e37a846835029d58 | symposion/speakers/admin.py | symposion/speakers/admin.py | from django.contrib import admin
from markedit.admin import MarkEditAdmin
from symposion.speakers.models import Speaker
class SpeakerAdmin(MarkEditAdmin):
list_display = ["name", "email", "created", "twitter_username"]
search_fields = ["name", "twitter_username"]
class MarkEdit:
fields = ['biog... | from django.contrib import admin
from markedit.admin import MarkEditAdmin
from symposion.speakers.models import Speaker
class SpeakerAdmin(MarkEditAdmin):
list_display = ["name", "email", "created", "twitter_username"]
raw_id_fields = ["user"]
search_fields = ["name", "twitter_username"]
class Mark... | Fix user selection for speaker add | Fix user selection for speaker add
When adding a speaker in the admin, the staff person had to
pick a user from a huge dropdown with all the users, unsorted.
Change 'user' to a raw id field, meaning to pick a user, the staff member clicks a magnifying glass icon next to the field and gets a popup listing all the user... | Python | bsd-3-clause | PyCon/pycon,PyCon/pycon,PyCon/pycon,PyCon/pycon |
f0fcde0988b705de752aa20e08c4c05fb504af3d | oz/__init__.py | oz/__init__.py | """
Class for automated operating system installation.
Oz is a set of classes to do automated operating system installation. It
has built-in knowledge of the proper things to do for each of the supported
operating systems, so the data that the user must provide is very minimal.
This data is supplied in the form of an... | """
Class for automated operating system installation.
Oz is a set of classes to do automated operating system installation. It
has built-in knowledge of the proper things to do for each of the supported
operating systems, so the data that the user must provide is very minimal.
This data is supplied in the form of an... | Fix up the example to be proper XML. | Fix up the example to be proper XML.
Signed-off-by: Chris Lalancette <60b62644009db6b194cc0445b64e9b27bb26433a@redhat.com>
| Python | lgpl-2.1 | mgagne/oz,NeilBryant/oz,nullr0ute/oz,imcleod/oz,ndonegan/oz,NeilBryant/oz,moofrank/oz,imcleod/oz,ndonegan/oz,cernops/oz,mgagne/oz,nullr0ute/oz,moofrank/oz,clalancette/oz,clalancette/oz,cernops/oz |
3ae56f6dc4801013c272cf9b7472522510e4b807 | 1-multiples-of-3-and-5.py | 1-multiples-of-3-and-5.py | def multiples_of_3_and_5(num=1000):
for i in range(num):
if i % 3 == 0 or i % 5 == 0:
yield i
if __name__ == '__main__':
print(sum(multiples_of_3_and_5()))
| from itertools import chain
def threes_and_fives_gen(num=1000):
for i in range(num):
if i % 3 == 0 or i % 5 == 0:
yield i
def threes_and_fives_fun(n):
return set(chain(range(3, n+1, 3), range(5, n+1, 5)))
if __name__ == '__main__':
print(sum(threes_and_fives_gen(10000000)))
| Add fun answer to 1 multiples of 3 and 5 | Add fun answer to 1 multiples of 3 and 5
| Python | mit | dawran6/project-euler |
4817784c6e1050034faabb1b3d04382fe8997b41 | numpy/_array_api/_constants.py | numpy/_array_api/_constants.py | from ._array_object import ndarray
from ._dtypes import float64
import numpy as np
e = ndarray._new(np.array(np.e, dtype=float64))
inf = ndarray._new(np.array(np.inf, dtype=float64))
nan = ndarray._new(np.array(np.nan, dtype=float64))
pi = ndarray._new(np.array(np.pi, dtype=float64))
| import numpy as np
e = np.e
inf = np.inf
nan = np.nan
pi = np.pi
| Make the array API constants Python floats | Make the array API constants Python floats
| Python | bsd-3-clause | seberg/numpy,numpy/numpy,simongibbons/numpy,charris/numpy,mhvk/numpy,simongibbons/numpy,mattip/numpy,seberg/numpy,pdebuyl/numpy,mattip/numpy,charris/numpy,endolith/numpy,numpy/numpy,anntzer/numpy,jakirkham/numpy,mhvk/numpy,anntzer/numpy,endolith/numpy,seberg/numpy,endolith/numpy,mattip/numpy,simongibbons/numpy,numpy/nu... |
b24ae1320af5387e339a12dc00e214330525e549 | src/BibleBot.Frontend/application.py | src/BibleBot.Frontend/application.py | """
Copyright (C) 2016-2022 Kerygma Digital Co.
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this file,
You can obtain one at https://mozilla.org/MPL/2.0/.
"""
import disnake
from disnake.ext import commands
from log... | """
Copyright (C) 2016-2022 Kerygma Digital Co.
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this file,
You can obtain one at https://mozilla.org/MPL/2.0/.
"""
import disnake
from disnake.ext import commands
from log... | Move commands out of test. | Move commands out of test.
| Python | mpl-2.0 | BibleBot/BibleBot,BibleBot/BibleBot,BibleBot/BibleBot |
18925af2a74c20e86867bce9c480b5cd710b6b32 | openbudgets/apps/sheets/utilities.py | openbudgets/apps/sheets/utilities.py | from django.conf import settings
def is_comparable():
"""Sets the value of TemplateNode.comparable to True or False."""
value = settings.OPENBUDGETS_COMPARABLE_TEMPLATENODE_DEFAULT
return value
| from django.conf import settings
def is_node_comparable(instance):
"""Sets the value of TemplateNode.comparable to True or False.
Relies on the non-abstract TemplateNode implementation where nodes
can belong to many templates.
"""
value = settings.OPENBUDGETS_COMPARABLE_TEMPLATENODE
if al... | Set comparable state of node. | Set comparable state of node.
| Python | bsd-3-clause | openbudgets/openbudgets,openbudgets/openbudgets,pwalsh/openbudgets,pwalsh/openbudgets,openbudgets/openbudgets,pwalsh/openbudgets |
dae46049bd72ce1599fd4169e3d8d6bd8ca1c622 | drfdocs/api_docs.py | drfdocs/api_docs.py | from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
class ApiDocumentation(object):
excluded_apps = ["admin", "drfdocs"]
root_urlconf = __import__(settings.ROOT_URLCONF)
def __init__(self):
self.view_names = []
self.get_all_view_names(se... | from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
class ApiDocumentation(object):
excluded_apps = ["admin", "drfdocs"]
excluded_endpoints = ["serve"]
root_urlconf = __import__(settings.ROOT_URLCONF)
def __init__(self):
self.view_names = []... | Exclude "serve" view (static files) | Exclude "serve" view (static files)
| Python | bsd-2-clause | manosim/django-rest-framework-docs,ekonstantinidis/django-rest-framework-docs,manosim/django-rest-framework-docs,manosim/django-rest-framework-docs,ekonstantinidis/django-rest-framework-docs,ekonstantinidis/django-rest-framework-docs |
02cb413b8e6671cead4ec9af55acef2daf451fc0 | contributr/contributr/wsgi.py | contributr/contributr/wsgi.py | """
WSGI config for contributr project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
os.e... | """
WSGI config for contributr project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
if os.environ.get("DJANGO_SETTIN... | Move production Cling settings into production-only block | Move production Cling settings into production-only block
The Cling import and call are moved into an if-block that is only
executed when the server is run with production settings. This
makes the server run locally again.
Resolves: #42
| Python | mit | SanketDG/contributr,iAmMrinal0/contributr,sofianugraha/contributr,nickpolet/contributr,Heasummn/contributr,JoshAddington/contributr,sofianugraha/contributr,troyleak/contributr,nickpolet/contributr,iAmMrinal0/contributr,SanketDG/contributr,planetirf/contributr,planetirf/contributr,planetirf/contributr,kakorrhaphio/contr... |
e63a9430d9ad4d6bbfd6af66b1de617e71490c2c | countylimits/views.py | countylimits/views.py | from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from countylimits.models import CountyLimit
@api_view(['GET'])
def county_limits(request):
""" Return all counties with their limits per state. """
... | from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from countylimits.models import CountyLimit
@api_view(['GET'])
def county_limits(request):
""" Return all counties with their limits per state. """
... | Return 400 when state is invalid | Return 400 when state is invalid
| Python | cc0-1.0 | amymok/owning-a-home-api,cfpb/owning-a-home-api,fna/owning-a-home-api |
c8de08c451943f8fc428a611575f1329024e001a | webmention_plugin.py | webmention_plugin.py | from webmentiontools.send import WebmentionSend
from webmentiontools.urlinfo import UrlInfo
def handle_new_or_edit(post):
url = post.permalink_url
in_reply_to = post.in_reply_to
if url and in_reply_to:
print "Sending webmention {} to {}".format(url, in_reply_to)
sender = WebmentionSend(... | from webmentiontools.send import WebmentionSend
from webmentiontools.urlinfo import UrlInfo
def handle_new_or_edit(post):
url = post.permalink_url
in_reply_to = post.in_reply_to
if url and in_reply_to:
print "Sending webmention {} to {}".format(url, in_reply_to)
sender = WebmentionSend(... | Add some debugging output to webmentions | Add some debugging output to webmentions
| Python | bsd-2-clause | Lancey6/redwind,thedod/redwind,thedod/redwind,Lancey6/redwind,Lancey6/redwind |
1046d952415fe48da1d2c06a5abb6e8e31074fab | arc_distance.py | arc_distance.py | from math import cos,sqrt
import numpy as np
from scipy.optimize import fsolve
def func(p, *data):
x,y = p
i,j,r = data
return ((x+r)*(i-x)+(j-y)*y,(x+r)**2+y**2-r**2)
data = (-7,10,5)
x,y = fsolve(func, [1,1], args=data)
print x,y
d = sqrt((data[0]-x)**2+(data[1]-y)**2)
print d
#make a change | from math import cos,sqrt
import numpy as np
from scipy.optimize import fsolve
def func(p, *data):
x,y = p
i,j,r = data
return ((x+r)*(i-x)+(j-y)*y,(x+r)**2+y**2-r**2)
data = (-7,10,5)
x,y = fsolve(func, [1,1], args=data)
print x,y
d = sqrt((data[0]-x)**2+(data[1]-y)**2)
print d
| Revert "Added files via upload" | Revert "Added files via upload"
This reverts commit d93c66fc467a9899343eacdd85e90bdfe8a0dbd3.
| Python | apache-2.0 | limatthewk/UAVs |
6d0b2b5787be4d3a23fa74eccebb4935cb85d48b | salt/runners/state.py | salt/runners/state.py | '''
Execute overstate functions
'''
# Import salt libs
import salt.overstate
import salt.output
def over(env='base', os_fn=None):
'''
Execute an overstate sequence to orchestrate the executing of states
over a group of systems
'''
stage_num = 0
overstate = salt.overstate.OverState(__opts__, e... | '''
Execute overstate functions
'''
# Import salt libs
import salt.overstate
import salt.output
def over(env='base', os_fn=None):
'''
Execute an overstate sequence to orchestrate the executing of states
over a group of systems
'''
stage_num = 0
overstate = salt.overstate.OverState(__opts__, e... | Fix traceback because outputter expects data in {'host', data.. } format | Fix traceback because outputter expects data in {'host', data.. } format
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
9f091fcc572eb6a65592f828818b34d3e1269083 | alg_bellman_ford_shortest_path.py | alg_bellman_ford_shortest_path.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def bellman_ford(w_graph_d, start_vertex):
"""Bellman-Ford algorithm for weighted / negative graph.
"""
pass
def main():
w_graph_d = {
's': {'a': 2, 'b': 6},
'a': {'b': 3},
... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def bellman_ford(w_graph_d, start_vertex):
"""Bellman-Ford algorithm for weighted / negative graph.
"""
pass
def main():
w_graph_d = {
's': {'a': 2, 'b': 6},
'a': {'b': 3, 'c'... | Revise main()'s weighted negative graph | Revise main()'s weighted negative graph
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
31a4253288637070f50a398cd80250176e785a19 | rnacentral_pipeline/cli/genes.py | rnacentral_pipeline/cli/genes.py | # -*- coding: utf-8 -*-
"""
Copyright [2009-2020] EMBL-European Bioinformatics Institute
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... | # -*- coding: utf-8 -*-
"""
Copyright [2009-2020] EMBL-European Bioinformatics Institute
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... | Clean up CLI a bit | Clean up CLI a bit
Default arguments are useful.
| Python | apache-2.0 | RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline |
9b2999d64b02cc65dc62434a29d0fe841b3d1886 | tests/commands/test_test.py | tests/commands/test_test.py | # Copyright 2014-present PlatformIO <contact@platformio.org>
#
# 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 applicabl... | # Copyright 2014-present PlatformIO <contact@platformio.org>
#
# 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 applicabl... | Fix test for "pio test" | Fix test for "pio test"
| Python | apache-2.0 | platformio/platformio,platformio/platformio-core,platformio/platformio-core |
756239f128f55481bb26e11fb21a4fe1fc5febb8 | thumbnails/tests/storage.py | thumbnails/tests/storage.py | import tempfile
import shutil
from django.core.files.storage import FileSystemStorage
"""
Temporary Storage class for test. Copied from Smiley Chris' Easy Thumbnails test package
https://github.com/SmileyChris/easy-thumbnails/blob/master/easy_thumbnails/test.py
"""
class TemporaryStorage(FileSystemStorage):
"""
... | import os
import shutil
import tempfile
from django.core.files.storage import FileSystemStorage
"""
Temporary Storage class for test. Copied from Smiley Chris' Easy Thumbnails test package
https://github.com/SmileyChris/easy-thumbnails/blob/master/easy_thumbnails/test.py
"""
class TemporaryStorage(FileSystemStorage):... | Make TemporaryStorage backend's location less random. | Make TemporaryStorage backend's location less random.
| Python | mit | ui/django-thumbnails |
234b3f157295baedca91895d2a2cb9e6f8355e2e | pyim/tools/annotate/main.py | pyim/tools/annotate/main.py | import sys
import argparse
import pandas as pd
from pyim.tools.annotate.rbm import RbmAnnotator
ANNOTATORS = {
'rbm': RbmAnnotator
}
def main():
# Setup main argument parser and annotator specific sub-parsers.
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='sub-command h... | import sys
import argparse
import pandas as pd
from pyim.tools.annotate.rbm import RbmAnnotator
ANNOTATORS = {
'rbm': RbmAnnotator
}
def main():
# Setup main argument parser and annotator specific sub-parsers.
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='Annotator to ... | Add help description for annotator. | Add help description for annotator.
| Python | mit | jrderuiter/pyim,jrderuiter/pyim |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.