diff
stringlengths 139
3.65k
| message
stringlengths 8
627
| diff_languages
stringclasses 1
value |
---|---|---|
diff --git a/signxml/__init__.py b/signxml/__init__.py
index <HASH>..<HASH> 100644
--- a/signxml/__init__.py
+++ b/signxml/__init__.py
@@ -69,7 +69,7 @@ def _get_signature_regex(ns_prefix=None):
tag = "Signature"
if ns_prefix is not None:
tag = ns_prefix + ":" + tag
- return re.compile(ensure_bytes("<{t}[>\s].*?</{t}>".format(t=tag)), flags=re.DOTALL)
+ return re.compile(ensure_bytes(r"<{t}[>\s].*?</{t}>".format(t=tag)), flags=re.DOTALL)
def _get_schema():
global _schema
|
Add raw string marker to regexp The regexp contains a single \s that would need to be escaped. So just add a 'r' to make this a raw string.
|
py
|
diff --git a/discord/ext/commands/core.py b/discord/ext/commands/core.py
index <HASH>..<HASH> 100644
--- a/discord/ext/commands/core.py
+++ b/discord/ext/commands/core.py
@@ -1132,6 +1132,7 @@ class Group(GroupMixin, Command):
return ret
async def invoke(self, ctx):
+ ctx.invoked_subcommand = None
early_invoke = not self.invoke_without_command
if early_invoke:
await self.prepare(ctx)
@@ -1159,6 +1160,7 @@ class Group(GroupMixin, Command):
await super().invoke(ctx)
async def reinvoke(self, ctx, *, call_hooks=False):
+ ctx.invoked_subcommand = None
early_invoke = not self.invoke_without_command
if early_invoke:
ctx.command = self
|
[commands] Explicitly assign invoked_subcommand to None before invoking This should fix instances of it not working as expected in nested groups.
|
py
|
diff --git a/install.py b/install.py
index <HASH>..<HASH> 100644
--- a/install.py
+++ b/install.py
@@ -128,7 +128,8 @@ def install_standalone(venv):
for app in 'standalone ipt taxtweb taxonomy'.split():
try:
subprocess.check_call(['%s/bin/pip' % venv, 'install',
- '--upgrade', STANDALONE % app])
+ '--upgrade', STANDALONE % app],
+ env={'PYBUILD_NAME': 'oq-taxonomy'})
except Exception as exc:
print('%s: could not install %s' % (exc, STANDALONE % app))
|
Passed PYBUILD_NAME in install.py [skip CI]
|
py
|
diff --git a/python_dashing/datastore.py b/python_dashing/datastore.py
index <HASH>..<HASH> 100644
--- a/python_dashing/datastore.py
+++ b/python_dashing/datastore.py
@@ -13,10 +13,10 @@ class RedisDataStore(object):
return RedisDataStore(self.redis, prefix=prefix)
def create(self, key, value):
- self.redis.set("{0}-{1}".format(self.prefix, key), value)
+ self.redis.set("{0}-{1}".format(self.prefix, key), json.dumps({"value": value}))
def retrieve(self, key):
- return self.redis.get("{0}-{1}".format(self.prefix, key))
+ return json.loads(self.redis.get("{0}-{1}".format(self.prefix, key)))["value"]
class JsonDataStore(object):
def __init__(self, location, prefix=""):
|
Always store as string with redis datastore
|
py
|
diff --git a/gwpy/io/tests/test_datafind.py b/gwpy/io/tests/test_datafind.py
index <HASH>..<HASH> 100644
--- a/gwpy/io/tests/test_datafind.py
+++ b/gwpy/io/tests/test_datafind.py
@@ -60,7 +60,7 @@ def test_find_frametype(connection):
with mock.patch('glue.datafind.GWDataFindHTTPConnection') as \
mock_connection, \
mock.patch('gwpy.io.datafind.num_channels', lambda x: 1), \
- mock.patch('gwpy.io.gwf.iter_channel_names',
+ mock.patch('gwpy.io.datafind.iter_channel_names',
lambda x: ['L1:LDAS-STRAIN']):
mock_connection.return_value = connection
assert io_datafind.find_frametype('L1:LDAS-STRAIN',
@@ -95,7 +95,7 @@ def test_find_best_frametype(connection):
with mock.patch('glue.datafind.GWDataFindHTTPConnection') as \
mock_connection, \
mock.patch('gwpy.io.datafind.num_channels', lambda x: 1), \
- mock.patch('gwpy.io.gwf.iter_channel_names',
+ mock.patch('gwpy.io.datafind.iter_channel_names',
lambda x: ['L1:LDAS-STRAIN']):
mock_connection.return_value = connection
assert io_datafind.find_best_frametype(
|
gwpy.io: fixed mock in test_datafind.py to mock the function in question properly
|
py
|
diff --git a/boussole/__init__.py b/boussole/__init__.py
index <HASH>..<HASH> 100644
--- a/boussole/__init__.py
+++ b/boussole/__init__.py
@@ -1,2 +1,2 @@
"""Commandline interface to build SASS projects using libsass-python"""
-__version__ = '1.1.0-pre.1'
+__version__ = '1.1.0-pre.2'
|
Bump to <I> pre release 2
|
py
|
diff --git a/taar/recommenders/utils.py b/taar/recommenders/utils.py
index <HASH>..<HASH> 100644
--- a/taar/recommenders/utils.py
+++ b/taar/recommenders/utils.py
@@ -39,5 +39,6 @@ def get_s3_json_content(s3_bucket, s3_key):
s3.download_fileobj(s3_bucket, s3_key, data)
except ClientError:
return None
- with open(local_path, 'r') as data:
- return json.loads(data.read())
+
+ with open(local_path, 'r') as data:
+ return json.loads(data.read())
|
Make sure to load the S3 cache file when available
|
py
|
diff --git a/ReText/window.py b/ReText/window.py
index <HASH>..<HASH> 100644
--- a/ReText/window.py
+++ b/ReText/window.py
@@ -1052,10 +1052,10 @@ class ReTextWindow(QMainWindow):
QFile('out'+defaultext).rename(fileName)
def getDocumentTitle(self, baseName=False):
- text = convertToUnicode(self.editBoxes[self.ind].toPlainText())
markup = self.markups[self.ind]
realTitle = ''
if markup and not baseName:
+ text = convertToUnicode(self.editBoxes[self.ind].toPlainText())
try:
realTitle = markup.get_document_title(text)
except:
|
getDocumentTitle: don't request text either
|
py
|
diff --git a/edisgo/grid/network.py b/edisgo/grid/network.py
index <HASH>..<HASH> 100644
--- a/edisgo/grid/network.py
+++ b/edisgo/grid/network.py
@@ -912,13 +912,13 @@ class ETraGoSpecs:
Attributes
----------
_battery_capacity: :obj:`float`
- Capacity of virtual battery at Transition Point
+ Capacity of virtual battery at Transition Point in kWh.
_battery_active_power : :pandas:`pandas.Series<series>`
Time series of active power the (virtual) battery (at Transition Point)
- is charged (negative) or discharged (positive) with
_dispatch : :pandas:`pandas.DataFrame<dataframe>`
Time series of active power for each type of generator normalized with
corresponding capacity given in `capacity`.
+ is charged (negative) or discharged (positive) with in kW.
Columns represent generator type:
* 'solar'
@@ -958,6 +958,13 @@ class ETraGoSpecs:
self._capacity = kwargs.get('capacity', None)
self._load = kwargs.get('load', None)
self._annual_load = kwargs.get('annual_load', None)
+ @property
+ def battery_capacity(self):
+ return self._battery_capacity
+
+ @property
+ def battery_active_power(self):
+ return self._battery_active_power
@property
def dispatch(self):
|
Add units and getters for battery attributes in etrago specs
|
py
|
diff --git a/jsonschema/compat.py b/jsonschema/compat.py
index <HASH>..<HASH> 100644
--- a/jsonschema/compat.py
+++ b/jsonschema/compat.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
import operator
import sys
|
Wait wat. Remove insanity.
|
py
|
diff --git a/alexandra/app.py b/alexandra/app.py
index <HASH>..<HASH> 100644
--- a/alexandra/app.py
+++ b/alexandra/app.py
@@ -74,7 +74,15 @@ class Application:
for _, slot in slot_list
}
- if intent_fn.func_code.co_argcount == 2:
+ code_list = inspect.getmembers(intent_fn, inspect.iscode)
+
+ # Python 2.7 compatibility.
+ if len(code_list) == 1:
+ (_, code) = code_list[0]
+ else:
+ (_, code) = code_list[1]
+
+ if code.co_argcount == 2:
return intent_fn(slots, session)
return intent_fn()
|
Missed a meta thing.
|
py
|
diff --git a/osbs/core.py b/osbs/core.py
index <HASH>..<HASH> 100755
--- a/osbs/core.py
+++ b/osbs/core.py
@@ -822,7 +822,7 @@ class Openshift(object):
break
if changetype == WATCH_ERROR:
- logger.error("Error watching ImageStream")
+ logger.error("Error watching ImageStream: %s", obj)
break
if changetype == WATCH_MODIFIED:
|
Log error response on import_image watch failure If watch API returns a response of type error, log the failure associated with it for easier debugging.
|
py
|
diff --git a/fastimport/processor.py b/fastimport/processor.py
index <HASH>..<HASH> 100644
--- a/fastimport/processor.py
+++ b/fastimport/processor.py
@@ -68,25 +68,7 @@ class ImportProcessor(object):
:param command_iter: an iterator providing commands
"""
- if self.working_tree is not None:
- self.working_tree.lock_write()
- elif self.branch is not None:
- self.branch.lock_write()
- elif self.repo is not None:
- self.repo.lock_write()
- try:
- self._process(command_iter)
- finally:
- # If an unhandled exception occurred, abort the write group
- if self.repo is not None and self.repo.is_in_write_group():
- self.repo.abort_write_group()
- # Release the locks
- if self.working_tree is not None:
- self.working_tree.unlock()
- elif self.branch is not None:
- self.branch.unlock()
- elif self.repo is not None:
- self.repo.unlock()
+ self._process(command_iter)
def _process(self, command_iter):
self.pre_process()
|
remove bzrisms from Processor.
|
py
|
diff --git a/openquake/hazard/opensha.py b/openquake/hazard/opensha.py
index <HASH>..<HASH> 100644
--- a/openquake/hazard/opensha.py
+++ b/openquake/hazard/opensha.py
@@ -713,7 +713,7 @@ class EventBasedMixin(BasePSHAMixin):
return results
def write_gmf_files(self, ses):
- """Generate a GeoTiff file and a NRML file for each GMF."""
+ """Generate a NRML file for each GMF."""
iml_list = [float(param)
for param
in self.params['INTENSITY_MEASURE_LEVELS'].split(",")]
@@ -723,9 +723,6 @@ class EventBasedMixin(BasePSHAMixin):
for event_set in ses:
for rupture in ses[event_set]:
- # NOTE(fab): we have to explicitly convert the JSON-decoded
- # tokens from Unicode to string, otherwise the path will not
- # be accepted by the GeoTiffFile constructor
common_path = os.path.join(self.base_path, self['OUTPUT_DIR'],
"gmf-%s-%s" % (str(event_set.replace("!", "_")),
str(rupture.replace("!", "_"))))
|
removed comment, no more needed Former-commit-id: a2d<I>f<I>a6ec4e<I>b<I>e<I>c9c<I>bd<I>
|
py
|
diff --git a/grimoire_elk/elk/bugzilla.py b/grimoire_elk/elk/bugzilla.py
index <HASH>..<HASH> 100644
--- a/grimoire_elk/elk/bugzilla.py
+++ b/grimoire_elk/elk/bugzilla.py
@@ -128,7 +128,6 @@ class BugzillaEnrich(Enrich):
eitem['severity'] = item['data']['bug_severity'][0]['__text__']
eitem['op_sys'] = item['data']['op_sys'][0]['__text__']
eitem['product'] = item['data']['product'][0]['__text__']
- eitem['project_name'] = item['data']['product'][0]['__text__']
eitem['component'] = item['data']['component'][0]['__text__']
eitem['platform'] = item['data']['rep_platform'][0]['__text__']
if '__text__' in item['data']['resolution'][0]:
|
[enrich][bugzilla] Remove project_name field to avoid confussions with dashboard projects
|
py
|
diff --git a/gruvi/http.py b/gruvi/http.py
index <HASH>..<HASH> 100644
--- a/gruvi/http.py
+++ b/gruvi/http.py
@@ -733,6 +733,7 @@ class HttpServer(protocols.RequestResponseProtocol):
env['wsgi.multithread'] = True
env['wsgi.multiprocess'] = True
env['wsgi.run_once'] = False
+ env['gruvi.transport'] = transport
return env
def _send_headers(self, transport):
|
[http] expose transport as "gruvi.transport" in environ
|
py
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -19,7 +19,7 @@ setup(
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
- 'License :: OSI Approved :: GPL License',
+ 'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
|
Changed license in Setup.py to BSD.
|
py
|
diff --git a/django_common/templatetags/custom_tags.py b/django_common/templatetags/custom_tags.py
index <HASH>..<HASH> 100644
--- a/django_common/templatetags/custom_tags.py
+++ b/django_common/templatetags/custom_tags.py
@@ -25,7 +25,9 @@ class FormFieldNode(template.Node):
widget = form_field.field.widget
- if isinstance(widget, widgets.RadioSelect):
+ if isinstance(widget, widgets.HiddenInput):
+ return form_field
+ elif isinstance(widget, widgets.RadioSelect):
t = get_template('common/fragments/radio_field.html')
elif isinstance(widget, widgets.CheckboxInput):
t = get_template('common/fragments/checkbox_field.html')
|
fix: Pass form fields with HiddenInput widget through render_form_field
|
py
|
diff --git a/src/util.py b/src/util.py
index <HASH>..<HASH> 100644
--- a/src/util.py
+++ b/src/util.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#-*- encoding: utf-8 -*-
#
# This file is part of python-gnupg, a Python wrapper around GnuPG.
# Copyright © 2013 Isis Lovecruft, Andrej B.
|
Remove script headers from src/util.py.
|
py
|
diff --git a/spyder_kernels/comms/commbase.py b/spyder_kernels/comms/commbase.py
index <HASH>..<HASH> 100644
--- a/spyder_kernels/comms/commbase.py
+++ b/spyder_kernels/comms/commbase.py
@@ -185,7 +185,7 @@ class CommBase(object):
Check to see if the other side replied.
The check is made with _set_pickle_protocol as this is the first call
- made. If comm_id is not specified, chack all comms.
+ made. If comm_id is not specified, check all comms.
"""
if comm_id is None:
# close all the comms
|
Update commbase.py
|
py
|
diff --git a/opendatalake/classification/named_folders.py b/opendatalake/classification/named_folders.py
index <HASH>..<HASH> 100644
--- a/opendatalake/classification/named_folders.py
+++ b/opendatalake/classification/named_folders.py
@@ -3,7 +3,9 @@ from scipy.misc import imread
from random import shuffle
import numpy as np
import json
-from datasets.tfrecords import PHASE_TRAIN, PHASE_VALIDATION
+
+PHASE_TRAIN = "train"
+PHASE_VALIDATION = "validation"
def one_hot(idx, max_idx):
|
Update named_folders.py
|
py
|
diff --git a/axiom/item.py b/axiom/item.py
index <HASH>..<HASH> 100644
--- a/axiom/item.py
+++ b/axiom/item.py
@@ -2,7 +2,7 @@
__metaclass__ = type
from twisted.python.reflect import qual
-from twisted.application.service import IService, MultiService
+from twisted.application.service import IService, IServiceCollection, MultiService
from axiom import slotmachine, _schema
@@ -82,7 +82,9 @@ def serviceSpecialCase(item, pups):
item.service = svc
return svc
-aggregateInterfaces = {IService: serviceSpecialCase}
+aggregateInterfaces = {
+ IService: serviceSpecialCase,
+ IServiceCollection: serviceSpecialCase}
class Empowered(object):
|
serviceSpecialCase provides a MultiService - MultiService implements IServiceCollection, too.
|
py
|
diff --git a/green/plugin.py b/green/plugin.py
index <HASH>..<HASH> 100644
--- a/green/plugin.py
+++ b/green/plugin.py
@@ -51,8 +51,9 @@ class Green(Plugin):
"""
I tell nosetests what options to add to its own "--help" command.
"""
+ # The superclass sets self.enabled to True if it sees the --with-green
+ # flag or the NOSE_WITH_GREEN environment variable set to non-blank.
super(Green, self).options(parser, env)
- self.enabled = bool(env.get('NOSE_WITH_GREEN', False))
def configure(self, options, conf):
|
Finished simplifying the options handling.
|
py
|
diff --git a/ubcpi/answer_pool.py b/ubcpi/answer_pool.py
index <HASH>..<HASH> 100644
--- a/ubcpi/answer_pool.py
+++ b/ubcpi/answer_pool.py
@@ -89,7 +89,7 @@ def get_other_answers_simple(answers, seeded_answers, get_student_item_dict, num
pool = convert_seeded_answers(seeded_answers)
# merge the dictionaries in the answer dictionary
for key in answers:
- total_in_pool += len(answers)
+ total_in_pool += len(answers[key])
if key in pool:
pool[key].update(answers[key].items())
else:
|
FIXED total pool count for the simple algorithm
|
py
|
diff --git a/pymatgen/io/abinit/nodes.py b/pymatgen/io/abinit/nodes.py
index <HASH>..<HASH> 100644
--- a/pymatgen/io/abinit/nodes.py
+++ b/pymatgen/io/abinit/nodes.py
@@ -1020,6 +1020,8 @@ class FileNode(Node):
return self._abiopen_abiext("_GSR.nc")
def _abiopen_abiext(self, abiext):
+ import glob
+ from abipy import abilab
if not self.filepath.endswith(abiext):
msg = """\n
File type does not match the abinit file extension.
@@ -1029,6 +1031,10 @@ Continuing anyway assuming that the netcdf file provides the API/dims/vars neeed
logger.warning(msg)
self.history.warning(msg)
+ #try to find file in the same path
+ filepath = os.path.dirname(self.filepath)
+ glob_result = glob.glob(os.path.join(filepath,"*%s"%abiext))
+ if len(glob_result): return abilab.abiopen(glob_result[0])
return self.abiopen()
|
FileNode will try to find GSR.nc file in the same path as the file used to initialize it.
|
py
|
diff --git a/testproject/settings.py b/testproject/settings.py
index <HASH>..<HASH> 100644
--- a/testproject/settings.py
+++ b/testproject/settings.py
@@ -140,3 +140,5 @@ INTERNAL_IPS = (
'172.25.10.10',
)
+
+AUP_URL = 'http://example.com/aup.html'
|
Added missing settings to conf file
|
py
|
diff --git a/sanic/__init__.py b/sanic/__init__.py
index <HASH>..<HASH> 100644
--- a/sanic/__init__.py
+++ b/sanic/__init__.py
@@ -1,6 +1,6 @@
from .sanic import Sanic
from .blueprints import Blueprint
-__version__ = '0.1.7'
+__version__ = '0.1.8'
__all__ = ['Sanic', 'Blueprint']
|
Increment version to <I>
|
py
|
diff --git a/setuptools/tests/test_build_meta.py b/setuptools/tests/test_build_meta.py
index <HASH>..<HASH> 100644
--- a/setuptools/tests/test_build_meta.py
+++ b/setuptools/tests/test_build_meta.py
@@ -236,3 +236,23 @@ class TestBuildMetaBackend:
build_backend = self.get_build_backend()
build_backend.build_sdist("temp")
+
+ _relative_path_import_files = {
+ 'setup.py': DALS("""
+ __import__('setuptools').setup(
+ name='foo',
+ version=__import__('hello').__version__,
+ py_modules=['hello']
+ )"""),
+ 'hello.py': '__version__ = "0.0.0"',
+ 'setup.cfg': DALS("""
+ [sdist]
+ formats=zip
+ """)
+ }
+
+ def test_build_sdist_relative_path_import(self, tmpdir_cwd):
+ build_files(self._relative_path_import_files)
+ build_backend = self.get_build_backend()
+ with pytest.raises(ImportError):
+ build_backend.build_sdist("temp")
|
Add test for relative path imports in build_meta Failing test adapted from PR #<I>
|
py
|
diff --git a/source/awesome_tool/mvc/models/state_machine.py b/source/awesome_tool/mvc/models/state_machine.py
index <HASH>..<HASH> 100644
--- a/source/awesome_tool/mvc/models/state_machine.py
+++ b/source/awesome_tool/mvc/models/state_machine.py
@@ -61,10 +61,12 @@ class StateMachineModel(ModelMT):
if info['method_name'] == 'root_state':
if self.state_machine.root_state != self.root_state.state:
new_root_state = self.state_machine.root_state
+ self.root_state.unregister_observer(self)
if isinstance(new_root_state, ContainerState):
self.root_state = ContainerStateModel(new_root_state)
else:
self.root_state = StateModel(new_root_state)
+ self.root_state.register_observer(self)
@ModelMT.observe("state_machine", after=True)
def marked_dirty_flag_changed(self, model, prop_name, info):
|
Fix registration when root state changed - When the root state is changed, the observer for the old root is unregistered - At the same time, an observer for the new root model is registered
|
py
|
diff --git a/bl/id.py b/bl/id.py
index <HASH>..<HASH> 100644
--- a/bl/id.py
+++ b/bl/id.py
@@ -54,6 +54,7 @@ ascii_chars = alphanum_chars + punct_chars
urlslug_punct = ['-', '_', '.', '+', '!', '*', "'", '(', ')', ',']
urlslug_chars = alphanum_chars + urlslug_punct
+slug_chars = urlslug_chars
def random_id(length=8, charset=id_chars, first_charset=lcase_chars, group_char='', group_length=0):
"""Creates a random id with the given length and charset.
|
bl.id.slug_chars as an abbrev of bl.id.urlslug_chars
|
py
|
diff --git a/source/awesome_tool/mvc/statemachine_helper.py b/source/awesome_tool/mvc/statemachine_helper.py
index <HASH>..<HASH> 100644
--- a/source/awesome_tool/mvc/statemachine_helper.py
+++ b/source/awesome_tool/mvc/statemachine_helper.py
@@ -270,6 +270,13 @@ class StateMachineHelper():
for prop_name, value in model_properties.iteritems():
new_state_m.__setattr__(prop_name, value)
+ # Set the parent of all child models to the new state model
+ if prop_name == "states":
+ for state_m in new_state_m.states.itervalues():
+ state_m.parent = new_state_m
+ if prop_name in ['input_data_ports', 'output_data_ports', 'transitions', 'data_flows', 'scoped_variables']:
+ for model in new_state_m.__getattribute__(prop_name):
+ model.parent = new_state_m
for transition_data in connected_transitions:
t = transition_data["transition"]
|
Fix bug in state type conversion routine After adding the old child models to the new state models, the parent of the child models was not set. This is fixed now. The parent of the new child models is set to the new state model.
|
py
|
diff --git a/charmhelpers/contrib/hahelpers/cluster.py b/charmhelpers/contrib/hahelpers/cluster.py
index <HASH>..<HASH> 100644
--- a/charmhelpers/contrib/hahelpers/cluster.py
+++ b/charmhelpers/contrib/hahelpers/cluster.py
@@ -44,6 +44,7 @@ from charmhelpers.core.hookenv import (
ERROR,
WARNING,
unit_get,
+ is_leader as juju_is_leader
)
from charmhelpers.core.decorators import (
retry_on_exception,
@@ -66,12 +67,18 @@ def is_elected_leader(resource):
Returns True if the charm executing this is the elected cluster leader.
It relies on two mechanisms to determine leadership:
- 1. If the charm is part of a corosync cluster, call corosync to
+ 1. If juju is sufficiently new and leadership election is supported,
+ the is_leader command will be used.
+ 2. If the charm is part of a corosync cluster, call corosync to
determine leadership.
- 2. If the charm is not part of a corosync cluster, the leader is
+ 3. If the charm is not part of a corosync cluster, the leader is
determined as being "the alive unit with the lowest unit numer". In
other words, the oldest surviving unit.
"""
+ try:
+ return juju_is_leader()
+ except NotImplementedError:
+ pass
if is_clustered():
if not is_crm_leader(resource):
log('Deferring action to CRM leader.', level=INFO)
|
Try using juju leadership for leadership determination
|
py
|
diff --git a/harpoon/overview.py b/harpoon/overview.py
index <HASH>..<HASH> 100644
--- a/harpoon/overview.py
+++ b/harpoon/overview.py
@@ -41,6 +41,8 @@ class Overview(object):
self.configuration.update(
{ "$@": harpoon.get("extra", "")
, "harpoon": harpoon
+ , "bash": cli_args["bash"] or NotSpecified
+ , "command": cli_args["command"] or NotSpecified
, "config_root" : self.configuration_folder
}
, source = "<cli>"
|
Pass in bash and command from cli options
|
py
|
diff --git a/goodtables/validate.py b/goodtables/validate.py
index <HASH>..<HASH> 100644
--- a/goodtables/validate.py
+++ b/goodtables/validate.py
@@ -32,7 +32,7 @@ def validate(source, **options):
(e.g. `structure`).
infer_schema (bool): Infer schema if one wasn't passed as an argument.
infer_fields (bool): Infer schema for columns not present in the received schema.
- infer_schema (bool): Order source columns based on schema fields order.
+ order_fields (bool): Order source columns based on schema fields order.
This is useful when you don't want to validate that the data
columns' order is the same as the schema's.
error_limit (int): Stop validation if the number of errors per table
|
[#<I>] Fix typo in docstrings Fixes #<I>
|
py
|
diff --git a/luigi/contrib/mrrunner.py b/luigi/contrib/mrrunner.py
index <HASH>..<HASH> 100644
--- a/luigi/contrib/mrrunner.py
+++ b/luigi/contrib/mrrunner.py
@@ -17,6 +17,10 @@
#
"""
+Since after Luigi 2.5.0, this is a private module to Luigi. Luigi users should
+not rely on that importing this module works. Furthermore, "luigi mr streaming"
+have been greatly superseeded by technoligies like Spark, Hive, etc.
+
The hadoop runner.
This module contains the main() method which will be used to run the
|
Make mrrunner module private to luigi And also guide away new users from using this pretty old technology.
|
py
|
diff --git a/sumy/parsers/plaintext.py b/sumy/parsers/plaintext.py
index <HASH>..<HASH> 100644
--- a/sumy/parsers/plaintext.py
+++ b/sumy/parsers/plaintext.py
@@ -76,8 +76,10 @@ class PlaintextParser(DocumentParser):
else:
text += " " + line
- sentences = self.tokenize_sentences(text.strip())
- sentence_objects += map(self._to_sentence, sentences)
+ text = text.strip()
+ if text:
+ sentences = self.tokenize_sentences(text)
+ sentence_objects += map(self._to_sentence, sentences)
return sentence_objects
|
Don't try to split empty string into sentences
|
py
|
diff --git a/gwpy/signal/qtransform.py b/gwpy/signal/qtransform.py
index <HASH>..<HASH> 100644
--- a/gwpy/signal/qtransform.py
+++ b/gwpy/signal/qtransform.py
@@ -518,7 +518,7 @@ class QGram(object):
Notes
-----
- This method will return a `Spectrogram` of dtype ``float32``
+ This method will return a `Spectrogram` of dtype ``float32`` if
``norm`` is given, and ``float64`` otherwise.
To optimize plot rendering with `~matplotlib.axes.Axes.pcolormesh`,
|
Update gwpy/signal/qtransform.py Fixing a typo
|
py
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -6,6 +6,7 @@ setup(
packages=['agnocomplete'],
include_package_data=True,
description='Frontend-agnostic Django autocomplete utilities',
+ url="https://github.com/peopledoc/django-agnocomplete",
author='Novapost',
license='MIT',
install_requires=[
|
Adding `url` argument to setup
|
py
|
diff --git a/ansible/modules/hashivault/hashivault_list.py b/ansible/modules/hashivault/hashivault_list.py
index <HASH>..<HASH> 100644
--- a/ansible/modules/hashivault/hashivault_list.py
+++ b/ansible/modules/hashivault/hashivault_list.py
@@ -87,18 +87,19 @@ def hashivault_list(params):
version = 2
secret = secret.lstrip('metadata/')
- response = None
try:
if version == 2:
- response = client.secrets.kv.v2.list_secrets(path=secret, mount_point=mount_point)
+ if secret:
+ response = client.secrets.kv.v2.read_secret_metadata(path=secret, mount_point=mount_point)
+ result['metadata'] = response.get('data', {})
+ else:
+ response = client.secrets.kv.v2.list_secrets('', mount_point=mount_point)
+ result['secrets'] = response.get('data', {}).get('keys', [])
else:
response = client.secrets.kv.v1.list_secrets(path=secret, mount_point=mount_point)
+ result['secrets'] = response.get('data', {}).get('keys', [])
except Exception as e:
- if response is None:
- response = {}
- else:
- return {'failed': True, 'msg': str(e)}
- result['secrets'] = response.get('data', {}).get('keys', [])
+ return {'failed': True, 'msg': str(e)}
return result
|
Add metadata read to kv2 list
|
py
|
diff --git a/registration/auth_urls.py b/registration/auth_urls.py
index <HASH>..<HASH> 100644
--- a/registration/auth_urls.py
+++ b/registration/auth_urls.py
@@ -44,7 +44,8 @@ urlpatterns = [
url(r'^password/reset/$',
auth_views.password_reset,
name='auth_password_reset'),
- url(r'^password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
+ url(r'^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/'
+ r'(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
auth_views.password_reset_confirm,
name='auth_password_reset_confirm'),
url(r'^password/reset/complete/$',
|
Fix the reset url as Django uses uid<I> instead of uidb<I>
|
py
|
diff --git a/benchexec/tablegenerator/__init__.py b/benchexec/tablegenerator/__init__.py
index <HASH>..<HASH> 100644
--- a/benchexec/tablegenerator/__init__.py
+++ b/benchexec/tablegenerator/__init__.py
@@ -369,10 +369,10 @@ def parse_results_file(resultFile, run_set_id=None, ignore_errors=False):
try:
with gzip.open(resultFile) as f:
resultElem = parse(f)
- except OSError:
+ except IOError:
with bz2.open(resultFile) as f:
resultElem = parse(f)
- except OSError:
+ except IOError:
resultElem = parse(resultFile)
except IOError as e:
|
Catch appropriate exception for Python <I>, where OSError and IOError are different classes.
|
py
|
diff --git a/auto/src/rabird/auto/window/win32.py b/auto/src/rabird/auto/window/win32.py
index <HASH>..<HASH> 100644
--- a/auto/src/rabird/auto/window/win32.py
+++ b/auto/src/rabird/auto/window/win32.py
@@ -45,7 +45,7 @@ class Window(common.Window):
return (cls.find(**kwargs) is not None)
@classmethod
- def find(cls, title=None, id=None, parent=None):
+ def find(cls, title=None, id=None, parent=None, found_limitation=1):
result = []
context = common.FindContext()
@@ -55,7 +55,7 @@ class Window(common.Window):
def enum_window_callback(hwnd, context):
if context.title is not None:
- if re.match(context.title, cls.get_title(hwnd)) is not None:
+ if re.match(context.title, cls.get_title(hwnd)) is None:
return True
if context.id is not None:
|
Fixed window not found even title matched.
|
py
|
diff --git a/SpiffWorkflow/bpmn/PythonScriptEngine.py b/SpiffWorkflow/bpmn/PythonScriptEngine.py
index <HASH>..<HASH> 100644
--- a/SpiffWorkflow/bpmn/PythonScriptEngine.py
+++ b/SpiffWorkflow/bpmn/PythonScriptEngine.py
@@ -58,7 +58,7 @@ class Box(dict):
try:
output = self[attr]
except:
- raise AttributeError("Dictionary has no attribute %s " % str(attr))
+ raise AttributeError("Dictionary has no attribute '%s' " % str(attr))
return output
def __setattr__(self, key, value):
|
slightly better error, quote the bit in question.
|
py
|
diff --git a/src/pymlab/sensors/SHT25_Example.py b/src/pymlab/sensors/SHT25_Example.py
index <HASH>..<HASH> 100755
--- a/src/pymlab/sensors/SHT25_Example.py
+++ b/src/pymlab/sensors/SHT25_Example.py
@@ -6,9 +6,8 @@ import sys
print "SHT25 humidity and temperature sensor example \r\n"
print "Temperature Humidity[%%] \r\n"
-time.sleep(0.5)
-
sht_sensor = SHT25.sht25(int(sys.argv[1]))
+time.sleep(0.5)
i=0
|
modify of dealay time after init and soft reset
|
py
|
diff --git a/blimpy/io/file_wrapper.py b/blimpy/io/file_wrapper.py
index <HASH>..<HASH> 100644
--- a/blimpy/io/file_wrapper.py
+++ b/blimpy/io/file_wrapper.py
@@ -3,7 +3,6 @@
"""
import os
-import sys
import h5py
import six
@@ -46,8 +45,7 @@ def open_file(filename, f_start=None, f_stop=None,t_start=None, t_stop=None,load
# Open HDF5 file
return H5Reader(filename, f_start=f_start, f_stop=f_stop, t_start=t_start, t_stop=t_stop,
load_data=load_data, max_load=max_load)
- elif blimpy.io.sigproc.is_filterbank(filename):
+ if blimpy.io.sigproc.is_filterbank(filename):
# Open FIL file
return FilReader(filename, f_start=f_start, f_stop=f_stop, t_start=t_start, t_stop=t_stop, load_data=load_data, max_load=max_load)
- else:
- raise NotImplementedError('Cannot open this type of file with Waterfall: {}'.format(filename))
+ raise NotImplementedError('Cannot open this type of file with Waterfall: {}'.format(filename))
|
"Cannot open ..." should name the offender
|
py
|
diff --git a/taskqueue/taskqueue.py b/taskqueue/taskqueue.py
index <HASH>..<HASH> 100644
--- a/taskqueue/taskqueue.py
+++ b/taskqueue/taskqueue.py
@@ -314,6 +314,10 @@ class TaskQueue(ThreadedQueue):
return executed
+ def block_until_empty(self, interval_sec=2):
+ while self.enqueued > 0:
+ time.sleep(interval_sec)
+
class MockTaskQueue(object):
def __init__(self, *args, **kwargs):
pass
|
feat: block_until_empty() which polls every 2 seconds by default
|
py
|
diff --git a/test/test_client.py b/test/test_client.py
index <HASH>..<HASH> 100644
--- a/test/test_client.py
+++ b/test/test_client.py
@@ -157,12 +157,6 @@ class TestClient(IntegrationTest, TestRequestMixin):
# No error.
connected(MongoClient())
- def assertIsInstance(self, obj, cls, msg=None):
- """Backport from Python 2.7."""
- if not isinstance(obj, cls):
- standardMsg = '%r is not an instance of %r' % (obj, cls)
- self.fail(self._formatMessage(msg, standardMsg))
-
def test_init_disconnected(self):
c = rs_or_single_client(connect=False)
|
Remove "assertIsInstance" backport. No longer required since we use unittest2 on Python <I>, and the method is in the standard library for Python <I>+.
|
py
|
diff --git a/salt/modules/gentoolkitmod.py b/salt/modules/gentoolkitmod.py
index <HASH>..<HASH> 100644
--- a/salt/modules/gentoolkitmod.py
+++ b/salt/modules/gentoolkitmod.py
@@ -94,7 +94,7 @@ def eclean_dist(destructive=False, package_names=False, size_limit=0,
if size_limit is not 0:
size_limit = parseSize(size_limit)
- clean_size=None
+ clean_size=0
engine = DistfilesSearch(lambda x: None)
clean_me, saved, deprecated = engine.findDistfiles(
destructive=destructive, package_names=package_names,
@@ -108,8 +108,8 @@ def eclean_dist(destructive=False, package_names=False, size_limit=0,
if clean_me:
cleaner = CleanUp(_eclean_progress_controller)
- clean_size = _pretty_size(cleaner.clean_dist(clean_me))
+ clean_size = cleaner.clean_dist(clean_me)
ret = {'cleaned': cleaned, 'saved': saved, 'deprecated': deprecated,
- 'total_cleaned': clean_size}
+ 'total_cleaned': _pretty_size(clean_size)}
return ret
|
Set initial clean total size to 0 in eclean_dist
|
py
|
diff --git a/wpull/proxy_test.py b/wpull/proxy_test.py
index <HASH>..<HASH> 100644
--- a/wpull/proxy_test.py
+++ b/wpull/proxy_test.py
@@ -1,6 +1,5 @@
# encoding=utf-8
import logging
-import tornado.curl_httpclient
import tornado.httpclient
import tornado.testing
@@ -13,8 +12,10 @@ import wpull.testing.goodapp
try:
import pycurl
+ import tornado.curl_httpclient
except ImportError:
pycurl = None
+ tornado.curl_httpclient = None
_logger = logging.getLogger(__name__)
|
proxy_test.py: Moves tornado curl_httpclient import to later.
|
py
|
diff --git a/src/escpos/escpos.py b/src/escpos/escpos.py
index <HASH>..<HASH> 100644
--- a/src/escpos/escpos.py
+++ b/src/escpos/escpos.py
@@ -106,6 +106,9 @@ class Escpos(object):
* `graphics`: prints with the `GS ( L`-command
* `bitImageColumn`: prints with the `ESC *`-command
+ When trying to center an image make sure you have initialized the printer with a valid profile, that
+ contains a media width pixel field. Otherwise the centering will have no effect.
+
:param img_source: PIL image or filename to load: `jpg`, `gif`, `png` or `bmp`
:param high_density_vertical: print in high density in vertical direction *default:* True
:param high_density_horizontal: print in high density in horizontal direction *default:* True
@@ -117,6 +120,10 @@ class Escpos(object):
im = EscposImage(img_source)
try:
+ if self.profile.profile_data['media']['width']['pixels'] == "Unknown":
+ print("The media.width.pixel field of the printer profile is not set. " +
+ "The center flag will have no effect.")
+
max_width = int(self.profile.profile_data['media']['width']['pixels'])
if im.width > max_width:
|
Added some documentation and error handling to the image center flag.
|
py
|
diff --git a/pullv/cli.py b/pullv/cli.py
index <HASH>..<HASH> 100644
--- a/pullv/cli.py
+++ b/pullv/cli.py
@@ -65,7 +65,7 @@ def get_parser():
main_parser.add_argument(
dest='config',
type=str,
- nargs='+',
+ nargs='?',
help='Pull the latest repositories from config(s)'
).completer = ConfigFileCompleter(
allowednames=('.yaml', '.json'), directories=False
@@ -93,7 +93,7 @@ def main():
setup_logger(level=args.log_level.upper() if 'log_level' in args else 'INFO')
try:
- if args.config and args.callback is command_load:
+ if not args.config or args.config and args.callback is command_load:
command_load(args)
else:
parser.print_help()
@@ -102,7 +102,7 @@ def main():
def command_load(args):
- if args.config == ['*']:
+ if not args.config or args.config == ['*']:
yaml_config = os.path.expanduser('~/.pullv.yaml')
has_yaml_config = os.path.exists(yaml_config)
json_config = os.path.expanduser('~/.pullv.json')
|
pullv works against with $ pullv
|
py
|
diff --git a/asn1crypto/util.py b/asn1crypto/util.py
index <HASH>..<HASH> 100644
--- a/asn1crypto/util.py
+++ b/asn1crypto/util.py
@@ -154,13 +154,17 @@ else:
"""
if width is None:
- width_ = math.ceil(value.bit_length() / 8) or 1
- try:
- return value.to_bytes(width_, byteorder='big', signed=signed)
- except (OverflowError):
- return value.to_bytes(width_ + 1, byteorder='big', signed=signed)
- else:
- return value.to_bytes(width, byteorder='big', signed=signed)
+ if signed:
+ if value < 0:
+ bits_required = abs(value + 1).bit_length()
+ else:
+ bits_required = value.bit_length()
+ if bits_required % 8 == 0:
+ bits_required += 1
+ else:
+ bits_required = value.bit_length()
+ width = math.ceil(bits_required / 8) or 1
+ return value.to_bytes(width, byteorder='big', signed=signed)
def int_from_bytes(value, signed=False):
"""
|
Implementation of util.int_to_bytes() on Python 3 no longer requires expensive try/except
|
py
|
diff --git a/tests/test_model_relations.py b/tests/test_model_relations.py
index <HASH>..<HASH> 100644
--- a/tests/test_model_relations.py
+++ b/tests/test_model_relations.py
@@ -35,15 +35,15 @@ class TestModelRelations:
self.prepare_testbed()
user = User(name='Joe').save()
employee = Employee(eid='E1', usr=user).save()
+ # need to wait a sec because we will query solr in the
+ # _save_backlinked_models of User object
+ sleep(1)
employee_from_db = Employee.objects.get(employee.key)
assert employee_from_db.usr.name == user.name
user_from_db = User.objects.get(user.key)
+
user_from_db.name = 'Joen'
- # pprint(user_from_db.clean_value())
- # FIXME: this 1 sec wait shouldn't be required
- sleep(1)
- # pprint(user_from_db.clean_value())
user_from_db.save()
employee_from_db = Employee.objects.get(employee.key)
assert employee_from_db.usr.name == user_from_db.name
|
we need to wait a sec to give enough time for riak/solr sync
|
py
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -12,6 +12,7 @@ setup(
description='Convert Python packages into a single script',
long_description=read("README"),
author='Michael Williamson',
+ author_email='[email protected]',
url='http://github.com/mwilliamson/stickytape',
scripts=["scripts/stickytape"],
packages=['stickytape'],
|
Add author_email to setup.py
|
py
|
diff --git a/vcs/backends/hg.py b/vcs/backends/hg.py
index <HASH>..<HASH> 100644
--- a/vcs/backends/hg.py
+++ b/vcs/backends/hg.py
@@ -104,13 +104,14 @@ class MercurialRepository(BaseRepository):
@LazyProperty
def branches(self):
+ if not self.revisions:return []
sortkey = lambda ctx: ('close' not in ctx._ctx.extra(), ctx._ctx.rev())
return sorted([self.get_changeset(short(head)) for head in
self.repo.branchtags().values()], key=sortkey, reverse=True)
@LazyProperty
def tags(self):
-
+ if not self.revisions:return []
sortkey = lambda ctx: ctx._ctx.rev()
return sorted([self.get_changeset(short(head)) for head in
self.repo.tags().values()], key=sortkey, reverse=True)
|
fixed branches and tags properties to return same result(ie. empty list) when there are no branches and tags, na error was raisen on tags before.
|
py
|
diff --git a/tswift.py b/tswift.py
index <HASH>..<HASH> 100644
--- a/tswift.py
+++ b/tswift.py
@@ -23,6 +23,7 @@ SONG_RE = r'http://www\.metrolyrics\.com/(.*)-lyrics-(.*)\.html'
def slugify(string):
return string.replace(' ', '-').lower()
+
def deslugify(string):
return string.replace('-', ' ').title()
|
pep8 pep8 oh yeah
|
py
|
diff --git a/dtool_config/cli.py b/dtool_config/cli.py
index <HASH>..<HASH> 100644
--- a/dtool_config/cli.py
+++ b/dtool_config/cli.py
@@ -145,3 +145,37 @@ def set_all(cache_directory_path):
scheme,
cache_directory_path
))
+
+
[email protected]()
+def azure():
+ """Configure Azure Storage."""
+
+
[email protected]()
[email protected]("container")
+def get(container):
+ """Print the secret access key of the specified Azure storage container."""
+ click.secho(dtool_config.utils.get_azure_secret_access_key(
+ CONFIG_PATH,
+ container,
+ ))
+
+
[email protected]()
[email protected]("container")
[email protected]("azure_secret_access_key")
+def set(container, azure_secret_access_key):
+ """Configure the cache directory of the specific storage scheme."""
+ click.secho(dtool_config.utils.set_azure_secret_access_key(
+ CONFIG_PATH,
+ container,
+ azure_secret_access_key
+ ))
+
+
[email protected]()
+def ls():
+ """List all Azure storage containers."""
+ for container in dtool_config.utils.list_azure_containers(CONFIG_PATH):
+ click.secho(container)
|
Add the azure get/set/ls cli commands
|
py
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -32,7 +32,7 @@ setup(name='spglm', #name of package
'Programming Language :: Python :: 3.5'
'Programming Language :: Python :: 3.6'
],
- license='3-Clause BSD',
+ license='2-Clause BSD',
packages=['spglm'],
install_requires=['scipy', 'numpy', 'libpysal'],
zip_safe=False,
|
changing license from 3 to 2 in setup.py to match LICENSE
|
py
|
diff --git a/libvcs/types.py b/libvcs/types.py
index <HASH>..<HASH> 100644
--- a/libvcs/types.py
+++ b/libvcs/types.py
@@ -1,12 +1,9 @@
from os import PathLike
from typing import Union
-# See also, if this type is baked in in typing in the future
-# - https://stackoverflow.com/q/53418046/1396928
-# - https://github.com/python/typeshed/issues/5912
-# PathLike = TypeVar("PathLike", str, pathlib.Path)
-# OptionalPathLike = TypeVar("OptionalPathLike", str, pathlib.Path, None)
+# via github.com/python/typeshed/blob/5df8de7/stdlib/_typeshed/__init__.pyi#L115-L118
-
-StrOrBytesPath = Union[str, bytes, PathLike[str], PathLike[bytes]] # stable
+#: :class:`os.PathLike` or :func:`str`
StrPath = Union[str, PathLike[str]] # stable
+#: :class:`os.PathLike`, :func:`str` or :term:`bytes-like object`
+StrOrBytesPath = Union[str, bytes, PathLike[str], PathLike[bytes]] # stable
|
docs(types): Note where StrPath comes from
|
py
|
diff --git a/sometimes/decorators.py b/sometimes/decorators.py
index <HASH>..<HASH> 100644
--- a/sometimes/decorators.py
+++ b/sometimes/decorators.py
@@ -80,6 +80,12 @@ def times(x,y):
wrapped.min += 1
fn(*args, **kwargs)
+ # Reset for another go
+ wrapped.min = wrapped.x
+ wrapped.max = random.randint(wrapped.x, wrapped.y)
+
+ wrapped.x = x
+ wrapped.y = y
wrapped.min = x
wrapped.max = random.randint(x,y)
|
Fix bug in times not being repeatable
|
py
|
diff --git a/pelix/ipopo/core.py b/pelix/ipopo/core.py
index <HASH>..<HASH> 100644
--- a/pelix/ipopo/core.py
+++ b/pelix/ipopo/core.py
@@ -1459,9 +1459,6 @@ class _StoredInstance(object):
if self.state == _StoredInstance.KILLED:
return
- # Unregister from service events
- self.bundle_context.remove_service_listener(self)
-
try:
self.invalidate(True)
@@ -2478,7 +2475,15 @@ class _IPopoService(object):
# Remove instances from the registry: avoids dependencies \
# update to link against a component from this factory again.
for instance in to_remove:
- self.kill(instance.name)
+ try:
+ # Kill the instance
+ self.kill(instance.name)
+
+ except ValueError as ex:
+ # Unknown instance: already killed by the invalidation
+ # callback of a component killed in this loop
+ # => ignore
+ pass
# Remove the factory from the registry
del self.__factories[factory_name]
|
unregister_factory(): protection against errors calling kill() Killing loop is now safe to ValueError, caused when a component marked as removable has been killed in the invalidation method of a component killed before, in the same loop.
|
py
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -5,14 +5,13 @@ long_description = open('README.rst').read()
setup(
name = '3d-wallet-generator',
packages = ['3d_wallet'], # this must be the same as the name above
- version = '0.1.10',
+ version = '0.1.11',
description = 'A tool to help you design and export 3D-printable wallets',
long_description=long_description,
author = 'BTC Spry',
author_email = '[email protected]',
url = 'https://github.com/btcspry/3d-wallet-generator',
install_requires=["bitcoin>=1.1.29","PyQrCode>=1.1"],
- scripts=['bin/3dwallet'],
keywords = ['bitcoin','litecoin','dogecoin','wallet','3d printer','cryptocurrency','altcoin','money'],
classifiers = ["Programming Language :: Python :: 3","License :: OSI Approved :: MIT License","Operating System :: OS Independent","Intended Audience :: End Users/Desktop","Environment :: Console","Development Status :: 4 - Beta","Topic :: Utilities"],
entry_points={
|
Removed bin/.... line in setup.py
|
py
|
diff --git a/fireplace/carddata/minions/basic.py b/fireplace/carddata/minions/basic.py
index <HASH>..<HASH> 100644
--- a/fireplace/carddata/minions/basic.py
+++ b/fireplace/carddata/minions/basic.py
@@ -29,6 +29,13 @@ class NEW1_009:
if self.game.currentPlayer is self.owner:
target.heal(1)
+# Bloodsail Corsair
+class NEW1_025:
+ def activate(self):
+ weapon = self.owner.opponent.hero.weapon
+ if self.owner.opponent.hero.weapon:
+ weapon.loseDurability(1)
+
# Voodoo Doctor
class EX1_011:
@@ -39,6 +46,12 @@ class EX1_011:
class EX1_015:
activate = drawCard
+# Acidic Swamp Ooze
+class EX1_066:
+ def activate(self):
+ if self.owner.opponent.hero.weapon:
+ self.owner.opponent.hero.weapon.destroy()
+
# Succubus
class EX1_306:
activate = discard(1)
@@ -48,6 +61,14 @@ class EX1_506:
def activate(self):
self.owner.summon("EX1_506a")
+# Harrison Jones
+class EX1_558:
+ def activate(self):
+ weapon = self.owner.opponent.hero.weapon
+ if weapon:
+ weapon.destroy()
+ self.owner.draw(weapon.getProperty("durability"))
+
# Priestess of Elune
class EX1_583:
targeting = TARGET_FRIENDLY_HERO
|
Implement Acidic Swamp Ooze, Bloodsail Corsair and Harrison Jones
|
py
|
diff --git a/htmresearch/frameworks/pytorch/sparse_speech_experiment.py b/htmresearch/frameworks/pytorch/sparse_speech_experiment.py
index <HASH>..<HASH> 100644
--- a/htmresearch/frameworks/pytorch/sparse_speech_experiment.py
+++ b/htmresearch/frameworks/pytorch/sparse_speech_experiment.py
@@ -81,6 +81,13 @@ class SparseSpeechExperiment(PyExperimentSuite):
self.loadDatasets(params)
+ # Parse 'n' and 'k' parameters
+ n = params["n"]
+ k = params["k"]
+ if isinstance(n, basestring):
+ n = map(int, n.split("_"))
+ if isinstance(k, basestring):
+ k = map(int, k.split("_"))
if params["model_type"] == "cnn":
assert(False)
@@ -89,8 +96,8 @@ class SparseSpeechExperiment(PyExperimentSuite):
in_channels=1)
elif params["model_type"] == "linear":
sp_model = SparseLinearNet(
- n=params["n"],
- k=params["k"],
+ n=n,
+ k=k,
inputSize=32*32,
outputSize=len(self.train_loader.dataset.classes),
boostStrength=params["boost_strength"],
|
Updated speech to multi layer sparse nets
|
py
|
diff --git a/newsplease/__init__.py b/newsplease/__init__.py
index <HASH>..<HASH> 100644
--- a/newsplease/__init__.py
+++ b/newsplease/__init__.py
@@ -1,3 +1,4 @@
+import datetime
import os
import sys
import urllib
@@ -90,17 +91,18 @@ class NewsPlease:
:return: A dict containing given URLs as keys, and extracted information as corresponding values.
"""
results = {}
+ download_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
if len(urls) == 0:
pass
elif len(urls) == 1:
url = urls[0]
html = SimpleCrawler.fetch_url(url)
- results[url] = NewsPlease.from_html(html, url)
+ results[url] = NewsPlease.from_html(html, url, download_date)
else:
results = SimpleCrawler.fetch_urls(urls)
for url in results:
- results[url] = NewsPlease.from_html(results[url], url)
+ results[url] = NewsPlease.from_html(results[url], url, download_date)
return results
|
add download_date to API download of single and multiple URLs
|
py
|
diff --git a/mintapi/cli.py b/mintapi/cli.py
index <HASH>..<HASH> 100644
--- a/mintapi/cli.py
+++ b/mintapi/cli.py
@@ -11,6 +11,7 @@ import configargparse
from mintapi.api import Mint
from mintapi.signIn import get_email_code
+from pandas import json_normalize
logger = logging.getLogger("mintapi")
@@ -332,6 +333,7 @@ def validate_file_extensions(options):
[
options.transactions,
options.extended_transactions,
+ options.investments,
]
):
if not (
@@ -359,6 +361,14 @@ def output_data(options, data, attention_msg=None):
else:
if options.filename is None:
print(json.dumps(data, indent=2))
+ # NOTE: While this logic is here, unless validate_file_extensions
+ # allows for other data types to export to CSV, this will
+ # only include investment data.
+ elif options.filename.endswith(".csv"):
+ # NOTE: Currently, investment_data, which is a flat JSON, is the only
+ # type of data that uses this section. So, if we open this up to
+ # other non-flat JSON data, we will need to revisit this.
+ json_normalize(data).to_csv(options.filename, index=False)
elif options.filename.endswith(".json"):
with open(options.filename, "w+") as f:
json.dump(data, f, indent=2)
|
✨ Feature: Export Investment Data to CSV (#<I>) * Adding json_to_csv function to convert investment data to csv * Adding a comment * Switch to json_normalize from pandas
|
py
|
diff --git a/rllib/evaluation/worker_set.py b/rllib/evaluation/worker_set.py
index <HASH>..<HASH> 100644
--- a/rllib/evaluation/worker_set.py
+++ b/rllib/evaluation/worker_set.py
@@ -144,10 +144,15 @@ class WorkerSet:
def stop(self) -> None:
"""Stop all rollout workers."""
- self.local_worker().stop()
- for w in self.remote_workers():
- w.stop.remote()
- w.__ray_terminate__.remote()
+ try:
+ self.local_worker().stop()
+ tids = [w.stop.remote() for w in self.remote_workers()]
+ ray.get(tids)
+ except Exception:
+ logger.exception("Failed to stop workers")
+ finally:
+ for w in self.remote_workers():
+ w.__ray_terminate__.remote()
@DeveloperAPI
def foreach_worker(self, func: Callable[[RolloutWorker], T]) -> List[T]:
|
[RLLIB] Wait for remote_workers to finish closing environments before terminating (#<I>)
|
py
|
diff --git a/gns3server/controller/__init__.py b/gns3server/controller/__init__.py
index <HASH>..<HASH> 100644
--- a/gns3server/controller/__init__.py
+++ b/gns3server/controller/__init__.py
@@ -62,8 +62,13 @@ class Controller:
console_host = host
if host == "0.0.0.0":
host = "127.0.0.1"
+
+ name = socket.gethostname()
+ if name == "gns3vm":
+ name = "Main server"
+
yield from self.add_compute(compute_id="local",
- name=socket.gethostname(),
+ name=name,
protocol=server_config.get("protocol", "http"),
host=host,
console_host=console_host,
|
Do not prevent the creation of a local server on a machine named gns3vm Fix #<I>
|
py
|
diff --git a/holidays/countries/united_kingdom.py b/holidays/countries/united_kingdom.py
index <HASH>..<HASH> 100644
--- a/holidays/countries/united_kingdom.py
+++ b/holidays/countries/united_kingdom.py
@@ -157,7 +157,7 @@ class UnitedKingdom(HolidayBase):
self[date(year, MAY, 31) + rd(weekday=MO(-1))] = name
# Late Summer bank holiday (last Monday in August)
- if self.state not in ("Scotland") and year >= 1971:
+ if self.state != "Scotland" and year >= 1971:
name = "Late Summer Bank Holiday"
if self.state == "UK":
name += " [England/Wales/Northern Ireland]"
|
Issue with state=None (#<I>)
|
py
|
diff --git a/drf_dynamic_fields/__init__.py b/drf_dynamic_fields/__init__.py
index <HASH>..<HASH> 100644
--- a/drf_dynamic_fields/__init__.py
+++ b/drf_dynamic_fields/__init__.py
@@ -18,7 +18,16 @@ class DynamicFieldsMixin(object):
warnings.warn('Context does not have access to request')
return
- fields = self.context['request'].query_params.get('fields', None)
+ # NOTE: drf test framework builds a request object where the query
+ # parameters are found under the GET attribute.
+ if hasattr(self.context['request'], 'query_params'):
+ fields = self.context['request'].query_params.get('fields', None)
+ elif hasattr(self.context['request'], 'GET'):
+ fields = self.context['request'].GET.get('fields', None)
+ else:
+ warnings.warn('Request object does not contain query paramters')
+ return
+
if fields:
fields = fields.split(',')
# Drop any fields that are not specified in the `fields` argument.
|
Check if request obj has query_params or GET attr (#3)
|
py
|
diff --git a/tests/python/pants_test/cache/test_artifact_cache.py b/tests/python/pants_test/cache/test_artifact_cache.py
index <HASH>..<HASH> 100644
--- a/tests/python/pants_test/cache/test_artifact_cache.py
+++ b/tests/python/pants_test/cache/test_artifact_cache.py
@@ -155,6 +155,7 @@ class TestArtifactCache(TestBase):
artifact_cache.delete(key)
self.assertFalse(artifact_cache.has(key))
+ @pytest.mark.skip(reason="flaky: https://github.com/pantsbuild/pants/issues/9426")
def test_local_backed_remote_cache(self):
"""make sure that the combined cache finds what it should and that it backfills."""
with self.setup_server() as server:
|
Skip flaky `TestArtifactCache` test. (#<I>) The `test_local_backed_remote_cache` test is flaky as described in #<I>.
|
py
|
diff --git a/dockermap/map/dep.py b/dockermap/map/dep.py
index <HASH>..<HASH> 100644
--- a/dockermap/map/dep.py
+++ b/dockermap/map/dep.py
@@ -185,9 +185,9 @@ class MultiDependencyResolver(BaseDependencyResolver):
:param items: Iterable or dictionary in the format `(dependent_item, dependencies)`.
:type items: iterable
"""
- for item, parents in _dependency_dict(items):
+ for item, parents in six.iteritems(_dependency_dict(items)):
dep = self._deps[item]
- self._deps[item] = Dependency(dep.parent.union(parents), None)
+ self._deps[item] = Dependency(dep.parent.union(parents.parent), None)
def update_backward(self, items):
"""
@@ -197,7 +197,11 @@ class MultiDependencyResolver(BaseDependencyResolver):
:param items: Iterable or dictionary in the format `(item, dependent_items)`.
:type items: iterable
"""
- for parent, sub_items in items:
+ if isinstance(items, dict):
+ iterator = six.iteritems(items)
+ else:
+ iterator = items
+ for parent, sub_items in iterator:
for si in sub_items:
dep = self._deps[si]
dep.parent.add(parent)
|
Fixed iterations in dependency resolution.
|
py
|
diff --git a/cmd2.py b/cmd2.py
index <HASH>..<HASH> 100755
--- a/cmd2.py
+++ b/cmd2.py
@@ -900,18 +900,17 @@ class Cmd(cmd.Cmd):
self.kept_state = None
if statement.parsed.pipeTo:
- # Pipe output from the command to the shell command via echo
- command_line = r'cat {} | {}'.format(self._temp_filename, statement.parsed.pipeTo)
-
- # Get the output and display it. Ignore non-zero return codes and print nothing.
- try:
- result = subprocess.check_output(command_line, shell=True)
- if six.PY3:
- self.stdout.write(result.decode())
- else:
- self.stdout.write(result)
- except subprocess.CalledProcessError:
- pass
+ # cat the tempfile and pipe the output to the specified shell command
+ cat_command = 'cat'
+ p1 = subprocess.Popen([cat_command, self._temp_filename], stdout=subprocess.PIPE)
+ p2 = subprocess.Popen(shlex.split(statement.parsed.pipeTo), stdin=p1.stdout, stdout=subprocess.PIPE)
+ p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
+ output, err = p2.communicate()
+
+ if six.PY3:
+ self.stdout.write(output.decode())
+ else:
+ self.stdout.write(output)
os.remove(self._temp_filename)
self._temp_filename = None
|
Command-line pipe is now handled by subprocess module instead of shell Instead of using shell functionality to pipe output of a command to a shell command, the Python subprocess is now used to pipe stdout of one process to another.
|
py
|
diff --git a/sos/jupyter/kernel.py b/sos/jupyter/kernel.py
index <HASH>..<HASH> 100644
--- a/sos/jupyter/kernel.py
+++ b/sos/jupyter/kernel.py
@@ -1100,7 +1100,7 @@ class SoS_Kernel(IPythonKernel):
out[key] = value
ret['user_expressions'] = out
#
- if not silent:
+ if not silent and store_history:
self._execution_count += 1
# make sure post_executed is triggered after the completion of all cell content
self.shell.user_ns.update(env.sos_dict._dict)
|
Fix execution count for statement executed in panel cell
|
py
|
diff --git a/astrodbkit/votools.py b/astrodbkit/votools.py
index <HASH>..<HASH> 100755
--- a/astrodbkit/votools.py
+++ b/astrodbkit/votools.py
@@ -161,6 +161,10 @@ def photparse(tab):
"""
+ # Check that source_id column is present
+ if 'source_id' not in tab[0].keys():
+ raise KeyError('phot=TRUE requires the source_id columb be included')
+
# Loop through the table and grab unique band names and source IDs
uniqueid = []
for i in range(len(tab)):
|
catch error when source_id column is not present
|
py
|
diff --git a/etk/data_extractors/table_extractor.py b/etk/data_extractors/table_extractor.py
index <HASH>..<HASH> 100644
--- a/etk/data_extractors/table_extractor.py
+++ b/etk/data_extractors/table_extractor.py
@@ -131,7 +131,9 @@ class TableClassification():
cell_text = [match.value for match in cell_text_path.find(cell)]
cell_data = [match.value for match in cell_extraction.find(cell)]
for text in cell_text:
- if any([re.sub('[^\w]', '', x) in self.sem_labels for x in text.lower().split(':')]):
+ text = re.sub('[^\w]', ' ', text)
+ text = re.sub('\s+', ' ', text)
+ if any([x in text for x in self.sem_labels]):
if 'SEMANTIC_TYPE' not in extractors_suceeded:
extractors_suceeded['SEMANTIC_TYPE'] = 1
else:
@@ -299,7 +301,7 @@ def extract(html_doc, min_data_rows = 1):
soup = BeautifulSoup(html_doc, 'html.parser')
if(soup.table == None):
- return None
+ return []
else:
result_tables = list()
tables = soup.findAll('table')
|
fixed bug, table extractor returns [] when there's no table.
|
py
|
diff --git a/src/rez/package_resources_.py b/src/rez/package_resources_.py
index <HASH>..<HASH> 100644
--- a/src/rez/package_resources_.py
+++ b/src/rez/package_resources_.py
@@ -376,7 +376,7 @@ class VariantResourceHelper(VariantResource):
else:
try:
reqs = self.parent.variants[self.index]
- except IndexError:
+ except (IndexError, TypeError):
raise ResourceError(
"Unexpected error - variant %s cannot be found in its "
"parent package %s" % (self.uri, self.parent.uri))
|
minor bugfix for case where a specific resource fail wasn't getting recognised as such
|
py
|
diff --git a/editor/editor.py b/editor/editor.py
index <HASH>..<HASH> 100644
--- a/editor/editor.py
+++ b/editor/editor.py
@@ -488,14 +488,13 @@ class Editor(App):
key = "root" if parent==self.project else widget.identifier
if root_tree_node:
parent.append(widget,key)
- if self.selectedWidget == self.project:
- self.on_widget_selection( widget )
for child in widget.children.values():
if type(child) == str:
continue
self.add_widget_to_editor(child, widget, False)
self.instancesWidget.update(self.project, self.selectedWidget)
+ self.on_widget_selection(widget)
def on_widget_selection(self, widget):
self.remove_box_shadow_selected_widget()
|
Editor - new widgets added gets now automatically selected.
|
py
|
diff --git a/cinderlib/cinderlib.py b/cinderlib/cinderlib.py
index <HASH>..<HASH> 100644
--- a/cinderlib/cinderlib.py
+++ b/cinderlib/cinderlib.py
@@ -393,6 +393,15 @@ class Backend(object):
@staticmethod
def list_supported_drivers():
"""Returns dictionary with driver classes names as keys."""
+
+ def convert_oslo_config(oslo_options):
+ options = []
+ for opt in oslo_options:
+ tmp_dict = {k: str(v) for k, v in vars(opt).items()
+ if not k.startswith('_')}
+ options.append(tmp_dict)
+ return options
+
def list_drivers(queue):
cwd = os.getcwd()
# Go to the parent directory directory where Cinder is installed
@@ -403,6 +412,9 @@ class Backend(object):
# Drivers contain class instances which are not serializable
for driver in mapping.values():
driver.pop('cls', None)
+ if 'driver_options' in driver:
+ driver['driver_options'] = convert_oslo_config(
+ driver['driver_options'])
finally:
os.chdir(cwd)
queue.put(mapping)
@@ -412,8 +424,8 @@ class Backend(object):
queue = multiprocessing.Queue()
p = multiprocessing.Process(target=list_drivers, args=(queue,))
p.start()
- p.join()
result = queue.get()
+ p.join()
return result
|
Convert the driver_options to a dictionary This patch converts the cinder interface driver_options to a dictionary so it can be pickled between processes. This patch also calls query.get() prior to join() so we don't run into a deadlock. Change-Id: I<I>fa8b9b<I>b8e8a<I>a8f<I>a<I>ea7e
|
py
|
diff --git a/doc2dash/parsers/__init__.py b/doc2dash/parsers/__init__.py
index <HASH>..<HASH> 100644
--- a/doc2dash/parsers/__init__.py
+++ b/doc2dash/parsers/__init__.py
@@ -4,8 +4,8 @@ from . import pydoctor, sphinx, intersphinx
DOCTYPES = [
- intersphinx.InterSphinxParser,
pydoctor.PyDoctorParser,
+ intersphinx.InterSphinxParser,
sphinx.SphinxParser,
]
|
look for pydoctor first
|
py
|
diff --git a/spyder/plugins/completion/kite/plugin.py b/spyder/plugins/completion/kite/plugin.py
index <HASH>..<HASH> 100644
--- a/spyder/plugins/completion/kite/plugin.py
+++ b/spyder/plugins/completion/kite/plugin.py
@@ -93,7 +93,7 @@ class KiteCompletionPlugin(SpyderCompletionPlugin):
is not possible yet or has already been displayed before.
:return:
"""
- if not self.main_window_visible \
+ if self.main_window_visible \
and self.kite_initialized \
and self.get_option('kite_show_onboarding', True):
onboarding_file = self.client.get_onboarding_file()
|
fix broken condition which was accidentaly changed by the last PR update
|
py
|
diff --git a/coveralls/api.py b/coveralls/api.py
index <HASH>..<HASH> 100644
--- a/coveralls/api.py
+++ b/coveralls/api.py
@@ -235,9 +235,14 @@ class Coveralls:
# attach a random value to ensure uniqueness
# TODO: an auto-incrementing integer might be easier to reason
# about if we could fetch the previous value
- new_id = '{}-{}'.format(
- self.config.get('service_job_id', 42),
- random.randint(0, sys.maxsize))
+ # N.B. Github Actions fails if this is not set to null.
+ # Other services fail if this is set to null. Sigh x2.
+ if os.environ.get('GITHUB_REPOSITORY'):
+ new_id = None
+ else:
+ new_id = '{}-{}'.format(
+ self.config.get('service_job_id', 42),
+ random.randint(0, sys.maxsize))
print('resubmitting with id {}'.format(new_id))
self.config['service_job_id'] = new_id
|
fix(github): send null job_id to fix <I> during resubmission (#<I>) If a submission is failed, the tool will check and adjust/resubmit again with a newly generated job_id. For GitHub Actions, this needs to be null again.
|
py
|
diff --git a/src/pybel/constants.py b/src/pybel/constants.py
index <HASH>..<HASH> 100644
--- a/src/pybel/constants.py
+++ b/src/pybel/constants.py
@@ -241,6 +241,8 @@ rev_abundance_labels = {
RELATION = 'relation'
#: The key for an internal edge data dictionary for the citation dictionary
CITATION = 'citation'
+CITATION_DB = NAMESPACE # for backwards compatibility
+CITATION_IDENTIFIER = IDENTIFIER # for backwards compatibility
#: The key for an internal edge data dictionary for the evidence string
EVIDENCE = 'evidence'
#: The key for an internal edge data dictionary for the annotations dictionary
@@ -248,7 +250,9 @@ ANNOTATIONS = 'annotations'
#: The key for free annotations
FREE_ANNOTATIONS = 'free_annotations'
SOURCE = 'source'
+SUBJECT = SOURCE # for backwards compatibility
TARGET = 'target'
+OBJECT = TARGET # for backwards compatibility
#: The key for an internal edge data dictionary for the source modifier dictionary
SOURCE_MODIFIER = 'source_modifier'
#: The key for an internal edge data dictionary for the target modifier dictionary
|
Add reverse compatibility for old constants
|
py
|
diff --git a/ginga/canvas/types/image.py b/ginga/canvas/types/image.py
index <HASH>..<HASH> 100644
--- a/ginga/canvas/types/image.py
+++ b/ginga/canvas/types/image.py
@@ -158,6 +158,8 @@ class ImageP(OnePointMixin, CanvasObjectBase):
self.make_callback('image-set', image)
def get_scaled_wdht(self):
+ if self.image is None:
+ return (0, 0)
width = self.image.width * self.scale_x
height = self.image.height * self.scale_y
return (width, height)
|
Fix for get_scaled_wdht() when no image is plotted
|
py
|
diff --git a/src/auditlog/mixins.py b/src/auditlog/mixins.py
index <HASH>..<HASH> 100644
--- a/src/auditlog/mixins.py
+++ b/src/auditlog/mixins.py
@@ -17,10 +17,8 @@ class LogEntryAdminMixin(object):
app_label, model = settings.AUTH_USER_MODEL.split('.')
viewname = 'admin:%s_%s_change' % (app_label, model.lower())
link = urlresolvers.reverse(viewname, args=[obj.actor.id])
- try:
- return u'<a href="%s">%s</a>' % (link, obj.actor.get_full_name())
- except AttributeError:
- return u'<a href="%s">%s</a>' % (link, obj.actor.email)
+ return u'<a href="%s">%s</a>' % (link, obj.actor)
+
return 'system'
user_url.allow_tags = True
user_url.short_description = 'User'
|
Changed to actor's string represantation Depending on actor's attributes is error prone, developers can extend the user model without the needed attributes.
|
py
|
diff --git a/twistes/parser.py b/twistes/parser.py
index <HASH>..<HASH> 100644
--- a/twistes/parser.py
+++ b/twistes/parser.py
@@ -108,7 +108,7 @@ class EsParser(object):
:param sub_paths: a list of sub paths
:return:
"""
- queued_params = [quote(str(c), '') for c in sub_paths if c not in NULL_VALUES]
+ queued_params = [quote(c.encode('utf-8'), '') for c in sub_paths if c not in NULL_VALUES]
queued_params.insert(0, '')
return '/'.join(queued_params)
|
Fix make_path to use .encode('utf-8') instead of str (#<I>)
|
py
|
diff --git a/project_generator/tools/visual_studio.py b/project_generator/tools/visual_studio.py
index <HASH>..<HASH> 100644
--- a/project_generator/tools/visual_studio.py
+++ b/project_generator/tools/visual_studio.py
@@ -25,6 +25,17 @@ from .tool import Tool, Exporter
# 4. To test the basic methods, like export or progen list tools, add this class to tools_supported
# use logging.debug to print that exporting is happening and other info if you need to
+# Not certain if the first step should not be to create templates. Generate a valid project for a tool,
+# create a new project there, make it compile for simple hello world and possibly to debug (verifies that
+# everything is correctly set up). Once we have a simple project, we can inspect the syntax . Where are files stored,
+# include paths, macros, target if any, and other variables. look at project.ProjectTemplate() class which
+# defines data needed for progen.
+# The fastest way is to copy the manually generated project, and replace data with jinja2 syntax. To fill in
+# all data we need (sources, includes, etc). Rename the files to tools_name.extensions.tmpl. They will be used
+# as templates.
+# We can later switch to full parsing the file and generate it on the fly, but this often is more time consuming to learn
+# how the tool is structured. Thus lets keep it simple for new tool, use jinja2
+
class VisualStudio(Tool, Exporter):
def __init__(self, workspace, env_settings):
|
Visual studio - adding a comment about template creation
|
py
|
diff --git a/jsonapi/resource.py b/jsonapi/resource.py
index <HASH>..<HASH> 100644
--- a/jsonapi/resource.py
+++ b/jsonapi/resource.py
@@ -160,6 +160,22 @@ class Resource(object):
@classmethod
def _get_fields_others_many_to_many(cls, model):
fields = {}
+ model_resource_map = cls.Meta.api.model_resource_map
+ for related_model, related_resource in model_resource_map.items():
+ if related_model == model:
+ # Do not check relationship with self
+ continue
+
+ for field in related_model._meta.many_to_many:
+ if field.rel.to == model:
+ fields[related_resource.Meta.name_plural] = {
+ "type": Resource.FIELD_TYPES.TO_MANY,
+ "name": field.rel.related_name or "{}_set".format(
+ # get actual (parent) model
+ field.model._meta.model_name
+ ),
+ "related_resource": related_resource,
+ }
return fields
@classproperty
|
add many to many investigation from other related resource
|
py
|
diff --git a/opbeat/contrib/django/models.py b/opbeat/contrib/django/models.py
index <HASH>..<HASH> 100644
--- a/opbeat/contrib/django/models.py
+++ b/opbeat/contrib/django/models.py
@@ -192,15 +192,6 @@ def register_handlers():
# Connect to Django's internal signal handler
got_request_exception.connect(opbeat_exception_handler)
- middleware_class = "opbeat.contrib.django.middleware.OpbeatAPMMiddleware"
- if middleware_class not in django_settings.MIDDLEWARE_CLASSES:
- if isinstance(django_settings.MIDDLEWARE_CLASSES, tuple):
- django_settings.MIDDLEWARE_CLASSES = (
- (middleware_class,) + django_settings.MIDDLEWARE_CLASSES
- )
- else:
- django_settings.MIDDLEWARE_CLASSES.insert(0, middleware_class)
-
# If Celery is installed, register a signal handler
if 'djcelery' in django_settings.INSTALLED_APPS:
|
Get rid of automagic middleware insertion because it doesn't always work.
|
py
|
diff --git a/lyricsgenius/artist.py b/lyricsgenius/artist.py
index <HASH>..<HASH> 100644
--- a/lyricsgenius/artist.py
+++ b/lyricsgenius/artist.py
@@ -77,7 +77,8 @@ class Artist(object):
from difflib import SequenceMatcher as sm # For comparing similarity of lyrics
# Idea credit: https://bigishdata.com/2016/10/25/talkin-bout-trucks-beer-and-love-in-country-songs-analyzing-genius-lyrics/
seqA = sm(None, s1.lyrics, s2['lyrics'])
- seqB = sm(None, s2['lyrics'], s1.lyrics)
+ if seqA.ratio() > 0.4:
+ seqB = sm(None, s2['lyrics'], s1.lyrics)
return seqA.ratio() > 0.5 or seqB.ratio() > 0.5
def songInArtist(new_song):
@@ -147,4 +148,4 @@ class Artist(object):
return '{0}, {1} songs'.format(self.name,self._num_songs)
def __repr__(self):
- return repr((self.name, '{0} songs'.format(self._num_songs)))
\ No newline at end of file
+ return repr((self.name, '{0} songs'.format(self._num_songs)))
|
Efficiency of 2nd SequenceMatcher In looking at the variation between the two SM function, there doesn't appear to be variation greater than <I> (Sample of <I> songs). I increased the threshold slightly to take into consideration outliers, but this should reduce the performance impact of having to run SM twice on everything. Only double checking songs which narrowly missed the <I> similarity determinate.
|
py
|
diff --git a/spyderlib/plugins/ipythonconsole.py b/spyderlib/plugins/ipythonconsole.py
index <HASH>..<HASH> 100644
--- a/spyderlib/plugins/ipythonconsole.py
+++ b/spyderlib/plugins/ipythonconsole.py
@@ -293,7 +293,7 @@ class IPythonClient(QWidget):
#------ Public API --------------------------------------------------------
def get_name(self):
"""Return client name"""
- return _("Client") + " " + self.client_name
+ return _("Console") + " " + self.client_name
def get_control(self):
"""Return the text widget (or similar) to give focus to"""
@@ -748,7 +748,7 @@ class IPythonConsole(SpyderPluginWidget):
index = self.get_shell_index_from_id(client_widget_id)
match = re.match('^kernel-(\d+).json', connection_file)
if match is not None: # should not fail, but we never know...
- name = "Client " + match.groups()[0] + '/' + chr(65)
+ name = _("Console") + " " + match.groups()[0] + '/' + chr(65)
self.tabwidget.setTabText(index, name)
def create_new_kernel(self):
|
IPython console: Rename 'Client' to 'Console' for the tab name of every client Update Issue <I>
|
py
|
diff --git a/uncompyle6/parsers/parse30.py b/uncompyle6/parsers/parse30.py
index <HASH>..<HASH> 100644
--- a/uncompyle6/parsers/parse30.py
+++ b/uncompyle6/parsers/parse30.py
@@ -258,7 +258,11 @@ class Python30Parser(Python31Parser):
if rule[0] == "iflaststmtl":
return not (jmp_false[0].attr <= tokens[last].offset)
else:
- return not (tokens[first].offset <= jmp_false[0].attr <= tokens[last].offset)
+ jmp_false_target = jmp_false[0].attr
+ if tokens[first].offset > jmp_false_target:
+ return True
+ return (
+ (jmp_false_target > tokens[last].offset) and tokens[last] != "JUMP_FORWARD")
pass
pass
pass
|
Remove more <I> parse errors... However this doesn't mean that some wrong rules still don't kid in. We still have control-flow "if/and/else" vs "if/if/else" problems.
|
py
|
diff --git a/entei.py b/entei.py
index <HASH>..<HASH> 100755
--- a/entei.py
+++ b/entei.py
@@ -45,8 +45,8 @@ def tokenize(template):
until = until or l_del
literal = get()
while not template.closed:
- if literal[-2:] == until:
- return literal[:-2]
+ if literal[-len(until):] == until:
+ return literal[:-len(until)]
literal += get()
@@ -96,8 +96,8 @@ def tokenize(template):
elif tag_type == 'set delimiter?':
if tag_key[-1] == '=':
- l_del, r_del = tag_key[:-1].split(' ')
- get(2)
+ dels = tag_key[:-1].strip().split(' ')
+ l_del, r_del = dels[0], dels[-1]
continue
elif tag_type in ['section', 'inverted section']:
|
Added support for delimiters to be any size Instead of needing them to be 2 characters. Also ignores all spaces in the center (instead of expecting one). And fixed a bug where delimiters would eat some trailing characters!
|
py
|
diff --git a/boundary/api_cli.py b/boundary/api_cli.py
index <HASH>..<HASH> 100755
--- a/boundary/api_cli.py
+++ b/boundary/api_cli.py
@@ -19,7 +19,6 @@ import argparse
import logging
import os
import requests
-import urllib2
import urllib
"""
@@ -273,7 +272,7 @@ class ApiCli(object):
"""
Determines what status codes represent a good response from an API call.
"""
- return status_code == urllib2.httplib.OK
+ return status_code == requests.codes.ok
def callAPI(self):
"""
|
Remove dependency on urllib2 by using requests.codes
|
py
|
diff --git a/openquake/hmtk/seismicity/utils.py b/openquake/hmtk/seismicity/utils.py
index <HASH>..<HASH> 100644
--- a/openquake/hmtk/seismicity/utils.py
+++ b/openquake/hmtk/seismicity/utils.py
@@ -171,7 +171,6 @@ def decimal_time(year, month, day, hour, minute, second):
tse = second
tmonth = tmo - 1
- tmonth = np.array([int(t) if not np.isnan(t) else 0 for t in tmonth])
day_count = MARKER_NORMAL[tmonth] + tda - 1
id_leap = leap_check(year)
leap_loc = np.where(id_leap)[0]
|
Removed some testing code from utils.py
|
py
|
diff --git a/seaworthy/definitions.py b/seaworthy/definitions.py
index <HASH>..<HASH> 100644
--- a/seaworthy/definitions.py
+++ b/seaworthy/definitions.py
@@ -56,7 +56,7 @@ class _DefinitionBase:
Setup this resource so that is ready to be used in a test. If the
resource has already been created, this call does nothing.
- For most resources, this just involes creating the resource in Docker.
+ For most resources, this just involves creating the resource in Docker.
:param helper:
The resource helper to use, if one was not provided when this
|
tyop: involes -> involves
|
py
|
diff --git a/make.py b/make.py
index <HASH>..<HASH> 100644
--- a/make.py
+++ b/make.py
@@ -69,7 +69,9 @@ def build_docs(cfg: Cfg):
data = ""
with open(html_file, 'r') as fr:
for line in fr:
- if 'modernizr.min.js"' not in line:
+ if 'modernizr.min.js"' not in line and \
+ 'js/theme.js' not in line:
+
data += line
with open(html_file, 'w') as fw:
|
Historic: Docs Build Script: Remove unused js file --- Note: This commit is related to sty's documentation website, which was removed from this git history, because it moved to another repo. --- * Customize theme.js. The page will not scroll the menu on page load any more.
|
py
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -38,7 +38,7 @@ with codecs.open(readme_md, encoding='utf-8') as f:
long_description = f.read()
-version = '0.1.19'
+version = '0.1.20'
class TestCommand(TestClass):
|
Update version number to <I>
|
py
|
diff --git a/webtul/db.py b/webtul/db.py
index <HASH>..<HASH> 100644
--- a/webtul/db.py
+++ b/webtul/db.py
@@ -51,9 +51,9 @@ class MySQL:
"""This function is the most use one, with the paramter times
it will try x times to execute the sql, default is 1.
"""
- self.log and self.log.debug('SQL: ' + str(sql))
+ self.log and self.log.debug('%s %s' % ('SQL:', sql))
if param is not ():
- self.log and self.log.debug('PARAMs: ' + str(param))
+ self.log and self.log.debug('%s %s' % ('PARAMs:', param))
for i in xrange(times):
try:
ret, res = self._execute(sql, param)
|
FIX a bug, execute fail having unicode in SQL or parameters
|
py
|
diff --git a/openquake/hazardlib/gsim/base.py b/openquake/hazardlib/gsim/base.py
index <HASH>..<HASH> 100644
--- a/openquake/hazardlib/gsim/base.py
+++ b/openquake/hazardlib/gsim/base.py
@@ -301,7 +301,7 @@ class ContextMaker(object):
:param sites: a (Filtered)SiteColletion
:param distance_type: default 'rjb'
:returns: (close sites, close distances)
- :raises: a FarAwayRupture exception is the rupture is far away
+ :raises: a FarAwayRupture exception if the rupture is far away
"""
distances = get_distances(rupture, sites.mesh, distance_type)
if self.maximum_distance is None: # for sites already filtered
|
Fixed typo [skip CI]
|
py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.