commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
d06b80227e404bd0ad36e6fd9d382c247e570ca9 | runtime/Python2/setup.py | runtime/Python2/setup.py | from setuptools import setup
v = '4.10.1'
setup(
name='antlr4-python2-runtime',
version=v,
url='http://www.antlr.org',
license='BSD',
packages=['antlr4', 'antlr4.atn', 'antlr4.dfa', 'antlr4.tree', 'antlr4.error', 'antlr4.xpath'],
package_dir={'': 'src'},
author='Eric Vergnaud, Terence Parr,... | from setuptools import setup
v = '4.10.1'
setup(
name='antlr4-python2-runtime',
version=v,
url='http://www.antlr.org',
license='BSD',
packages=['antlr4', 'antlr4.atn', 'antlr4.dfa', 'antlr4.tree', 'antlr4.error', 'antlr4.xpath'],
package_dir={'': 'src'},
author='Eric Vergnaud, Terence Parr,... | Fix SyntaxError due to F string | [py2] Fix SyntaxError due to F string
Signed-off-by: Travis Thieman <f1ef50ba1343ab5680bff0994219d82815f791bd@gmail.com>
| Python | bsd-3-clause | parrt/antlr4,parrt/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,antlr/antlr4,parrt/antlr4,antlr/antlr4,antlr/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4,parrt/antlr4,antlr/antlr4,parrt/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4,parrt/antlr4,ericvergnaud/antlr... | ---
+++
@@ -10,5 +10,5 @@
package_dir={'': 'src'},
author='Eric Vergnaud, Terence Parr, Sam Harwell',
author_email='eric.vergnaud@wanadoo.fr',
- description=f'ANTLR {v} runtime for Python 2.7.12'
+ description='ANTLR %s runtime for Python 2.7.12' % v
) |
c86e22a16eb2c1f2c95f81c232ae8535e447e935 | solutions/pybasic_ex1_3_1.py | solutions/pybasic_ex1_3_1.py | # Use the codon variables you defined previously
S = "TCT"
L = "CTT"
Y = "TAT"
C = "TGT"
# Create a list for the protein sequence CLYSY
codons = [C, L, Y, S, Y]
# Print the DNA sequence of the protein
print("DNA sequence:", codons)
# Print the DNA sequence of the last amino acid
print("Last codon:", codons[-1])
# C... | # Use the codon variables you defined previously
S = "TCT"
L = "CTT"
Y = "TAT"
C = "TGT"
# Create a list for the protein sequence CLYSY
codons = [C, L, Y, S, Y]
# Print the DNA sequence of the protein
print("DNA sequence:", codons)
# Print the DNA sequence of the last amino acid
print("Last codon:", codons[-1])
# C... | Remove join in exercise 1.3.1 not seen yet in course | Remove join in exercise 1.3.1 not seen yet in course
| Python | unlicense | pycam/python-basic,pycam/python-basic | ---
+++
@@ -24,4 +24,4 @@
codons.append(stop)
# Print the resulting DNA sequence
-print("DNA sequence after alteration:", "".join(codons))
+print("DNA sequence after alteration:", codons) |
8dc69dca8538eb992989da396b65ade4fe2e5088 | polls/models.py | polls/models.py | from django.db import models
from django.utils import timezone
from datetime import timedelta
class Poll(models.Model):
text = models.CharField(max_length=200)
created_ts = models.DateTimeField()
updated_ts = models.DateTimeField(null=True, default=None)
is_published = models.BooleanField(default=Fals... | from django.db import models
from django.utils import timezone
from datetime import timedelta
class Poll(models.Model):
text = models.CharField(max_length=200)
created_ts = models.DateTimeField()
updated_ts = models.DateTimeField(null=True, default=None)
is_published = models.BooleanField(default=Fals... | Fix was_published_recently reporting polls from the future | Fix was_published_recently reporting polls from the future
| Python | mit | fernandocanizo/django-poll-site,fernandocanizo/django-poll-site,fernandocanizo/django-poll-site | ---
+++
@@ -17,7 +17,8 @@
return self.text
def was_published_recently(self):
- return self.publication_date >= timezone.now() - timedelta(days=1)
+ now = timezone.now()
+ return now - timedelta(days=1) <= self.publication_date <= now
def save(self, *args, **kwargs):
... |
c898d3f3d142727d0a55303238cda8044d729437 | motobot/core_plugins/commands.py | motobot/core_plugins/commands.py | from motobot import command, Notice, split_response, IRCBot
@command('commands')
def commands_command(bot, database, context, message, args):
userlevel = bot.get_userlevel(context.channel, context.nick)
valid_command = lambda plugin: plugin.type == IRCBot.command_plugin \
and plugin.level <= userleve... | from motobot import command, Notice, split_response, IRCBot
from collections import defaultdict
def filter_plugins(plugins, userlevel):
return map(
lambda plugin: (plugin.arg.trigger, plugin.func), filter(
lambda plugin: plugin.type == IRCBot.command_plugin and
plugi... | Revert "Revert "Cleans up split_response"" | Revert "Revert "Cleans up split_response""
This reverts commit c3c62feb9fbd8b7ff35d70eaaa5fecfb2093dbb0.
| Python | mit | Motoko11/MotoBot | ---
+++
@@ -1,23 +1,30 @@
from motobot import command, Notice, split_response, IRCBot
+from collections import defaultdict
+
+
+def filter_plugins(plugins, userlevel):
+ return map(
+ lambda plugin: (plugin.arg.trigger, plugin.func), filter(
+ lambda plugin: plugin.type == IRCBot.command_plugin ... |
7e78408dad1aab6bb42fd62601ee52e5f0ab3bd9 | stanczyk/proxy.py | stanczyk/proxy.py | from twisted.internet import endpoints, reactor
from txampext.multiplexing import ProxyingFactory
def connectProxy(namespace, identifier, _reactor=reactor):
"""Start listening on some free local port; connections will be
proxied to the virtual server with the given identifier.
"""
remote = namespace.... | from stanczyk.util import _getRemote
from twisted.internet import endpoints, reactor
from txampext.multiplexing import ProxyingFactory
def connectProxy(namespace, identifier, _reactor=reactor):
"""Start listening on some free local port; connections will be
proxied to the virtual server with the given identif... | Use the new fancy refactored remote logic | Use the new fancy refactored remote logic
| Python | isc | crypto101/stanczyk | ---
+++
@@ -1,3 +1,4 @@
+from stanczyk.util import _getRemote
from twisted.internet import endpoints, reactor
from txampext.multiplexing import ProxyingFactory
@@ -7,13 +8,8 @@
proxied to the virtual server with the given identifier.
"""
- remote = namespace.get("remote")
- if remote is None:
- ... |
7a582488a3f8d86820dca7c3b44ff86b8dbe4412 | changes/__init__.py | changes/__init__.py | import os
import subprocess
try:
VERSION = __import__('pkg_resources') \
.get_distribution('changes').version
except Exception, e:
VERSION = 'unknown'
def _get_git_revision(path):
try:
r = subprocess.check_output('git rev-parse HEAD', cwd=path, shell=True)
except Exception:
re... | import os
import subprocess
try:
VERSION = __import__('pkg_resources') \
.get_distribution('changes').version
except Exception:
VERSION = 'unknown'
def _get_git_revision(path):
try:
r = subprocess.check_output('git rev-parse HEAD', cwd=path, shell=True)
except Exception:
retur... | Update exception syntax to be py3 compat | Update exception syntax to be py3 compat
| Python | apache-2.0 | bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes | ---
+++
@@ -4,7 +4,7 @@
try:
VERSION = __import__('pkg_resources') \
.get_distribution('changes').version
-except Exception, e:
+except Exception:
VERSION = 'unknown'
|
f5613b2b03f20f9d8f2a8d221ba1fae86664839c | modules/mpi-ring/bin/onramp_status.py | modules/mpi-ring/bin/onramp_status.py | #!/usr/bin/env python
#
# Curriculum Module Status Script
# - Run while the job is running
# - Run -outside- of the allocation
# - onramp_run_params.ini file is available in current working directory
#
import sys
import re
#
# Display any special message you want the user to see, or leave blank if nothing.
# Please r... | #!/usr/bin/env python
#
# Curriculum Module Status Script
# - Run while the job is running
# - Run -outside- of the allocation
# - onramp_run_params.ini file is available in current working directory
#
import sys
import re
#
# Display any special message you want the user to see, or leave blank if nothing.
# Please r... | Update the status.py to look for the output.txt in the new location | Update the status.py to look for the output.txt in the new location
| Python | bsd-3-clause | OnRampOrg/onramp,koepked/onramp,OnRampOrg/onramp,ssfoley/onramp,OnRampOrg/onramp,koepked/onramp,ssfoley/onramp,koepked/onramp,OnRampOrg/onramp,koepked/onramp,ssfoley/onramp,ssfoley/onramp,OnRampOrg/onramp,koepked/onramp,OnRampOrg/onramp,OnRampOrg/onramp,koepked/onramp | ---
+++
@@ -15,7 +15,7 @@
#
# Read in the output file
-lines = [line.rstrip('\n') for line in open('onramp/output.txt')]
+lines = [line.rstrip('\n') for line in open('output.txt')]
# If the file is empty then nothing to do
if len(lines) <= 0: |
00b798c309d8807a562efb31751e82e5149ac7c8 | molo/core/api/tests/test_importers.py | molo/core/api/tests/test_importers.py | """
Test the importing module.
This module relies heavily on an external service and requires
quite a bit of mocking.
"""
import json
from django.test import TestCase
from molo.core.tests.base import MoloTestCaseMixin
from molo.core.api import importers
from molo.core.api.tests import constants
class ArticleImportT... | """
Test the importing module.
This module relies heavily on an external service and requires
quite a bit of mocking.
"""
import json
from django.test import TestCase
from molo.core.tests.base import MoloTestCaseMixin
from molo.core.api import importers
from molo.core.api.tests import constants
class ArticleImportT... | Write test for importer initialisation | Write test for importer initialisation
| Python | bsd-2-clause | praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo | ---
+++
@@ -20,3 +20,5 @@
def test_importer_initializtion(self):
content = json.dumps(constants.AVAILABLE_ARTICLES)
importer = importers.ArticlePageImporter(content=content)
+
+ self.assertEqual(importer.articles(), content["items"]) |
190b4b193a2b33d7904310d24891e8aec18a126f | pipreq/cli.py | pipreq/cli.py | import argparse
import sys
from pipreq.command import Command
def create_parser():
parser = argparse.ArgumentParser(
description='Manage Python package requirements across multiple environments using '
'per-environment requirements files.')
parser.add_argument('-g', '--generate',... | import argparse
import sys
from pipreq.command import Command
def create_parser():
parser = argparse.ArgumentParser(
description='Manage Python package requirements across multiple environments using '
'per-environment requirements files.')
parser.add_argument('-g', '--generate',... | Remove unnecessary u on string | Remove unnecessary u on string
| Python | mit | jessamynsmith/pipwrap,jessamynsmith/pipreq,jessamynsmith/pipwrap,jessamynsmith/pipreq | ---
+++
@@ -22,7 +22,7 @@
def verify_args(args):
if not args.create and not args.generate and not args.upgrade:
- return u'Must specify generate (-g) or create/upgrade (-[cu]) with packages'
+ return 'Must specify generate (-g) or create/upgrade (-[cu]) with packages'
return None
|
cb6f11ad05ef07facf651f8fbccae9e86e0a77c8 | processing.py | processing.py | #!/usr/bin/env python
"""
Processing routines for the waveFlapper case.
"""
import foampy
import numpy as np
import matplotlib.pyplot as plt
width_2d = 0.1
width_3d = 3.66
def plot_force():
"""Plots the streamwise force on the paddle over time."""
def plot_moment():
data = foampy.load_forces_moments()
... | #!/usr/bin/env python
"""
Processing routines for the waveFlapper case.
"""
import foampy
import numpy as np
import matplotlib.pyplot as plt
width_2d = 0.1
width_3d = 3.66
m_paddle = 1270.0 # Paddle mass in kg, from OMB manual
h_piston = 3.3147
I_paddle = 1/3*m_paddle*h_piston**2
def plot_force():
"""Plots th... | Add paddle inertia to calculations | Add paddle inertia to calculations
| Python | cc0-1.0 | petebachant/waveFlapper-OpenFOAM,petebachant/waveFlapper-OpenFOAM,petebachant/waveFlapper-OpenFOAM | ---
+++
@@ -10,6 +10,9 @@
width_2d = 0.1
width_3d = 3.66
+m_paddle = 1270.0 # Paddle mass in kg, from OMB manual
+h_piston = 3.3147
+I_paddle = 1/3*m_paddle*h_piston**2
def plot_force():
"""Plots the streamwise force on the paddle over time."""
@@ -20,6 +23,12 @@
t = data["time"][i:]
m = data[... |
db977f65a6f986508c826b645b9c94e5eff4f83f | oidc_provider/management/commands/creatersakey.py | oidc_provider/management/commands/creatersakey.py | from Crypto.PublicKey import RSA
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Randomly generate a new RSA key for the OpenID server'
def handle(self, *args, **options):
try:
key = RSA.generate(1024)
f... | from Crypto.PublicKey import RSA
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Randomly generate a new RSA key for the OpenID server'
def handle(self, *args, **options):
try:
key = RSA.generate(1024)
f... | Append binary file mode to write RSA exported key needed by Python 3 | Append binary file mode to write RSA exported key needed by Python 3
| Python | mit | ByteInternet/django-oidc-provider,bunnyinc/django-oidc-provider,wayward710/django-oidc-provider,ByteInternet/django-oidc-provider,wojtek-fliposports/django-oidc-provider,wayward710/django-oidc-provider,juanifioren/django-oidc-provider,bunnyinc/django-oidc-provider,torreco/django-oidc-provider,wojtek-fliposports/django-... | ---
+++
@@ -11,7 +11,7 @@
try:
key = RSA.generate(1024)
file_path = settings.BASE_DIR + '/OIDC_RSA_KEY.pem'
- with open(file_path, 'w') as f:
+ with open(file_path, 'wb') as f:
f.write(key.exportKey('PEM'))
self.stdout.write('RSA k... |
90bc04a92bbe6f29d1487fbd87a4fad811f22c93 | setup/setup-test-docs.py | setup/setup-test-docs.py | #!/usr/bin/python
#
# SCRIPT FOR POPULATING TEST SOLR SERVER CORE WITH TEST DOCUMENTS
#
# Usage: python setup-test-docs.py <Solr Endpoint Url>
#
# Solr endpoint URL should be in the form:
# https://example.com/solr/<core-name>/
#
# .txt files in the directory ./txt/ will be committed to user-provided Solr
# core matchi... | #!/usr/bin/python
#
# SCRIPT FOR POPULATING TEST SOLR SERVER CORE WITH TEST DOCUMENTS
#
# Usage: python setup-test-docs.py <Solr Endpoint Url>
#
# Solr endpoint URL should be in the form:
# https://example.com/solr/<core-name>/
#
# .txt files in the directory ./txt/ will be committed to user-provided Solr
# core matchi... | Use test_docs as directory for test documents for solr server | Use test_docs as directory for test documents for solr server
| Python | mit | gios-asu/search-api | ---
+++
@@ -16,11 +16,13 @@
import json
import sys
+TEST_DOC_DIR = 'test_docs'
+
arguments = sys.argv
solrApiUrl = arguments[1]
-filePaths = [f for f in listdir('txt') if isfile(join('txt', f))]
+filePaths = [f for f in listdir(TEST_DOC_DIR) if isfile(join(TEST_DOC_DIR, f))]
TEMPLATE = """
{
@@ -38,7 +4... |
f34de068e71c57b434c48c9c2b90471112bb4a2b | common/djangoapps/util/bad_request_rate_limiter.py | common/djangoapps/util/bad_request_rate_limiter.py | """
A utility class which wraps the RateLimitMixin 3rd party class to do bad request counting
which can be used for rate limiting
"""
from ratelimitbackend.backends import RateLimitMixin
from django.conf import settings
if settings.FEATURES.get('EDRAAK_RATELIMIT_APP', False):
from edraak_ratelimit.backends import ... | """
A utility class which wraps the RateLimitMixin 3rd party class to do bad request counting
which can be used for rate limiting
"""
from ratelimitbackend.backends import RateLimitMixin
from django.conf import settings
if settings.FEATURES.get('EDRAAK_RATELIMIT_APP', False):
from edraak_ratelimit.backends import ... | Fix object has no db_log_failed_attempt | Fix object has no db_log_failed_attempt
| Python | agpl-3.0 | Edraak/edraak-platform,Edraak/edraak-platform,Edraak/edraak-platform,Edraak/edraak-platform | ---
+++
@@ -22,7 +22,7 @@
counts = self.get_counters(request)
is_exceeded = sum(counts.values()) >= self.requests
- if is_exceeded:
+ if is_exceeded and settings.FEATURES.get('EDRAAK_RATELIMIT_APP', False):
self.db_log_failed_attempt(request)
return is_exceede... |
35201e71037d544893a59bfda8c4538fcb6fb4b7 | api/tests/test_scrape_item.py | api/tests/test_scrape_item.py | from api.scrapers.item import scrape_item_by_id
from api import app
from flask.json import loads
import unittest
app.config['TESTING'] = True
class ScrapeItem(unittest.TestCase):
def test_scrape_item_by_id(self):
item = scrape_item_by_id('d19447e548d')
self.assertEqual('d19447e548d', item.lode... | from api.scrapers.item import scrape_item_by_id
from api import app, db
from flask.json import loads
import unittest
app.config['TESTING'] = True
db.create_all()
class ScrapeItem(unittest.TestCase):
def test_scrape_item_by_id(self):
item = scrape_item_by_id('d19447e548d')
self.assertEqual('d19... | Create tables in database before running tests | Create tables in database before running tests
| Python | mit | Demotivated/loadstone | ---
+++
@@ -1,11 +1,12 @@
from api.scrapers.item import scrape_item_by_id
-from api import app
+from api import app, db
from flask.json import loads
import unittest
app.config['TESTING'] = True
+db.create_all()
class ScrapeItem(unittest.TestCase): |
3e7d83d51fa43f8e93ad548b07193f13791f8abe | django_lightweight_queue/middleware/transaction.py | django_lightweight_queue/middleware/transaction.py | from django.db import transaction, connection
class TransactionMiddleware(object):
def process_job(self, job):
if not connection.in_atomic_block:
transaction.set_autocommit(False)
def process_result(self, job, result, duration):
if not connection.in_atomic_block:
transa... | from django.db import transaction, connection
class TransactionMiddleware(object):
def process_job(self, job):
if not connection.in_atomic_block:
transaction.set_autocommit(False)
def process_result(self, job, result, duration):
if not connection.in_atomic_block:
transa... | Add a legacy version for older versions of Django. | Add a legacy version for older versions of Django.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
| Python | bsd-3-clause | thread/django-lightweight-queue,lamby/django-lightweight-queue,prophile/django-lightweight-queue,thread/django-lightweight-queue,prophile/django-lightweight-queue | ---
+++
@@ -12,3 +12,22 @@
def process_exception(self, job, time_taken, *exc_info):
if not connection.in_atomic_block:
transaction.rollback()
+
+# Legacy
+if not hasattr(connection, 'in_atomic_block'):
+ class TransactionMiddleware(object):
+ def process_job(self, job):
+ ... |
b6c98dd016aa440f96565ceaee2716cd530beae5 | pages/search_indexes.py | pages/search_indexes.py | """Django haystack `SearchIndex` module."""
from pages.models import Page, Content
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
import datetime
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True... | """Django haystack `SearchIndex` module."""
from pages.models import Page, Content
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
import datetime
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True... | Add a url attribute to the SearchIndex for pages. | Add a url attribute to the SearchIndex for pages.
This is useful when displaying a list of search results because we
can create a link to the result without having to hit the database
for every object in the result list.
| Python | bsd-3-clause | remik/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,pombredanne/django-page-cms-1,pombredanne/django-page-cms-1,oliciv/django-page-cms,remik/django-page-cms,remik/django-page-... | ---
+++
@@ -10,6 +10,7 @@
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
title = CharField(model_attr='title')
+ url = CharField(model_attr='get_absolute_url')
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self)... |
7f86ab26fb1c6ba01f81fdc3f5b66a0f079c23ff | tests/test_app.py | tests/test_app.py | import asyncio
from unittest import mock
import aiohttp
import pytest
from bottery.app import App
def test_app_session():
app = App()
assert isinstance(app.session, aiohttp.ClientSession)
def test_app_already_configured_session():
app = App()
app._session = 'session'
assert app.session == 'ses... | import asyncio
import sys
from unittest import mock
import aiohttp
import pytest
from bottery.app import App
@pytest.fixture
def mocked_engine():
mocked_engine_module = mock.MagicMock()
mocked_engine_instance = mocked_engine_module.engine.return_value
mocked_engine_instance.tasks.return_value = [(mock.M... | Increase the code coverage of App.configure_platforms method | Increase the code coverage of App.configure_platforms method
| Python | mit | rougeth/bottery | ---
+++
@@ -1,10 +1,26 @@
import asyncio
+import sys
from unittest import mock
import aiohttp
import pytest
from bottery.app import App
+
+
+@pytest.fixture
+def mocked_engine():
+ mocked_engine_module = mock.MagicMock()
+ mocked_engine_instance = mocked_engine_module.engine.return_value
+ mocked_en... |
2e9c6c883de12b7293b9e932e5268a2d806e714c | chatterbot/logic/time_adapter.py | chatterbot/logic/time_adapter.py | from __future__ import unicode_literals
from datetime import datetime
from .logic_adapter import LogicAdapter
class TimeLogicAdapter(LogicAdapter):
"""
The TimeLogicAdapter returns the current time.
"""
def __init__(self, **kwargs):
super(TimeLogicAdapter, self).__init__(**kwargs)
fro... | from __future__ import unicode_literals
from datetime import datetime
from .logic_adapter import LogicAdapter
class TimeLogicAdapter(LogicAdapter):
"""
The TimeLogicAdapter returns the current time.
"""
def __init__(self, **kwargs):
super(TimeLogicAdapter, self).__init__(**kwargs)
fro... | Remove textblob dependency in time logic adapter | Remove textblob dependency in time logic adapter
| Python | bsd-3-clause | gunthercox/ChatterBot,vkosuri/ChatterBot,Gustavo6046/ChatterBot,davizucon/ChatterBot,Reinaesaya/OUIRL-ChatBot,Reinaesaya/OUIRL-ChatBot,maclogan/VirtualPenPal | ---
+++
@@ -10,27 +10,56 @@
def __init__(self, **kwargs):
super(TimeLogicAdapter, self).__init__(**kwargs)
- from textblob.classifiers import NaiveBayesClassifier
+ from nltk import NaiveBayesClassifier
- training_data = [
- ('what time is it', 1),
- ('do y... |
025c95a59b079d630c778646d5c82f5e0679b47c | sale_automatic_workflow/models/account_invoice.py | sale_automatic_workflow/models/account_invoice.py | # -*- coding: utf-8 -*-
# © 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com>
# © 2013 Camptocamp SA (author: Guewen Baconnier)
# © 2016 Sodexis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, fields
class AccountInvoice(models.Model):
_inherit = "account.invoice... | # -*- coding: utf-8 -*-
# © 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com>
# © 2013 Camptocamp SA (author: Guewen Baconnier)
# © 2016 Sodexis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, fields
class AccountInvoice(models.Model):
_inherit = "account.invoice"... | Fix issue on account.invoice about workflow_process_id: if a user duplicate an invoice, it copy also the workflow and validations (the reason of bugs) | [FIX] Fix issue on account.invoice about workflow_process_id: if a user duplicate an invoice, it copy also the workflow and validations (the reason of bugs)
| Python | agpl-3.0 | kittiu/sale-workflow,kittiu/sale-workflow | ---
+++
@@ -3,7 +3,6 @@
# © 2013 Camptocamp SA (author: Guewen Baconnier)
# © 2016 Sodexis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
-
from odoo import models, fields
@@ -12,5 +11,6 @@
workflow_process_id = fields.Many2one(
comodel_name='sale.workflow.process',
- s... |
7e2440c00ce75dc3ff0eac53e63d629981a9873a | raven/contrib/celery/__init__.py | raven/contrib/celery/__init__.py | """
raven.contrib.celery
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
try:
from celery.task import task
except ImportError:
from celery.decorators import task
from celery.signals import task_failure
from ra... | """
raven.contrib.celery
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
try:
from celery.task import task
except ImportError:
from celery.decorators import task
from celery.signals import task_failure
from ra... | Fix celery task_failure signal definition | Fix celery task_failure signal definition
| Python | bsd-3-clause | lepture/raven-python,recht/raven-python,lepture/raven-python,beniwohli/apm-agent-python,dbravender/raven-python,patrys/opbeat_python,recht/raven-python,jbarbuto/raven-python,getsentry/raven-python,akalipetis/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,patrys/opbeat_python,ewdurbin/raven-python,nikolas/rav... | ---
+++
@@ -29,15 +29,15 @@
def register_signal(client):
- def process_failure_signal(exception, traceback, sender, task_id,
- signal, args, kwargs, einfo, **kw):
- exc_info = (type(exception), exception, traceback)
+ @task_failure.connect(weak=False)
+ def process_f... |
9d68808a363ad00c3fc0b0907d625e5c75bdb8ae | ptt_preproc_sampling.py | ptt_preproc_sampling.py | #!/usr/bin/env python
from pathlib import Path
from random import shuffle
from shutil import copy
# configs
N = 10000
SAMPLED_DIR_PATH = Path('sampled/')
# mkdir if doesn't exist
if not SAMPLED_DIR_PATH.exists():
SAMPLED_DIR_PATH.mkdir()
# sample and copy
paths = [p for p in Path('preprocessed/').iterdir()... | #!/usr/bin/env python
from pathlib import Path
from random import sample
from os import remove
# configs
N = 10000
# remove unsampled
paths = [path for path in Path('preprocessed/').iterdir()]
paths_len = len(paths)
if paths_len <= N:
raise RuntimeError('file count {:,} <= N {:,}'.format(paths_len, N))
for... | Use removing rather than copying | Use removing rather than copying
| Python | mit | moskytw/mining-news | ---
+++
@@ -2,24 +2,21 @@
from pathlib import Path
-from random import shuffle
-from shutil import copy
+from random import sample
+from os import remove
# configs
N = 10000
-SAMPLED_DIR_PATH = Path('sampled/')
-# mkdir if doesn't exist
+# remove unsampled
-if not SAMPLED_DIR_PATH.exists():
- SAMP... |
b5e4af74bfc12eb3ae9ca14ab4cebc49daf05fdc | api/wb/urls.py | api/wb/urls.py | from django.conf.urls import url
from api.wb import views
app_name = 'osf'
urlpatterns = [
url(r'^move/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
url(r'^copy/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
]
| from django.conf.urls import url
from api.wb import views
app_name = 'osf'
urlpatterns = [
url(r'^(?P<node_id>\w+)/move/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
url(r'^(?P<node_id>\w+)/copy/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
]
| Add node id to url. | Add node id to url.
| Python | apache-2.0 | baylee-d/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,caseyrollins/osf.io,erinspace/osf.io,pattisdr/osf.io,erinspace/osf.io,icereval/osf.io,adlius/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,HalcyonChimera/osf.io,mattclark/osf.io,adlius/osf.io,felliott/osf.io,Johnetordoff/osf.io,felliott/osf.io,fe... | ---
+++
@@ -4,6 +4,6 @@
app_name = 'osf'
urlpatterns = [
- url(r'^move/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
- url(r'^copy/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
+ url(r'^(?P<node_id>\w+)/move/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
+ u... |
44893be528063d25d0b2305c9d24be4605c49f3c | mcserver/config/core.py | mcserver/config/core.py | """
MCServer Tools config loader
"""
import json
import os.path
class CoreConfig(object):
"""
MCServer Tools configuration
"""
SETTINGS_FILE = 'mcserver.settings'
def __init__(self, path):
"""
Load configuration from the given file path
"""
self.settings_file = os.path.join(path, self.SETTINGS_FILE)
... | """
MCServer Tools config loader
"""
import json
import os.path
from mcserver import MCServerError
class CoreConfig(object):
"""
MCServer Tools configuration
"""
SETTINGS_FILE = 'mcserver.settings'
def __init__(self, path):
"""
Load configuration from the given file path
"""
self.settings_file = os.p... | Check for the existance of the settings file and report if its not there | Check for the existance of the settings file and report if its not there
| Python | mit | cadyyan/mcserver-tools,cadyyan/mcserver-tools | ---
+++
@@ -4,6 +4,8 @@
import json
import os.path
+
+from mcserver import MCServerError
class CoreConfig(object):
"""
@@ -27,8 +29,11 @@
Load the settings from disk
"""
- with open(self.settings_file, 'r') as fh:
- self._settings = json.load(fh)
+ try:
+ with open(self.settings_file, 'r') as f... |
20224e4fe8b93dee087dd7a455f9709b9795a026 | app/models.py | app/models.py | from app import database
class Talk(database.Model):
id = database.Column(database.Integer, primary_key=True, autoincrement=True)
title = database.Column(database.String(128), nullable=False)
description = database.Column(database.String(512))
speaker_facebook_id = database.Column(database.BIGINT, dat... | from app import database
class Talk(database.Model):
id = database.Column(database.Integer, primary_key=True, autoincrement=True)
title = database.Column(database.String(128), unique=True, nullable=False)
description = database.Column(database.String(512))
speaker_facebook_id = database.Column(databas... | Make title unique Talk property | Make title unique Talk property
| Python | mit | Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot | ---
+++
@@ -3,7 +3,7 @@
class Talk(database.Model):
id = database.Column(database.Integer, primary_key=True, autoincrement=True)
- title = database.Column(database.String(128), nullable=False)
+ title = database.Column(database.String(128), unique=True, nullable=False)
description = database.Column... |
3611e8a1b6477d251ddb2c90211e0cfee370671d | cal_pipe/easy_RFI_flagging.py | cal_pipe/easy_RFI_flagging.py |
import sys
import os
'''
Easier searching for good RFI flagging values
'''
try:
vis = sys.argv[1]
except IndexError:
vis = raw_input("Input vis? : ")
# Just want the number of SPWs
tb.open(os.path.join(vis, "SPECTRAL_WINDOW"))
nchans = tb.getcol('NUM_CHAN')
tb.close()
spws = range(len(nchans))
default('fl... |
import sys
import os
'''
Easier searching for good RFI flagging values
'''
try:
ms_name = sys.argv[1]
except IndexError:
ms_name = raw_input("Input vis? : ")
# Just want the number of SPWs
tb.open(os.path.join(ms_name, "SPECTRAL_WINDOW"))
nchans = tb.getcol('NUM_CHAN')
tb.close()
spws = range(len(nchans))
... | CHange name so it isn't reset | CHange name so it isn't reset
| Python | mit | e-koch/canfar_scripts,e-koch/canfar_scripts | ---
+++
@@ -7,12 +7,12 @@
'''
try:
- vis = sys.argv[1]
+ ms_name = sys.argv[1]
except IndexError:
- vis = raw_input("Input vis? : ")
+ ms_name = raw_input("Input vis? : ")
# Just want the number of SPWs
-tb.open(os.path.join(vis, "SPECTRAL_WINDOW"))
+tb.open(os.path.join(ms_name, "SPECTRAL_WINDOW"... |
be458ff809f6f49e21be06054ad096ff3f5430f9 | masters/master.client.syzygy/master_site_config.py | masters/master.client.syzygy/master_site_config.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
class Syzygy(object):
project_name = 'Syzygy'
master_port = 8142
slave_port = 8242
master_port_alt = 8342
tree_clos... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
class Syzygy(object):
project_name = 'Syzygy'
master_port = 8042
slave_port = 8142
master_port_alt = 8242
tree_clos... | Fix ports for syzygy master to match previous ports. | Fix ports for syzygy master to match previous ports.
TBR=chrisha@chromium.org
BUG=
Review URL: https://chromiumcodereview.appspot.com/12315047
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@183944 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | ---
+++
@@ -6,9 +6,9 @@
class Syzygy(object):
project_name = 'Syzygy'
- master_port = 8142
- slave_port = 8242
- master_port_alt = 8342
+ master_port = 8042
+ slave_port = 8142
+ master_port_alt = 8242
tree_closing_notification_recipients = []
from_address = 'buildbot@chromium.org'
master_host = ... |
80acc483f9b5d7fb462d81a2df092d16f5dbf035 | openprocurement/tender/limited/subscribers.py | openprocurement/tender/limited/subscribers.py | from pyramid.events import subscriber
from openprocurement.tender.core.events import TenderInitializeEvent
from openprocurement.tender.core.utils import get_now, calculate_business_date
@subscriber(TenderInitializeEvent, procurementMethodType="reporting")
def tender_init_handler(event):
""" initialization handler... | from pyramid.events import subscriber
from openprocurement.tender.core.events import TenderInitializeEvent
from openprocurement.tender.core.utils import get_now, calculate_business_date
@subscriber(TenderInitializeEvent, procurementMethodType="reporting")
def tender_init_handler_1(event):
""" initialization handl... | Change tender init handlers names | Change tender init handlers names
| Python | apache-2.0 | openprocurement/openprocurement.tender.limited | ---
+++
@@ -4,13 +4,13 @@
@subscriber(TenderInitializeEvent, procurementMethodType="reporting")
-def tender_init_handler(event):
+def tender_init_handler_1(event):
""" initialization handler for tenders """
event.tender.date = get_now()
@subscriber(TenderInitializeEvent, procurementMethodType="neg... |
689dd5cb67516fd091a69e39708b547c66f96750 | nap/dataviews/models.py | nap/dataviews/models.py |
from .fields import Field
from .views import DataView
from django.utils.six import with_metaclass
class MetaView(type):
def __new__(mcs, name, bases, attrs):
meta = attrs.get('Meta', None)
try:
model = meta.model
except AttributeError:
if name != 'ModelDataView'... |
from django.db.models.fields import NOT_PROVIDED
from django.utils.six import with_metaclass
from . import filters
from .fields import Field
from .views import DataView
# Map of ModelField name -> list of filters
FIELD_FILTERS = {
'DateField': [filters.DateFilter],
'TimeField': [filters.TimeFilter],
'Da... | Add Options class Add field filters lists Start proper model field introspection | Add Options class
Add field filters lists
Start proper model field introspection
| Python | bsd-3-clause | limbera/django-nap,MarkusH/django-nap | ---
+++
@@ -1,36 +1,56 @@
+from django.db.models.fields import NOT_PROVIDED
+from django.utils.six import with_metaclass
+
+from . import filters
from .fields import Field
from .views import DataView
-from django.utils.six import with_metaclass
+
+# Map of ModelField name -> list of filters
+FIELD_FILTERS = {
+... |
10e23fdd5c0427ad1ff5a5284410c755378a0e6d | SoftLayer/CLI/object_storage/list_accounts.py | SoftLayer/CLI/object_storage/list_accounts.py | """List Object Storage accounts."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
@click.command()
@environment.pass_env
def cli(env):
"""List object storage accounts."""
mgr = SoftLayer.ObjectStorageM... | """List Object Storage accounts."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
@click.command()
@environment.pass_env
def cli(env):
"""List object storage accounts."""
mgr = SoftLayer.ObjectStorageM... | Fix object storage apiType for S3 and Swift. | Fix object storage apiType for S3 and Swift.
| Python | mit | allmightyspiff/softlayer-python,softlayer/softlayer-python,kyubifire/softlayer-python | ---
+++
@@ -17,9 +17,9 @@
accounts = mgr.list_accounts()
table = formatting.Table(['id', 'name', 'apiType'])
table.sortby = 'id'
- global api_type
+ api_type = None
for account in accounts:
- if 'vendorName' in account and 'Swift' == account['vendorName']:
+ if 'vendorName' in ... |
e9386e24bea91b8659b5184fe146002f555ccd15 | versions/xmlib.py | versions/xmlib.py | #!/usr/bin/env python
#
# Xm
#
# The xm library is hard to find and requires this special code.
#
# Author P G Jones - 11/07/2012 <p.g.jones@qmul.ac.uk> : First revision
# Author P G Jones - 22/09/2012 <p.g.jones@qmul.ac.uk> : Major refactor of snoing.
###################################################################... | #!/usr/bin/env python
#
# Xm
#
# The xm library is hard to find and requires this special code.
#
# Author P G Jones - 11/07/2012 <p.g.jones@qmul.ac.uk> : First revision
# Author P G Jones - 22/09/2012 <p.g.jones@qmul.ac.uk> : Major refactor of snoing.
###################################################################... | Fix Xm library location error. | Fix Xm library location error.
| Python | mit | mjmottram/snoing,mjmottram/snoing | ---
+++
@@ -19,9 +19,9 @@
""" Check the Xm state, slightly more involved on macs."""
if self._system.get_os_type() == system.System.Mac:
if os.path.exists("/sw/include/Xm"):
- flags = [ "-I%s" % "/sw/include/Xm", "-L%s" % "/sw/lib" ]
+ flags = [ "-I%s" % "/... |
026aa257bff85b897e8e3ef1999b8fc6f7e3cc30 | socketdjango/socketdjango/__init__.py | socketdjango/socketdjango/__init__.py | """
Socketdjango Project Module
Interesting Docstring goes here!
"""
__version__ = '0.0.1'
| """
Socketdjango Project Module
Interesting Docstring goes here!
"""
__version__ = '0.1.0'
| Change Initial Version Number to '0.1.0' | Change Initial Version Number to '0.1.0'
Change __version__ to '0.1.0'
| Python | mit | bobbyrussell/django-socketio,bobbyrussell/django-socketio,bobbyrussell/django-socketio | ---
+++
@@ -4,4 +4,4 @@
Interesting Docstring goes here!
"""
-__version__ = '0.0.1'
+__version__ = '0.1.0' |
502a5cb7179aaedf68f3f16bf8d2ef7eb1ad0032 | nsq/sockets/__init__.py | nsq/sockets/__init__.py | '''Sockets that wrap different connection types'''
# Not all platforms support all types of sockets provided here. For those that
# are not available, the corresponding socket wrapper is imported as None.
from .. import logger
# Snappy support
try:
from .snappy import SnappySocket
except ImportError: # pragma: ... | '''Sockets that wrap different connection types'''
# Not all platforms support all types of sockets provided here. For those that
# are not available, the corresponding socket wrapper is imported as None.
from .. import logger
# Snappy support
try:
from .snappy import SnappySocket
except ImportError: # pragma: ... | Reduce log severity of socket import messages | Reduce log severity of socket import messages | Python | mit | dlecocq/nsq-py,dlecocq/nsq-py | ---
+++
@@ -9,7 +9,7 @@
try:
from .snappy import SnappySocket
except ImportError: # pragma: no cover
- logger.warn('Snappy compression not supported')
+ logger.debug('Snappy compression not supported')
SnappySocket = None
@@ -17,7 +17,7 @@
try:
from .deflate import DeflateSocket
except I... |
7dfe9c435b102eacddd9e0617540495f0af46416 | app/config.py | app/config.py | import os
if os.environ['DATABASE_URL'] is None:
SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
else:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
| import os
if os.environ.get('DATABASE_URL') is None:
SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
else:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
| Fix the SQLite URL problem | Fix the SQLite URL problem
| Python | mit | Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot | ---
+++
@@ -1,7 +1,7 @@
import os
-if os.environ['DATABASE_URL'] is None:
+if os.environ.get('DATABASE_URL') is None:
SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
else:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] |
28e0a10925d866572cae86507a3ace845fbff6a9 | observers/middleware.py | observers/middleware.py | from .models import Observer
class ObserverMiddleware(object):
"""
Attaches an observer instance to every request coming from an
authenticated user.
"""
def process_request(self, request):
assert hasattr(request, 'user'), "ObserverMiddleware requires auth middleware to be installed."
... | from .models import Observer
class ObserverMiddleware(object):
"""
Attaches an observer instance to every request coming from an
authenticated user.
"""
def process_request(self, request):
assert hasattr(request, 'user'), "ObserverMiddleware requires auth middleware to be installed."
... | Use is_authenticated as a property. | Use is_authenticated as a property.
| Python | mit | zsiciarz/variablestars.net,zsiciarz/variablestars.net,zsiciarz/variablestars.net | ---
+++
@@ -8,7 +8,7 @@
"""
def process_request(self, request):
assert hasattr(request, 'user'), "ObserverMiddleware requires auth middleware to be installed."
- if request.user and request.user.is_authenticated():
+ if request.user and request.user.is_authenticated:
requ... |
a50a46ee26e5d7d325a228559bc701c86d1b392d | arg-reader.py | arg-reader.py | #!/usr/bin/env python3
# References:
# http://docs.python.org/3.3/library/argparse.html?highlight=argparse#argparse
# http://bip.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/argparse/index.html
import argparse
def main():
'''
Read arguments from a file
'''
parser = argparse.ArgumentParser(descrip... | #!/usr/bin/env python3
# References:
# http://docs.python.org/3.3/library/argparse.html?highlight=argparse#argparse
# http://bip.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/argparse/index.html
import argparse
def main():
'''
For help, use argument -h
$ ./arg-reader.py -h
To specify an argument, p... | Add more comments about usage. | Add more comments about usage.
| Python | mit | beepscore/argparse | ---
+++
@@ -8,10 +8,17 @@
def main():
'''
- Read arguments from a file
+ For help, use argument -h
+ $ ./arg-reader.py -h
+ To specify an argument, prefix with -
+ $ ./arg-reader.py -animalbig hippo -animalsmall fly
+ To read arguments from a file, prefix file name with @
+ $ ./arg-reader... |
da05390fa11a12d0491caff18d38e71a1e134b82 | spicedham/sqlalchemywrapper/models.py | spicedham/sqlalchemywrapper/models.py | from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import UniqueConstraint
Base = declarative_base()
class Store(Base):
__tablename__ = 'store'
id = Column(Integer, primary_key=True, autoincrement=True)
key = Column(String)
tag... | from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import PrimaryKeyConstraint
Base = declarative_base()
class Store(Base):
__tablename__ = 'store'
key = Column(String)
tag = Column(String)
value = Column(String)
__table_ar... | Make tag and key be a composite primary key | Make tag and key be a composite primary key
| Python | mpl-2.0 | mozilla/spicedham,mozilla/spicedham | ---
+++
@@ -1,16 +1,15 @@
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy.schema import UniqueConstraint
+from sqlalchemy.schema import PrimaryKeyConstraint
Base = declarative_base()
class Store(Base):
__tablename__ = 'store'
- id... |
63d1eb69fc614cb3f019e7b37dd4ec10896c644e | chartflo/views.py | chartflo/views.py | # -*- coding: utf-8 -*-
from django.views.generic import TemplateView
from chartflo.factory import ChartDataPack
class ChartsView(TemplateView):
template_name = 'chartflo/charts.html'
graph_type = "pie"
title = ""
def get_data(self):
return {}
def get_context_data(self, **kwargs):
... | # -*- coding: utf-8 -*-
from django.views.generic import TemplateView
from chartflo.factory import ChartDataPack
class ChartsView(TemplateView):
template_name = 'chartflo/charts.html'
chart_type = "pie"
title = ""
def get_data(self):
return {}
def get_context_data(self, **kwargs):
... | Change graph_type for chart_type and remove it from context | Change graph_type for chart_type and remove it from context
| Python | mit | synw/django-chartflo,synw/django-chartflo,synw/django-chartflo | ---
+++
@@ -6,7 +6,7 @@
class ChartsView(TemplateView):
template_name = 'chartflo/charts.html'
- graph_type = "pie"
+ chart_type = "pie"
title = ""
def get_data(self):
@@ -23,11 +23,10 @@
datapack['legend'] = True
datapack['export'] = False
context['datapack'] = da... |
e66468faaf9c4885f13545329baa20fe4914f49c | historia.py | historia.py | from eve import Eve
from eve_swagger import swagger
from eve.auth import BasicAuth
from config import *
from hashlib import md5
class MyBasicAuth(BasicAuth):
def check_auth(self, username, password, allowed_roles, resource,
method):
accounts = app.data.driver.db['accounts']
accou... | from eve import Eve
from eve_swagger import swagger
from eve.auth import BasicAuth
from config import *
from hashlib import md5
class MyBasicAuth(BasicAuth):
def check_auth(self, username, password, allowed_roles, resource,
method):
accounts = app.data.driver.db['accounts']
accou... | Use MD5 to encode passwords | Use MD5 to encode passwords
| Python | mit | waoliveros/historia | ---
+++
@@ -9,11 +9,11 @@
method):
accounts = app.data.driver.db['accounts']
account = accounts.find_one({'username': username})
- return account and password == account['password']
+ return account and md5(password).hexdigest() == account['password']
def set_rep... |
4f9e51ff45f6faf6d0be6a442b4b04c3301026fe | cloudenvy/commands/envy_snapshot.py | cloudenvy/commands/envy_snapshot.py | from cloudenvy.envy import Envy
class EnvySnapshot(object):
"""Create a snapshot of an ENVy."""
def __init__(self, argparser):
self._build_subparser(argparser)
def _build_subparser(self, subparsers):
subparser = subparsers.add_parser('snapshot', help='snapshot help')
subparser.se... | from cloudenvy.envy import Envy
class EnvySnapshot(object):
"""Create a snapshot of an ENVy."""
def __init__(self, argparser):
self._build_subparser(argparser)
def _build_subparser(self, subparsers):
subparser = subparsers.add_parser('snapshot', help='snapshot help')
subparser.se... | Add missing --name flag to 'envy snapshot' | Add missing --name flag to 'envy snapshot'
| Python | apache-2.0 | cloudenvy/cloudenvy | ---
+++
@@ -11,6 +11,9 @@
subparser = subparsers.add_parser('snapshot', help='snapshot help')
subparser.set_defaults(func=self.run)
+ subparser.add_argument('-n', '--name', action='store', default='',
+ help='Specify custom name for an ENVy.')
+
return... |
68724546ba4f6063559ba14b8625c7e7ecdf9732 | src/read_key.py | src/read_key.py | #!/usr/bin/python
def readKey(keyFileName):
return open("../options-and-settings/api-keys/" + keyFileName, "r").readline()
| #!/usr/bin/python
def readKey(keyFileName):
return open("../options-and-settings/api-keys/" + keyFileName, "r").readline().rstrip('\n').rstrip('\r')
| Remove newline and carraige return characters from key files so that API calls work | Remove newline and carraige return characters from key files so that API calls work
| Python | mit | nilnullzip/StalkerBot,nilnullzip/StalkerBot | ---
+++
@@ -1,5 +1,5 @@
#!/usr/bin/python
def readKey(keyFileName):
- return open("../options-and-settings/api-keys/" + keyFileName, "r").readline()
+ return open("../options-and-settings/api-keys/" + keyFileName, "r").readline().rstrip('\n').rstrip('\r')
|
b362d4b898493a856a810880079d3f44fe7d5d41 | project/members/tests/test_application.py | project/members/tests/test_application.py | # -*- coding: utf-8 -*-
import pytest
from django.core.urlresolvers import reverse
from members.tests.fixtures.memberlikes import MembershipApplicationFactory
from members.tests.fixtures.types import MemberTypeFactory
from members.models import Member
@pytest.mark.django_db
def test_application_approve():
mtypes =... | # -*- coding: utf-8 -*-
import pytest
from django.core.urlresolvers import reverse
from members.tests.fixtures.memberlikes import MembershipApplicationFactory, MemberFactory
from members.tests.fixtures.types import MemberTypeFactory
from members.models import Member
@pytest.mark.django_db
def test_application_approve(... | Add quick admin-site tests too | Add quick admin-site tests too
| Python | mit | jautero/asylum,jautero/asylum,rambo/asylum,hacklab-fi/asylum,hacklab-fi/asylum,HelsinkiHacklab/asylum,jautero/asylum,hacklab-fi/asylum,rambo/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,jautero/asylum,rambo/asylum,rambo/asylum,hacklab-fi/asylum | ---
+++
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import pytest
from django.core.urlresolvers import reverse
-from members.tests.fixtures.memberlikes import MembershipApplicationFactory
+from members.tests.fixtures.memberlikes import MembershipApplicationFactory, MemberFactory
from members.tests.fixtures.types impo... |
5456bee257cb36e4d1400da7e27480beadbf21fd | examples/arabic.py | examples/arabic.py | #!/usr/bin/env python
"""
Example using Arabic
===============
Generating a wordcloud from Arabic text
Other dependencies: bidi.algorithm, arabic_reshaper
"""
from os import path
import codecs
from wordcloud import WordCloud
import arabic_reshaper
from bidi.algorithm import get_display
d = path.dirname(__file__)
# R... | #!/usr/bin/env python
"""
Create wordcloud with Arabic
===============
Generating a wordcloud from Arabic text
Other dependencies: bidi.algorithm, arabic_reshaper
"""
from os import path
import codecs
from wordcloud import WordCloud
import arabic_reshaper
from bidi.algorithm import get_display
d = path.dirname(__file... | Change the title of the example | Change the title of the example
| Python | mit | amueller/word_cloud | ---
+++
@@ -1,6 +1,6 @@
#!/usr/bin/env python
"""
-Example using Arabic
+Create wordcloud with Arabic
===============
Generating a wordcloud from Arabic text
Other dependencies: bidi.algorithm, arabic_reshaper |
9e783b39e89e34ded032dc550bc8cc9016f1eded | cacheops/__init__.py | cacheops/__init__.py | VERSION = (3, 0, 1)
__version__ = '.'.join(map(str, VERSION if VERSION[-1] else VERSION[:2]))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
class CacheopsCon... | VERSION = (3, 0, 1)
__version__ = '.'.join(map(str, VERSION if VERSION[-1] else VERSION[:2]))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
from .utils import ... | Make debug_cache_key a part of API | Make debug_cache_key a part of API
| Python | bsd-3-clause | LPgenerator/django-cacheops,Suor/django-cacheops | ---
+++
@@ -9,6 +9,7 @@
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
+from .utils import debug_cache_key # noqa
class CacheopsConfig(AppConfig): |
843f84877d06329179f326600980eff0558e37e0 | report_qweb_pdf_watermark/__manifest__.py | report_qweb_pdf_watermark/__manifest__.py | # © 2016 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Pdf watermark",
"version": "12.0.1.0.0",
"author": "Therp BV, "
"Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Technical Settings",
"summary": ... | # © 2016 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Pdf watermark",
"version": "12.0.1.0.0",
"author": "Therp BV, "
"Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Technical Settings",
"summary": ... | Fix 'installable' syntax in manifest file | [FIX] Fix 'installable' syntax in manifest file
| Python | agpl-3.0 | OCA/reporting-engine,OCA/reporting-engine,OCA/reporting-engine,OCA/reporting-engine | ---
+++
@@ -20,7 +20,7 @@
"demo": [
"demo/report.xml"
],
- "intallable": True,
+ "installable": True,
'external_dependencies': {
'python': [
'PyPDF2', |
e35d55f46ffb9d42736ad4e57ae2a6c29838b054 | board/tests.py | board/tests.py | from django.test import TestCase
# Create your tests here.
| from test_plus.test import TestCase
class BoardTest(TestCase):
def test_get_board_list(self):
board_list_url = self.reverse("board:list")
self.get_check_200(board_list_url)
| Add board list test code. | Add board list test code.
| Python | mit | 9XD/9XD,9XD/9XD,9XD/9XD,9XD/9XD | ---
+++
@@ -1,3 +1,8 @@
-from django.test import TestCase
+from test_plus.test import TestCase
-# Create your tests here.
+
+class BoardTest(TestCase):
+ def test_get_board_list(self):
+ board_list_url = self.reverse("board:list")
+ self.get_check_200(board_list_url)
+ |
31fedddedc5ece0b7e68762269730e2cce110cb9 | pnnl/models/__init__.py | pnnl/models/__init__.py | import importlib
import logging
from volttron.platform.agent import utils
_log = logging.getLogger(__name__)
utils.setup_logging()
__version__ = "0.1"
__all__ = ['Model']
class Model(object):
def __init__(self, config, **kwargs):
self.model = None
config = self.store_model_config(config)
... | import importlib
import logging
from volttron.platform.agent import utils
_log = logging.getLogger(__name__)
utils.setup_logging()
__version__ = "0.1"
__all__ = ['Model']
class Model(object):
def __init__(self, config, **kwargs):
self.model = None
config = self.store_model_config(config)
... | Fix self.model is not set. | Fix self.model is not set.
| Python | bsd-3-clause | VOLTTRON/volttron-applications,VOLTTRON/volttron-applications,VOLTTRON/volttron-applications,VOLTTRON/volttron-applications,VOLTTRON/volttron-applications | ---
+++
@@ -24,6 +24,7 @@
_file, model_type = model_type.split(".")
module = importlib.import_module(base_module + _file)
self.model_class = getattr(module, model_type)
+ self.model = self.model_class(config, self)
def get_q(self, _set, sched_index, market_index, occupied):
... |
3d2b4536803df4a202d8c1c9b5d0e689f1053378 | tests/config.py | tests/config.py | import sys
sys.path.append('../ideascaly')
from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import unittest
testing_community = 'fiveheads.ideascale.com'
testing_token = '5b3326f8-50a5-419d-8f02-eef6a42fd61a'
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = c... | import os
import sys
import unittest
sys.path.append('../ideascaly')
from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
testing_community = 'fiveheads.ideascale.com'
testing_token = os.environ.get('TOKEN', '')
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = cre... | Read token from environment variable | Read token from environment variable
| Python | mit | joausaga/ideascaly | ---
+++
@@ -1,13 +1,13 @@
+import os
import sys
+import unittest
sys.path.append('../ideascaly')
from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
-import unittest
-
testing_community = 'fiveheads.ideascale.com'
-testing_token = '5b3326f8-50a5-419d-8f02-eef6a42fd61a'
+testing_token = os.env... |
7845e017b264a38472d0dc94988a0afe6938132f | tests/acceptance/conftest.py | tests/acceptance/conftest.py | # -*- coding: utf-8 -*-
import mock
import pytest
@pytest.fixture
def default_trace_id_generator(dummy_request):
return lambda dummy_request: '17133d482ba4f605'
@pytest.fixture
def settings():
return {
'zipkin.tracing_percent': 100,
'zipkin.trace_id_generator': default_trace_id_generator,
... | # -*- coding: utf-8 -*-
import mock
import pytest
@pytest.fixture
def default_trace_id_generator(dummy_request):
return lambda dummy_request: '17133d482ba4f605'
@pytest.fixture
def settings():
return {
'zipkin.tracing_percent': 100,
'zipkin.trace_id_generator': default_trace_id_generator,
... | Allow any ip in the get_span expected span since it's not deterministic | Allow any ip in the get_span expected span since it's not deterministic
| Python | apache-2.0 | Yelp/pyramid_zipkin | ---
+++
@@ -29,7 +29,7 @@
'name': 'GET /sample',
'traceId': '17133d482ba4f605',
'localEndpoint': {
- 'ipv4': '127.0.0.1',
+ 'ipv4': mock.ANY,
'port': 80,
'serviceName': 'acceptance_service',
}, |
c96e82caaa3fd560263c54db71772b44e9cd78d7 | examples/upgrade_local_charm_k8s.py | examples/upgrade_local_charm_k8s.py | """
This example:
1. Connects to the current model
2. Deploy a bundle and waits until it reports itself active
3. Destroys the units and applications
"""
from juju import jasyncio
from juju.model import Model
async def main():
model = Model()
print('Connecting to model')
# Connect to current model with ... | """
This example:
1. Connects to the current model
2. Deploy a bundle and waits until it reports itself active
3. Upgrades the charm with a local path
4. Destroys the units and applications
"""
from juju import jasyncio
from juju.model import Model
async def main():
model = Model()
print('Connecting to mode... | Make the example more informative | Make the example more informative
| Python | apache-2.0 | juju/python-libjuju,juju/python-libjuju | ---
+++
@@ -3,7 +3,8 @@
1. Connects to the current model
2. Deploy a bundle and waits until it reports itself active
-3. Destroys the units and applications
+3. Upgrades the charm with a local path
+4. Destroys the units and applications
"""
from juju import jasyncio
@@ -26,7 +27,9 @@
await model.wai... |
1b9b4365a46cdbfbfe88e2f5e271ba387fe4274f | var_log_dieta/constants.py | var_log_dieta/constants.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division
import logging
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
DATA_DIR = 'data'
DEFAULT_CONVERSIONS = {
'kg': {'g': 1000},
'l': {'ml': 1000},
} # yapf: disable
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division
import logging
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
DATA_DIR = 'data'
DEFAULT_CONVERSIONS = {
'kg': {'g': 1000},
'l': {'ml': 1000},
'taza': {'ml': 250},
't... | Add taza, tazon and vaso global conversions | Add taza, tazon and vaso global conversions
| Python | bsd-3-clause | pignacio/vld | ---
+++
@@ -11,4 +11,7 @@
DEFAULT_CONVERSIONS = {
'kg': {'g': 1000},
'l': {'ml': 1000},
+ 'taza': {'ml': 250},
+ 'tazon': {'ml': 350},
+ 'vaso': {'ml': 300},
} # yapf: disable |
18da33bd5524a7e9a043de90fb9b7aa78a26412d | addons/meme.py | addons/meme.py | import discord
import random
from discord.ext import commands
class Meme:
"""
Meme commands.
"""
def __init__(self, bot):
self.bot = bot
print('Addon "{}" loaded'.format(self.__class__.__name__))
@commands.has_permissions(kick_members=True)
@commands.command(pass_context=True... | import discord
import random
from discord.ext import commands
class Meme:
"""
Meme commands.
"""
def __init__(self, bot):
self.bot = bot
print('Addon "{}" loaded'.format(self.__class__.__name__))
@commands.command(pass_context=True, hidden=True, name="bam")
async def bam_memb... | Allow everyone to bam and warm, hide commands | Allow everyone to bam and warm, hide commands | Python | apache-2.0 | 916253/Kurisu-Reswitched | ---
+++
@@ -12,16 +12,14 @@
self.bot = bot
print('Addon "{}" loaded'.format(self.__class__.__name__))
- @commands.has_permissions(kick_members=True)
- @commands.command(pass_context=True, name="bam")
+ @commands.command(pass_context=True, hidden=True, name="bam")
async def bam_member... |
b82fc6f21245cba7fadb35a6676433f015aad516 | tripleo_common/utils/tarball.py | tripleo_common/utils/tarball.py | # Copyright 2016 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | # Copyright 2016 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | Exclude more unneeded files from default plan | Exclude more unneeded files from default plan
This patch exludes more file types from the tarball uploaded to swift as
the default deployment plan.
Change-Id: I8b6d8de8d7662604cdb871fa6a4fb872c7937e25
Closes-Bug: #1613286
| Python | apache-2.0 | openstack/tripleo-common,openstack/tripleo-common | ---
+++
@@ -23,7 +23,8 @@
"""Create a tarball of a directory."""
LOG.debug('Creating tarball of %s at location %s' % (directory, filename))
processutils.execute('/usr/bin/tar', '-C', directory, options, filename,
- '--exclude', '.git', '--exclude', '.tox', '.')
+ ... |
7ac384be36e22919a15fc7d25de25aa7afcd9382 | statscache/consumer.py | statscache/consumer.py | import copy
import fedmsg.consumers
import logging
log = logging.getLogger("fedmsg")
class StatsConsumer(fedmsg.consumers.FedmsgConsumer):
"""
The actual 'cache' of statscache that accumulates messages to be processed.
"""
topic = '*'
config_key = 'statscache.consumer.enabled'
def __init__(s... | import copy
import fedmsg.consumers
import logging
log = logging.getLogger("fedmsg")
class StatsConsumer(fedmsg.consumers.FedmsgConsumer):
"""
The actual 'cache' of statscache that accumulates messages to be processed.
"""
topic = '*'
config_key = 'statscache.consumer.enabled'
def __init__(s... | Create missing bucket for one-day frequency | Create missing bucket for one-day frequency
| Python | lgpl-2.1 | yazman/statscache,yazman/statscache,yazman/statscache | ---
+++
@@ -21,6 +21,7 @@
'OneSecond': [],
'FiveSecond': [],
'OneMinute': [],
+ 'OneDay': [],
}
def consume(self, raw_msg): |
8cbc55794d67571831ccc22b1ccdcf716362d814 | tests/test_hmmsearch3.py | tests/test_hmmsearch3.py | import os
import unittest
import sys
# hack to allow tests to find inmembrane in directory above
module_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(module_dir, '..'))
import inmembrane
class TestHmmsearch3(unittest.TestCase):
def setUp(self):
self.dir = os.path.join(modul... | import os
import unittest
import sys
# hack to allow tests to find inmembrane in directory above
module_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(module_dir, '..'))
import inmembrane
class TestHmmsearch3(unittest.TestCase):
def setUp(self):
self.dir = os.path.join(modul... | Put correct directory for profiles in test_hmmsearch | Put correct directory for profiles in test_hmmsearch
| Python | bsd-2-clause | boscoh/inmembrane | ---
+++
@@ -21,7 +21,7 @@
self.params = inmembrane.get_params()
self.params['fasta'] = "hmmsearch3.fasta"
- self.params['hmm_profiles_dir'] = "../../protocols/gram_neg_profiles"
+ self.params['hmm_profiles_dir'] = "../../protocols/gram_pos_profiles"
self.seqids, self.proteins = \
i... |
cbadf5c564d7f5f701499409e2ae77ff90ba477c | tests/test_tensorflow.py | tests/test_tensorflow.py | import unittest
import numpy as np
import tensorflow as tf
from common import gpu_test
class TestTensorflow(unittest.TestCase):
def test_addition(self):
op = tf.add(2, 3)
sess = tf.Session()
result = sess.run(op)
self.assertEqual(5, result)
@gpu_test
... | import unittest
import numpy as np
import tensorflow as tf
from common import gpu_test
class TestTensorflow(unittest.TestCase):
def test_addition(self):
op = tf.add(2, 3)
sess = tf.Session()
result = sess.run(op)
self.assertEqual(5, result)
def test_conv2d(... | Add conv2d test for tensorflow | Add conv2d test for tensorflow
| Python | apache-2.0 | Kaggle/docker-python,Kaggle/docker-python | ---
+++
@@ -14,6 +14,15 @@
result = sess.run(op)
self.assertEqual(5, result)
+
+ def test_conv2d(self):
+ input = tf.random_normal([1,2,2,1])
+ filter = tf.random_normal([1,1,1,1])
+
+ op = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='SAME')
+ with tf.S... |
dfd4a6f6b23447538b2b22da11666f5218d791db | mots_vides/constants.py | mots_vides/constants.py | """
Constants for mots-vides
"""
import os
DATA_DIRECTORY = os.path.join(
os.path.dirname(
os.path.abspath(__file__)),
'datas/'
)
| """
Constants for mots-vides
"""
import os
DATA_DIRECTORY = os.path.join(
os.path.dirname(
os.path.abspath(__file__)),
'datas/'
)
LANGUAGE_CODES = {
'af': 'afrikaans',
'ar': 'arabic',
'az': 'azerbaijani',
'bg': 'bulgarian',
'be': 'belarusian',
'bn': 'bengali',
'br': 'breton... | Define a complete list of language code, for easy future maintenance | Define a complete list of language code, for easy future maintenance
| Python | bsd-3-clause | Fantomas42/mots-vides,Fantomas42/mots-vides | ---
+++
@@ -8,3 +8,78 @@
os.path.abspath(__file__)),
'datas/'
)
+
+LANGUAGE_CODES = {
+ 'af': 'afrikaans',
+ 'ar': 'arabic',
+ 'az': 'azerbaijani',
+ 'bg': 'bulgarian',
+ 'be': 'belarusian',
+ 'bn': 'bengali',
+ 'br': 'breton',
+ 'bs': 'bosnian',
+ 'ca': 'catalan',
+ 'cs':... |
8dc6c7567f9bc94dc1b4a96b80d059f1231039bc | st2auth_flat_file_backend/__init__.py | st2auth_flat_file_backend/__init__.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | Fix code so it also works under Python 3. | Fix code so it also works under Python 3.
| Python | apache-2.0 | StackStorm/st2-auth-backend-flat-file | ---
+++
@@ -13,7 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from flat_file import FlatFileAuthenticationBackend
+from __future__ import absolute_import
+
+from .flat_file import FlatFileAuthenticationBackend
__all__ = [
'FlatFileAuthent... |
4abd7baafcd982993471d5c0137d4b506ea49e8b | src/runcommands/util/enums.py | src/runcommands/util/enums.py | import enum
import os
import subprocess
import sys
import blessings
from .misc import isatty
if isatty(sys.stdout) and os.getenv("TERM"):
Terminal = blessings.Terminal
else:
class Terminal:
def __getattr__(self, name):
return ""
TERM = Terminal()
class Color(enum.Enum):
none = ... | import enum
import os
import subprocess
import sys
import blessings
from .misc import isatty
if isatty(sys.stdout) and os.getenv("TERM"):
Terminal = blessings.Terminal
else:
# XXX: Mock terminal that returns "" for all attributes
class TerminalValue:
registry = {}
@classmethod
d... | Fix Color enum setup when TERM isn't set | Fix Color enum setup when TERM isn't set
The previous version of this didn't work right because all the values
were the same empty string.
This works around that by creating distinct values that evaluate to "".
Amends 94b55ead63523f7f5677989f1a4999994b205cdf
| Python | mit | wylee/runcommands,wylee/runcommands | ---
+++
@@ -11,10 +11,28 @@
if isatty(sys.stdout) and os.getenv("TERM"):
Terminal = blessings.Terminal
else:
+ # XXX: Mock terminal that returns "" for all attributes
+ class TerminalValue:
+ registry = {}
+
+ @classmethod
+ def get(cls, name):
+ if name not in cls.registr... |
c4ee061f62e34c70cc67286ed0291423353cbcbe | imgur_cli/utils.py | imgur_cli/utils.py | import json
def cli_arg(*args, **kwargs):
"""Decorator for CLI args"""
def _decorator(func):
add_arg(func, *args, **kwargs)
return func
return _decorator
def add_arg(func, *args, **kwargs):
"""Bind CLI arguments a 'cmd_' format function"""
if not hasattr(func, 'arguments'):
... | import json
def cli_arg(*args, **kwargs):
"""Decorator for CLI args"""
def _decorator(func):
add_arg(func, *args, **kwargs)
return func
return _decorator
def add_arg(func, *args, **kwargs):
"""Bind CLI arguments to a 'cmd_' format function"""
if not hasattr(func, 'arguments'):
... | Define function and decorators for subparsers | Define function and decorators for subparsers
| Python | mit | ueg1990/imgur-cli | ---
+++
@@ -10,7 +10,7 @@
def add_arg(func, *args, **kwargs):
- """Bind CLI arguments a 'cmd_' format function"""
+ """Bind CLI arguments to a 'cmd_' format function"""
if not hasattr(func, 'arguments'):
func.arguments = []
@@ -20,6 +20,20 @@
func.arguments.insert(0, (args, kwargs)... |
5ff58311b6cf2dc8ad03351e818d05fca9e33e1b | hastexo/migrations/0010_add_user_foreign_key.py | hastexo/migrations/0010_add_user_foreign_key.py | from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations, models
import django.db.models.deletion
import logging
logger = logging.getLogger(__name__)
class Migration(migrations.Migration):
def backfill_learner(apps, schema_editor):
"""
... | from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations, models
import django.db.models.deletion
import logging
logger = logging.getLogger(__name__)
class Migration(migrations.Migration):
def backfill_learner(apps, schema_editor):
"""
... | Apply additional fix to add_user_foreign_key migration | Apply additional fix to add_user_foreign_key migration
The hack in 583fb729b1e201c830579345dca5beca4b131006 modified
0010_add_user_foreign_key in such a way that it ended up *not* setting
a database constraint when it should have.
Enable the database-enforced constraint in the right place.
Co-authored-by: Florian Ha... | Python | agpl-3.0 | hastexo/hastexo-xblock,hastexo/hastexo-xblock,hastexo/hastexo-xblock,hastexo/hastexo-xblock | ---
+++
@@ -40,4 +40,13 @@
to=settings.AUTH_USER_MODEL),
),
migrations.RunPython(backfill_learner),
+ migrations.AlterField(
+ model_name='stack',
+ name='learner',
+ field=models.ForeignKey(
+ db_constraint=True,
+ ... |
ea73cd99b6ff67d65c0784471603d8734b6b3d75 | scripts/plot_example.py | scripts/plot_example.py | import os
import matplotlib.pyplot as plt
plt.style.use("ggplot")
plt.rcParams["figure.figsize"] = 10, 5
plt.rcParams["font.family"] = "serif"
plt.rcParams["font.size"] = 12
import pyhector
from pyhector import rcp26, rcp45, rcp60, rcp85
path = os.path.join(os.path.dirname(__file__),
'./example-p... | import os
import matplotlib.pyplot as plt
plt.style.use("ggplot")
plt.rcParams["figure.figsize"] = 10, 5
plt.rcParams["font.family"] = "serif"
plt.rcParams["font.size"] = 12
import pyhector
from pyhector import rcp26, rcp45, rcp60, rcp85
path = os.path.join(os.path.dirname(__file__),
'./example-p... | Update example plot script with new API | Update example plot script with new API
| Python | agpl-3.0 | openclimatedata/pyhector,openclimatedata/pyhector,openclimatedata/pyhector | ---
+++
@@ -13,7 +13,7 @@
'./example-plot.png')
for rcp in [rcp26, rcp45, rcp60, rcp85]:
- output, _ = pyhector.run(rcp, {"core": {"endDate": 2100}})
+ output = pyhector.run(rcp, {"core": {"endDate": 2100}})
temp = output["temperature.Tgav"]
temp = temp.loc[1850:] - temp.loc[18... |
7519bebe1d9d87930275858a537dcc0a0a64f007 | tools/strip_filenames.py | tools/strip_filenames.py | #!/bin/python
import os
directory = os.listdir()
illegal_characters = "%?_'*+$!\""
tolowercase=True
for a in range(len(directory)):
newname=""
for c in directory[a]:
if c in illegal_characters:
continue
if c.isalnum() or c == '.':
newname=newname+c.lower()
print("con... | #!/bin/env python3
"""
Use only legal characters from files or current directory
Usage:
strip_filenames.py [<filename>...]
Options:
-l, --lowercase Only lowercase
-h, --help Show this screen and exit.
"""
import sys
import os
from docopt import docopt
# docopt(doc, argv=None, help=True, version=None, op... | Use legal characters for stripping filenames | Use legal characters for stripping filenames
| Python | mit | dgengtek/scripts,dgengtek/scripts | ---
+++
@@ -1,16 +1,41 @@
-#!/bin/python
+#!/bin/env python3
+"""
+Use only legal characters from files or current directory
+Usage:
+ strip_filenames.py [<filename>...]
+Options:
+ -l, --lowercase Only lowercase
+ -h, --help Show this screen and exit.
+"""
+
+import sys
import os
-directory = os.listdir(... |
0fac3d59a34a861c7a826b0d1fa2f3002356e04c | src/shared.py | src/shared.py | # -*- coding: utf-8 -*-
import logging
import os
import queue
import threading
listening_port = 8444
send_outgoing_connections = True
listen_for_connections = True
data_directory = 'minode_data/'
source_directory = os.path.dirname(os.path.realpath(__file__))
trusted_peer = None
# trusted_peer = ('127.0.0.1', 8444)
lo... | # -*- coding: utf-8 -*-
import logging
import os
import queue
import threading
listening_port = 8444
send_outgoing_connections = True
listen_for_connections = True
data_directory = 'minode_data/'
source_directory = os.path.dirname(os.path.realpath(__file__))
trusted_peer = None
# trusted_peer = ('127.0.0.1', 8444)
lo... | Change User Agent to comply with specification | Change User Agent to comply with specification
| Python | mit | TheKysek/MiNode,TheKysek/MiNode | ---
+++
@@ -19,7 +19,7 @@
services = 3 # NODE_NETWORK, NODE_SSL
stream = 1
nonce = os.urandom(8)
-user_agent = b'MiNode-v0.2.0'
+user_agent = b'/MiNode:0.2.1/'
timeout = 600
header_length = 24
|
c0b76d401b305c1bcd2ed5814a89719d4c6a3d83 | heat_cfnclient/tests/test_cli.py | heat_cfnclient/tests/test_cli.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... | Disable tests until new repo is stable | Disable tests until new repo is stable
Change-Id: Ic6932c1028c72b5600d03ab59102d1c1cff1b36c
| Python | apache-2.0 | openstack-dev/heat-cfnclient | ---
+++
@@ -21,6 +21,7 @@
basepath = os.path.join(heat_cfnclient.__path__[0], os.path.pardir)
+@testtools.skip
class CliTest(testtools.TestCase):
def test_heat_cfn(self): |
82ad6bf164000940e17dcb01b27b22b97c69beba | questionnaire/urls.py | questionnaire/urls.py | # vim: set fileencoding=utf-8
from django.conf.urls.defaults import *
from views import *
urlpatterns = patterns('',
url(r'^$',
questionnaire, name='questionnaire_noargs'),
url(r'^csv/(?P<qid>\d+)/',
export_csv, name='export_csv'),
url(r'^(?P<runcode>[^/]+)/(?P<qs>\d+)/$',
... | # vim: set fileencoding=utf-8
from django.conf.urls.defaults import *
from views import *
urlpatterns = patterns('',
url(r'^$',
questionnaire, name='questionnaire_noargs'),
url(r'^csv/(?P<qid>\d+)/',
export_csv, name='export_csv'),
url(r'^(?P<runcode>[^/]+)/(?P<qs>[-]{0,1}\d+)/$',
... | Enable questionsets with negative sortids | Enable questionsets with negative sortids
| Python | bsd-3-clause | JanOosting/ed-questionnaire,affan2/ed-questionnaire,seantis/seantis-questionnaire,n3storm/seantis-questionnaire,affan2/ed-questionnaire,daniboy/seantis-questionnaire,eugena/ed-questionnaire,eugena/seantis-questionnaire,JanOosting/ed-questionnaire,eugena/seantis-questionnaire,trantu/seantis-questionnaire,daniboy/seantis... | ---
+++
@@ -8,7 +8,7 @@
questionnaire, name='questionnaire_noargs'),
url(r'^csv/(?P<qid>\d+)/',
export_csv, name='export_csv'),
- url(r'^(?P<runcode>[^/]+)/(?P<qs>\d+)/$',
+ url(r'^(?P<runcode>[^/]+)/(?P<qs>[-]{0,1}\d+)/$',
questionnaire, name='questionset'),
url... |
c3bb58fbcbd7c1699571859af736952c36f3029a | project/library/urls.py | project/library/urls.py | from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('library',
url(r'^all$',
view='views.listing',
kwargs={'template':'book_listing.html'},
name='listing'
),
url(r... | from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('library',
url(r'^all$',
view='views.listing',
kwargs={'template':'book_listing.html'},
name='listing'
),
url(r... | Update url for books to be more semantic | Update url for books to be more semantic
| Python | mit | DUCSS/ducss-site-old,DUCSS/ducss-site-old,DUCSS/ducss-site-old | ---
+++
@@ -10,7 +10,7 @@
kwargs={'template':'book_listing.html'},
name='listing'
),
- url(r'^library/(?P<id>[-\w]+)/$',
+ url(r'^book/(?P<id>[-\w]+)/$',
view='views.book',
kwargs={'template':'book.html'},
name='book' |
a15518111b6d03a4b67a2dbaa759afff15fe3302 | spec/Report_S52_spec.py | spec/Report_S52_spec.py | from expects import expect, equal
from primestg.report import Report
with fdescription('Report S52 example'):
with before.all:
self.data_filename = 'spec/data/MRTR000000822522_0_S52_1_20200929001048'
self.report = {}
with open(self.data_filename) as data_file:
self.report = R... | from expects import expect, equal
from primestg.report import Report
with description('Report S52 example'):
with before.all:
self.data_filename = 'spec/data/MRTR000000822522_0_S52_1_20200929001048'
self.report = {}
with open(self.data_filename) as data_file:
self.report = Re... | FIX only pass S52 test | FIX only pass S52 test
| Python | agpl-3.0 | gisce/primestg | ---
+++
@@ -2,7 +2,7 @@
from primestg.report import Report
-with fdescription('Report S52 example'):
+with description('Report S52 example'):
with before.all:
self.data_filename = 'spec/data/MRTR000000822522_0_S52_1_20200929001048' |
8d5d45f3a04235a9ee4fd1cadd39cc0010775ac9 | humbug/ratelimit.py | humbug/ratelimit.py | import traceback
from hashlib import sha256
from datetime import datetime, timedelta
# Adapted http://djangosnippets.org/snippets/2242/ by user s29 (October 25, 2010)
class _RateLimitFilter(object):
last_error = 0
def filter(self, record):
from django.conf import settings
from django.core.cac... | import traceback
from hashlib import sha256
from datetime import datetime, timedelta
# Adapted http://djangosnippets.org/snippets/2242/ by user s29 (October 25, 2010)
class _RateLimitFilter(object):
last_error = datetime.min
def filter(self, record):
from django.conf import settings
from djan... | Use datetime.min for initial last_error rather than int 0. | Use datetime.min for initial last_error rather than int 0.
Otherwise, code may break when it encounters a comparison against
last_error.
(imported from commit 301f256fba065ae9704b1d7f6e91e69ec54f1aa1)
| Python | apache-2.0 | levixie/zulip,zwily/zulip,reyha/zulip,rht/zulip,jrowan/zulip,praveenaki/zulip,esander91/zulip,jeffcao/zulip,Juanvulcano/zulip,zachallaun/zulip,Batterfii/zulip,KingxBanana/zulip,krtkmj/zulip,zorojean/zulip,christi3k/zulip,easyfmxu/zulip,arpitpanwar/zulip,glovebx/zulip,yuvipanda/zulip,ashwinirudrappa/zulip,johnnygaddarr/... | ---
+++
@@ -5,7 +5,7 @@
# Adapted http://djangosnippets.org/snippets/2242/ by user s29 (October 25, 2010)
class _RateLimitFilter(object):
- last_error = 0
+ last_error = datetime.min
def filter(self, record):
from django.conf import settings |
79c6c71ab6edd8313fd6c9c6441d69ad04d50721 | update-database/stackdoc/namespaces/microsoftkb.py | update-database/stackdoc/namespaces/microsoftkb.py | import re
import urllib
############### Functions called by stackdoc
def get_version():
return 1
def get_ids(title, body, tags):
ids = []
if "http://support.microsoft.com/":
urls = re.findall(r'<a href="([^"]+)"', body)
for url in urls:
m = re.match("http://support\.microsoft... | import re
import urllib
############### Functions called by stackdoc
def get_version():
return 1
def get_ids(title, body, tags):
ids = []
if "http://support.microsoft.com/":
urls = re.findall(r'<a href="([^"]+)"', body)
for url in urls:
m = re.match("http://support\.microsoft... | Support another form of KB URL. | Support another form of KB URL.
| Python | bsd-3-clause | alnorth/stackdoc,alnorth/stackdoc,alnorth/stackdoc | ---
+++
@@ -12,9 +12,12 @@
if "http://support.microsoft.com/":
urls = re.findall(r'<a href="([^"]+)"', body)
for url in urls:
- m = re.match("http://support\.microsoft\.com/(?:default.aspx/)?kb/(\w+)", url)
+ m = re.match("http://support\.microsoft\.com/(?:default\.aspx/)?... |
640ad3ed45eef21f2b7a71b4fd73a469ebed4b44 | reobject/models/fields.py | reobject/models/fields.py | import attr
def Field(*args, default=attr.NOTHING, **kwargs):
if callable(default):
default = attr.Factory(default)
return attr.ib(*args, default=default, **kwargs)
def ManyToManyField(cls, *args, **kwargs):
metadata = {
'related': {
'target': cls,
'type': 'ManyT... | import attr
def Field(*args, default=attr.NOTHING, **kwargs):
if callable(default):
default = attr.Factory(default)
return attr.ib(*args, default=default, **kwargs)
def ManyToManyField(cls, *args, **kwargs):
metadata = {
'related': {
'target': cls,
'type': 'ManyT... | Fix tests on Python 3.3 and 3.4 | Fix tests on Python 3.3 and 3.4
| Python | apache-2.0 | onyb/reobject,onyb/reobject | ---
+++
@@ -16,4 +16,4 @@
}
}
- return attr.ib(*args, **kwargs, metadata=metadata)
+ return attr.ib(*args, metadata=metadata, **kwargs) |
c32bdff4b0ee570ed58cd869830d89e3251cf82a | pytils/test/__init__.py | pytils/test/__init__.py | # -*- coding: utf-8 -*-
"""
Unit tests for pytils
"""
__all__ = ["test_numeral", "test_dt", "test_translit", "test_utils", "test_typo"]
import unittest
def get_django_suite():
try:
import django
except ImportError:
return unittest.TestSuite()
import pytils.test.templatetags
return... | # -*- coding: utf-8 -*-
"""
Unit tests for pytils
"""
__all__ = ["test_numeral", "test_dt", "test_translit", "test_utils", "test_typo"]
import unittest
import sys
def get_django_suite():
try:
import django
except ImportError:
return unittest.TestSuite()
import pytils.test.templatetags... | Exit with non-0 status if there are failed tests or errors. | Py3: Exit with non-0 status if there are failed tests or errors.
| Python | mit | Forever-Young/pytils,j2a/pytils | ---
+++
@@ -5,6 +5,7 @@
__all__ = ["test_numeral", "test_dt", "test_translit", "test_utils", "test_typo"]
import unittest
+import sys
def get_django_suite():
try:
@@ -40,7 +41,9 @@
def run(verbosity=1):
"""Run all unit-test of pytils"""
suite = get_suite()
- unittest.TextTestRunner(verbosity... |
7e25472dab7732dc76bfb81d720946c18811962f | src/appengine/driver.py | src/appengine/driver.py | """List drivers and send them commands."""
import logging
import flask
from appengine import device, rest
class Query(object):
def iter(self):
for name, cls in device.DEVICE_TYPES.iteritems():
yield Driver(name, cls)
class Driver(object):
"""This is a fake for compatibility with the rest module"""
... | """List drivers and send them commands."""
import logging
import flask
from appengine import device, rest
class Query(object):
def iter(self):
for name, cls in device.DEVICE_TYPES.iteritems():
yield Driver(name, cls)
class Driver(object):
"""This is a fake for compatibility with the rest module"""
... | Fix 'put is not a command' error on static commands | Fix 'put is not a command' error on static commands
| Python | mit | tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation | ---
+++
@@ -33,6 +33,10 @@
return func
@staticmethod
+ def put():
+ pass
+
+ @staticmethod
def query():
return Query()
|
a54933f5fb5e958c890839c58fcba4e658c8e2a0 | bitbots_head_behavior/scripts/testHeadBehaviour.py | bitbots_head_behavior/scripts/testHeadBehaviour.py | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
import rospy
from humanoid_league_msgs.msg import BallInImage, BallRelative, BallsInImage
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
def run():
pub_ball = rospy.Publisher("ball_in_image", BallsInImage, queue_size=1)
pub_hmg = rospy.Publ... | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
import rospy
from humanoid_league_msgs.msg import BallInImage, BallRelative, BallInImageArray
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
def run():
pub_ball = rospy.Publisher("ball_in_image", BallsInImage, queue_size=1)
pub_hmg = rospy.... | Test Head Behavior: Apply new HLM | Test Head Behavior: Apply new HLM
| Python | bsd-3-clause | bit-bots/bitbots_behaviour | ---
+++
@@ -2,7 +2,7 @@
# -*- coding:utf-8 -*-
import rospy
-from humanoid_league_msgs.msg import BallInImage, BallRelative, BallsInImage
+from humanoid_league_msgs.msg import BallInImage, BallRelative, BallInImageArray
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
@@ -19,7 +19,7 @@
... |
14d0e3b887b469c2b1979352804d8ade3184ef18 | scripts/symlinks/parent/foogroup.py | scripts/symlinks/parent/foogroup.py | #!/usr/bin/env python
import json
print json.dumps({
"_meta": {
"hostvars": {
'afoo': {}
},
},
"foo": {
"hosts": ['afoo']
}
}) | #!/usr/bin/env python
import json
print(json.dumps({
"_meta": {
"hostvars": {
'afoo': {}
},
},
"foo": {
"hosts": ['afoo']
}
}))
| Fix print statement to be py3 compatible | Fix print statement to be py3 compatible
| Python | mit | AlanCoding/Ansible-inventory-file-examples,AlanCoding/Ansible-inventory-file-examples | ---
+++
@@ -1,7 +1,7 @@
#!/usr/bin/env python
import json
-print json.dumps({
+print(json.dumps({
"_meta": {
"hostvars": {
'afoo': {}
@@ -10,4 +10,4 @@
"foo": {
"hosts": ['afoo']
}
-})
+})) |
24e80d80034084f6d2067df39fdc070e4eb41447 | diceclient.py | diceclient.py | from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from ampserver import Sum, Divide
def doMath():
d1 = ClientCreator(reactor, amp.AMP).connectTCP(
'127.0.0.1', 1234).addCallback(
lambda p: p.callRemote(Sum, a=13, b... | from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from diceserver import Sum, Divide
def doMath():
d1 = ClientCreator(reactor, amp.AMP).connectTCP(
'127.0.0.1', 1234).addCallback(
lambda p: p.callRemote(Sum, a=13, ... | Fix import path to match rename | Fix import path to match rename
| Python | mit | dripton/ampchat | ---
+++
@@ -1,7 +1,7 @@
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
-from ampserver import Sum, Divide
+from diceserver import Sum, Divide
def doMath(): |
14dd9f6cab99be6832ab98291337f4d38faae936 | fellowms/forms.py | fellowms/forms.py | from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"home_lon",
"home_lat",
"inauguration_year",
"funding_notes",
... | from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"user",
"home_lon",
"home_lat",
"inauguration_year",
"fun... | Exclude user field from form | Exclude user field from form
| Python | bsd-3-clause | softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat | ---
+++
@@ -6,6 +6,7 @@
class Meta:
model = Fellow
exclude = [
+ "user",
"home_lon",
"home_lat",
"inauguration_year", |
785208c904caacd69cb98f9ea44ee9f720752baf | src/tmlib/imextract/argparser.py | src/tmlib/imextract/argparser.py | '''
Arguments of the command line program.
'''
from . import __version__
from .cli import Imextract
from .args import ImextractInitArgs
parser, subparsers = Imextract.get_parser_and_subparsers(
required_subparsers=['init', 'run', 'submit', 'cleanup'])
parser.description = '''
Extract images from heterogeneo... | '''
Arguments of the command line program.
'''
from . import __version__
from .cli import Imextract
from .args import ImextractInitArgs
parser, subparsers = Imextract.get_parser_and_subparsers(
required_subparsers=['init', 'run', 'submit', 'cleanup', 'log'])
parser.description = '''
Extract images from hete... | Fix bug in imextract argument parser module | Fix bug in imextract argument parser module
| Python | agpl-3.0 | TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary | ---
+++
@@ -8,7 +8,7 @@
parser, subparsers = Imextract.get_parser_and_subparsers(
- required_subparsers=['init', 'run', 'submit', 'cleanup'])
+ required_subparsers=['init', 'run', 'submit', 'cleanup', 'log'])
parser.description = '''
Extract images from heterogeneous microscopic image file formats |
629bfe7ba928bc9650217b90190409708740ee82 | lib/cretonne/meta/isa/intel/defs.py | lib/cretonne/meta/isa/intel/defs.py | """
Intel definitions.
Commonly used definitions.
"""
from __future__ import absolute_import
from cdsl.isa import TargetISA, CPUMode
import base.instructions
from . import instructions as x86
ISA = TargetISA('intel', [base.instructions.GROUP, x86.GROUP])
# CPU modes for 32-bit and 64-bit operation.
I32 = CPUMode('I3... | """
Intel definitions.
Commonly used definitions.
"""
from __future__ import absolute_import
from cdsl.isa import TargetISA, CPUMode
import base.instructions
from . import instructions as x86
ISA = TargetISA('intel', [base.instructions.GROUP, x86.GROUP])
# CPU modes for 32-bit and 64-bit operation.
I64 = CPUMode('I6... | Define I64 before I32 for better encoding table compression. | Define I64 before I32 for better encoding table compression.
The encoding list compression algorithm is not the sharpest knife in the
drawer. It can reuse subsets of I64 encoding lists for I32 instructions,
but only when the I64 lists are defined first.
With this change and the previous change to the encoding list fo... | Python | apache-2.0 | sunfishcode/cretonne,stoklund/cretonne,sunfishcode/cretonne,stoklund/cretonne,stoklund/cretonne,sunfishcode/cretonne | ---
+++
@@ -11,5 +11,5 @@
ISA = TargetISA('intel', [base.instructions.GROUP, x86.GROUP])
# CPU modes for 32-bit and 64-bit operation.
+I64 = CPUMode('I64', ISA)
I32 = CPUMode('I32', ISA)
-I64 = CPUMode('I64', ISA) |
d028f66964249bab928a29d92ab4cff075352546 | integration/main.py | integration/main.py | from spec import Spec, skip
class Tessera(Spec):
def is_importable(self):
import tessera
assert tessera.app
assert tessera.db
| from contextlib import contextmanager
import os
from shutil import rmtree
from tempfile import mkdtemp
from spec import Spec, skip
@contextmanager
def _tmp():
try:
tempdir = mkdtemp()
yield tempdir
finally:
rmtree(tempdir)
@contextmanager
def _db():
with _tmp() as tempdir:
... | Add temp DB test harness + basic test | Add temp DB test harness + basic test
| Python | apache-2.0 | tessera-metrics/tessera,jmptrader/tessera,aalpern/tessera,Slach/tessera,filippog/tessera,aalpern/tessera,aalpern/tessera,section-io/tessera,urbanairship/tessera,aalpern/tessera,urbanairship/tessera,Slach/tessera,jmptrader/tessera,urbanairship/tessera,Slach/tessera,urbanairship/tessera,urbanairship/tessera,tessera-metri... | ---
+++
@@ -1,4 +1,40 @@
+from contextlib import contextmanager
+import os
+from shutil import rmtree
+from tempfile import mkdtemp
+
from spec import Spec, skip
+
+
+@contextmanager
+def _tmp():
+ try:
+ tempdir = mkdtemp()
+ yield tempdir
+ finally:
+ rmtree(tempdir)
+
+@contextmanager
+... |
1100830d3b48262dd9b94d96eb50d75c8ff69fe4 | Cogs/Emoji.py | Cogs/Emoji.py | import discord
from discord.ext import commands
from Cogs import GetImage
def setup(bot):
bot.add_cog(Emoji(bot))
class Emoji(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def emoji(self, ctx, emoji = None):
'''Outputs your CUSTOM emoji... but bigge... | import discord
from discord.ext import commands
from Cogs import GetImage
def setup(bot):
bot.add_cog(Emoji(bot))
class Emoji(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def emoji(self, ctx, emoji = None):
'''Outputs the passed emoji... but bigger... | Add support for built-in emojis | Add support for built-in emojis | Python | mit | corpnewt/CorpBot.py,corpnewt/CorpBot.py | ---
+++
@@ -12,14 +12,27 @@
@commands.command()
async def emoji(self, ctx, emoji = None):
- '''Outputs your CUSTOM emoji... but bigger! (Does not work with standard discord emojis)'''
+ '''Outputs the passed emoji... but bigger!'''
+ if emoji is None:
+ await ctx.send("Usag... |
6464028097b13b5d03969c20bae56f9f70acbbd1 | saleor/cart/middleware.py | saleor/cart/middleware.py | from __future__ import unicode_literals
from . import SessionCart, CART_SESSION_KEY
class CartMiddleware(object):
'''
Saves the cart instance into the django session.
'''
def process_request(self, request):
try:
cart_data = request.session[CART_SESSION_KEY]
cart = Ses... | from __future__ import unicode_literals
from . import SessionCart, CART_SESSION_KEY
class CartMiddleware(object):
'''
Saves the cart instance into the django session.
'''
def process_request(self, request):
try:
cart_data = request.session[CART_SESSION_KEY]
cart = Ses... | Store cart in session only when it was modified | Store cart in session only when it was modified
| Python | bsd-3-clause | HyperManTT/ECommerceSaleor,taedori81/saleor,car3oon/saleor,UITools/saleor,rodrigozn/CW-Shop,mociepka/saleor,spartonia/saleor,UITools/saleor,arth-co/saleor,UITools/saleor,paweltin/saleor,hongquan/saleor,Drekscott/Motlaesaleor,UITools/saleor,avorio/saleor,josesanch/saleor,tfroehlich82/saleor,maferelo/saleor,spartonia/sal... | ---
+++
@@ -17,6 +17,6 @@
setattr(request, 'cart', cart)
def process_response(self, request, response):
- if hasattr(request, 'cart'):
+ if hasattr(request, 'cart') and request.cart.modified:
request.session[CART_SESSION_KEY] = request.cart.for_storage()
return resp... |
3dfa781ce8e073f40eda3d80794ad1caff5d5920 | samples/migrateAccount.py | samples/migrateAccount.py | #### Migrate person to a new account within the same Org
# Requires admin role
# Useful when migrating to Enterprise Logins.
# Reassigns all items/groups to new owner and
# adds userTo to all groups which userFrom is a member.'''
from agoTools.admin import Admin
myAgol = Admin('<username>') # Replace <userna... | #### Migrate a member to a new account within the same Organization
# Requires admin role
# Useful when migrating to Enterprise Logins
# Reassigns all items/groups to new owner
# Adds userTo to all groups which userFrom is a member
from agoTools.admin import Admin
myAgol = Admin('<username>') # Replace <user... | Enhance comments in Migrate Account sample | Enhance comments in Migrate Account sample
| Python | apache-2.0 | oevans/ago-tools | ---
+++
@@ -1,15 +1,17 @@
-#### Migrate person to a new account within the same Org
+#### Migrate a member to a new account within the same Organization
# Requires admin role
-# Useful when migrating to Enterprise Logins.
-# Reassigns all items/groups to new owner and
-# adds userTo to all groups which userFrom is... |
a90c2eecf95323a6f968e1313c3d7852e4eb25b2 | speeches/management/commands/populatespeakers.py | speeches/management/commands/populatespeakers.py | from django.core.management.base import NoArgsCommand
from django.conf import settings
from popit import PopIt
from speeches.models import Speaker
class Command(NoArgsCommand):
help = 'Populates the database with people from Popit'
def handle_noargs(self, **options):
api = PopIt(instance = settings.PO... | import logging
from django.core.management.base import NoArgsCommand
from django.conf import settings
from popit import PopIt
from speeches.models import Speaker
logger = logging.getLogger(__name__)
class Command(NoArgsCommand):
help = 'Populates the database with people from Popit'
def handle_noargs(self, ... | Update speaker population command to set popit_url instead of popit_id | Update speaker population command to set popit_url instead of popit_id
| Python | agpl-3.0 | opencorato/sayit,opencorato/sayit,opencorato/sayit,opencorato/sayit | ---
+++
@@ -1,9 +1,13 @@
+import logging
from django.core.management.base import NoArgsCommand
from django.conf import settings
from popit import PopIt
from speeches.models import Speaker
+logger = logging.getLogger(__name__)
+
class Command(NoArgsCommand):
+
help = 'Populates the database with people fro... |
a5ef9a5d141ba5fd0d1d6c983cd8ac82079a1782 | run_tests.py | run_tests.py | #!/usr/bin/env python3
import os
import tempfile
from distutils.sysconfig import get_python_lib
from coalib.tests.TestHelper import TestHelper
if __name__ == '__main__':
parser = TestHelper.create_argparser(description="Runs coalas tests.")
parser.add_argument("-b",
"--ignore-bear-te... | #!/usr/bin/env python3
import os
import tempfile
from distutils.sysconfig import get_python_lib
from coalib.tests.TestHelper import TestHelper
if __name__ == '__main__':
parser = TestHelper.create_argparser(description="Runs coalas tests.")
parser.add_argument("-b",
"--ignore-bear-te... | Update run_test.py to fix coverage | tests: Update run_test.py to fix coverage
| Python | agpl-3.0 | Asalle/coala,ManjiriBirajdar/coala,jayvdb/coala,Asnelchristian/coala,RJ722/coala,abhiroyg/coala,FeodorFitsner/coala,meetmangukiya/coala,sils1297/coala,Tanmay28/coala,yashLadha/coala,Asalle/coala,scottbelden/coala,stevemontana1980/coala,sophiavanvalkenburg/coala,Tanmay28/coala,JohnS-01/coala,Nosferatul/coala,yashLadha/c... | ---
+++
@@ -29,7 +29,7 @@
ignore_list = [
os.path.join(tempfile.gettempdir(), "**"),
- os.path.join(get_python_lib(), "**"),
+ os.path.join(os.path.dirname(get_python_lib()), "**"),
os.path.join("coalib", "tests", "**"),
os.path.join("bears", "tests", "**")
] |
6de9457215e5a41a40acaf428132f46ab94fed2c | miniraf/combine.py | miniraf/combine.py | import astropy.io.fits as fits
import numpy as np
import sys
from .util import stack_fits_data
METHOD_MAP = {"median": lambda x: np.median(x, axis=0, overwrite_input=True),
"average": lambda x: np.average(x, axis=0),
"sum": lambda x: np.sum(x, axis=0)}
def create_parser(subparsers):
p... | import astropy.io.fits as fits
import numpy as np
import sys
from .util import stack_fits_data
METHOD_MAP = {"median": lambda x: np.median(x, axis=0, overwrite_input=True),
"average": lambda x: np.mean(x, axis=0),
"sum": lambda x: np.sum(x, axis=0)}
def create_parser(subparsers):
pars... | Use np.mean instead for unweighted mean | Use np.mean instead for unweighted mean
Signed-off-by: Lizhou Sha <d6acb26e253550574bc1141efa0eb5e6de15daeb@mit.edu>
| Python | mit | vulpicastor/miniraf | ---
+++
@@ -5,7 +5,7 @@
from .util import stack_fits_data
METHOD_MAP = {"median": lambda x: np.median(x, axis=0, overwrite_input=True),
- "average": lambda x: np.average(x, axis=0),
+ "average": lambda x: np.mean(x, axis=0),
"sum": lambda x: np.sum(x, axis=0)}
def creat... |
81f2a561ac27d13fb43edae1fb94b237951ff9cc | tests/rietveld/test_braggtree.py | tests/rietveld/test_braggtree.py | from __future__ import absolute_import, print_function
import unittest
from qtpy.QtWidgets import QApplication
from addie.rietveld.braggtree import BraggTree, BankRegexException
class BraggTreeTests(unittest.TestCase):
def setUp(self):
self.main_window = QApplication([])
def tearDown(self):
s... | from __future__ import absolute_import, print_function
import pytest
from addie.main import MainWindow
from addie.rietveld.braggtree import BraggTree, BankRegexException
@pytest.fixture
def braggtree():
return BraggTree(None)
def test_get_bank_id(qtbot, braggtree):
"""Test we can extract a bank id from bank ... | Refactor BraggTree test to use pytest-qt | Refactor BraggTree test to use pytest-qt
| Python | mit | neutrons/FastGR,neutrons/FastGR,neutrons/FastGR | ---
+++
@@ -1,35 +1,27 @@
from __future__ import absolute_import, print_function
-import unittest
-from qtpy.QtWidgets import QApplication
+import pytest
+from addie.main import MainWindow
from addie.rietveld.braggtree import BraggTree, BankRegexException
-
-class BraggTreeTests(unittest.TestCase):
- def setUp... |
5daa628d59576f00d0c5d49358a800dd728c6fdf | necropsy/models.py | necropsy/models.py | # -*- coding: utf-8 -*-
from django.db import models
# Create your models here.
class Necropsy (models.Model):
clinical_information = models.TextField(null=True, blank=True)
macroscopic = models.TextField(null=True, blank=True)
microscopic = models.TextField(null=True, blank=True)
conclusion = models.TextField(nul... | # -*- coding: utf-8 -*-
from django.db import models
from modeling.exam import Exam
from modeling.report import ReportStatus
class NecropsyStatus(models.Model):
description = models.CharField(max_length=50)
class Necropsy(models.Model):
clinical_information = models.TextField(null=True, blank=True)
main... | Add NecropsyReport in Model Necropsy | Add NecropsyReport in Model Necropsy
| Python | mit | msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub | ---
+++
@@ -1,12 +1,33 @@
# -*- coding: utf-8 -*-
+
from django.db import models
+from modeling.exam import Exam
+from modeling.report import ReportStatus
-# Create your models here.
-class Necropsy (models.Model):
- clinical_information = models.TextField(null=True, blank=True)
- macroscopic = models.TextField(n... |
2ba4e0758c04bebcd1dcde78e99605d0b9460abf | foldatlas/monitor.py | foldatlas/monitor.py | import os
# must call "sudo apt-get install sendmail" first...
# if sts != 0:
# print("Sendmail exit status "+str(sts))
def send_error(recipient, error_details):
SENDMAIL = "/usr/sbin/sendmail" # sendmail location
p = os.popen("%s -t" % SENDMAIL, "w")
p.write("To: "+recipient+"\n")
p.write("Subject: Fold... | import traceback
import os
import urllib.request # the lib that handles the url stuff
test_url = "http://www.foldatlas.com/transcript/AT2G45180.1"
recipient = "matthew.gs.norris@gmail.com"
search_str = "AT2G45180.1"
def run_test():
try:
data = urllib.request.urlopen(test_url) # it's a file like object and works ... | Monitor now checks and emails | Monitor now checks and emails
| Python | mit | mnori/foldatlas,mnori/foldatlas,mnori/foldatlas,mnori/foldatlas | ---
+++
@@ -1,20 +1,32 @@
+import traceback
import os
+import urllib.request # the lib that handles the url stuff
-# must call "sudo apt-get install sendmail" first...
+test_url = "http://www.foldatlas.com/transcript/AT2G45180.1"
+recipient = "matthew.gs.norris@gmail.com"
+search_str = "AT2G45180.1"
+def run_te... |
6b0774eab70c42fbdd28869b6bcdab9b81183b8e | run_tests.py | run_tests.py | #!/usr/bin/env python
# tests require pytest-cov and pytest-xdist
import os
import signal
import sys
from bluesky.testing.noseclasses import KnownFailure
import pytest
try:
from pcaspy import Driver, SimpleServer
from multiprocessing import Process
def to_subproc():
prefix = 'BSTEST:'
pv... | #!/usr/bin/env python
# tests require pytest-cov and pytest-xdist
import os
import signal
import sys
import pytest
try:
from pcaspy import Driver, SimpleServer
from multiprocessing import Process
def to_subproc():
prefix = 'BSTEST:'
pvdb = {
'VAL': {
'prec': 3... | Remove deleted subpackage. Add better args to pytest | TST: Remove deleted subpackage. Add better args to pytest
| Python | bsd-3-clause | ericdill/bluesky,ericdill/bluesky | ---
+++
@@ -4,7 +4,6 @@
import os
import signal
import sys
-from bluesky.testing.noseclasses import KnownFailure
import pytest
try:
@@ -45,7 +44,8 @@
if p is not None:
p.start()
try:
- args = ['--cov bluesky']
+ # adding rxs to show extra info on skips and xfails
+ args ... |
c3a184a188d18f87bad2d7f34a2dfd3a7cca4827 | signac/common/errors.py | signac/common/errors.py | # Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
class Error(Exception):
pass
class ConfigError(Error, RuntimeError):
pass
class AuthenticationError(Error, RuntimeError):
def __str__(self):
if len... | # Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
from . import six
class Error(Exception):
pass
class ConfigError(Error, RuntimeError):
pass
class AuthenticationError(Error, RuntimeError):
def __str__(self... | Fix py27 issue in error module. | Fix py27 issue in error module.
Inherit signac internal FileNotFoundError class from IOError
instead of FileNotFoundError in python 2.7.
| Python | bsd-3-clause | csadorf/signac,csadorf/signac | ---
+++
@@ -1,7 +1,7 @@
# Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
-
+from . import six
class Error(Exception):
pass
@@ -25,8 +25,12 @@
pass
-class FileNotFoundError(Error, FileNotFoundError):
- ... |
54e78b61db2660a57762b0f0115d532b308386e4 | opal/tests/test_core_commandline.py | opal/tests/test_core_commandline.py | """
Unittests for opal.core.commandline
"""
from opal.core.test import OpalTestCase
from opal.core import commandline
| """
Unittests for opal.core.commandline
"""
from mock import patch, MagicMock
from opal.core.test import OpalTestCase
from opal.core import commandline
class StartprojectTestCase(OpalTestCase):
def test_startproject(self):
mock_args = MagicMock(name='Mock Args')
mock_args.name = 'projectname'
... | Add simple basic unittests for some of our commandline argparse target functions | Add simple basic unittests for some of our commandline argparse target functions
| Python | agpl-3.0 | khchine5/opal,khchine5/opal,khchine5/opal | ---
+++
@@ -1,6 +1,28 @@
"""
Unittests for opal.core.commandline
"""
+from mock import patch, MagicMock
+
from opal.core.test import OpalTestCase
from opal.core import commandline
+
+
+class StartprojectTestCase(OpalTestCase):
+
+ def test_startproject(self):
+ mock_args = MagicMock(name='Mock Args')... |
c00a55b8337dbc354921c195dfa4becc7ee1346a | ipython/profile_default/startup/00-imports.py | ipython/profile_default/startup/00-imports.py | """Imports for IPython"""
# pylint: disable=W0611
# import this
import os
import re
import sys
import inspect
pyprint = print
mores = []
try:
from rich.console import Console
console = Console(color_system="standard")
print = console.print
mores += ["rich"]
except ImportError:
pass
try:
fr... | """Imports for IPython"""
# pylint: disable=W0611
# import this
import os
import re
import sys
import inspect
pyprint = print
mores = []
try:
from rich.console import Console
console = Console(color_system="standard")
print = console.print
mores += ["rich"]
from rich import pretty
pretty.in... | Use rich for printing in ipython | Use rich for printing in ipython
| Python | mit | jalanb/jab,jalanb/dotjab,jalanb/dotjab,jalanb/jab | ---
+++
@@ -17,6 +17,8 @@
console = Console(color_system="standard")
print = console.print
mores += ["rich"]
+ from rich import pretty
+ pretty.install()
except ImportError:
pass
|
80ca0bebce22f64d0d01377493126ed95d8a64cb | falcom/luhn.py | falcom/luhn.py | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
def get_check_digit_from_checkable_int (number):
return (9 * ((number // 10) + rotate_digit(number % 10))) % 10
def rotate_digit (digit)... | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
def rotate_digit (digit):
if digit > 4:
return (digit * 2) - 9
else:
return digit * 2
def get_check_digit_from_chec... | Reorder methods to make sense | Reorder methods to make sense
| Python | bsd-3-clause | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation | ---
+++
@@ -1,9 +1,6 @@
# Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
-
-def get_check_digit_from_checkable_int (number):
- return (9 * ((number // 10) + rotate_digit(number % 10))... |
d5ee1185f0249d2e29f78866eb29552921b69ec9 | config.py | config.py | import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
@staticmethod
def init_app(app):
repo_root = os.path.abspath(os.path.dirname(__file__))
template_folders = [
os.path.join(repo_root,
'bower_components/govuk_template... | import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
STATIC_URL_PATH = '/supplier/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_class': 'with-proposition'
}
@stat... | Add supplier/ prefix to static file paths | Add supplier/ prefix to static file paths
| Python | mit | mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,mtek... | ---
+++
@@ -4,7 +4,15 @@
basedir = os.path.abspath(os.path.dirname(__file__))
-class Config:
+class Config(object):
+ DEBUG = False
+ STATIC_URL_PATH = '/supplier/static'
+ ASSET_PATH = STATIC_URL_PATH + '/'
+ BASE_TEMPLATE_DATA = {
+ 'asset_path': ASSET_PATH,
+ 'header_class': 'with-pr... |
286dced2c23b90dba53848423d6f29873779d177 | config.py | config.py | import os
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY')
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL')
class TestingConfig(Config):
... | import os
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY')
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL')
class TestingConfig(Config):
... | Use sqlite as DB for test if none set in environment | Use sqlite as DB for test if none set in environment
| Python | mit | boltzj/movies-in-sf | ---
+++
@@ -17,7 +17,12 @@
class TestingConfig(Config):
TESTING = True
- SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL')
+
+ if os.environ.get('TEST_DATABASE_URL'):
+ SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL')
+ else:
+ basedir = os.path.abspath(os.path.... |
a6e46fc5429840fd3ff47c03d8b0d9f3b28c7811 | src/sentry/api/endpoints/group_events_latest.py | src/sentry/api/endpoints/group_events_latest.py | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api import client
from sentry.api.base import DocSection
from sentry.api.bases.group import GroupEndpoint
class GroupEventsLatestEndpoint(GroupEndpoint):
doc_section = DocSection.EVENTS
def get(self, request, gr... | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api import client
from sentry.api.base import DocSection
from sentry.api.bases.group import GroupEndpoint
class GroupEventsLatestEndpoint(GroupEndpoint):
doc_section = DocSection.EVENTS
def get(self, request, gr... | Handle no latest event (fixes GH-1727) | Handle no latest event (fixes GH-1727)
| Python | bsd-3-clause | imankulov/sentry,hongliang5623/sentry,fotinakis/sentry,BuildingLink/sentry,gencer/sentry,mitsuhiko/sentry,BuildingLink/sentry,beeftornado/sentry,mvaled/sentry,daevaorn/sentry,wong2/sentry,ifduyue/sentry,jean/sentry,ifduyue/sentry,Kryz/sentry,jean/sentry,kevinlondon/sentry,fotinakis/sentry,pauloschilling/sentry,korealer... | ---
+++
@@ -20,6 +20,8 @@
"""
event = group.get_latest_event()
+ if not event:
+ return Response({'detail': 'No events found for group'}, status=404)
try:
return client.get('/events/{}/'.format(event.id), request.user, request.auth) |
666fc19e2949a30cbe40bf6020c141e84dfcae1e | app/soc/models/project_survey.py | app/soc/models/project_survey.py | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# 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... | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# 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... | Set the default prefix for ProjectSurveys to gsoc_program. | Set the default prefix for ProjectSurveys to gsoc_program.
| Python | apache-2.0 | rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son | ---
+++
@@ -32,6 +32,5 @@
def __init__(self, *args, **kwargs):
super(ProjectSurvey, self).__init__(*args, **kwargs)
- # TODO: prefix has to be set to gsoc_program once data has been transferred
- self.prefix = 'program'
+ self.prefix = 'gsoc_program'
self.taking_access = 'student' |
1b9aa9909b284489c9f8a5d38b1c5520d5916dc7 | feature_extraction/measurements/__init__.py | feature_extraction/measurements/__init__.py | from collections import defaultdict
from feature_extraction.util import DefaultAttributeDict
class Measurement(object):
"""
A generic feature measurement.
Attributes
----------
default_options
Can be set by subclasses to set default option values
"""
default_options = {}
def __init__(self, options=None):
... | from collections import defaultdict
from feature_extraction.util import AttributeDict
class Measurement(object):
"""
A generic feature measurement.
Attributes
----------
default_options
Can be set by subclasses to set default option values
"""
default_options = {}
def __init__(self, options=None):
"""
... | Switch back to AttributeDict for measurement options | Switch back to AttributeDict for measurement options
| Python | apache-2.0 | widoptimization-willett/feature-extraction | ---
+++
@@ -1,5 +1,5 @@
from collections import defaultdict
-from feature_extraction.util import DefaultAttributeDict
+from feature_extraction.util import AttributeDict
class Measurement(object):
"""
@@ -23,7 +23,7 @@
options : dict
A dict of options for this measurement.
"""
- self.options = Default... |
f0bca27d58fb4bc74b6627275486dbfd159954d6 | tests/test_datafeed_fms_teams.py | tests/test_datafeed_fms_teams.py | import unittest2
import datetime
from google.appengine.ext import testbed
from datafeeds.datafeed_fms import DatafeedFms
class TestDatafeedFmsTeams(unittest2.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_urlfetch_stub()
se... | import unittest2
import datetime
from google.appengine.ext import testbed
from datafeeds.datafeed_fms import DatafeedFms
class TestDatafeedFmsTeams(unittest2.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_urlfetch_stub()
se... | Update test case for 2014 | Update test case for 2014
| Python | mit | tsteward/the-blue-alliance,verycumbersome/the-blue-alliance,1fish2/the-blue-alliance,fangeugene/the-blue-alliance,synth3tk/the-blue-alliance,synth3tk/the-blue-alliance,bvisness/the-blue-alliance,nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,1fish2/the-blue-alliance,verycumber... | ---
+++
@@ -28,7 +28,7 @@
for team in teams:
if team.team_number == 177:
found_177 = True
- self.assertEqual(team.name, "UTC / Ensign Bickford Aerospace & Defense & South Windsor High School")
+ self.assertEqual(team.name, "ClearEdge Power / United ... |
c43e120319248a804328893aad34fc774c4928d3 | stdup/kde.py | stdup/kde.py | # -*- coding: utf-8 -*-
# Copyright 2013 Jacek Mitręga
# 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 o... | # -*- coding: utf-8 -*-
# Copyright 2013 Jacek Mitręga
# 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 o... | Add KDE show & hide logging | Add KDE show & hide logging
| Python | apache-2.0 | waawal/standup-desktop,waawal/standup-desktop | ---
+++
@@ -30,12 +30,14 @@
self.workspace = 6
def show(self):
+ logger.info('kde show')
envoy.run('qdbus org.kde.kwin /KWin org.kde.KWin.setCurrentDesktop 6',
timeout=2)
# envoy.run('killall firefox', timeout=2)
# envoy.connect('firefox http://stan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.