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 |
|---|---|---|---|---|---|---|---|---|---|---|
4bc31e675659af54ee26fe5df16a0ee3ebeb5947 | firefed/__main__.py | firefed/__main__.py | import argparse
import os
import re
from firefed import Firefed
from feature import feature_map, Summary
def feature_type(val):
try:
return feature_map()[val]
except KeyError as key:
raise argparse.ArgumentTypeError(
'Feature %s not found. Choose from: {%s}' %
(key, ', ... | import argparse
import os
import re
from firefed import Firefed
from feature import feature_map, Summary
def feature_type(val):
try:
return feature_map()[val]
except KeyError as key:
raise argparse.ArgumentTypeError(
'Feature %s not found. Choose from: {%s}' %
(key, ', ... | Add default argument for profile | Add default argument for profile
| Python | mit | numirias/firefed | ---
+++
@@ -39,7 +39,7 @@
'--profile',
help='profile name or directory',
type=profile_dir,
- required=True)
+ default='default')
parser.add_argument(
'-f',
'--feature', |
138df31dc628daad0c60f062b05774d6c7d4338d | src/kuas_api/modules/const.py | src/kuas_api/modules/const.py | #-*- coding: utf-8 -*-
device_version = {
"android": "2.1.2",
"android_donate": "2.1.2",
"ios": "1.4.3"
}
# Token duration in seconds
token_duration = 3600
# HTTP Status Code
ok = 200
no_content = 204
| #-*- coding: utf-8 -*-
device_version = {
"android": "2.1.3",
"android_donate": "2.1.2",
"ios": "1.6.0"
}
# Token duration in seconds
token_duration = 3600
serect_key = "usapoijupojfa;dsj;lv;ldakjads;lfkjapoiuewqprjf"
# HTTP Status Code
ok = 200
no_content = 204
| Change android version to 2.1.3 | Change android version to 2.1.3
| Python | mit | JohnSounder/AP-API,kuastw/AP-API,kuastw/AP-API,JohnSounder/AP-API | ---
+++
@@ -1,14 +1,14 @@
#-*- coding: utf-8 -*-
-
device_version = {
- "android": "2.1.2",
+ "android": "2.1.3",
"android_donate": "2.1.2",
- "ios": "1.4.3"
+ "ios": "1.6.0"
}
# Token duration in seconds
token_duration = 3600
+serect_key = "usapoijupojfa;dsj;lv;ldakjads;lfkjapoiuewqprjf"
... |
1d9e9f2b7a2259f19a48ab0e0f41439ba5224648 | src/adhocracy/lib/auth/shibboleth.py | src/adhocracy/lib/auth/shibboleth.py | from pylons import config
def get_userbadge_mapping(config=config):
mapping = config.get('adhocracy.shibboleth.userbadge_mapping', u'')
return (line.strip().split(u' ')
for line in mapping.strip().split(u'\n')
if line is not u'')
def _attribute_equals(request, key, value):
return... | from pylons import config
def get_userbadge_mapping(config=config):
mapping = config.get('adhocracy.shibboleth.userbadge_mapping', u'')
return (line.strip().split(u' ')
for line in mapping.strip().split(u'\n')
if line is not u'')
def _attribute_equals(request, key, value):
"""
... | Add userbade mappings contains and contains_substring | Add userbade mappings contains and contains_substring
| Python | agpl-3.0 | DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,liqd/adhocracy,alkadis/vcv,SysTheron/adhocracy,phihag/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,alkadis/vcv,alkadis/vcv,liqd/adhocracy,SysTheron/adhocracy,liqd/adhocracy,phihag/adhocracy,SysTheron/adhocracy,phihag/adhocracy,phihag/adhocracy,liqd/a... | ---
+++
@@ -9,9 +9,29 @@
def _attribute_equals(request, key, value):
+ """
+ exact match
+ """
return request.headers.get(key) == value
+
+
+def _attribute_contains(request, key, value):
+ """
+ contains element
+ """
+ elements = (e.strip() for e in request.headers.get(key).split(','))... |
bd6c8b0354e9a32c47593ea19d09789d2a36912f | conanfile.py | conanfile.py | from conans import ConanFile
class CtreConan(ConanFile):
name = "CTRE"
version = "2.0"
license = "MIT"
url = "https://github.com/hanickadot/compile-time-regular-expressions.git"
author = "Hana Dusíková (ctre@hanicka.net)"
description = "Compile Time Regular Expression for C++17/20"
homepag... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile
class CtreConan(ConanFile):
name = "CTRE"
version = "2.0"
license = "MIT"
url = "https://github.com/hanickadot/compile-time-regular-expressions.git"
author = "Hana Dusíková (ctre@hanicka.net)"
description = "Compile Tim... | Use UTF-8 in Conan recipe | Use UTF-8 in Conan recipe
- Force python interpreter to use UTF-8
Signed-off-by: Uilian Ries <d4bad57018205bdda203549c36d3feb0bfe416a7@gmail.com>
| Python | apache-2.0 | hanickadot/compile-time-regular-expressions,hanickadot/compile-time-regular-expressions,hanickadot/compile-time-regular-expressions,hanickadot/syntax-parser | ---
+++
@@ -1,3 +1,5 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
from conans import ConanFile
|
ae424937a7d9341862329cf7f04bd91ccdf345cd | converter.py | converter.py | import json
import csv
def json_to_csv(json_file):
with open(json_file, 'r') as jsonfile, open('output.csv', 'w', newline='') as csvfile:
jsn = json.load(jsonfile)
fieldnames = []
for name in jsn[0]:
fieldnames += [name]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for ... | import json
import csv
import argparse
def json_to_csv(json_file):
with open(json_file, 'r') as jsonfile, open('output.csv', 'w', newline='') as csvfile:
jsn = json.load(jsonfile)
fieldnames = []
for name in jsn[0]:
fieldnames += [name]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writ... | Add command-line arguments and main function | Add command-line arguments and main function
| Python | mit | SkullTech/json-csv-converter | ---
+++
@@ -1,5 +1,6 @@
import json
import csv
+import argparse
def json_to_csv(json_file):
with open(json_file, 'r') as jsonfile, open('output.csv', 'w', newline='') as csvfile:
@@ -21,6 +22,22 @@
jsn += [row]
json.dump(jsn, jsonfile)
-
-filename = input('Enter filename of CSV file: ')
-csv_to_json... |
6a5413ce81a606476734d9b37b33f683ed0c85e3 | cards/card.py | cards/card.py | """
Created on Dec 04, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
from abc import ABCMeta, abstractproperty
class Card(metaclass=ABCMeta):
def __init__(self, suit, rank):
self._rank = rank
self._suit = suit
sel... | """
Created on Dec 04, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
from abc import ABCMeta, abstractproperty
class Card(metaclass=ABCMeta):
def __init__(self, suit, rank):
self._rank = rank
self._suit = suit
sel... | Switch to pre-python 3.6 string formatting for Codeship | Switch to pre-python 3.6 string formatting for Codeship
| Python | mit | johnpapa2/twenty-one,johnpapa2/twenty-one | ---
+++
@@ -16,7 +16,8 @@
self._value = None
def __str__(self):
- return f"{self._rank} of {self._suit}"
+ # return f"{self.rank} of {self.suit}"
+ return "{0} of {1}".format(self.rank, self.suit)
@property
def rank(self): |
58daf6f2225cdf52079072eee47f23a6d188cfa9 | resync/resource_set.py | resync/resource_set.py | """A set of Resource objects used for Capability List
Indexes and ResourceSync Description documents.
FIXME - what should the ordering be?
"""
class ResourceSet(dict):
"""Implementation of class to store resources in Capability List
Indexes and ResourceSync Description documents.
Key properties of this c... | """A set of Resource objects used for Capability List
Indexes and ResourceSync Description documents.
Ordinging is currently alphanumeric (using sorted(..)) on the
uri which is the key.
"""
class ResourceSet(dict):
"""Implementation of class to store resources in Capability List
Indexes and ResourceSync Desc... | Change comment to indicate choice of alphanum order by uri | Change comment to indicate choice of alphanum order by uri
| Python | apache-2.0 | lindareijnhoudt/resync,resync/resync,lindareijnhoudt/resync,dans-er/resync,dans-er/resync | ---
+++
@@ -1,7 +1,8 @@
"""A set of Resource objects used for Capability List
Indexes and ResourceSync Description documents.
-FIXME - what should the ordering be?
+Ordinging is currently alphanumeric (using sorted(..)) on the
+uri which is the key.
"""
class ResourceSet(dict): |
d2ad097e08b8c5e9d318968f0a6f859f03f7c07a | mycli/packages/special/dbcommands.py | mycli/packages/special/dbcommands.py | import logging
from .main import special_command, RAW_QUERY, PARSED_QUERY
log = logging.getLogger(__name__)
@special_command('\\dt', '\\dt', 'List or describe tables.', arg_type=PARSED_QUERY, case_sensitive=True)
def list_tables(cur, arg=None, arg_type=PARSED_QUERY):
if arg:
query = 'SHOW FIELDS FROM {0}'... | import logging
from .main import special_command, RAW_QUERY, PARSED_QUERY
log = logging.getLogger(__name__)
@special_command('\\dt', '\\dt [table]', 'List or describe tables.', arg_type=PARSED_QUERY, case_sensitive=True)
def list_tables(cur, arg=None, arg_type=PARSED_QUERY):
if arg:
query = 'SHOW FIELDS F... | Change \dt syntax to add an optional table name. | Change \dt syntax to add an optional table name.
| Python | bsd-3-clause | mdsrosa/mycli,jinstrive/mycli,j-bennet/mycli,martijnengler/mycli,martijnengler/mycli,mdsrosa/mycli,danieljwest/mycli,j-bennet/mycli,jinstrive/mycli,shoma/mycli,danieljwest/mycli,shoma/mycli | ---
+++
@@ -3,7 +3,7 @@
log = logging.getLogger(__name__)
-@special_command('\\dt', '\\dt', 'List or describe tables.', arg_type=PARSED_QUERY, case_sensitive=True)
+@special_command('\\dt', '\\dt [table]', 'List or describe tables.', arg_type=PARSED_QUERY, case_sensitive=True)
def list_tables(cur, arg=None, arg... |
b6096dbe06f636a462f2c1ff85470599754f613f | app/main/views/sub_navigation_dictionaries.py | app/main/views/sub_navigation_dictionaries.py | def features_nav():
return [
{
"name": "Features",
"link": "main.features",
},
{
"name": "Roadmap",
"link": "main.roadmap",
},
{
"name": "Security",
"link": "main.security",
},
{
... | def features_nav():
return [
{
"name": "Features",
"link": "main.features",
},
{
"name": "Roadmap",
"link": "main.roadmap",
},
{
"name": "Security",
"link": "main.security",
},
{
... | Remove performance link from features nav | Remove performance link from features nav
The features nav is supposed to navigate your between pages in the app.
It’s very unexpected to have it open an external link.
Performance isn’t strictly a part of Support, but it’s worked having it
there for long enough that it’s probably not a bother.
| Python | mit | gov-cjwaszczuk/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,gov-cjwaszczuk/notifications-admin,gov-cjwaszczuk/notifications-admin,gov-cjwaszczuk/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin | ---
+++
@@ -13,11 +13,6 @@
"link": "main.security",
},
{
- "name": "Performance",
- "link": "https://www.gov.uk/performance/govuk-notify",
- "external_link": True,
- },
- {
"name": "Terms of use",
"link": "main.ter... |
d565786278eaf32761957dd1e064a5d549ef3ab4 | praw/models/reddit/mixins/savable.py | praw/models/reddit/mixins/savable.py | """Provide the SavableMixin class."""
from ....const import API_PATH
class SavableMixin(object):
"""Interface for RedditBase classes that can be saved."""
def save(self, category=None):
"""Save the object.
:param category: The category to save to (Default: None).
"""
self._r... | """Provide the SavableMixin class."""
from ....const import API_PATH
class SavableMixin(object):
"""Interface for RedditBase classes that can be saved."""
def save(self, category=None):
"""Save the object.
:param category: (Gold) The category to save to (Default:
None). If your u... | Clarify that category is a gold feature for saving an item | Clarify that category is a gold feature for saving an item
| Python | bsd-2-clause | 13steinj/praw,RGood/praw,RGood/praw,darthkedrik/praw,darthkedrik/praw,leviroth/praw,gschizas/praw,leviroth/praw,gschizas/praw,praw-dev/praw,nmtake/praw,praw-dev/praw,nmtake/praw,13steinj/praw | ---
+++
@@ -8,7 +8,9 @@
def save(self, category=None):
"""Save the object.
- :param category: The category to save to (Default: None).
+ :param category: (Gold) The category to save to (Default:
+ None). If your user does not have gold this value is ignored by
+ Red... |
55dfcce3d2c42433249f401ff5021820c341a691 | entity_networks/activations.py | entity_networks/activations.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
def prelu(features, initializer=tf.constant_initializer(1), name=None):
"""
Implementation of [Parametric ReLU](https://arxiv.org/abs/1502.01852) borrowed from Keras.
"""
... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
def prelu(features, initializer=None, name=None):
"""
Implementation of [Parametric ReLU](https://arxiv.org/abs/1502.01852) borrowed from Keras.
"""
with tf.variable_sco... | Remove default initializer from prelu | Remove default initializer from prelu
| Python | mit | mikalyoung/recurrent-entity-networks,jimfleming/recurrent-entity-networks,mikalyoung/recurrent-entity-networks,jimfleming/recurrent-entity-networks | ---
+++
@@ -4,7 +4,7 @@
import tensorflow as tf
-def prelu(features, initializer=tf.constant_initializer(1), name=None):
+def prelu(features, initializer=None, name=None):
"""
Implementation of [Parametric ReLU](https://arxiv.org/abs/1502.01852) borrowed from Keras.
""" |
8a8d4905c169b9a1060f1283d0286c433af24f43 | word2gauss/words.py | word2gauss/words.py |
from itertools import islice
from .embeddings import text_to_pairs
def iter_pairs(fin, vocab, batch_size=10, nsamples=2, window=5):
'''
Convert a document stream to batches of pairs used for training embeddings.
iter_pairs is a generator that yields batches of pairs that can
be passed to GaussianEm... |
from itertools import islice
from .embeddings import text_to_pairs
def iter_pairs(fin, vocab, batch_size=10, nsamples=2, window=5):
'''
Convert a document stream to batches of pairs used for training embeddings.
iter_pairs is a generator that yields batches of pairs that can
be passed to GaussianEm... | Change the interface on tokenize in vocabulary | Change the interface on tokenize in vocabulary
| Python | mit | seomoz/word2gauss,seomoz/word2gauss | ---
+++
@@ -24,7 +24,7 @@
batch = list(islice(documents, batch_size))
while len(batch) > 0:
text = [
- vocab.tokenize(doc, remove_oov=False, return_ids=True)
+ vocab.tokenize_ids(doc, remove_oov=False)
for doc in batch
]
pairs = text_to_pairs(tex... |
11220e1df49a2fb7dfd4032bb03f595188d8178f | buildPy2app.py | buildPy2app.py | """
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'icon... | """
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'icon... | Set 10.11.0 as minimum macOS version in the .app bundle | Set 10.11.0 as minimum macOS version in the .app bundle
| Python | apache-2.0 | NeverDecaf/syncplay,alby128/syncplay,NeverDecaf/syncplay,Syncplay/syncplay,alby128/syncplay,Syncplay/syncplay | ---
+++
@@ -22,7 +22,8 @@
'CFBundleName':'Syncplay',
'CFBundleShortVersionString':syncplay.version,
'CFBundleIdentifier':'pl.syncplay.Syncplay',
- 'NSHumanReadableCopyright': '@ 2017 Syncplay All Rights Reserved'
+ 'LSMinimumSystemVersion':'10.11.0',
+ 'NSHumanReadableCopyright': '@ 2018 Syncplay All Righ... |
85df39bb82907dfec52735be3096c926c6b8bd54 | src/waldur_mastermind/marketplace/migrations/0034_change_offering_geo_data.py | src/waldur_mastermind/marketplace/migrations/0034_change_offering_geo_data.py | # Generated by Django 2.2.13 on 2020-11-23 13:44
from django.db import migrations, models
def fill_new_geo_fields(apps, schema_editor):
Offering = apps.get_model('marketplace', 'Offering')
for offering in Offering.objects.all():
if not offering.geolocations:
geolocation = offering.geoloca... | # Generated by Django 2.2.13 on 2020-11-23 13:44
from django.db import migrations, models
def fill_new_geo_fields(apps, schema_editor):
Offering = apps.get_model('marketplace', 'Offering')
for offering in Offering.objects.all():
if offering.geolocations:
geolocation = offering.geolocation... | Fix typo in database migration script. | Fix typo in database migration script.
| Python | mit | opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind | ---
+++
@@ -6,7 +6,7 @@
def fill_new_geo_fields(apps, schema_editor):
Offering = apps.get_model('marketplace', 'Offering')
for offering in Offering.objects.all():
- if not offering.geolocations:
+ if offering.geolocations:
geolocation = offering.geolocations[0]
offer... |
8111a7e32ec80a35f16c081664946292111485fe | scripts/create_shop.py | scripts/create_shop.py | #!/usr/bin/env python
"""Create a shop with article and order sequences.
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.services.shop.sequence import service as sequence_service
from byceps.services.shop.shop import service as shop_service
fr... | #!/usr/bin/env python
"""Create a shop with article and order sequences.
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.services.shop.sequence import service as sequence_service
from byceps.services.shop.shop import service as shop_service
fr... | Remove unintentional commas from argument list | Remove unintentional commas from argument list
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -16,9 +16,9 @@
@click.command()
-@click.argument('shop_id',)
+@click.argument('shop_id')
@click.argument('title')
-@click.argument('email_config_id',)
+@click.argument('email_config_id')
@click.argument('article_prefix')
@click.argument('order_prefix')
def execute(shop_id, title, email_config_id, ... |
8348f46fb78b55c5d2bcd6401f4041e8890072db | gviewer/keys/vim.py | gviewer/keys/vim.py | from collections import OrderedDict
keys = OrderedDict([
("j", "down"),
("k", "up"),
("ctrl f", "page down"),
("ctrl b", "page up")]
)
| from collections import OrderedDict
keys = OrderedDict([
("j", "down"),
("k", "up"),
("ctrl f", "page down"),
("ctrl d", "page down"),
("ctrl b", "page up"),
("ctrl u", "page up")]
)
| Add ctrl+d/ctrl+u for page down and page up | Add ctrl+d/ctrl+u for page down and page up
| Python | mit | chhsiao90/gviewer | ---
+++
@@ -5,5 +5,7 @@
("j", "down"),
("k", "up"),
("ctrl f", "page down"),
- ("ctrl b", "page up")]
+ ("ctrl d", "page down"),
+ ("ctrl b", "page up"),
+ ("ctrl u", "page up")]
) |
e2e9a7a0339ae269a239156972595d6ff590cebe | src/yunohost/data_migrations/0009_migrate_to_apps_json.py | src/yunohost/data_migrations/0009_migrate_to_apps_json.py | from moulinette.utils.log import getActionLogger
from yunohost.app import app_fetchlist, app_removelist
from yunohost.tools import Migration
logger = getActionLogger('yunohost.migration')
class MyMigration(Migration):
"Migrate from official.json to apps.json"
def migrate(self):
# Remove official.js... | from moulinette.utils.log import getActionLogger
from yunohost.app import app_fetchlist, app_removelist, _read_appslist_list
from yunohost.tools import Migration
logger = getActionLogger('yunohost.migration')
class MyMigration(Migration):
"Migrate from official.json to apps.json"
def migrate(self):
... | Remove all deprecated lists, not just 'yunohost' | Remove all deprecated lists, not just 'yunohost'
| Python | agpl-3.0 | YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost | ---
+++
@@ -1,5 +1,5 @@
from moulinette.utils.log import getActionLogger
-from yunohost.app import app_fetchlist, app_removelist
+from yunohost.app import app_fetchlist, app_removelist, _read_appslist_list
from yunohost.tools import Migration
logger = getActionLogger('yunohost.migration')
@@ -10,12 +10,21 @@
... |
8b5973b5581fb6da27891f8c2256886c1dc7e8a8 | server/src/db_layer.py | server/src/db_layer.py | from pymongo import MongoClient
# Magic decorator for defining constants
def constant(f):
def fset(self, value):
raise TypeError
def fget(self):
return f()
return property(fget, fset)
class Model:
def __init__(self):
pass
@staticmethod
@constant
def COLLECTION_... | from pymongo import MongoClient
# Magic decorator for defining constants
def constant(f):
def fset(self, value):
raise TypeError
def fget(self):
return f()
return property(fget, fset)
class Model:
def __init__(self):
pass
@staticmethod
@constant
def COLLECTION_... | Add users to the list of models. | Add users to the list of models.
| Python | mit | Opportunity-Hack-2015-Arizona/Team1,Opportunity-Hack-2015-Arizona/Team1,Opportunity-Hack-2015-Arizona/Team1 | ---
+++
@@ -32,6 +32,16 @@
return "posts"
+class User(Model):
+ def __init__(self):
+ Model.__init__(self)
+
+ @staticmethod
+ @constant
+ def COLLECTION_NAME():
+ return "users"
+
+
class GideonDatabaseClient:
@staticmethod
@constant
@@ -44,3 +54,4 @@
def get_... |
8ee2bed47efadf8bedf086295c0f67850fad6876 | pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py | pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py | # -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store_const',
dest='foo',
help='alias for --foo'
)
@pytest.fixture
def bar(request):
return request.config.op... | # -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store',
dest='foo',
help='alias for --foo'
)
@pytest.fixture
def bar(request):
return request.config.option.f... | Fix action in plugin module | Fix action in plugin module
| Python | mit | s0undt3ch/cookiecutter-pytest-plugin,luzfcb/cookiecutter-pytest-plugin,pytest-dev/cookiecutter-pytest-plugin | ---
+++
@@ -7,7 +7,7 @@
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
- action='store_const',
+ action='store',
dest='foo',
help='alias for --foo'
) |
849fbdf724528df99f2ac53d389274f7c2631f11 | invitation/admin.py | invitation/admin.py | from django.contrib import admin
from invitation.models import InvitationKey, InvitationUser, InvitationRequest, InvitationCode
class InvitationKeyAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'from_user', 'date_invited', 'key_expired')
class InvitationUserAdmin(admin.ModelAdmin):
list_display = (... | from django.contrib import admin
from invitation.models import InvitationKey, InvitationUser, InvitationRequest, InvitationCode
class InvitationKeyAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'from_user', 'date_invited', 'key_expired')
class InvitationUserAdmin(admin.ModelAdmin):
list_display = (... | Improve the invite_user action name. | Improve the invite_user action name. | Python | bsd-3-clause | adieu/django-invitation | ---
+++
@@ -17,7 +17,7 @@
invitation_request.invited = True
invitation_request.save()
-invite_user.short_description = "Invite this user"
+invite_user.short_description = "Invite selected invitation requests"
class InvitationRequestAdmin(admin.ModelAdmin): |
ba23baaee867ed79762fb3e3ac10af47d028d9ed | ergae/app.py | ergae/app.py | # ergae --- Earth Reader on Google App Engine
# Copyright (C) 2014 Hong Minhee
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any... | # ergae --- Earth Reader on Google App Engine
# Copyright (C) 2014 Hong Minhee
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any... | Create random HMAC secret and save it | Create random HMAC secret and save it
| Python | agpl-3.0 | earthreader/ergae | ---
+++
@@ -15,10 +15,18 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
+import os
+
from flask import Flask
+from .config import get_config, set_config
from .dropbox import mod
app = Flask(__name__)
app.register_blueprint(mod)
+
+app.se... |
82d90487a43e309074e5572b6ac529a707345274 | fileutils.py | fileutils.py | ##-*- coding: utf-8 -*-
#!/usr/bin/python
"""
Utilities related to Files.
"""
from io import FileIO, BufferedWriter
__author__ = 'SeomGi, Han'
__credits__ = ['SeomGi, Han']
__copyright__ = 'Copyright 2015, Python Utils Project'
__license__ = 'MIT'
__version__ = '1.0.0'
__maintainer__ = 'SeomGi, Han'
__email__ = 'iand... | ##-*- coding: utf-8 -*-
#!/usr/bin/python
"""
Utilities related to Files.
"""
import os
from io import FileIO, BufferedReader, BufferedWriter
__author__ = 'SeomGi, Han'
__credits__ = ['SeomGi, Han']
__copyright__ = 'Copyright 2015, Python Utils Project'
__license__ = 'MIT'
__version__ = '1.0.0'
__maintainer__ = 'Seom... | Add wrapped raw file copy function that use BufferedReader. And add logic to make directory if target directory isn't exist. | Add wrapped raw file copy function that use BufferedReader. And add logic to make directory if target directory isn't exist.
| Python | mit | iandmyhand/python-utils | ---
+++
@@ -3,7 +3,8 @@
"""
Utilities related to Files.
"""
-from io import FileIO, BufferedWriter
+import os
+from io import FileIO, BufferedReader, BufferedWriter
__author__ = 'SeomGi, Han'
__credits__ = ['SeomGi, Han']
@@ -18,7 +19,11 @@
class FileUtils:
+ def copy_file_stream_to_file(self, file, to... |
a353e2227e9d8f7c5ccdb890fa70d4166751af22 | example/wsgi.py | example/wsgi.py | """
WSGI config for test2 project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` se... | import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test2.settings")
application = get_wsgi_application()
| Fix an occurrence of E402 | Fix an occurrence of E402
| Python | bsd-3-clause | diegobz/django-admin-sso,matthiask/django-admin-sso,matthiask/django-admin-sso,diegobz/django-admin-sso | ---
+++
@@ -1,28 +1,8 @@
-"""
-WSGI config for test2 project.
+import os
-This module contains the WSGI application used by Django's development server
-and any production WSGI deployments. It should expose a module-level variable
-named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
-thi... |
0418609dd429a45a327ace191514ce2c4233ea11 | tests_django/test_settings.py | tests_django/test_settings.py | """
Test Django settings
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'chatterbot.ext.django_chatterbot',
'tests_django',
]
CHATTERB... | """
Test Django settings
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'chatterbot.ext.django_chatterbot',
'tests_django',
]
CHATTERB... | Set USE_TZ in test settings | Set USE_TZ in test settings
| Python | bsd-3-clause | davizucon/ChatterBot,maclogan/VirtualPenPal,Reinaesaya/OUIRL-ChatBot,gunthercox/ChatterBot,Gustavo6046/ChatterBot,vkosuri/ChatterBot,Reinaesaya/OUIRL-ChatBot | ---
+++
@@ -42,3 +42,5 @@
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
+
+USE_TZ = True |
4fa22298598add3541baf8ac4b3636eb4c64b9ec | fuzzer/tasks.py | fuzzer/tasks.py | import redis
from celery import Celery
from .Fuzzer import Fuzzer
import os
import time
import driller.config as config
import logging
l = logging.getLogger("fuzzer.tasks")
backend_url = "redis://%s:%d" % (config.REDIS_HOST, config.REDIS_PORT)
app = Celery('fuzzer', broker=config.BROKER_URL, backend=backend_url)
@... | import redis
from celery import Celery
from .Fuzzer import Fuzzer
import os
import time
import driller.config as config
import logging
l = logging.getLogger("fuzzer.tasks")
backend_url = "redis://%s:%d" % (config.REDIS_HOST, config.REDIS_PORT)
app = Celery('fuzzer', broker=config.BROKER_URL, backend=backend_url)
@... | Fix function declaration for fuzz task | Fix function declaration for fuzz task
| Python | bsd-2-clause | shellphish/driller | ---
+++
@@ -14,7 +14,7 @@
app = Celery('fuzzer', broker=config.BROKER_URL, backend=backend_url)
@app.task
-def drill(binary, input, fuzz_bitmap, exit_on_eof=False):
+def fuzz(binary):
binary_path = os.path.join(config.BINARY_DIR, binary)
fuzzer = Fuzzer(binary_path, "tests", config.FUZZER_INSTANCES) |
45bb9872978311774b97d9243358ffe9eaad3389 | client/main.py | client/main.py | import yaml
import sys
from conversation import Conversation
def isLocal():
return len(sys.argv) > 1 and sys.argv[1] == "--local"
if isLocal():
from local_mic import Mic
else:
from mic import Mic
if __name__ == "__main__":
print "==========================================================="
prin... | import yaml
import sys
from conversation import Conversation
def isLocal():
return len(sys.argv) > 1 and sys.argv[1] == "--local"
if isLocal():
from local_mic import Mic
else:
from mic import Mic
if __name__ == "__main__":
print "==========================================================="
prin... | Check if first_name is set for profile beforehand | Check if first_name is set for profile beforehand | Python | mit | syardumi/jasper-client,benhoff/jasper-client,tsaitsai/jasper-client,densic/HomeAutomation,sunu/jasper-client,fritz-fritz/jasper-client,jskye/voicehud-jasper,clumsical/hackthehouse-marty,djeraseit/jasper-client,markferry/jasper-client,jasperproject/jasper-client,densic/HomeAutomation,sunu/jasper-client,rowhit/jasper-cli... | ---
+++
@@ -23,7 +23,10 @@
mic = Mic("languagemodel.lm", "dictionary.dic",
"languagemodel_persona.lm", "dictionary_persona.dic")
- mic.say("How can I be of service, %s?" % (profile["first_name"]))
+ addendum = ""
+ if 'first_name' in profile:
+ addendum = ", %s" % profile["first_... |
d0f425d215f0d1c4f57a3517ad3e4c15f2b35e86 | tests/travis_test/TravisBuildTest.py | tests/travis_test/TravisBuildTest.py | import unittest as ut
class TravisBuildTest(ut.TestCase):
def test_success(self):
self.assertEqual(1, 1, "1 is not equal to 1?!")
def main():
ut.main()
if __name__ == '__main__':
main()
| import unittest as ut
class TravisBuildTest(ut.TestCase):
def test_success(self):
self.assertEqual(1, 1, "1 is not equal to 1?!")
def test_failing(self):
self.assertEqual(1, 2)
def main():
ut.main()
if __name__ == '__main__':
main()
| Add failing test to dev branch to test, if master badge stay green | Add failing test to dev branch to test, if master badge stay green
| Python | mit | PatrikValkovic/grammpy | ---
+++
@@ -4,6 +4,9 @@
class TravisBuildTest(ut.TestCase):
def test_success(self):
self.assertEqual(1, 1, "1 is not equal to 1?!")
+
+ def test_failing(self):
+ self.assertEqual(1, 2)
def main(): |
5dbdac674692b67f8f08627453b145c4d24ac32f | tests/integration/conftest.py | tests/integration/conftest.py | # coding: utf-8
"""Pytest config."""
import os
import sys
import pytest
from kiteconnect import KiteConnect
sys.path.append(os.path.join(os.path.dirname(__file__), '../helpers'))
def pytest_addoption(parser):
"""Add available args."""
parser.addoption("--api-key", action="store", default="Api key")
pars... | # coding: utf-8
"""Pytest config."""
import os
import sys
import pytest
from kiteconnect import KiteConnect
sys.path.append(os.path.join(os.path.dirname(__file__), '../helpers'))
def pytest_addoption(parser):
"""Add available args."""
parser.addoption("--api-key", action="store", default="Api key")
pars... | Rename cmd flag root to root-url for integrated tests | Rename cmd flag root to root-url for integrated tests
| Python | mit | rainmattertech/pykiteconnect | ---
+++
@@ -13,14 +13,14 @@
"""Add available args."""
parser.addoption("--api-key", action="store", default="Api key")
parser.addoption("--access-token", action="store", default="Access token")
- parser.addoption("--root", action="store", default="")
+ parser.addoption("--root-url", action="store... |
15808c86b273363c9f6466107d0cbc14030a97fa | ykman/scanmap/__init__.py | ykman/scanmap/__init__.py | from enum import Enum
from . import us
class KEYBOARD_LAYOUT(Enum):
US = 'US Keyboard Layout'
def get_scan_codes(data, keyboard_layout=KEYBOARD_LAYOUT.US):
if keyboard_layout == KEYBOARD_LAYOUT.US:
scancodes = us.scancodes
else:
raise ValueError('Keyboard layout not supported!')
try:... | from enum import Enum
from . import us
class KEYBOARD_LAYOUT(Enum):
US = 'US Keyboard Layout'
def get_scan_codes(data, keyboard_layout=KEYBOARD_LAYOUT.US):
if keyboard_layout == KEYBOARD_LAYOUT.US:
scancodes = us.scancodes
else:
raise ValueError('Keyboard layout not supported!')
try:... | Clarify what character that was missing | Clarify what character that was missing
| Python | bsd-2-clause | Yubico/yubikey-manager,Yubico/yubikey-manager | ---
+++
@@ -13,5 +13,5 @@
raise ValueError('Keyboard layout not supported!')
try:
return bytes(bytearray(scancodes[c] for c in data))
- except KeyError:
- raise ValueError('Character not available in keyboard layout!')
+ except KeyError as e:
+ raise ValueError('Unsuppor... |
611218f302d30213fece13c1a8997f87a44afa70 | djangosqladmin/databases/views.py | djangosqladmin/databases/views.py | from django.shortcuts import render
from django.http import HttpResponse
def dashboard(request):
return HttpResponse('SUCCESS!')
| from django.shortcuts import render
from django.http import HttpResponse
def dashboard(request):
context = {}
if request.user.is_authenticated:
context['databases'] = request.user.database_set.all()
return render(request, 'databases/dashboard.html', context)
| Add databases to dashboard context | Add databases to dashboard context
| Python | mit | jakesen/djangosqladmin,jakesen/djangosqladmin,jakesen/djangosqladmin | ---
+++
@@ -2,4 +2,7 @@
from django.http import HttpResponse
def dashboard(request):
- return HttpResponse('SUCCESS!')
+ context = {}
+ if request.user.is_authenticated:
+ context['databases'] = request.user.database_set.all()
+ return render(request, 'databases/dashboard.html', context) |
151c3484da58fa02f7d2c69454be3cb4e3395d05 | recipes/recipe_modules/bot_update/tests/ensure_checkout.py | recipes/recipe_modules/bot_update/tests/ensure_checkout.py | # Copyright 2018 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.
from recipe_engine import post_process
DEPS = [
'bot_update',
'gclient',
'recipe_engine/json',
]
def RunSteps(api):
api.gclient.set_config('depot_... | # Copyright 2018 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.
from recipe_engine import post_process
DEPS = [
'bot_update',
'gclient',
'recipe_engine/json',
]
def RunSteps(api):
api.gclient.set_config('depot_... | Replace post-process checks with ones that are not deprecated | Replace post-process checks with ones that are not deprecated
R=40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org
Bug: 899266
Change-Id: Ia9b1f38590d636fa2858a2bd0bbf75d6b2cfe8fa
Reviewed-on: https://chromium-review.googlesource.com/c/1483033
Reviewed-by: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@... | Python | bsd-3-clause | CoherentLabs/depot_tools,CoherentLabs/depot_tools | ---
+++
@@ -19,7 +19,7 @@
def GenTests(api):
yield (
api.test('basic') +
- api.post_process(post_process.StatusCodeIn, 0) +
+ api.post_process(post_process.StatusSuccess) +
api.post_process(post_process.DropExpectation)
)
@@ -29,6 +29,6 @@
'bot_update',
api.json.... |
50bb7a20ee055b870794607022e4e30f8842f80d | openedx/core/djangoapps/appsembler/settings/settings/devstack_lms.py | openedx/core/djangoapps/appsembler/settings/settings/devstack_lms.py | """
Settings for Appsembler on devstack/LMS.
"""
from os import path
from openedx.core.djangoapps.appsembler.settings.settings import devstack_common
def plugin_settings(settings):
"""
Appsembler LMS overrides for devstack.
"""
devstack_common.plugin_settings(settings)
settings.DEBUG_TOOLBAR_PAT... | """
Settings for Appsembler on devstack/LMS.
"""
from os import path
from openedx.core.djangoapps.appsembler.settings.settings import devstack_common
def plugin_settings(settings):
"""
Appsembler LMS overrides for devstack.
"""
devstack_common.plugin_settings(settings)
settings.DEBUG_TOOLBAR_PAT... | Set the customer_themes static dir prefix for devstack (no S3) customer theme file storage to match expectation in SiteConfiguration model method | Set the customer_themes static dir prefix for devstack (no S3) customer theme file storage to match expectation in SiteConfiguration model method
| Python | agpl-3.0 | appsembler/edx-platform,appsembler/edx-platform,appsembler/edx-platform,appsembler/edx-platform | ---
+++
@@ -31,7 +31,7 @@
# LMS-generated files looks like: `appsembler-academy.tahoe.appsembler.com.css`
customer_themes_dir = path.join(settings.COMPREHENSIVE_THEME_DIRS[0], 'customer_themes')
if path.isdir(customer_themes_dir):
- settings.STATICFILES_DIRS.insert(0, customer_th... |
7cc357584ddd4f8e57783b5e0a462b5ad0daf411 | footer.py | footer.py | import htmlify
from socket import gethostname as hostname
from time import time as unixTime
def showFooter():
# Footer
htmlify.dispHTML("br")
htmlify.dispHTML("hr")
heart = "<i class=\"fa fa-heart\" aria-hidden=\"true\"></i>"
so = "<i class=\"fa fa-stack-overflow\" aria-hidden=\"true\"></i>"
tProfileLink = html... | import htmlify
from socket import gethostname as hostname
from time import time as unixTime
def showFooter():
# Footer
htmlify.dispHTML("br")
htmlify.dispHTML("hr")
heart = "<i class=\"fa fa-heart\" aria-hidden=\"true\" title=\"love\"></i>"
so = "<i class=\"fa fa-stack-overflow\" aria-hidden=\"true\" title=\"Sta... | Add titles to FA icons | Add titles to FA icons
| Python | apache-2.0 | ISD-Sound-and-Lights/InventoryControl | ---
+++
@@ -7,8 +7,8 @@
# Footer
htmlify.dispHTML("br")
htmlify.dispHTML("hr")
- heart = "<i class=\"fa fa-heart\" aria-hidden=\"true\"></i>"
- so = "<i class=\"fa fa-stack-overflow\" aria-hidden=\"true\"></i>"
+ heart = "<i class=\"fa fa-heart\" aria-hidden=\"true\" title=\"love\"></i>"
+ so = "<i class=\"fa f... |
42d038f09bb9b24802ee78f92a5c7a309acf3a7a | zerver/migrations/0301_fix_unread_messages_in_deactivated_streams.py | zerver/migrations/0301_fix_unread_messages_in_deactivated_streams.py | from django.db import connection, migrations
from django.db.backends.postgresql.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def mark_messages_read(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
Stream = apps.get_model("zerver", "Stream")
deactivated_stre... | from django.db import migrations
class Migration(migrations.Migration):
"""
We're changing the stream deactivation process to make it mark all messages
in the stream as read. For things to be consistent with streams that have been
deactivated before this change, we need a migration to fix those old st... | Fix 0301 to replace a Python loop with SQL. | migrations: Fix 0301 to replace a Python loop with SQL.
The previous code is correctly flagged by semgrep 0.23 as a violation
of our sql-format rule.
Signed-off-by: Anders Kaseorg <dfdb7392591db597bc41cf266a9c3bc12a2706e5@zulip.com>
| Python | apache-2.0 | zulip/zulip,andersk/zulip,showell/zulip,punchagan/zulip,hackerkid/zulip,showell/zulip,eeshangarg/zulip,showell/zulip,rht/zulip,rht/zulip,andersk/zulip,eeshangarg/zulip,zulip/zulip,punchagan/zulip,showell/zulip,andersk/zulip,hackerkid/zulip,rht/zulip,andersk/zulip,punchagan/zulip,zulip/zulip,punchagan/zulip,showell/zuli... | ---
+++
@@ -1,20 +1,5 @@
-from django.db import connection, migrations
-from django.db.backends.postgresql.schema import DatabaseSchemaEditor
-from django.db.migrations.state import StateApps
+from django.db import migrations
-
-def mark_messages_read(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
-... |
19c6017077af2207169b4dbb67b2fe67f0a36568 | kpi/backends.py | kpi/backends.py | from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import AnonymousUser
class ObjectPermissionBackend(ModelBackend):
def get_group_permissions(self, user_obj, obj=None):
# probably won't be used
return super(ObjectPermissionBackend, self
).get_group_pe... | from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import AnonymousUser
class ObjectPermissionBackend(ModelBackend):
def get_group_permissions(self, user_obj, obj=None):
# probably won't be used
return super(ObjectPermissionBackend, self
).get_group_pe... | Fix insanity-inducing argument omission mistake | Fix insanity-inducing argument omission mistake
| Python | agpl-3.0 | kobotoolbox/kpi,onaio/kpi,onaio/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,onaio/kpi,onaio/kpi | ---
+++
@@ -14,7 +14,7 @@
def has_perm(self, user_obj, perm, obj=None):
if obj is None or not hasattr(obj, 'has_perm'):
return super(ObjectPermissionBackend, self
- ).has_perm(user_obj, obj)
+ ).has_perm(user_obj, perm, obj)
if not user_obj.is_active a... |
ababb2a603d91f407d4ecfc46ceabb2849413914 | test/TestVariableHasSpaces.py | test/TestVariableHasSpaces.py | import unittest
from ansiblelint import RulesCollection
from ansiblelint.rules.VariableHasSpacesRule import VariableHasSpacesRule
from test import RunFromText
TASK_VARIABLES = '''
- name: good variable format
debug:
msg: "{{ good_format }}"
- name: good variable format
debug:
msg: "Value: {{ good_format }... | import unittest
from ansiblelint import RulesCollection
from ansiblelint.rules.VariableHasSpacesRule import VariableHasSpacesRule
from test import RunFromText
TASK_VARIABLES = '''
- name: good variable format
debug:
msg: "{{ good_format }}"
- name: good variable format
debug:
msg: "Value: {{ good_format }... | Add a test for false positive with nested JSON | Add a test for false positive with nested JSON
Closes: #791
| Python | mit | willthames/ansible-lint | ---
+++
@@ -35,6 +35,9 @@
debug:
msg: "test"
example: "data = ${lookup{$local_part}lsearch{/etc/aliases}}"
+- name: JSON inside jinja is valid
+ debug:
+ msg: "{{ {'test': {'subtest': variable}} }}"
'''
|
172b6b417cbd3bc2ffacf7f38b3a49f84510d13c | localeurl/models.py | localeurl/models.py | from django.conf import settings
from django.core import urlresolvers
from django.utils import translation
from localeurl import utils
def reverse(*args, **kwargs):
reverse_kwargs = kwargs.get('kwargs', {})
locale = utils.supported_language(reverse_kwargs.pop('locale',
translation.get_language()))
... | from django.conf import settings
from django.core import urlresolvers
from django.utils import translation
from localeurl import utils
def reverse(*args, **kwargs):
reverse_kwargs = kwargs.get('kwargs', {})
if reverse_kwargs!=None:
locale = utils.supported_language(reverse_kwargs.pop('locale',
... | Handle situation when kwargs is None | Handle situation when kwargs is None
| Python | mit | jmagnusson/django-localeurl,simonluijk/django-localeurl | ---
+++
@@ -5,8 +5,11 @@
def reverse(*args, **kwargs):
reverse_kwargs = kwargs.get('kwargs', {})
- locale = utils.supported_language(reverse_kwargs.pop('locale',
- translation.get_language()))
+ if reverse_kwargs!=None:
+ locale = utils.supported_language(reverse_kwargs.pop('locale',
+... |
aff5a09eb3d61f77cb277b076820481b8ba145d5 | tests/test_coroutine.py | tests/test_coroutine.py | import tests
try:
import asyncio
exec('''if 1:
def hello_world(result, delay):
result.append("Hello")
# retrieve the event loop from the policy
yield from asyncio.sleep(delay)
result.append('World')
''')
except ImportError:
import trollius as asy... | import tests
try:
import asyncio
exec('''if 1:
def hello_world(result, delay):
result.append("Hello")
# retrieve the event loop from the policy
yield from asyncio.sleep(delay)
result.append('World')
return "."
def waiter(result):
... | Add more complex coroutine example | Add more complex coroutine example
| Python | apache-2.0 | overcastcloud/aioeventlet | ---
+++
@@ -9,16 +9,41 @@
# retrieve the event loop from the policy
yield from asyncio.sleep(delay)
result.append('World')
+ return "."
+
+ def waiter(result):
+ loop = asyncio.get_event_loop()
+ fut = asyncio.Future(loop=loop)
+ ... |
42bfa6b69697c0c093a961df5708f477288a6efa | icekit/plugins/twitter_embed/forms.py | icekit/plugins/twitter_embed/forms.py | import re
from django import forms
from fluent_contents.forms import ContentItemForm
class TwitterEmbedAdminForm(ContentItemForm):
def clean_twitter_url(self):
"""
Make sure the URL provided matches the twitter URL format.
"""
url = self.cleaned_data['twitter_url']
if url:... | import re
from django import forms
from fluent_contents.forms import ContentItemForm
from icekit.plugins.twitter_embed.models import TwitterEmbedItem
class TwitterEmbedAdminForm(ContentItemForm):
class Meta:
model = TwitterEmbedItem
fields = '__all__'
def clean_twitter_url(self):
"""
... | Add model and firld information to form. | Add model and firld information to form.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | ---
+++
@@ -1,9 +1,14 @@
import re
from django import forms
from fluent_contents.forms import ContentItemForm
+from icekit.plugins.twitter_embed.models import TwitterEmbedItem
class TwitterEmbedAdminForm(ContentItemForm):
+ class Meta:
+ model = TwitterEmbedItem
+ fields = '__all__'
+
de... |
21bb022987c54b8c3343cfe5f4994203d799dc20 | street_score/project/urls.py | street_score/project/urls.py | from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from . import resources, views
# Uncomment the next two lines to enable the admin:
from django.contrib.gis import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'project.views.home... | from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from . import resources, views
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'project.views.home', n... | Remove gis dependency in admin | Remove gis dependency in admin
| Python | mit | openplans/streetscore,openplans/streetscore,openplans/streetscore | ---
+++
@@ -3,7 +3,7 @@
from . import resources, views
# Uncomment the next two lines to enable the admin:
-from django.contrib.gis import admin
+from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('', |
10a787c9f2147081001239029146b5b049db17f0 | featureflow/__init__.py | featureflow/__init__.py | __version__ = '1.16.14'
from model import BaseModel
from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \
PickleFeature
from extractor import Node, Graph, Aggregator, NotEnoughData
from bytestream import ByteStream, ByteStreamFeature, ZipWrapper, iter_zip
from data import \
IdProvider... | __version__ = '1.16.14'
from model import BaseModel
from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \
PickleFeature
from extractor import Node, Graph, Aggregator, NotEnoughData
from bytestream import ByteStream, ByteStreamFeature, ZipWrapper, iter_zip
from data import \
IdProvider... | Add PickleDecoder to the public API | Add PickleDecoder to the public API
| Python | mit | JohnVinyard/featureflow,JohnVinyard/featureflow | ---
+++
@@ -20,7 +20,7 @@
from encoder import IdentityEncoder
-from decoder import Decoder
+from decoder import Decoder, PickleDecoder
from lmdbstore import LmdbDatabase
|
e62e090f2282426d14dad52a06eeca788789846f | kpi/serializers/v2/user_asset_subscription.py | kpi/serializers/v2/user_asset_subscription.py | # coding: utf-8
from django.utils.translation import ugettext as _
from rest_framework import serializers
from kpi.constants import (
ASSET_TYPE_COLLECTION,
PERM_DISCOVER_ASSET,
PERM_VIEW_ASSET
)
from kpi.fields import RelativePrefixHyperlinkedRelatedField
from kpi.models import Asset
from kpi.models impor... | # coding: utf-8
from django.utils.translation import ugettext as _
from rest_framework import serializers
from kpi.constants import (
ASSET_TYPE_COLLECTION,
PERM_DISCOVER_ASSET,
PERM_VIEW_ASSET
)
from kpi.fields import RelativePrefixHyperlinkedRelatedField
from kpi.models import Asset
from kpi.models impor... | Improve (a tiny bit) validation error message | Improve (a tiny bit) validation error message
| Python | agpl-3.0 | kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi | ---
+++
@@ -41,7 +41,7 @@
def validate_asset(self, asset):
if asset.asset_type != ASSET_TYPE_COLLECTION:
raise serializers.ValidationError(
- _('Invalid asset type. Only `{asset_type}`').format(
+ _('Invalid asset type. Only `{asset_type}` is allowed').format(
... |
984089c3e963998d62768721f23d7e7c72880e39 | tests/testapp/test_fhadmin.py | tests/testapp/test_fhadmin.py | from django.contrib.auth.models import User
from django.test import Client, TestCase
class AdminTest(TestCase):
def login(self):
client = Client()
u = User.objects.create(
username="test", is_active=True, is_staff=True, is_superuser=True
)
client.force_login(u)
... | from django.contrib import admin
from django.contrib.auth.models import User
from django.test import Client, RequestFactory, TestCase
from fhadmin.templatetags.fhadmin_module_groups import generate_group_list
class AdminTest(TestCase):
def login(self):
client = Client()
u = User.objects.create(
... | Test the app list generation a bit | Test the app list generation a bit
| Python | bsd-3-clause | feinheit/django-fhadmin,feinheit/django-fhadmin,feinheit/django-fhadmin | ---
+++
@@ -1,5 +1,8 @@
+from django.contrib import admin
from django.contrib.auth.models import User
-from django.test import Client, TestCase
+from django.test import Client, RequestFactory, TestCase
+
+from fhadmin.templatetags.fhadmin_module_groups import generate_group_list
class AdminTest(TestCase):
@@ -1... |
d7ea417103bbe5a5c314b65a48dd823aca5df658 | webpipe/xrender_test.py | webpipe/xrender_test.py | #!/usr/bin/python -S
"""
xrender_test.py: Tests for xrender.py
"""
import unittest
import xrender # module under test
CSV = """\
name,age
<carol>,10
<dave>,20
"""
class FunctionsTest(unittest.TestCase):
def testRenderCsv(self):
html, orig = xrender.RenderCsv('dir/foo.csv', 'foo.csv', CSV)
print html
... | #!/usr/bin/python -S
"""
xrender_test.py: Tests for xrender.py
"""
import unittest
import xrender # module under test
CSV = """\
name,age
<carol>,10
<dave>,20
"""
class FunctionsTest(unittest.TestCase):
def testGuessFileType(self):
self.assertEqual('png', xrender.GuessFileType('Rplot001.png'))
self.asse... | Remove test moved to plugin. | Remove test moved to plugin.
| Python | bsd-3-clause | andychu/webpipe,andychu/webpipe,andychu/webpipe,andychu/webpipe,andychu/webpipe | ---
+++
@@ -14,10 +14,6 @@
"""
class FunctionsTest(unittest.TestCase):
-
- def testRenderCsv(self):
- html, orig = xrender.RenderCsv('dir/foo.csv', 'foo.csv', CSV)
- print html
def testGuessFileType(self):
self.assertEqual('png', xrender.GuessFileType('Rplot001.png')) |
c8c610c7249100e3e514b029a2f4209866910f3a | lumos/source.py | lumos/source.py | """
Client/Source
Generates and sends E1.31 packets over UDP
"""
import socket
import struct
from packet import E131Packet
def ip_from_universe(universe):
# derive multicast IP address from Universe
high_byte = (universe >> 8) & 0xff
low_byte = universe & 0xff
return "239.255.{}.{}".format(high_byte... | """
Client/Source
Generates and sends E1.31 packets over UDP
"""
import socket
import struct
from packet import E131Packet
def ip_from_universe(universe):
# derive multicast IP address from Universe
high_byte = (universe >> 8) & 0xff
low_byte = universe & 0xff
return "239.255.{}.{}".format(high_byt... | Allow a specific address to be specified for sending | Allow a specific address to be specified for sending | Python | bsd-3-clause | ptone/Lumos | ---
+++
@@ -9,19 +9,27 @@
from packet import E131Packet
+
def ip_from_universe(universe):
# derive multicast IP address from Universe
high_byte = (universe >> 8) & 0xff
low_byte = universe & 0xff
return "239.255.{}.{}".format(high_byte, low_byte)
+
class DMXSource(object):
+ """
+ b... |
f9eac3523d4ab72d3abbfa8ee57801466552f18a | speedbar/modules/hostinformation.py | speedbar/modules/hostinformation.py | from __future__ import absolute_import
from .base import BaseModule
import os
class HostInformationModule(BaseModule):
key = 'host'
def get_metrics(self):
return {'name': os.uname()[1]}
def init():
return HostInformationModule
| import socket
from .base import BaseModule
class HostInformationModule(BaseModule):
key = 'host'
def get_metrics(self):
return {'name': socket.gethostname()}
def init():
return HostInformationModule
| Use more portable function to get hostname | Use more portable function to get hostname
This addresses #11
| Python | mit | mixcloud/django-speedbar,theospears/django-speedbar,theospears/django-speedbar,mixcloud/django-speedbar,mixcloud/django-speedbar,theospears/django-speedbar | ---
+++
@@ -1,13 +1,13 @@
-from __future__ import absolute_import
+import socket
+
from .base import BaseModule
-import os
class HostInformationModule(BaseModule):
key = 'host'
def get_metrics(self):
- return {'name': os.uname()[1]}
+ return {'name': socket.gethostname()}
def init... |
025da22574df8423bfdfea2f7b5bded5ab55054f | manage.py | manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "QuesCheetah.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| DELETE - delete default setting | DELETE - delete default setting
| Python | mit | mingkim/QuesCheetah,mingkim/QuesCheetah,mingkim/QuesCheetah,mingkim/QuesCheetah | ---
+++
@@ -3,8 +3,6 @@
import sys
if __name__ == "__main__":
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "QuesCheetah.settings")
-
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
8623aae8778307648e4a0380d84ca7dc7a63f3f2 | oneflow/core/context_processors.py | oneflow/core/context_processors.py | # -*- coding: utf-8 -*-
from .models.nonrel import User
def mongodb_user(request):
if request.user.is_anonymous():
return {u'mongodb_user': None}
try:
mongodb_user = User.objects.get(id=request.session[u'mongodb_user_id'])
except KeyError:
mongodb_user = User.objects.get(django... | # -*- coding: utf-8 -*-
def mongodb_user(request):
""" not the most usefull context manager in the world. """
if request.user.is_anonymous():
return {u'mongodb_user': None}
return {u'mongodb_user': request.user.mongo}
| Simplify the context processor. Not very useful anymore, in fact. | Simplify the context processor. Not very useful anymore, in fact.
| Python | agpl-3.0 | 1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow,WillianPaiva/1flow | ---
+++
@@ -1,20 +1,10 @@
# -*- coding: utf-8 -*-
-
-from .models.nonrel import User
def mongodb_user(request):
+ """ not the most usefull context manager in the world. """
if request.user.is_anonymous():
return {u'mongodb_user': None}
- try:
- mongodb_user = User.objects.get(id=r... |
58270d88592e6a097763ce0052ef6a8d22e9bbcb | compose/const.py | compose/const.py | import os
import sys
DEFAULT_TIMEOUT = 10
IS_WINDOWS_PLATFORM = (sys.platform == "win32")
LABEL_CONTAINER_NUMBER = 'com.docker.compose.container-number'
LABEL_ONE_OFF = 'com.docker.compose.oneoff'
LABEL_PROJECT = 'com.docker.compose.project'
LABEL_SERVICE = 'com.docker.compose.service'
LABEL_VERSION = 'com.docker.comp... | import os
import sys
DEFAULT_TIMEOUT = 10
HTTP_TIMEOUT = int(os.environ.get('COMPOSE_HTTP_TIMEOUT', os.environ.get('DOCKER_CLIENT_TIMEOUT', 60)))
IS_WINDOWS_PLATFORM = (sys.platform == "win32")
LABEL_CONTAINER_NUMBER = 'com.docker.compose.container-number'
LABEL_ONE_OFF = 'com.docker.compose.oneoff'
LABEL_PROJECT = 'c... | Remove duplicate and re-order alphabetically | Remove duplicate and re-order alphabetically
Signed-off-by: Mazz Mosley <a54aae760072825ca6733a7dfc4aa39211f100a9@houseofmnowster.com>
| Python | apache-2.0 | johnstep/docker.github.io,mdaue/compose,danix800/docker.github.io,phiroict/docker,jeanpralo/compose,jzwlqx/denverdino.github.io,jonaseck2/compose,denverdino/compose,docker/docker.github.io,JimGalasyn/docker.github.io,andrewgee/compose,alexandrev/compose,jzwlqx/denverdino.github.io,albers/compose,denverdino/denverdino.g... | ---
+++
@@ -2,6 +2,7 @@
import sys
DEFAULT_TIMEOUT = 10
+HTTP_TIMEOUT = int(os.environ.get('COMPOSE_HTTP_TIMEOUT', os.environ.get('DOCKER_CLIENT_TIMEOUT', 60)))
IS_WINDOWS_PLATFORM = (sys.platform == "win32")
LABEL_CONTAINER_NUMBER = 'com.docker.compose.container-number'
LABEL_ONE_OFF = 'com.docker.compose.one... |
b0701b50bb5d3dd3a7255ef4cf205f75513d790e | froide/helper/email_sending.py | froide/helper/email_sending.py | from django.core.mail import EmailMessage, get_connection
from django.conf import settings
try:
from froide.bounce.utils import make_bounce_address
except ImportError:
make_bounce_address = None
HANDLE_BOUNCES = settings.FROIDE_CONFIG['bounce_enabled']
def get_mail_connection(**kwargs):
return get_conne... | from django.core.mail import (
EmailMessage, EmailMultiAlternatives, get_connection
)
from django.conf import settings
try:
from froide.bounce.utils import make_bounce_address
except ImportError:
make_bounce_address = None
HANDLE_BOUNCES = settings.FROIDE_CONFIG['bounce_enabled']
def get_mail_connection... | Add support for html emails and extra headers | Add support for html emails and extra headers | Python | mit | fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide | ---
+++
@@ -1,4 +1,6 @@
-from django.core.mail import EmailMessage, get_connection
+from django.core.mail import (
+ EmailMessage, EmailMultiAlternatives, get_connection
+)
from django.conf import settings
try:
@@ -18,8 +20,9 @@
def send_mail(subject, body, user_email,
from_email=None,
+ ... |
ea947950d2ee8c6bd9f7693d977f0abfa1410548 | migrations/002_add_month_start.py | migrations/002_add_month_start.py | """
Add _week_start_at field to all documents in all collections
"""
from backdrop.core.bucket import utc
from backdrop.core.records import Record
import logging
log = logging.getLogger(__name__)
def up(db):
for name in db.collection_names():
log.info("Migrating collection: {0}".format(name))
col... | """
Add _week_start_at field to all documents in all collections
"""
from backdrop.core.bucket import utc
from backdrop.core.records import Record
import logging
log = logging.getLogger(__name__)
def up(db):
for name in db.collection_names():
log.info("Migrating collection: {0}".format(name))
col... | Fix migrations 002 for monthly grouping | Fix migrations 002 for monthly grouping
@gtrogers
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop | ---
+++
@@ -18,6 +18,8 @@
}
for document in collection.find(query):
document['_timestamp'] = utc(document['_timestamp'])
+ if '_week_start_at' in document:
+ document.pop('_week_start_at')
record = Record(document)
collection.save(re... |
796ac91df7dd4c63e76aa60b8eeec3d12354ecc7 | node/sort.py | node/sort.py | #!/usr/bin/env python
from nodes import Node
class Sort(Node):
char = "S"
args = 1
results = 1
@Node.test_func([[2,3,4,1]], [[1,2,3,4]])
@Node.test_func(["test"], ["estt"])
def func(self, a: Node.indexable):
"""sorted(a) - returns the same type as given"""
if isinstance(a,... | #!/usr/bin/env python
from nodes import Node
class Sort(Node):
char = "S"
args = 1
results = 1
@Node.test_func([[2,3,4,1]], [[1,2,3,4]])
@Node.test_func(["test"], ["estt"])
def func(self, a: Node.indexable):
"""sorted(a) - returns the same type as given"""
if isinstance(a,... | Change 1 based range so it counts up to n | Change 1 based range so it counts up to n
| Python | mit | muddyfish/PYKE,muddyfish/PYKE | ---
+++
@@ -17,8 +17,8 @@
return "".join(sorted(a))
return [sorted(a)]
- @Node.test_func([3], [[1,2]])
+ @Node.test_func([3], [[1,2,3]])
def one_range(self, a:int):
"""range(1,a)"""
- return [list(range(1,a))]
+ return [list(range(1,a+1))]
|
a86c7d9be7b7399b117b1289d6548f50b657efe6 | openstack_dashboard/dashboards/project/stacks/resource_types/tables.py | openstack_dashboard/dashboards/project/stacks/resource_types/tables.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | Remove Orchestration Resource Types names restriction | Remove Orchestration Resource Types names restriction
The additional columns "Implementation", "Component" and "Resource"
are representative for a limited resource type group only. Resource
type name can have less or more than three words and Heat even allows
to specify a URL as a resource type. Horizon should not use... | Python | apache-2.0 | yeming233/horizon,openstack/horizon,bac/horizon,BiznetGIO/horizon,noironetworks/horizon,coreycb/horizon,sandvine/horizon,noironetworks/horizon,yeming233/horizon,ChameleonCloud/horizon,openstack/horizon,openstack/horizon,sandvine/horizon,openstack/horizon,NeCTAR-RC/horizon,yeming233/horizon,bac/horizon,sandvine/horizon,... | ---
+++
@@ -17,25 +17,9 @@
class ResourceTypesTable(tables.DataTable):
- class ResourceColumn(tables.Column):
- def get_raw_data(self, datum):
- attr_list = ['implementation', 'component', 'resource']
- info_list = datum.resource_type.split('::')
- info_list[0] = info_l... |
4c39b8691762596c13cf197305c05fde5d4c3b5f | app.py | app.py | import sys
from flask import Flask, render_template, jsonify, request
from digitalocean import SSHKey, Manager
app = Flask(__name__)
manager = Manager(token="24611cca29682d3d54f8208b67a47dbe8b6ea01b2c8103ba61150ece4b6259b6")
my_droplets = manager.get_all_droplets()
# Check for success
print(my_droplets)
# Get from ... | import sys
from flask import Flask, render_template, jsonify, request
import subprocess
from digitalocean import SSHKey, Manager
app = Flask(__name__)
@app.route('/login')
def login():
# Get from Chrome extension
token = request.args.get('token')
manager = Manager(token=token)
# Instantiate ``api``... | Create /login, /create routes for API | Create /login, /create routes for API
| Python | mit | CapsLockHacks/do-server | ---
+++
@@ -1,39 +1,46 @@
import sys
from flask import Flask, render_template, jsonify, request
-
+import subprocess
from digitalocean import SSHKey, Manager
+
app = Flask(__name__)
-manager = Manager(token="24611cca29682d3d54f8208b67a47dbe8b6ea01b2c8103ba61150ece4b6259b6")
-my_droplets = manager.get_all_drople... |
2a93ed05a95aad9a27362f24abc766d9d1fc19fe | tests/functional/preview_and_dev/test_email_auth.py | tests/functional/preview_and_dev/test_email_auth.py | from tests.test_utils import recordtime
from tests.pages.rollups import sign_in_email_auth
@recordtime
def test_email_auth(driver, profile, base_url):
# login email auth user
sign_in_email_auth(driver, profile)
# assert url is research mode service's dashboard
assert driver.current_url == base_url + ... | from tests.test_utils import recordtime
from tests.pages.rollups import sign_in_email_auth
@recordtime
def test_email_auth(driver, profile, base_url):
# login email auth user
sign_in_email_auth(driver, profile)
# assert url is research mode service's dashboard
assert (
driver.current_url == b... | Update tests for new dashboard URL | Update tests for new dashboard URL
Includes both so we can migrate from one to the other. Currently blocking admin deploy. | Python | mit | alphagov/notifications-functional-tests,alphagov/notifications-functional-tests | ---
+++
@@ -8,4 +8,8 @@
# login email auth user
sign_in_email_auth(driver, profile)
# assert url is research mode service's dashboard
- assert driver.current_url == base_url + '/services/{}/dashboard'.format(profile.notify_research_service_id)
+ assert (
+ driver.current_url == base_url + ... |
ac7102a85a30754d31d941395613b63574bfe026 | xunit-autolabeler-v2/ast_parser/python_bootstrap.py | xunit-autolabeler-v2/ast_parser/python_bootstrap.py | #!/usr/bin/env python3.8
# ^ Use python 3.8 since Pip isn't configured for newer versions (3.9+)
# Copyright 2020 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://w... | #!/usr/bin/env python3
# Copyright 2020 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | Revert "Backdate python version to fix tests" | Revert "Backdate python version to fix tests"
This reverts commit dee546098a383df0b4f38324ecac9482c74cb2ae.
| Python | apache-2.0 | GoogleCloudPlatform/repo-automation-playground,GoogleCloudPlatform/repo-automation-playground,GoogleCloudPlatform/repo-automation-playground,GoogleCloudPlatform/repo-automation-playground,GoogleCloudPlatform/repo-automation-playground,GoogleCloudPlatform/repo-automation-playground,GoogleCloudPlatform/repo-automation-pl... | ---
+++
@@ -1,5 +1,4 @@
-#!/usr/bin/env python3.8
-# ^ Use python 3.8 since Pip isn't configured for newer versions (3.9+)
+#!/usr/bin/env python3
# Copyright 2020 Google LLC.
# |
8d167a4db654dab46a0afbdd620349db9c68dc82 | lcp/settings/staging.py | lcp/settings/staging.py | import os
from lcp.settings.base import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
| import os
from lcp.settings.base import * # noqa
# FIXME: The wildcard is only here while testing on Vagrant.
# Host header checking fails without it.
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
| Set temporary ALLOWED_HOSTS for Vagrant testing. | Set temporary ALLOWED_HOSTS for Vagrant testing.
| Python | bsd-2-clause | mblayman/lcp,mblayman/lcp,mblayman/lcp | ---
+++
@@ -1,6 +1,10 @@
import os
from lcp.settings.base import * # noqa
+
+# FIXME: The wildcard is only here while testing on Vagrant.
+# Host header checking fails without it.
+ALLOWED_HOSTS = ['*']
DATABASES = {
'default': { |
de35aee09f153999e0ae59879b2c57069616509b | polyaxon/polyaxon/config_settings/versions.py | polyaxon/polyaxon/config_settings/versions.py | from polyaxon.utils import config
CLI_MIN_VERSION = config.get_string('POLYAXON_CLI_MIN_VERSION',
is_optional=True,
default='0.0.0')
CLI_LATEST_VERSION = config.get_string('POLYAXON_CLI_LATEST_VERSION',
is_op... | from polyaxon.utils import config
CLI_MIN_VERSION = config.get_string('POLYAXON_CLI_MIN_VERSION',
is_optional=True,
default='0.0.0')
CLI_LATEST_VERSION = config.get_string('POLYAXON_CLI_LATEST_VERSION',
is_op... | Fix type of env variable is chart upgrade | Fix type of env variable is chart upgrade
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -21,4 +21,4 @@
CHART_VERSION = config.get_string('POLYAXON_CHART_VERSION',
is_optional=True,
default='0.0.0')
-CHART_IS_UPGRADE = config.get_string('POLYAXON_CHART_IS_UPGRADE')
+CHART_IS_UPGRADE = config.get_boolean('POLYAXON_CHART_IS_U... |
4250ae648ab975076fa8d87c8b40c0eca990fff7 | numba/intrinsic/__init__.py | numba/intrinsic/__init__.py | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import llvm.core
from .intrinsic import IntrinsicLibrary
from .numba_intrinsic import is_numba_intrinsic
__all__ = []
all = {}
def _import_all():
global __all__
mods = ['math_intrinsic',
'string_intrinsic']
... | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import llvm.core
from .intrinsic import IntrinsicLibrary
from .numba_intrinsic import is_numba_intrinsic
__all__ = []
all = {}
def _import_all():
global __all__
mods = ['string_intrinsic']
for k in mods:
mod =... | Fix old import of math intrinsics | Fix old import of math intrinsics
| Python | bsd-2-clause | gmarkall/numba,sklam/numba,numba/numba,GaZ3ll3/numba,pombredanne/numba,pombredanne/numba,pombredanne/numba,gdementen/numba,stefanseefeld/numba,cpcloud/numba,numba/numba,shiquanwang/numba,IntelLabs/numba,stonebig/numba,sklam/numba,pitrou/numba,seibert/numba,IntelLabs/numba,numba/numba,gmarkall/numba,pombredanne/numba,cp... | ---
+++
@@ -9,8 +9,7 @@
def _import_all():
global __all__
- mods = ['math_intrinsic',
- 'string_intrinsic']
+ mods = ['string_intrinsic']
for k in mods:
mod = __import__(__name__ + '.' + k, fromlist=['__all__'])
__all__.extend(mod.__all__) |
f6ed06bf16329f075b52b89f2fdfb061bb1355c1 | mitmproxy/builtins/replace.py | mitmproxy/builtins/replace.py | import re
from mitmproxy import exceptions
from mitmproxy import filt
class Replace:
def __init__(self):
self.lst = []
def configure(self, options, updated):
"""
.replacements is a list of tuples (fpat, rex, s):
fpatt: a string specifying a filter pattern.
... | import re
from mitmproxy import exceptions
from mitmproxy import filt
class Replace:
def __init__(self):
self.lst = []
def configure(self, options, updated):
"""
.replacements is a list of tuples (fpat, rex, s):
fpatt: a string specifying a filter pattern.
... | Convert to flags=value for future compatibility | Convert to flags=value for future compatibility
| Python | mit | mhils/mitmproxy,zlorb/mitmproxy,vhaupert/mitmproxy,laurmurclar/mitmproxy,mosajjal/mitmproxy,MatthewShao/mitmproxy,StevenVanAcker/mitmproxy,cortesi/mitmproxy,Kriechi/mitmproxy,Kriechi/mitmproxy,mhils/mitmproxy,MatthewShao/mitmproxy,mitmproxy/mitmproxy,StevenVanAcker/mitmproxy,mitmproxy/mitmproxy,laurmurclar/mitmproxy,St... | ---
+++
@@ -36,9 +36,9 @@
for rex, s, cpatt in self.lst:
if cpatt(f):
if f.response:
- f.response.replace(rex, s, re.DOTALL)
+ f.response.replace(rex, s, flags=re.DOTALL)
else:
- f.request.replace(rex, s, ... |
41fd6e8aae4044520a2e44d590c005dd71150c0c | web/attempts/migrations/0008_add_submission_date.py | web/attempts/migrations/0008_add_submission_date.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(... | Revert "Revert "Make migration SQLite compatible"" | Revert "Revert "Make migration SQLite compatible""
This reverts commit b16016994f20945a8a2bbb63b9cb920d856ab66f.
| Python | agpl-3.0 | ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo | ---
+++
@@ -27,14 +27,12 @@
),
migrations.RunSQL(
'''UPDATE attempts_attempt
- SET submission_date = subquery.submission_date
- FROM (
- SELECT user_id, part_id, max(history_date) AS submission_date
+ SET submission_da... |
6edb40320a5338cbdb70321170f21ff9beb9d39a | personal-site/blog/views.py | personal-site/blog/views.py | from django.shortcuts import render
from django.views.generic.base import TemplateView
from django.views.generic.detail import DetailView
from taggit.models import Tag
from blog.models import Post
class BlogHomeView(TemplateView):
template_name = 'blog/post.html'
def get_context_data(self, **kwargs):
... | from django.shortcuts import render
from django.views.generic.base import TemplateView
from django.views.generic.detail import DetailView
from taggit.models import Tag
from blog.models import Post
class BlogHomeView(TemplateView):
template_name = 'blog/post.html'
def get_context_data(self, **kwargs):
... | Fix field lookup for tag | Fix field lookup for tag
| Python | bsd-3-clause | brandonw/personal-site,brandonw/personal-site,brandonw/personal-site | ---
+++
@@ -33,6 +33,6 @@
tagslug = kwargs['slug']
tag = Tag.objects.get(slug=tagslug)
context['tag'] = tag.name
- context['taggedposts'] = Post.objects.filter(tags__name__in=[tag.name]).distinct()
+ context['taggedposts'] = Post.objects.filter(tags__name__exact=tag.name).dis... |
a90041e444edd8a88bc264db5b1a9305ba94d88f | commands/laws.py | commands/laws.py | @command("laws")
def echo(nick, user, channel, message):
argv = message.split(maxsplit=1)
if len(argv) == 0:
f = open('files/laws.txt', 'r')
i = 1
for line in f:
say(channel, '{}. {}'.format(i, line))
i = i + 1
f.close()
elif argv[0] == 'rese... | @command("laws")
def echo(nick, user, channel, message):
argv = message.split(maxsplit=1)
if len(argv) == 0:
try:
f = open('files/laws.txt', 'r')
for i,line in enumerate(f):
say(channel, '{}. {}'.format(i+1, line))
f.close()
except IOE... | Handle file exceptions. Use enumerate. Err msg. Close files sooner. | Handle file exceptions. Use enumerate. Err msg. Close files sooner.
| Python | unlicense | ccowmu/botler | ---
+++
@@ -3,22 +3,22 @@
argv = message.split(maxsplit=1)
if len(argv) == 0:
- f = open('files/laws.txt', 'r')
- i = 1
- for line in f:
- say(channel, '{}. {}'.format(i, line))
- i = i + 1
- f.close()
+ try:
+ f = open('files/law... |
e3054d71d3988a5fbc79c0ece8e37e06ef9e6851 | driveGraphs.py | driveGraphs.py |
from EnsoMetricsGraph import EnsoMetricsTable
#EnsoMetrics =[{'col1':'IPSL-CM5A-LR','col2':0.82,'col3':4.1},
# {'col1':'IPSL-CM5A-MR','col2':1.2,'col3':4.5}]
EnsoMetrics =[[1,2,3],[4,5,6]]
fig=EnsoMetricsTable(EnsoMetrics, 'EnsoMetrics')
|
from EnsoMetricsGraph import EnsoMetricsTable
EnsoMetrics =[['IPSL-CM5A-LR','0.82','4.1'],
['IPSL-CM5A-MR','1.2','4.5']]
#EnsoMetrics =[[1,2,3],[4,5,6]]
fig=EnsoMetricsTable(EnsoMetrics, 'EnsoMetrics')
| Create metrics table in EnsoMetricsGraph.py | Create metrics table in EnsoMetricsGraph.py
| Python | bsd-3-clause | eguil/ENSO_metrics,eguil/ENSO_metrics | ---
+++
@@ -1,8 +1,8 @@
from EnsoMetricsGraph import EnsoMetricsTable
-#EnsoMetrics =[{'col1':'IPSL-CM5A-LR','col2':0.82,'col3':4.1},
-# {'col1':'IPSL-CM5A-MR','col2':1.2,'col3':4.5}]
-EnsoMetrics =[[1,2,3],[4,5,6]]
+EnsoMetrics =[['IPSL-CM5A-LR','0.82','4.1'],
+ ['IPSL-CM5A-MR','1.2','... |
fecb3e2b610609ff24b8b19483e0c4b19f23e6c9 | ansi/doc/conf.py | ansi/doc/conf.py | # -*- coding: utf-8 -*-
import sys, os
needs_sphinx = '1.0'
extensions = ['sphinx.ext.intersphinx', 'sphinxcontrib.issuetracker']
source_suffix = '.rst'
master_doc = 'index'
project = u'sphinxcontrib-ansi'
copyright = u'2010, Sebastian Wiesner'
version = '0.5'
release = '0.5'
exclude_patterns = ['_build']
html_t... | # -*- coding: utf-8 -*-
import sys, os
needs_sphinx = '1.0'
extensions = ['sphinx.ext.intersphinx', 'sphinxcontrib.issuetracker']
source_suffix = '.rst'
master_doc = 'index'
project = u'sphinxcontrib-ansi'
copyright = u'2010, Sebastian Wiesner'
version = '0.5'
release = '0.5'
exclude_patterns = ['_build']
html_t... | Update for Sphinx 1.0 intersphinx format and remove broken Sphinx inventory | Update for Sphinx 1.0 intersphinx format and remove broken Sphinx inventory
| Python | bsd-2-clause | sphinx-contrib/spelling,sphinx-contrib/spelling | ---
+++
@@ -19,8 +19,9 @@
html_theme = 'default'
html_static_path = []
-intersphinx_mapping = {'http://docs.python.org/': None,
- 'http://sphinx.pocoo.org/': None,}
+intersphinx_mapping = {'python': ('http://docs.python.org/', None)}
+ # broken in Sphinx 1.0
+ ... |
7e8d89a6e0f9ad406b5fffb16fe2850e0bf7b550 | api/auth/urls.py | api/auth/urls.py | """Urls for authentication views"""
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^google/$', views.google, name='google')
]
| """Urls for authentication views"""
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^google$', views.google, name='google')
]
| Remove slash from Google Auth url | auth(google): Remove slash from Google Auth url
| Python | agpl-3.0 | tv-notify/tv-notify-server | ---
+++
@@ -5,5 +5,5 @@
from . import views
urlpatterns = [
- url(r'^google/$', views.google, name='google')
+ url(r'^google$', views.google, name='google')
] |
acda2de1d6b317308a4a4f75d707774f06f16062 | numba/control_flow/__init__.py | numba/control_flow/__init__.py | from numba.control_flow.control_flow import (ControlBlock, ControlFlowAnalysis,
FuncDefExprNode)
from numba.control_flow.cfstats import *
| from numba.control_flow.control_flow import (ControlBlock, ControlFlowAnalysis,
FuncDefExprNode)
from numba.control_flow.cfstats import *
from numba.control_flow.delete_cfnode import DeleteStatement | Add DeleteStatement to control flow package | Add DeleteStatement to control flow package
| Python | bsd-2-clause | cpcloud/numba,stonebig/numba,numba/numba,IntelLabs/numba,numba/numba,GaZ3ll3/numba,ssarangi/numba,stefanseefeld/numba,seibert/numba,stuartarchibald/numba,jriehl/numba,ssarangi/numba,stuartarchibald/numba,jriehl/numba,seibert/numba,stuartarchibald/numba,stefanseefeld/numba,stuartarchibald/numba,numba/numba,cpcloud/numba... | ---
+++
@@ -1,3 +1,4 @@
from numba.control_flow.control_flow import (ControlBlock, ControlFlowAnalysis,
FuncDefExprNode)
from numba.control_flow.cfstats import *
+from numba.control_flow.delete_cfnode import DeleteStatement |
a95fa658116ce4df9d05681bbf4ef75f6af682c9 | oscarapi/serializers/login.py | oscarapi/serializers/login.py | from django.contrib.auth import get_user_model, authenticate
from rest_framework import serializers
from oscarapi.utils import overridable
User = get_user_model()
def field_length(fieldname):
field = next(
field for field in User._meta.fields if field.name == fieldname)
return field.max_length
cl... | from django.contrib.auth import get_user_model, authenticate
from rest_framework import serializers
from oscarapi.utils import overridable
User = get_user_model()
def field_length(fieldname):
field = next(
field for field in User._meta.fields if field.name == fieldname)
return field.max_length
cl... | Fix LoginSerializer to support custom username fields of custom user models | Fix LoginSerializer to support custom username fields of custom user models
| Python | bsd-3-clause | crgwbr/django-oscar-api,regulusweb/django-oscar-api | ---
+++
@@ -17,18 +17,18 @@
class Meta:
model = User
fields = overridable('OSCARAPI_USER_FIELDS', (
- 'username', 'id', 'date_joined',))
+ User.USERNAME_FIELD, 'id', 'date_joined',))
class LoginSerializer(serializers.Serializer):
username = serializers.CharField(... |
2515509c8e0d0461df043b26e74bcc5b574464a9 | pybtex/bibtex/exceptions.py | pybtex/bibtex/exceptions.py | # Copyright (C) 2006, 2007, 2008 Andrey Golovizin
#
# This file is part of pybtex.
#
# pybtex is free software; you can redistribute it and/or modify
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later vers... | # Copyright (C) 2006, 2007, 2008 Andrey Golovizin
#
# This file is part of pybtex.
#
# pybtex is free software; you can redistribute it and/or modify
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later vers... | Make BibTeXError a subclass of PybtexError. | Make BibTeXError a subclass of PybtexError.
| Python | mit | live-clones/pybtex | ---
+++
@@ -17,5 +17,7 @@
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
-class BibTeXError(Exception):
+from pybtex.exceptions import PybtexError
+
+class BibTeXError(PybtexError):
pass |
fd32bdaa00c61d11edcf0ca60e4058e6d0b6b2d0 | backend/pycon/settings/prod.py | backend/pycon/settings/prod.py | import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from .base import * # noqa
from .base import env
SECRET_KEY = env("SECRET_KEY")
# CELERY_BROKER_URL = env("CELERY_BROKER_URL")
USE_SCHEDULER = False
# if FRONTEND_URL == "http://testfrontend.it/":
# raise ImproperlyConfigured("Please... | import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from .base import * # noqa
from .base import env
SECRET_KEY = env("SECRET_KEY")
# CELERY_BROKER_URL = env("CELERY_BROKER_URL")
USE_SCHEDULER = False
# if FRONTEND_URL == "http://testfrontend.it/":
# raise ImproperlyConfigured("Please... | Add better default for s3 region | Add better default for s3 region
| Python | mit | patrick91/pycon,patrick91/pycon | ---
+++
@@ -21,6 +21,6 @@
DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
AWS_STORAGE_BUCKET_NAME = env("AWS_MEDIA_BUCKET", None)
-AWS_S3_REGION_NAME = env("AWS_REGION_NAME", None)
+AWS_S3_REGION_NAME = env("AWS_REGION_NAME", "eu-central-1")
AWS_ACCESS_KEY_ID = env("AWS_ACCESS_KEY_ID", None)
A... |
5da0e3a5d7389ab754ac20ce929a6ca28669c371 | tests/test_induced_distributions.py | tests/test_induced_distributions.py | from unittest import TestCase
from equadratures.induced_distributions import InducedSampling
class TestInducedDistribution(TestCase):
def test_generate_sample_measure(self):
# test if the method returns a function object for induced sampling
measure = InducedSampling(1, 1, 1, "Chebyshev", 0, 0)
... | from unittest import TestCase
# from equadratures.induced_distributions import InducedSampling
class TestInducedDistribution(TestCase):
def test_generate_sample_measure(self):
# test if the method returns a function object for induced sampling
# measure = InducedSampling(1, 1, 1, "Chebyshev", 0, ... | Remove previous induced sampling test as this is not relevent for now | Remove previous induced sampling test as this is not relevent for now
The class in concern is currently a skeleton
| Python | lgpl-2.1 | psesh/Effective-Quadratures,Effective-Quadratures/Effective-Quadratures | ---
+++
@@ -1,11 +1,11 @@
from unittest import TestCase
-from equadratures.induced_distributions import InducedSampling
+# from equadratures.induced_distributions import InducedSampling
class TestInducedDistribution(TestCase):
def test_generate_sample_measure(self):
# test if the method returns ... |
f17a70980f1964e40a22fad5e54f4cafcdcf9d52 | useless_passport_validator/ulibrary.py | useless_passport_validator/ulibrary.py | #!/usr/bin/python3.4
from collections import namedtuple
"""Document constants"""
countries = ["Mordor", "Gondor", "Lorien", "Shire"]
genders = ["Male", "Female"]
cities = {
'Mordor': 'Minas Morgul,Barad Dur',
'Gondor': 'Minas Tirith,Isengard,Osgiliath',
'Lorien': 'Lorien',
'Shire': 'Hobbiton,Waymeet,F... | #!/usr/bin/python3.4
from collections import namedtuple
def init():
"""Document constants"""
global countries
countries = ["Mordor", "Gondor", "Lorien", "Shire"]
global genders
genders = ["Male", "Female"]
global cities
cities = {
'Mordor': 'Minas Morgul,Barad Dur',
'Gondor... | Define init function. Make variables actually global | Define init function. Make variables actually global
| Python | mit | Hethurin/UApp | ---
+++
@@ -2,19 +2,28 @@
from collections import namedtuple
-"""Document constants"""
-countries = ["Mordor", "Gondor", "Lorien", "Shire"]
-genders = ["Male", "Female"]
-cities = {
- 'Mordor': 'Minas Morgul,Barad Dur',
- 'Gondor': 'Minas Tirith,Isengard,Osgiliath',
- 'Lorien': 'Lorien',
- 'Shire': '... |
b6f0f3dfbf62b8b009155d3d510a908b73b53ab8 | runtests.py | runtests.py | # -*- coding: utf-8 -*-
"""
Entry point for Django tests.
This script will setup the basic configuration needed by Django.
"""
import sys
from os.path import abspath, dirname, join
try:
from django.conf import settings
from django.test.utils import get_runner
settings.configure(
DEBUG=True,
... | # -*- coding: utf-8 -*-
"""
Entry point for Django tests.
This script will setup the basic configuration needed by Django.
"""
import sys
from os.path import abspath, dirname, join
try:
from django.conf import settings
from django.test.utils import get_runner
settings.configure(
DEBUG=True,
... | Remove suit_dashboard from INSTALLED_APPS causing py35 tests breaking as no models | Remove suit_dashboard from INSTALLED_APPS causing py35 tests breaking as no models
| Python | isc | Pawamoy/django-suit-dashboard,Pawamoy/django-suit-dashboard,Pawamoy/django-suit-dashboard,Pawamoy/django-suit-dashboard | ---
+++
@@ -26,7 +26,6 @@
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
- 'suit_dashboard',
],
SITE_ID=1,
MIDDLEWARE_CLASSES=() |
daeeb010ce18fbcb0db62008285650916d2ed18f | action_plugins/insights.py | action_plugins/insights.py | from ansible.plugins.action import ActionBase
from ansible.utils.vars import merge_hash
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
results = super(ActionModule, self).run(tmp, task_vars)
# copy our egg
tmp = self._make_tmp_path()
source_full = self._... | from ansible.plugins.action import ActionBase
from ansible.utils.vars import merge_hash
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
results = super(ActionModule, self).run(tmp, task_vars)
remote_user = task_vars.get('ansible_ssh_user') or self._play_context.remote_use... | Update action plugin to fix _make_tmp_path issue | Update action plugin to fix _make_tmp_path issue
_make_tmp_path expects 2 arguments. One of those is the remote_user.
Add two lines to the action plugin to look at the ansible playbook
or config to get that value.
| Python | lgpl-2.1 | kylape/ansible-insights-client | ---
+++
@@ -6,9 +6,10 @@
def run(self, tmp=None, task_vars=None):
results = super(ActionModule, self).run(tmp, task_vars)
+ remote_user = task_vars.get('ansible_ssh_user') or self._play_context.remote_user
# copy our egg
- tmp = self._make_tmp_path()
+ tmp = self._make_... |
a882dc4df8c69880182f258e6c1d37646584fbb2 | models/stock.py | models/stock.py | # -*- encoding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models, api
class StockQuant(model... | # -*- encoding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models, api
class StockQuant(model... | Use browse record instead of ids | [MOD] Use browse record instead of ids
| Python | agpl-3.0 | acsone/stock-logistics-warehouse,kmee/stock-logistics-warehouse,avoinsystems/stock-logistics-warehouse,open-synergy/stock-logistics-warehouse,factorlibre/stock-logistics-warehouse | ---
+++
@@ -11,9 +11,9 @@
@api.multi
def merge_stock_quants(self):
- pending_quants_ids = self.ids
+ pending_quants = self.filtered(lambda x: True)
for quant2merge in self:
- if (quant2merge.id in pending_quants_ids and
+ if (quant2merge in pending_quants and
... |
8c1cc6895f5f8772d2b09a9efab7395b0a6b39ba | wake/filters.py | wake/filters.py | import markdown
from datetime import datetime
from twitter_text import TwitterText
from flask import Markup
def relative_time(timestamp):
delta = (datetime.now() - datetime.fromtimestamp(timestamp))
delta_s = delta.days * 86400 + delta.seconds
if delta_s < 60:
return "less than a minute ago"
el... | import markdown
from datetime import datetime
from twitter_text import TwitterText
from flask import Markup
def relative_time(timestamp):
delta = (datetime.now() - datetime.fromtimestamp(timestamp))
delta_s = delta.days * 86400 + delta.seconds
if delta_s < 60:
return "less than a minute ago"
el... | Update Markdown filter to recognize metadata. | Update Markdown filter to recognize metadata.
| Python | bsd-3-clause | chromakode/wake | ---
+++
@@ -25,4 +25,5 @@
return Markup(TwitterText(text).autolink.auto_link())
def markup_markdown(text):
- return Markup(markdown.markdown(text))
+ md = markdown.Markdown(extensions=['meta'])
+ return Markup(md.convert(text)) |
d60112e569e13333cfd6316d30683282ceff8bee | changes/jobs/cleanup_builds.py | changes/jobs/cleanup_builds.py | from datetime import datetime, timedelta
from changes.config import db, queue
from changes.constants import Status
from changes.models.build import Build
def cleanup_builds():
"""
Look for any jobs which haven't checked in (but are listed in a pending state)
and mark them as finished in an unknown state.... | from datetime import datetime, timedelta
from sqlalchemy.sql import func
from changes.config import db, queue
from changes.constants import Status
from changes.models.build import Build
def cleanup_builds():
"""
Look for any jobs which haven't checked in (but are listed in a pending state)
and mark them ... | Use func.now for timestamp update | Use func.now for timestamp update
| Python | apache-2.0 | dropbox/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes | ---
+++
@@ -1,4 +1,5 @@
from datetime import datetime, timedelta
+from sqlalchemy.sql import func
from changes.config import db, queue
from changes.constants import Status
@@ -21,7 +22,7 @@
db.session.query(Build).filter(
Build.id.in_(b.id for b in build_list),
).update({
- Build.date_m... |
a98fc5ee439b651f669dac527fc95636f8e2d9bf | django/applications/catmaid/management/commands/catmaid_set_user_profiles_to_default.py | django/applications/catmaid/management/commands/catmaid_set_user_profiles_to_default.py | from django.conf import settings
from django.contrib.auth.models import User
from django.core.management.base import NoArgsCommand, CommandError
from optparse import make_option
class Command(NoArgsCommand):
help = "Set the user profile settings of every user to the defaults"
option_list = NoArgsCommand.opti... | from django.conf import settings
from django.contrib.auth.models import User
from django.core.management.base import NoArgsCommand, CommandError
from optparse import make_option
class Command(NoArgsCommand):
help = "Set the user profile settings of every user to the defaults"
option_list = NoArgsCommand.opti... | Bring user profile defaults management command up to date | Bring user profile defaults management command up to date
| Python | agpl-3.0 | htem/CATMAID,fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID | ---
+++
@@ -22,10 +22,13 @@
up = u.userprofile
# Expect user profiles to be there and add all default settings
up.inverse_mouse_wheel = settings.PROFILE_DEFAULT_INVERSE_MOUSE_WHEEL
+ up.independent_ontology_workspace_is_default = \
+ settings.PROFILE_IN... |
978fe280a610c6cf9fb83b4726c7c1f536b92720 | project/urls.py | project/urls.py | # Django
# Third-Party
from rest_framework.documentation import include_docs_urls
from rest_framework.schemas import get_schema_view
# from django.views.generic import TemplateView
# from api.views import variance, ann
from django.conf import settings
from django.conf.urls import (
include,
url,
)
from django.c... | # Django
# Third-Party
from rest_framework.documentation import include_docs_urls
from rest_framework.schemas import get_schema_view
# from django.views.generic import TemplateView
# from api.views import variance, ann
from django.conf import settings
from django.conf.urls import (
include,
url,
)
from django.c... | Add direct forward to admin | Add direct forward to admin
| Python | bsd-2-clause | dbinetti/barberscore-django,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore,barberscore/barberscore-api | ---
+++
@@ -10,13 +10,14 @@
url,
)
from django.contrib import admin
-from django.http import HttpResponse
+from django.http import HttpResponse, HttpResponseRedirect
schema_view = get_schema_view(
title='Barberscore API',
)
urlpatterns = [
+ url(r'^$', lambda r: HttpResponseRedirect('admin/')),
... |
ea93225dd2da27a18f61de0a92f371766d5317ec | scanpointgenerator/point.py | scanpointgenerator/point.py | from collections import OrderedDict
class Point(object):
"""Contains information about for each scan point
Attributes:
positions (dict): Dict of str position_name -> float position for each
scannable dimension. E.g. {"x": 0.1, "y": 2.2}
lower (dict): Dict of str position_name -> f... |
class Point(object):
"""Contains information about for each scan point
Attributes:
positions (dict): Dict of str position_name -> float position for each
scannable dimension. E.g. {"x": 0.1, "y": 2.2}
lower (dict): Dict of str position_name -> float lower_bound for each
... | Update Point to use normal dictionaries for its coordinates | Update Point to use normal dictionaries for its coordinates
| Python | apache-2.0 | dls-controls/scanpointgenerator | ---
+++
@@ -1,4 +1,3 @@
-from collections import OrderedDict
class Point(object):
@@ -16,7 +15,7 @@
"""
def __init__(self):
- self.positions = OrderedDict()
- self.lower = OrderedDict()
- self.upper = OrderedDict()
+ self.positions = {}
+ self.lower = {}
+ se... |
eb1d581a94f87feb2bc09dbf45b13de282a205e8 | pyqode/json/modes/autocomplete.py | pyqode/json/modes/autocomplete.py | from pyqode.core import modes
from pyqode.core.api import TextHelper
class AutoCompleteMode(modes.AutoCompleteMode):
def __init__(self):
super(AutoCompleteMode, self).__init__()
self.QUOTES_FORMATS.pop("'")
self.SELECTED_QUOTES_FORMATS.pop("'")
self.MAPPING.pop("'")
def _on_ke... | from pyqode.core import modes
from pyqode.core.api import TextHelper
class AutoCompleteMode(modes.AutoCompleteMode):
def __init__(self):
super(AutoCompleteMode, self).__init__()
try:
self.QUOTES_FORMATS.pop("'")
self.SELECTED_QUOTES_FORMATS.pop("'")
self.MAPPING... | Fix issue with auto complete when more than 1 editor has been created | Fix issue with auto complete when more than 1 editor has been created
| Python | mit | pyQode/pyqode.json,pyQode/pyqode.json | ---
+++
@@ -5,9 +5,12 @@
class AutoCompleteMode(modes.AutoCompleteMode):
def __init__(self):
super(AutoCompleteMode, self).__init__()
- self.QUOTES_FORMATS.pop("'")
- self.SELECTED_QUOTES_FORMATS.pop("'")
- self.MAPPING.pop("'")
+ try:
+ self.QUOTES_FORMATS.pop("'... |
a60fa6989abd1080cafc860121885ec210d16771 | script/update-frameworks.py | script/update-frameworks.py | #!/usr/bin/env python
import sys
import os
from lib.util import safe_mkdir, extract_zip, tempdir, download
SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
FRAMEWORKS_URL = 'https://github.com/atom/atom-shell/releases/download/v0.11.10'
def main():
os.chdir(SOURCE_ROOT)
safe_mkdir('fra... | #!/usr/bin/env python
import sys
import os
from lib.util import safe_mkdir, extract_zip, tempdir, download
SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
FRAMEWORKS_URL = 'https://github.com/atom/atom-shell-frameworks/releases/download/v0.0.1'
def main():
os.chdir(SOURCE_ROOT)
safe_m... | Use atom/atom-shell-frameworks until atom/atom-shell is public | Use atom/atom-shell-frameworks until atom/atom-shell is public
| Python | mit | Rokt33r/electron,shiftkey/electron,Jacobichou/electron,shaundunne/electron,systembugtj/electron,dkfiresky/electron,subblue/electron,wan-qy/electron,brave/muon,preco21/electron,farmisen/electron,icattlecoder/electron,sshiting/electron,dkfiresky/electron,kostia/electron,MaxWhere/electron,chrisswk/electron,electron/electr... | ---
+++
@@ -7,7 +7,7 @@
SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
-FRAMEWORKS_URL = 'https://github.com/atom/atom-shell/releases/download/v0.11.10'
+FRAMEWORKS_URL = 'https://github.com/atom/atom-shell-frameworks/releases/download/v0.0.1'
def main():
os.chdir(SOURCE_ROOT) |
9445c23e70cabe519d51282bf4849a8d08e21039 | robotpy_ext/misc/precise_delay.py | robotpy_ext/misc/precise_delay.py |
import wpilib
class PreciseDelay:
'''
Used to synchronize a timing loop.
Usage::
delay = PreciseDelay(time_to_delay)
while something:
# do things here
delay.wait()
'''
def __init__(self, delay_period):
... |
import hal
import time
import wpilib
class PreciseDelay:
'''
Used to synchronize a timing loop. Will delay precisely so that
the next invocation of your loop happens at the same period, as long
as your code does not run longer than the length of the delay.
Our experience ... | Fix PreciseDelay to work properly | Fix PreciseDelay to work properly
| Python | bsd-3-clause | robotpy/robotpy-wpilib-utilities,Twinters007/robotpy-wpilib-utilities,robotpy/robotpy-wpilib-utilities,Twinters007/robotpy-wpilib-utilities | ---
+++
@@ -1,9 +1,16 @@
+import hal
+import time
import wpilib
+
class PreciseDelay:
'''
- Used to synchronize a timing loop.
+ Used to synchronize a timing loop. Will delay precisely so that
+ the next invocation of your loop happens at the same period, as long
+ as your code ... |
e4fcebfe4e87b57ae8505437f54c69f3afd59c04 | python/tests.py | python/tests.py | #!/usr/bin/env python
"""
Created on Thu 6 March 2014
Contains testing routines for `SolarCoreModel.py`.
@author Kristoffer Braekken
"""
import SolarCoreModel
from numpy import log10
def opacity_test(tol=1.e-10):
"""
Function for testing that the opacity is fetched correctly.
"""
# Test values
T... | #!/usr/bin/env python
"""
Created on Thu 6 March 2014
Contains testing routines for `SolarCoreModel.py`.
@author Kristoffer Braekken
"""
import SolarCoreModel
from numpy import log10
def opacity_test(tol=1.e-10):
"""
Function for testing that the opacity is fetched correctly.
"""
# Test values
T... | Fix test to take care of units. | TODO: Fix test to take care of units.
| Python | mit | PaulMag/AST3310-Prj01,PaulMag/AST3310-Prj01 | ---
+++
@@ -17,6 +17,7 @@
# Test values
T = 10**(5.) # Feth 5.00 row
rho = 1.e-6 # Fetch -5.0 column
+ rho /= 1.e3; rho *= 1./1e6 # Convert to SI units [kg m^-3]
ans = log10(SolarCoreModel.kappa(T, rho))
if abs(ans - (-0.068)) < tol: |
09a6e2528f062581c90ed3f3225f19b36f0ac0f9 | eve_api/forms.py | eve_api/forms.py | import re
from django import forms
from eve_api.models import EVEAccount, EVEPlayerCharacter, EVEPlayerCorporation
class EveAPIForm(forms.Form):
""" EVE API input form """
user_id = forms.IntegerField(label=u'User ID')
api_key = forms.CharField(label=u'API Key', max_length=64)
description = forms.Ch... | import re
from django import forms
from eve_api.models import EVEAccount, EVEPlayerCharacter, EVEPlayerCorporation
class EveAPIForm(forms.Form):
""" EVE API input form """
user_id = forms.IntegerField(label=u'User ID')
api_key = forms.CharField(label=u'API Key', max_length=64)
description = forms.Ch... | Fix the validation data on the EVEAPIForm | Fix the validation data on the EVEAPIForm
| Python | bsd-3-clause | nikdoof/test-auth | ---
+++
@@ -19,6 +19,8 @@
if re.search(r'[^\.a-zA-Z0-9]', self.cleaned_data['api_key']):
raise forms.ValidationError("Provided API Key has invalid characters.")
+ return self.cleaned_data['api_key']
+
def clean_user_id(self):
if not 'user_id' in self.cleaned_data or self... |
216f128bb8baf65a06c1f35356ab0f7fe50db967 | telemetry/telemetry/core/backends/chrome/inspector_memory_unittest.py | telemetry/telemetry/core/backends/chrome/inspector_memory_unittest.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.
from telemetry import benchmark
from telemetry.unittest import tab_test_case
class InspectorMemoryTest(tab_test_case.TabTestCase):
@benchmark.Enabled('h... | # 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.
from telemetry import benchmark
from telemetry.unittest import tab_test_case
class InspectorMemoryTest(tab_test_case.TabTestCase):
@benchmark.Enabled('h... | Add warnings to inspector DOM count unittest baselines. | Add warnings to inspector DOM count unittest baselines.
The unit test failure indicates a serious Document leak, where all
WebCore::Document loaded in Chrome is leaking.
This CL adds warning comments to the baseline to avoid regressions.
BUG=392121
NOTRY=true
Review URL: https://codereview.chromium.org/393123003
gi... | Python | bsd-3-clause | SummerLW/Perf-Insight-Report,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,catapult-project/catapult,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult,sahiljain/catapult,SummerLW/Perf-Insight-Report,be... | ---
+++
@@ -16,7 +16,15 @@
self.Navigate('dom_counter_sample.html')
+ # Document_count > 1 indicates that WebCore::Document loaded in Chrome
+ # is leaking! The baseline should exactly match the numbers on:
+ # unittest_data/dom_counter_sample.html
+ # Please contact kouhei@, hajimehoshi@ when re... |
c721ba7badc0b980d9c58822b5c0b626b1321f1a | grokapi/cli.py | grokapi/cli.py | # -*- coding: utf-8 -*-
from queries import Grok
def print_monthly_views(site, pages, year, month):
grok = Grok(site)
for page in pages:
result = grok.get_views_for_month(page, year, month)
print result['daily_views']
def main():
""" main script. """
from argparse import ArgumentPar... | # -*- coding: utf-8 -*-
from queries import Grok
def print_monthly_views(site, pages, year, month):
grok = Grok(site)
for page in pages:
result = grok.get_views_for_month(page, year, month)
print result['daily_views']
def main():
""" main script. """
from argparse import ArgumentPar... | Fix default values of Argument Parser | Fix default values of Argument Parser
| Python | mit | Commonists/Grokapi | ---
+++
@@ -19,19 +19,17 @@
type=str,
dest="lang",
default="en",
- required=True,
+ required=False,
help="Language code for Wikipedia")
parser.add_argument("-y", "--ye... |
73b7da1a0360f50e660e1983ec02dd5225bde3a3 | mitmproxy/platform/__init__.py | mitmproxy/platform/__init__.py | import sys
resolver = None
if sys.platform == "linux2":
from . import linux
resolver = linux.Resolver
elif sys.platform == "darwin":
from . import osx
resolver = osx.Resolver
elif sys.platform.startswith("freebsd"):
from . import osx
resolver = osx.Resolver
elif sys.platform == "win32":
fr... | import sys
import re
resolver = None
if re.match(r"linux(?:2)?", sys.platform):
from . import linux
resolver = linux.Resolver
elif sys.platform == "darwin":
from . import osx
resolver = osx.Resolver
elif sys.platform.startswith("freebsd"):
from . import osx
resolver = osx.Resolver
elif sys.pla... | Fix platform import on Linux using python3 | Fix platform import on Linux using python3
Using python3, sys.platform returns "linux" instead of "linux2" using
python2. This patch accepts "linux" as well as "linux2".
| Python | mit | mosajjal/mitmproxy,vhaupert/mitmproxy,laurmurclar/mitmproxy,Kriechi/mitmproxy,dwfreed/mitmproxy,xaxa89/mitmproxy,ujjwal96/mitmproxy,mosajjal/mitmproxy,Kriechi/mitmproxy,mitmproxy/mitmproxy,mitmproxy/mitmproxy,laurmurclar/mitmproxy,ujjwal96/mitmproxy,vhaupert/mitmproxy,zlorb/mitmproxy,StevenVanAcker/mitmproxy,Kriechi/mi... | ---
+++
@@ -1,8 +1,9 @@
import sys
+import re
resolver = None
-if sys.platform == "linux2":
+if re.match(r"linux(?:2)?", sys.platform):
from . import linux
resolver = linux.Resolver
elif sys.platform == "darwin": |
b19b3d1e3433465e6e05a9b50d79206b7049cbf6 | lib/windspharm/__init__.py | lib/windspharm/__init__.py | """Spherical harmonic vector wind analysis."""
# Copyright (c) 2012-2013 Andrew Dawson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the ... | """Spherical harmonic vector wind analysis."""
# Copyright (c) 2012-2013 Andrew Dawson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the ... | Reset version number for maintenance branch. | Reset version number for maintenance branch.
| Python | mit | nicolasfauchereau/windspharm,ajdawson/windspharm | ---
+++
@@ -29,7 +29,7 @@
__all__ = []
# Package version number.
-__version__ = '1.2.0'
+__version__ = '1.2.x'
try:
from . import cdms |
4b855e62bd4f92c7aa9b2614cb6eb57e112d7db6 | reclass/__init__.py | reclass/__init__.py | #
# -*- coding: utf-8 -*-
#
# This file is part of reclass (http://github.com/madduck/reclass)
#
# Copyright © 2007–13 martin f. krafft <madduck@madduck.net>
# Released under the terms of the Artistic Licence 2.0
#
from output import OutputLoader
from storage import StorageBackendLoader
def get_data(storage_type, nod... | #
# -*- coding: utf-8 -*-
#
# This file is part of reclass (http://github.com/madduck/reclass)
#
# Copyright © 2007–13 martin f. krafft <madduck@madduck.net>
# Released under the terms of the Artistic Licence 2.0
#
from output import OutputLoader
from storage import StorageBackendLoader
def get_data(storage_type, nod... | Allow node to be None to trigger inventory | Allow node to be None to trigger inventory
Signed-off-by: martin f. krafft <acc3492a66a5949176a2fc8886cf441478ca46a1@madduck.net>
| Python | artistic-2.0 | madduck/reclass,rmoorman/reclass,jeroen92/reclass,michaelkuty/reclass,jeroen92/reclass,rmoorman/reclass | ---
+++
@@ -13,7 +13,7 @@
def get_data(storage_type, nodes_uri, classes_uri, applications_postfix, node):
storage_class = StorageBackendLoader(storage_type).load()
storage = storage_class(nodes_uri, classes_uri, applications_postfix)
- if node is False:
+ if not node:
ret = storage.inventory... |
d43a08706f3072a0b97d01526ffd0de0d4a4110c | niworkflows/conftest.py | niworkflows/conftest.py | """py.test configuration"""
import os
from pathlib import Path
import numpy
import pytest
from .utils.bids import collect_data
test_data_env = os.getenv('TEST_DATA_HOME',
str(Path.home() / '.cache' / 'stanford-crn'))
data_dir = Path(test_data_env) / 'BIDS-examples-1-enh-ds054'
@pytest.fixt... | """py.test configuration"""
import os
from pathlib import Path
import numpy as np
import nibabel as nb
import pytest
import tempfile
from .utils.bids import collect_data
test_data_env = os.getenv('TEST_DATA_HOME',
str(Path.home() / '.cache' / 'stanford-crn'))
data_dir = Path(test_data_env) /... | Make nifti_fname available to doctests | DOCTEST: Make nifti_fname available to doctests
| Python | apache-2.0 | oesteban/niworkflows,oesteban/niworkflows,poldracklab/niworkflows,oesteban/niworkflows,poldracklab/niworkflows | ---
+++
@@ -1,8 +1,10 @@
"""py.test configuration"""
import os
from pathlib import Path
-import numpy
+import numpy as np
+import nibabel as nb
import pytest
+import tempfile
from .utils.bids import collect_data
@@ -13,12 +15,19 @@
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
- doctest... |
e8afa1408618d7dc4e39b84963199dd87c217ef9 | app/main/views/buyers.py | app/main/views/buyers.py | from flask import render_template, request, flash
from flask_login import login_required
from .. import main
from ... import data_api_client
from ..auth import role_required
@main.route('/buyers', methods=['GET'])
@login_required
@role_required('admin')
def find_buyer_by_brief_id():
brief_id = request.args.get('... | from flask import render_template, request, flash
from flask_login import login_required
from .. import main
from ... import data_api_client
from ..auth import role_required
@main.route('/buyers', methods=['GET'])
@login_required
@role_required('admin')
def find_buyer_by_brief_id():
brief_id = request.args.get('... | Remove unnecessary variable from route | Remove unnecessary variable from route
Jinja will set any variable it can't find to None, so the title variable
is unnecessary.
| Python | mit | alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend | ---
+++
@@ -20,7 +20,6 @@
return render_template(
"view_buyers.html",
users=list(),
- title=None,
brief_id=brief_id
), 404
|
c24bd93a88a3998ac306a82f7c74b0a782aa8e04 | bokeh/application.py | bokeh/application.py | from __future__ import absolute_import
from .document import Document
class Application(object):
"""An Application is a factory for Document instances"""
def __init__(self):
self._handlers = []
# TODO (havocp) should this potentially create multiple documents?
# or does multiple docs mean mu... | from __future__ import absolute_import
from .document import Document
import logging
log = logging.getLogger(__name__)
class Application(object):
"""An Application is a factory for Document instances"""
def __init__(self):
self._handlers = []
# TODO (havocp) should this potentially create mult... | Add basic reporting of handler errors | Add basic reporting of handler errors
This isn't very nice but it's very helpful for debugging :-)
Improve it later.
| Python | bsd-3-clause | azjps/bokeh,timsnyder/bokeh,quasiben/bokeh,timsnyder/bokeh,azjps/bokeh,philippjfr/bokeh,justacec/bokeh,Karel-van-de-Plassche/bokeh,justacec/bokeh,philippjfr/bokeh,rs2/bokeh,phobson/bokeh,ericmjl/bokeh,stonebig/bokeh,htygithub/bokeh,phobson/bokeh,stonebig/bokeh,Karel-van-de-Plassche/bokeh,DuCorey/bokeh,gpfreitas/bokeh,q... | ---
+++
@@ -1,6 +1,10 @@
from __future__ import absolute_import
from .document import Document
+
+import logging
+
+log = logging.getLogger(__name__)
class Application(object):
"""An Application is a factory for Document instances"""
@@ -17,6 +21,9 @@
# TODO (havocp) we need to check the 'fai... |
7f08e4c9fd370e375ad8e174a98478c0281ecb6e | tools/manifest/tool.py | tools/manifest/tool.py | import os
import time
import pwd
from .utils import effective_user
class Tool(object):
USER_NAME_PATTERN = 'tools.%s'
class InvalidToolException(Exception):
pass
def __init__(self, name, username, uid, gid, home):
self.name = name
self.uid = uid
self.gid = gid
se... | import os
import datetime
import pwd
from .utils import effective_user
class Tool(object):
USER_NAME_PATTERN = 'tools.%s'
class InvalidToolException(Exception):
pass
def __init__(self, name, username, uid, gid, home):
self.name = name
self.uid = uid
self.gid = gid
... | Use isoformat in datetime logs, rather than asctime | Use isoformat in datetime logs, rather than asctime
Change-Id: Ic11a70e28288517b6f174d7066f71a12efd5f4f1
| Python | mit | wikimedia/operations-software-tools-manifest | ---
+++
@@ -1,5 +1,5 @@
import os
-import time
+import datetime
import pwd
from .utils import effective_user
@@ -37,7 +37,7 @@
"""
Write to a log file in the tool's homedir
"""
- log_line = "%s %s" % (time.asctime(), message)
+ log_line = "%s %s" % (datetime.datetime.now(... |
8d0b9da511d55191609ffbd88a8b11afd6ff0367 | remedy/radremedy.py | remedy/radremedy.py | #!/usr/bin/env python
"""
radremedy.py
Main web application file. Contains initial setup of database, API, and other components.
Also contains the setup of the routes.
"""
from flask import Flask, url_for, request, abort
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from ra... | #!/usr/bin/env python
"""
radremedy.py
Main web application file. Contains initial setup of database, API, and other components.
Also contains the setup of the routes.
"""
from flask import Flask, url_for, request, abort
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from fl... | Move around imports and not shadow app | Move around imports and not shadow app
| Python | mpl-2.0 | radioprotector/radremedy,radioprotector/radremedy,radioprotector/radremedy,AllieDeford/radremedy,AllieDeford/radremedy,radremedy/radremedy,radremedy/radremedy,radremedy/radremedy,AllieDeford/radremedy,radioprotector/radremedy,radremedy/radremedy | ---
+++
@@ -8,22 +8,27 @@
from flask import Flask, url_for, request, abort
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
+from flask.ext.login import current_user
from rad.models import db, Resource
def create_app(config, models=()):
- from remedyblueprint im... |
290280725db406dac9a185b08600bcb0fba3d2e3 | src/gn.py | src/gn.py | '''
GotoNewest
A tool to quickly transfer to the latest directory
created in a base directory, provided the name of
the base directory is supplied as an argument
'''
import os
def transfer(basepath=None):
''' Transfer to the newest directory in the basepath
directory
'''
if basepath is None:
... | '''
GotoNewest
A tool to quickly transfer to the latest directory
created in a base directory, provided the name of
the base directory is supplied as an argument
'''
import os
import sys
import gn_helper
def transfer(basepath=None):
''' Transfer to the newest directory in the basepath
directory
'''
i... | Add main method to test directory change | Add main method to test directory change
| Python | bsd-2-clause | ambidextrousTx/GotoNewest | ---
+++
@@ -7,6 +7,8 @@
'''
import os
+import sys
+import gn_helper
def transfer(basepath=None):
''' Transfer to the newest directory in the basepath
@@ -37,3 +39,17 @@
latest_subdir = subdir
return latest_subdir
+
+def main():
+ ''' Get the latest directory created in the directory... |
26a4dc79b6ef9b19b9c5f2394386980aa452dc8e | licensing/data/location.py | licensing/data/location.py | import httplib2
import json
import itertools
from collections import defaultdict
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run
class Locations(object):
CLIENT_SECRETS_FILE = 'client_secrets.jso... | import httplib2
import json
import itertools
from collections import defaultdict
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run
class Locations(object):
CLIENT_SECRETS_FILE = 'client_secrets.jso... | Fix referencing of oauth flow. | Fix referencing of oauth flow.
@gtrogers
@robyoung
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop | ---
+++
@@ -20,7 +20,7 @@
credentials = storage.get()
if credentials is None or credentials.invalid:
- credentials = run(FLOW, storage)
+ credentials = run(self.FLOW, storage)
http = httplib2.Http()
http = credentials.authorize(http) |
608325c33cb2d446b89c263ba0bb02ced5c4ffe8 | portal/views.py | portal/views.py | import csv
from django.shortcuts import render
from django.http import HttpResponse
from . import services
def index(request):
data = services.overview()
return render(request, 'index.html', data)
def meter_runs(request):
"""Render the table of exported MeterRun results in html"""
data = services.me... | import csv
from django.shortcuts import render
from django.http import HttpResponse
from . import services
def index(request):
data = services.overview()
return render(request, 'index.html', data)
def meter_runs(request):
"""Render the table of exported MeterRun results in html"""
data = services.me... | Use the meterrun_export service to power csv export | Use the meterrun_export service to power csv export
| Python | mit | impactlab/oeem-energy-datastore,impactlab/oeem-energy-datastore,impactlab/oeem-energy-datastore | ---
+++
@@ -19,7 +19,11 @@
response = HttpResponse(content_type="text/csv")
response["Content-Disposition"] = 'attachment; filename="meter_runs.csv"'
- writer = csv.writer(response)
- writer.writerow(['First row', 'Foo', 'Bar'])
+ data = services.meterruns_export()
+
+ writer = csv.DictWriter(... |
cca2bd0d4cfb14dbf85e4275fd9d064b9ffa08cc | urlgetters/yle_urls.py | urlgetters/yle_urls.py | import requests
url = "https://ua.api.yle.fi/graphql?app_id=8d7303fe&app_key=105875199ef3a1f7e0fbf7e2834b2dc&query={uutisetMostRecentNews:articleList(publisher:YLE_UUTISET,limit:100,offset:0,coverage:NATIONAL){meta{count,total,remaining},items{fullUrl,properties}}}"
i = 0
while True:
url = "https://ua.api.yle.f... |
import requests
url = "https://ua.api.yle.fi/graphql?app_id=8d7303fe&app_key=105875199ef3a1f7e0fbf7e2834b2dc&query={uutisetMostRecentNews:articleList(publisher:YLE_UUTISET,limit:100,offset:0,coverage:NATIONAL){meta{count,total,remaining},items{fullUrl,properties}}}"
i = 0
while True:
url = "https://ua.api.yle.... | Make script run and fix all typos | Make script run and fix all typos
| Python | mit | HIIT/mediacollection | ---
+++
@@ -1,3 +1,4 @@
+
import requests
url = "https://ua.api.yle.fi/graphql?app_id=8d7303fe&app_key=105875199ef3a1f7e0fbf7e2834b2dc&query={uutisetMostRecentNews:articleList(publisher:YLE_UUTISET,limit:100,offset:0,coverage:NATIONAL){meta{count,total,remaining},items{fullUrl,properties}}}"
@@ -11,13 +12,13 @@
... |
54d67ce544e95ecb58a62062ffe50fcd95db6f09 | sso/apps.py | sso/apps.py | from django.apps import AppConfig
class SsoConfig(AppConfig):
name = 'sso'
github_client_id = '844189c44c56ff04e727'
github_client_secret = '0bfecee7a78ee0e800b6bff85b08c140b91be4cc'
| import json
import os.path
from django.apps import AppConfig
from fmproject import settings
class SsoConfig(AppConfig):
base_config = json.load(
open(os.path.join(settings.BASE_DIR, 'fmproject', 'config.json'))
)
name = 'sso'
github_client_id = base_config['github']['client_id']
github_cli... | Load github config from external file | Load github config from external file
| Python | mit | favoritemedium/sso-prototype,favoritemedium/sso-prototype | ---
+++
@@ -1,7 +1,14 @@
+import json
+import os.path
from django.apps import AppConfig
+from fmproject import settings
class SsoConfig(AppConfig):
+ base_config = json.load(
+ open(os.path.join(settings.BASE_DIR, 'fmproject', 'config.json'))
+ )
name = 'sso'
- github_client_id = '844189c44... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.