diff
stringlengths 139
3.65k
| message
stringlengths 8
627
| diff_languages
stringclasses 1
value |
|---|---|---|
diff --git a/tests/pycut_test.py b/tests/pycut_test.py
index <HASH>..<HASH> 100644
--- a/tests/pycut_test.py
+++ b/tests/pycut_test.py
@@ -327,9 +327,9 @@ class PycutTest(unittest.TestCase):
gc.set_seeds(seeds)
gc.apriori = apriori
gc.run()
- import sed3
- ed = sed3.sed3(img, contour=(gc.segmentation==0))
- ed.show()
+ # import sed3
+ # ed = sed3.sed3(img, contour=(gc.segmentation==0))
+ # ed.show()
self.assertLess(
np.sum(
|
visualization with sed3 removed from test
|
py
|
diff --git a/spyder/plugins/editor/panels/indentationguides.py b/spyder/plugins/editor/panels/indentationguides.py
index <HASH>..<HASH> 100644
--- a/spyder/plugins/editor/panels/indentationguides.py
+++ b/spyder/plugins/editor/panels/indentationguides.py
@@ -7,13 +7,12 @@
"""
This module contains the indentation guide panel.
"""
+
# Third party imports
from qtpy.QtCore import Qt
from qtpy.QtGui import QPainter, QColor
-from intervaltree import IntervalTree
# Local imports
-from spyder.plugins.editor.utils.editor import TextBlockHelper
from spyder.api.panel import Panel
@@ -44,14 +43,12 @@ class IndentationGuide(Panel):
color = QColor(self.color)
color.setAlphaF(.5)
painter.setPen(color)
- offset = self.editor.document().documentMargin() + \
- self.editor.contentOffset().x()
+ offset = (self.editor.document().documentMargin() +
+ self.editor.contentOffset().x())
folding_panel = self.editor.panels.get('FoldingPanel')
folding_regions = folding_panel.folding_regions
- folding_status = folding_panel.folding_status
leading_whitespaces = self.editor.leading_whitespaces
for line_number in folding_regions:
- post_update = False
end_line = folding_regions[line_number]
start_block = self.editor.document().findBlockByNumber(
line_number)
|
Indent guides: Remove unused imports and variables
|
py
|
diff --git a/salt/modules/pip.py b/salt/modules/pip.py
index <HASH>..<HASH> 100644
--- a/salt/modules/pip.py
+++ b/salt/modules/pip.py
@@ -303,7 +303,7 @@ def _process_requirements(requirements, cmd, cwd, saltenv, user):
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
- __utils__['win_dacl.set_permissions'](
+ __utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
|
The loader uses win_dacl's virtual name
|
py
|
diff --git a/spinoff/contrib/monitoring/monitor.py b/spinoff/contrib/monitoring/monitor.py
index <HASH>..<HASH> 100644
--- a/spinoff/contrib/monitoring/monitor.py
+++ b/spinoff/contrib/monitoring/monitor.py
@@ -139,19 +139,24 @@ class MonitorClient(Actor):
def receive(self, msg):
if 'ack' == msg:
- self.watch(self.monitor)
if not self.connected:
self.connected = True
self.connecting.cancel()
self.connecting = None
+
elif ('terminated', self.monitor) == msg:
self.connected = False
self.connect(delayed=True)
+
elif self.connected:
self.monitor << msg
+
elif not self.connecting:
self.connect()
+ else:
+ pass
+
def connect(self, delayed=False):
if self.connecting and not self.connecting.called:
self.connecting.cancel()
|
Minor simplification and cleanup in spinoff.contrib.monitoring
|
py
|
diff --git a/tests/test.py b/tests/test.py
index <HASH>..<HASH> 100644
--- a/tests/test.py
+++ b/tests/test.py
@@ -155,6 +155,7 @@ def test_number_smashing():
eq_(tokenize('1', 'en', combine_numbers=True), ['1'])
eq_(tokenize('3.14', 'en', combine_numbers=True), ['0.00'])
eq_(tokenize('24601', 'en', combine_numbers=True), ['00000'])
+ eq_(word_frequency('24601', 'en'), word_frequency('90210', 'en'))
def test_phrase_freq():
|
test that number-smashing still happens in freq lookups
|
py
|
diff --git a/examples/outdoor.py b/examples/outdoor.py
index <HASH>..<HASH> 100755
--- a/examples/outdoor.py
+++ b/examples/outdoor.py
@@ -29,13 +29,13 @@ norms = []
for i in range(17):
row = []
for j in range(17):
- row.append(Vertex(0, 0, 0))
+ row.append(Vertex(0, 0, 1))
norms.append(row)
dists = []
for i in range(17):
row = []
for j in range(17):
- row.append((i % 2) + ((j+1) % 2)) # funky pattern
+ row.append(((i % 2) + ((j+1) % 2)) * 4) # funky pattern
dists.append(row)
d = DispInfo(4, norms, dists)
|
Fixed disp map numbers in Outdoor sample map. It actually works\! (#8)
|
py
|
diff --git a/bitshares/wallet.py b/bitshares/wallet.py
index <HASH>..<HASH> 100644
--- a/bitshares/wallet.py
+++ b/bitshares/wallet.py
@@ -118,6 +118,8 @@ class Wallet():
if "UNLOCK" in os.environ:
log.debug("Trying to use environmental variable to unlock wallet")
self.unlock(os.environ.get("UNLOCK"))
+ else:
+ raise WrongMasterPasswordException
def lock(self):
""" Lock the wallet database
|
[password] fail if no password provided an non available in environment
|
py
|
diff --git a/QUANTAXIS/QAUtil/QASetting.py b/QUANTAXIS/QAUtil/QASetting.py
index <HASH>..<HASH> 100644
--- a/QUANTAXIS/QAUtil/QASetting.py
+++ b/QUANTAXIS/QAUtil/QASetting.py
@@ -29,7 +29,7 @@ from QUANTAXIS.QAUtil import QA_util_log_info, QA_util_sql_mongo_setting
class QA_Setting():
QA_util_sql_mongo_ip = os.getenv('MONGO_IP') if os.getenv('MONGO_IP') else '127.0.0.1'
- QA_util_sql_mongo_port = os.getenv('MONGO_PORT') if os.getenv('MONGO_PORT') else '127.0.0.1'
+ QA_util_sql_mongo_port = os.getenv('MONGO_PORT') if os.getenv('MONGO_PORT') else '27017'
client = QA_util_sql_mongo_setting(
QA_util_sql_mongo_ip, QA_util_sql_mongo_port)
|
fix(QASetting): correct default port number
|
py
|
diff --git a/pylutron/__init__.py b/pylutron/__init__.py
index <HASH>..<HASH> 100644
--- a/pylutron/__init__.py
+++ b/pylutron/__init__.py
@@ -244,7 +244,7 @@ class LutronXmlDbParser(object):
# other assets and attributes. Here we index the groups to be bound to
# Areas later.
groups = root.find('OccupancyGroups')
- for group_xml in groups.getiterator('OccupancyGroup'):
+ for group_xml in groups.iter('OccupancyGroup'):
group = self._parse_occupancy_group(group_xml)
if group.group_number:
self._occupancy_groups[group.group_number] = group
@@ -256,7 +256,7 @@ class LutronXmlDbParser(object):
top_area = root.find('Areas').find('Area')
self.project_name = top_area.get('Name')
areas = top_area.find('Areas')
- for area_xml in areas.getiterator('Area'):
+ for area_xml in areas.iter('Area'):
area = self._parse_area(area_xml)
self.areas.append(area)
return True
|
Fix xml iterators to be compatible with python 3 (#<I>) getiterator was deprecated in <I>. Python <I> has finally removed it. iter() is the appropriate method.
|
py
|
diff --git a/django_coverage_plugin/plugin.py b/django_coverage_plugin/plugin.py
index <HASH>..<HASH> 100644
--- a/django_coverage_plugin/plugin.py
+++ b/django_coverage_plugin/plugin.py
@@ -163,14 +163,12 @@ class DjangoTemplatePlugin(
def file_reporter(self, filename):
return FileReporter(filename)
- def find_unexecuted_files(self, src_dir):
- res = []
+ def find_executable_files(self, src_dir):
for i, (dirpath, dirnames, filenames) in enumerate(os.walk(src_dir)):
for filename in filenames:
- if re.match(r"^[^.#~!$@%^&*()+=,]+\.html?$", filename):
- filepath = os.path.join(dirpath, filename)
- res.append(filepath)
- return res
+ ignored, ext = os.path.splitext(filename)
+ if ext in (".htm", ".html"):
+ yield os.path.join(dirpath, filename)
# --- FileTracer methods
|
Rename hook, use generator and splitext instead of regex
|
py
|
diff --git a/alertaclient/config.py b/alertaclient/config.py
index <HASH>..<HASH> 100644
--- a/alertaclient/config.py
+++ b/alertaclient/config.py
@@ -14,6 +14,7 @@ default_config = {
'timezone': 'Europe/London',
'timeout': 5.0,
'sslverify': True,
+ 'use_local': [], # eg. set to ['endpoint'] to prevent server override
'output': 'simple',
'color': True,
'debug': False
@@ -52,4 +53,8 @@ class Config:
except requests.RequestException as e:
raise
- self.options = {**self.options, **remote_config}
+ # remove local exclusions from remote config
+ remote_config_only = {k: v for k, v in remote_config.items() if k not in self.options['use_local']}
+
+ # merge local config with remote, giving precedence to remote
+ self.options = {**self.options, **remote_config_only}
|
Allow local config exclusions to prevent remote override (#<I>)
|
py
|
diff --git a/mach9/config.py b/mach9/config.py
index <HASH>..<HASH> 100644
--- a/mach9/config.py
+++ b/mach9/config.py
@@ -18,6 +18,7 @@ _address_dict = {
LOGGING = {
'version': 1,
+ 'disable_existing_loggers': False,
'filters': {
'accessFilter': {
'()': DefaultFilter,
|
Add disable_existing_loggers (#<I>)
|
py
|
diff --git a/pyforms/Controls/ControlEmptyWidget.py b/pyforms/Controls/ControlEmptyWidget.py
index <HASH>..<HASH> 100755
--- a/pyforms/Controls/ControlEmptyWidget.py
+++ b/pyforms/Controls/ControlEmptyWidget.py
@@ -40,6 +40,7 @@ class ControlEmptyWidget(ControlBase, QtGui.QWidget):
def value(self, value):
ControlBase.value.fset(self, value)
if value is None:
+ self.clearLayout()
return
if isinstance(self._value, list):
@@ -70,6 +71,8 @@ class ControlEmptyWidget(ControlBase, QtGui.QWidget):
self.value.save(data['value'])
def load(self, data):
+ # TODO: remove print
+ print(data)
if 'value' in data:
self.value.load(data['value'])
|
clear content if value is none, which means, if a control has no window, nothing is displayed
|
py
|
diff --git a/oceansdb/etopo.py b/oceansdb/etopo.py
index <HASH>..<HASH> 100644
--- a/oceansdb/etopo.py
+++ b/oceansdb/etopo.py
@@ -67,22 +67,26 @@ class ETOPO_var_nc(object):
self.ncs.append(netCDF4.Dataset(s, 'r'))
self.load_dims(dims=['lat', 'lon'])
-
- def keys(self):
- return ['elevation']
+ self.set_keys()
def __getitem__(self, item):
# elevation
return self.data[item]
- def load_dims(self):
- dims = ['lat', 'lon']
+ def keys(self):
+ return self.KEYS
+
+ def load_dims(self, dims):
self.dims = {}
for d in dims:
self.dims[d] = self.ncs[0].variables[d][:]
for nc in self.ncs[1:]:
assert (self.dims[d] == nc.variables[d][:]).all()
+ def set_keys(self):
+ self.KEYS = ['elevation']
+
+
def subset(self, lat, lon, var):
dims = {}
|
Cosmetics to make etopo conform with WOA & CARS.
|
py
|
diff --git a/lark/parsers/earley_forest.py b/lark/parsers/earley_forest.py
index <HASH>..<HASH> 100644
--- a/lark/parsers/earley_forest.py
+++ b/lark/parsers/earley_forest.py
@@ -459,15 +459,20 @@ class PackedData():
that comes from the left child and the right child.
"""
+ class _NoData():
+ pass
+
+ NO_DATA = _NoData()
+
def __init__(self, node, data):
- self.left = None
- self.right = None
+ self.left = self.NO_DATA
+ self.right = self.NO_DATA
if data:
- if node.left:
+ if node.left is not None:
self.left = data[0]
- if len(data) > 1 and node.right:
+ if len(data) > 1:
self.right = data[1]
- elif node.right:
+ else:
self.right = data[0]
class ForestToParseTree(ForestTransformer):
@@ -558,12 +563,12 @@ class ForestToParseTree(ForestTransformer):
children = []
assert len(data) <= 2
data = PackedData(node, data)
- if data.left is not None:
+ if data.left is not PackedData.NO_DATA:
if node.left.is_intermediate and isinstance(data.left, list):
children += data.left
else:
children.append(data.left)
- if data.right is not None:
+ if data.right is not PackedData.NO_DATA:
children.append(data.right)
if node.parent.is_intermediate:
return children
|
Fix IndexError (issue #<I>)
|
py
|
diff --git a/quark/ipam.py b/quark/ipam.py
index <HASH>..<HASH> 100644
--- a/quark/ipam.py
+++ b/quark/ipam.py
@@ -980,13 +980,13 @@ class QuarkIpamBOTH(QuarkIpam):
reuse_after, version=None,
ip_address=None, segment_id=None,
subnets=None, **kwargs):
- both_versions = []
- for ver in (4, 6):
- address = super(QuarkIpamBOTH, self).attempt_to_reallocate_ip(
- context, net_id, port_id, reuse_after, ver, ip_address,
- segment_id, subnets=subnets, **kwargs)
- both_versions.extend(address)
- return both_versions
+ ip_address_version = 4 if not ip_address else ip_address.version
+ # NOTE(quade): We do not attempt to reallocate ipv6, so just return
+ if ip_address_version == 6:
+ return []
+ return super(QuarkIpamBOTH, self).attempt_to_reallocate_ip(
+ context, net_id, port_id, reuse_after, ip_address_version,
+ ip_address, segment_id, subnets=subnets, **kwargs)
def _choose_available_subnet(self, context, net_id, version=None,
segment_id=None, ip_address=None,
|
Optimized reallocation for BOTH strategy JIRA:NCP-<I> Reallocation algorithm would originally attempt to reallocate an ip as both an ipv6 and an ipv4. This change sets the algorithm to only attempt to reallocate a given ip based on the given ip version or to attempt to reallocate an ipv4 given the parameters.
|
py
|
diff --git a/seleniumbase/console_scripts/sb_install.py b/seleniumbase/console_scripts/sb_install.py
index <HASH>..<HASH> 100755
--- a/seleniumbase/console_scripts/sb_install.py
+++ b/seleniumbase/console_scripts/sb_install.py
@@ -42,7 +42,7 @@ urllib3.disable_warnings()
DRIVER_DIR = os.path.dirname(os.path.realpath(drivers.__file__))
LOCAL_PATH = "/usr/local/bin/" # On Mac and Linux systems
DEFAULT_CHROMEDRIVER_VERSION = "2.44" # (Specify "latest" to get the latest)
-DEFAULT_GECKODRIVER_VERSION = "v0.28.0"
+DEFAULT_GECKODRIVER_VERSION = "v0.29.0"
DEFAULT_EDGEDRIVER_VERSION = "87.0.664.66" # (Looks for LATEST_STABLE first)
DEFAULT_OPERADRIVER_VERSION = "v.84.0.4147.89"
|
Update the default version of geckodriver installed
|
py
|
diff --git a/xdot.py b/xdot.py
index <HASH>..<HASH> 100755
--- a/xdot.py
+++ b/xdot.py
@@ -676,10 +676,10 @@ class ZoomToAnimation(MoveToAnimation):
distance = math.hypot(self.source_x - self.target_x,
self.source_y - self.target_y)
rect = self.dot_widget.get_allocation()
- visible = min(rect.width, rect.height) * .9
- if distance > visible:
- desired_middle_zoom = visible / distance
- self.extra_zoom = min(0, 4 * (desired_middle_zoom - middle_zoom))
+ visible = min(rect.width, rect.height) * self.dot_widget.zoom_ratio
+ visible *= 0.9
+ desired_middle_zoom = visible / distance
+ self.extra_zoom = min(0, 4 * (desired_middle_zoom - middle_zoom))
def animate(self, t):
a, b, c = self.source_zoom, self.extra_zoom, self.target_zoom
|
Fix unit mismatch in comparison. distance was in device units, visible was in pixels, the if condition made no sense. Also, I've essentially replaced the nonfunctional if with a working min(), so remove the now-redundant check anyway. From: Marius Gedminas <<EMAIL>>
|
py
|
diff --git a/usb/backend/libusb0.py b/usb/backend/libusb0.py
index <HASH>..<HASH> 100644
--- a/usb/backend/libusb0.py
+++ b/usb/backend/libusb0.py
@@ -653,7 +653,7 @@ class _LibUSB(usb.backend.IBackend):
def __get_driver_name(self, dev_handle, intf):
if not hasattr(_lib, 'usb_get_driver_np'):
- raise NotImplementedError(self.is_kernel_driver_active.__name__)
+ raise NotImplementedError('usb_get_driver_np')
buf = usb.util.create_buffer(_USBFS_MAXDRIVERNAME + 1)
name, length = buf.buffer_info()
length *= buf.itemsize
|
libusb0: differentiate when usb_get_driver_np is missing Fixes: #<I> Closes: #<I>
|
py
|
diff --git a/salt/cloud/clouds/digital_ocean_v2.py b/salt/cloud/clouds/digital_ocean_v2.py
index <HASH>..<HASH> 100644
--- a/salt/cloud/clouds/digital_ocean_v2.py
+++ b/salt/cloud/clouds/digital_ocean_v2.py
@@ -111,7 +111,7 @@ def avail_images(call=None):
ret[image['id']][item] = str(image[item])
page += 1
- fetch = next in items['links']['pages']
+ fetch = 'next' in items['links']['pages']
return ret
|
Correctly detect additional pages in DigitalOcean API v2
|
py
|
diff --git a/sseclient.py b/sseclient.py
index <HASH>..<HASH> 100644
--- a/sseclient.py
+++ b/sseclient.py
@@ -14,7 +14,7 @@ import six
import requests
-__version__ = '0.0.24'
+__version__ = '0.0.25'
# Technically, we should support streams that mix line endings. This regex,
# however, assumes that a system will provide consistent line endings.
|
Updated version to <I>
|
py
|
diff --git a/slackchat/models/channel.py b/slackchat/models/channel.py
index <HASH>..<HASH> 100644
--- a/slackchat/models/channel.py
+++ b/slackchat/models/channel.py
@@ -6,7 +6,6 @@ from urllib.parse import urljoin
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.urls import reverse
-from django.utils import timezone
from django.utils.encoding import escape_uri_path
from django.utils.safestring import mark_safe
from markdown import markdown
@@ -22,7 +21,7 @@ class Channel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
api_id = models.SlugField(
- max_length=10,
+ max_length=15,
null=True,
blank=True,
editable=False,
@@ -30,7 +29,7 @@ class Channel(models.Model):
)
team_id = models.SlugField(
- max_length=10,
+ max_length=15,
null=True,
blank=True,
editable=False,
|
increase api_id and team_id limits
|
py
|
diff --git a/src/python/test/test_dxclient.py b/src/python/test/test_dxclient.py
index <HASH>..<HASH> 100755
--- a/src/python/test/test_dxclient.py
+++ b/src/python/test/test_dxclient.py
@@ -497,11 +497,6 @@ class TestDXBuildApp(DXTestCase):
with self.assertSubprocessFailure(stderr_regexp="make in target directory failed with exit code"):
run("dx build --no-parallel-build " + app_dir)
- def test_dxapp_checks(self):
- app_dir = self.write_app_directory("dxapp_checks", "{\"invalid_json\":}", code_filename="code.py")
- with self.assertSubprocessFailure(stderr_regexp="dxapp\\.json", exit_code=1):
- run("dx build " + app_dir)
-
def test_syntax_checks(self):
app_spec = {
"name": "syntax_checks",
|
Remove redundant test. This test was broken due to an exit code change and is now redundant with test_build_applet_with_malformed_dxapp_json.
|
py
|
diff --git a/datadog_checks_dev/tests/tooling/commands/test_create.py b/datadog_checks_dev/tests/tooling/commands/test_create.py
index <HASH>..<HASH> 100644
--- a/datadog_checks_dev/tests/tooling/commands/test_create.py
+++ b/datadog_checks_dev/tests/tooling/commands/test_create.py
@@ -24,7 +24,7 @@ def test_new_check_test():
run_command([sys.executable, '-m', 'pip', 'install', check_path], capture=True, check=True)
with chdir(check_path):
- ignored_env_vars = [TESTING_PLUGIN]
+ ignored_env_vars = [TESTING_PLUGIN, 'PYTEST_ADDOPTS']
ignored_env_vars.extend(ev for ev in os.environ if ev.startswith(E2E_PREFIX))
with EnvVars(ignore=ignored_env_vars):
|
Ignore flags to ddev test (#<I>)
|
py
|
diff --git a/gherkin/python/setup.py b/gherkin/python/setup.py
index <HASH>..<HASH> 100644
--- a/gherkin/python/setup.py
+++ b/gherkin/python/setup.py
@@ -1,7 +1,7 @@
# coding: utf-8
from distutils.core import setup
setup(name='gherkin-official',
- packages=['gherkin', 'gherkin.pickles'],
+ packages=['gherkin', 'gherkin.pickles', 'gherkin.stream'],
version='4.1.0',
description='Gherkin parser (official, by Cucumber team)',
author='Cucumber Ltd and Björn Rasmusson',
@@ -14,4 +14,5 @@ setup(name='gherkin-official',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
+ package_data={'gherkin': ['gherkin-languages.json']},
)
|
gherkin-python: Fix for #<I>
|
py
|
diff --git a/command/upload.py b/command/upload.py
index <HASH>..<HASH> 100644
--- a/command/upload.py
+++ b/command/upload.py
@@ -186,7 +186,7 @@ class upload(PyPIRCCommand):
http.putheader('Authorization', auth)
http.endheaders()
http.send(body)
- except socket.error as e:
+ except OSError as e:
self.announce(str(e), log.ERROR)
return
|
Issue #<I>: get rid of socket.error, replace with OSError
|
py
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -1,14 +1,12 @@
from setuptools import setup
-setup(name='greenwavecontrol',
- description='Greenwave Reality Smart Bulb Interface Library',
- version='0.1',
- url='https://github.com/dfiel/greenwavecontrol',
- author='David Fiel',
- author_email='greenwave@dfiel.com',
- license='MIT',
- classifiers=[
- 'License :: OSI Approved :: MIT Software License',
- 'Programming Language :: Python :: 3'
- ],
- packages=['greenwavecontrol']
+
+setup(
+ name='greenwavecontrol',
+ version='0.1',
+ packages=[''],
+ url='https://github.com/dfiel/greenwavecontrol',
+ license='MIT',
+ author='David Fiel',
+ author_email='github@dfiel.com',
+ description='Control of Greenwave Reality Lights'
)
|
Update Setup.py to work
|
py
|
diff --git a/src/richenum/enums.py b/src/richenum/enums.py
index <HASH>..<HASH> 100644
--- a/src/richenum/enums.py
+++ b/src/richenum/enums.py
@@ -2,6 +2,8 @@ import collections
import copy
import new
+from operator import itemgetter
+
class EnumConstructionException(Exception):
"""
@@ -28,12 +30,16 @@ def enum(**enums):
>>> MY_ENUM.BAR
2
"""
+ # Enum values must be hashable to support reverse lookup.
+ if not all(isinstance(val, collections.Hashable) for val in enums.itervalues()):
+ raise EnumConstructionException('All enum values must be hashable.')
+
# NB: cheating here by just maintaining a copy of the original dict for iteration because iterators are hard
# it must be a deepcopy because new.classobj() modifies the original
en = copy.deepcopy(enums)
e = new.classobj('Enum', (), enums)
e._dict = en
- e.choices = [(v, k) for k, v in en.iteritems()]
+ e.choices = [(v, k) for k, v in sorted(en.iteritems(), key=itemgetter(1))]
e.get_id_by_label = e._dict.get
e.get_label_by_id = dict([(v, k) for (k, v) in e._dict.items()]).get
|
Small fixups for simple enums For testability, return choices in a known order. Also, check that all enum values are hashable (otherwise enum blows up when trying to do a reverse lookup).
|
py
|
diff --git a/exit_wrapper.py b/exit_wrapper.py
index <HASH>..<HASH> 100644
--- a/exit_wrapper.py
+++ b/exit_wrapper.py
@@ -87,8 +87,11 @@ class BBLStack(object):
self._stack_dict[addr] = []
def ret(self, addr):
- # Return from a function. Remove the corresponding stack
- del self._stack_dict[addr]
+ if addr in self._stack_dict:
+ # Return from a function. Remove the corresponding stack
+ del self._stack_dict[addr]
+ else:
+ l.warning("Attempting to ret from a non-existing stack frame %s." % addr)
def push(self, func_addr, bbl):
if func_addr not in self._stack_dict:
|
A bug fixing to make loop detection more robust.
|
py
|
diff --git a/quantrisk/positions.py b/quantrisk/positions.py
index <HASH>..<HASH> 100644
--- a/quantrisk/positions.py
+++ b/quantrisk/positions.py
@@ -52,7 +52,7 @@ def get_portfolio_alloc(df_pos_vals):
return df_pos_alloc
-def get_long_short_pos(df_pos):
+def get_long_short_pos(df_pos, gross_lev=1.):
df_pos_wo_cash = df_pos.drop('cash', axis='columns')
df_long = df_pos_wo_cash.apply(lambda x: x[x > 0].sum(), axis='columns')
df_short = -df_pos_wo_cash.apply(lambda x: x[x < 0].sum(), axis='columns')
@@ -61,6 +61,12 @@ def get_long_short_pos(df_pos):
df_long_short = pd.DataFrame({'long': df_long,
'short': df_short,
'cash': df_cash})
+ # Renormalize
+ df_long_short /= df_long_short.sum(axis='columns')
+
+ # Renormalize to leverage
+ df_long_short *= gross_lev
+
return df_long_short
|
BUG Long/short/cash positions did not sum to 1. This commit fixes this issue by renormalizing. Also, and addition kwarg is added to allow rescaling to leverage as requested in #<I>.
|
py
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -72,6 +72,7 @@ setup(
'admin = ceph_deploy.admin:make',
'pkg = ceph_deploy.pkg:make',
'calamari = ceph_deploy.calamari:make',
+ 'rgw = ceph_deploy.rgw:make',
],
},
|
Expose rgw CLI commands
|
py
|
diff --git a/tests/core_test.py b/tests/core_test.py
index <HASH>..<HASH> 100644
--- a/tests/core_test.py
+++ b/tests/core_test.py
@@ -194,7 +194,7 @@ class CoreTest(jtu.JaxTestCase):
@parameterized.parameters(test_specs)
def test_vjp(self, f, args):
jtu.check_vjp(f, partial(vjp, f), args,
- rtol={onp.float32: 7e-2, onp.float64: 1e-5},
+ rtol={onp.float32: 3e-1, onp.float64: 1e-5},
atol={onp.float32: 1e-2, onp.float64: 1e-5})
def test_jvp_closure(self):
|
Relax test tolerance for core_test.py test_vjp to fix flakiness.
|
py
|
diff --git a/werkzeug/contrib/cache.py b/werkzeug/contrib/cache.py
index <HASH>..<HASH> 100644
--- a/werkzeug/contrib/cache.py
+++ b/werkzeug/contrib/cache.py
@@ -58,6 +58,7 @@
"""
import os
import re
+import errno
import tempfile
from hashlib import md5
from time import time
@@ -590,8 +591,12 @@ class FileSystemCache(BaseCache):
self._path = cache_dir
self._threshold = threshold
self._mode = mode
- if not os.path.exists(self._path):
+
+ try:
os.makedirs(self._path)
+ except OSError as ex:
+ if ex.errno != errno.EEXIST:
+ raise
def _list_dir(self):
"""return a list of (fully qualified) cache filenames
|
add try-except for concurrent FileSystemCache initialization, fix #<I>
|
py
|
diff --git a/testsuite.py b/testsuite.py
index <HASH>..<HASH> 100644
--- a/testsuite.py
+++ b/testsuite.py
@@ -781,15 +781,14 @@ g
# Test recursive 'source' detection
- got_syntax_exception = False
try:
Kconfig("Kconfiglib/tests/Krecursive1")
except KconfigSyntaxError:
- got_syntax_exception = True
-
- verify(got_syntax_exception,
- "recursive 'source' did not raise KconfigSyntaxError")
-
+ pass
+ except:
+ fail("recursive 'source' raised wrong exception")
+ else:
+ fail("recursive 'source' did not raise exception")
print("Testing visibility")
|
Improve recursive 'source' test Check for incorrect exceptions instead of propagating them, and get rid of the flag.
|
py
|
diff --git a/meshio/ply/_ply.py b/meshio/ply/_ply.py
index <HASH>..<HASH> 100644
--- a/meshio/ply/_ply.py
+++ b/meshio/ply/_ply.py
@@ -388,7 +388,9 @@ def write(filename, mesh, binary=True): # noqa: C901
if key not in cells:
continue
dat = cells[key]
- out = numpy.column_stack([numpy.full(dat.shape[0], dat.shape[1]), dat])
+ out = numpy.column_stack(
+ [numpy.full(dat.shape[0], dat.shape[1], dtype=dat.dtype), dat]
+ )
# savetxt is slower
# numpy.savetxt(fh, out, "%d %d %d %d")
fmt = " ".join(["{}"] * out.shape[1])
|
fix for PLY ascii writes
|
py
|
diff --git a/troposphere/ecs.py b/troposphere/ecs.py
index <HASH>..<HASH> 100644
--- a/troposphere/ecs.py
+++ b/troposphere/ecs.py
@@ -5,7 +5,9 @@ from .validators import boolean, network_port, positive_integer
class Cluster(AWSObject):
resource_type = "AWS::ECS::Cluster"
- props = {}
+ props = {
+ 'ClusterName': (basestring, False),
+ }
class LoadBalancer(AWSProperty):
@@ -137,6 +139,7 @@ class TaskDefinition(AWSObject):
props = {
'ContainerDefinitions': ([ContainerDefinition], True),
- 'Volumes': ([Volume], False),
+ 'Family': (basestring, False),
'TaskRoleArn': (basestring, False),
+ 'Volumes': ([Volume], False),
}
|
Add new properties to ECS - Add Clustername property to Cluster - Add Family property to TaskDefinition
|
py
|
diff --git a/trezor_agent/server.py b/trezor_agent/server.py
index <HASH>..<HASH> 100644
--- a/trezor_agent/server.py
+++ b/trezor_agent/server.py
@@ -89,7 +89,7 @@ def serve(public_keys, signer, sock_path=None):
def run_process(command, environ, use_shell=False):
- log.debug('running %r with %r', command, environ)
+ log.info('running %r with %r', command, environ)
env = dict(os.environ)
env.update(environ)
try:
|
server: log command with INFO level
|
py
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -11,7 +11,7 @@ setup(
'versiontools >= 1.4',
],
install_requires = [
- 'phonenumbers',
+ 'phonenumbers >= 5.9b1',
],
long_description=open('README.rst').read(),
author='Stefan Foulis',
|
Defining version for pip <I>+ PIP <I>+ treats version numbers which aren’t compliant with PEP<I> as pre-releases, and won’t use them… `phonenumbers` uses such version numbers. Setting a similarly non-compliant version gets around this (feel free to propose an alternative version to compare with).
|
py
|
diff --git a/source/rafcon/mvc/mygaphas/items/ports.py b/source/rafcon/mvc/mygaphas/items/ports.py
index <HASH>..<HASH> 100644
--- a/source/rafcon/mvc/mygaphas/items/ports.py
+++ b/source/rafcon/mvc/mygaphas/items/ports.py
@@ -479,7 +479,17 @@ class PortView(Model):
# self._port_side_size = 5.
-class IncomeView(PortView):
+class LogicPortView(PortView):
+ """Base class for ports connecting transitions
+
+ A logic port is either a income our an outcome.
+ """
+
+ def draw(self, context, state):
+ raise NotImplementedError
+
+
+class IncomeView(LogicPortView):
def __init__(self, parent, port_side_size):
super(IncomeView, self).__init__(in_port=True, port_side_size=port_side_size, parent=parent,
@@ -489,7 +499,7 @@ class IncomeView(PortView):
self.draw_port(context, constants.LABEL_COLOR, state.transparent)
-class OutcomeView(PortView):
+class OutcomeView(LogicPortView):
def __init__(self, outcome_m, parent, port_side_size):
super(OutcomeView, self).__init__(in_port=False, port_side_size=port_side_size, name=outcome_m.outcome.name,
|
Derive IncomeView and OutcomeView from LogicalPortView
|
py
|
diff --git a/jax/tools/jax_to_hlo.py b/jax/tools/jax_to_hlo.py
index <HASH>..<HASH> 100644
--- a/jax/tools/jax_to_hlo.py
+++ b/jax/tools/jax_to_hlo.py
@@ -61,7 +61,7 @@ This generates two BUILD targets:
//your/thing:prog_hlo.txt
You can then depend on one of these as a data dependency and invoke it using
-XLA's public C++ APIs.
+XLA's public C++ APIs (See tensorflow/compiler/xla/service/hlo_runner.h).
Note that XLA's backwards-compatibility guarantees for saved HLO are currently
(2019-06-13) best-effort. It will mostly work, but it will occasionally break,
|
Add link to XLA header in jax_to_hlo
|
py
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -4,7 +4,7 @@ setup(
name='NoseDjango',
version='0.6',
author='Victor Ng',
- author_email = 'victor@monkeybean.ca',
+ author_email = 'crankycoder@gmail.com',
description = 'nose plugin for easy testing of django projects ' \
'and apps. Sets up a test database (or schema) and installs apps ' \
'from test settings file before tests are run, and tears the test ' \
|
oops. wrong email address in setup.py
|
py
|
diff --git a/jax/util.py b/jax/util.py
index <HASH>..<HASH> 100644
--- a/jax/util.py
+++ b/jax/util.py
@@ -107,6 +107,7 @@ def curry(f):
def toposort(end_nodes):
if not end_nodes: return []
+ end_nodes = _remove_duplicates(end_nodes)
child_counts = {}
stack = list(end_nodes)
@@ -141,6 +142,15 @@ def check_toposort(nodes):
assert all(id(parent) in visited for parent in node.parents)
visited.add(id(node))
+def _remove_duplicates(node_list):
+ seen = set()
+ out = []
+ for n in node_list:
+ if id(n) not in seen:
+ seen.add(id(n))
+ out.append(n)
+ return out
+
def split_merge(predicate, xs):
sides = list(map(predicate, xs))
lhs = [x for x, s in zip(xs, sides) if s]
|
Rm duplicates from end_nodes in toposort
|
py
|
diff --git a/aiohttp_apispec/decorators.py b/aiohttp_apispec/decorators.py
index <HASH>..<HASH> 100644
--- a/aiohttp_apispec/decorators.py
+++ b/aiohttp_apispec/decorators.py
@@ -25,7 +25,8 @@ def docs(**kwargs):
"""
def wrapper(func):
- kwargs["produces"] = ["application/json"]
+ if not kwargs.get("produces"):
+ kwargs["produces"] = ["application/json"]
if not hasattr(func, "__apispec__"):
func.__apispec__ = {"parameters": [], "responses": {}}
extra_parameters = kwargs.pop("parameters", [])
|
Allow to set content-type using docs decorator Currently, produces is forced to "application/json", which is clearly a reasonable default value. If the user sets it, pass it as-is to apispec.
|
py
|
diff --git a/pyemu/mat/mat_handler.py b/pyemu/mat/mat_handler.py
index <HASH>..<HASH> 100644
--- a/pyemu/mat/mat_handler.py
+++ b/pyemu/mat/mat_handler.py
@@ -1701,7 +1701,10 @@ class Matrix(object):
#print("new binary format detected...")
data = np.fromfile(f, Matrix.coo_rec_dt, icount)
-
+ if data['i'].min() < 0:
+ raise Exception("Matrix.from_binary(): 'i' index values less than 0")
+ if data['j'].min() < 0:
+ raise Exception("Matrix.from_binary(): 'j' index values less than 0")
x = np.zeros((nrow, ncol))
x[data['i'], data['j']] = data["dtemp"]
data = x
|
sanity check for postive indices in from_binary()
|
py
|
diff --git a/flask_github.py b/flask_github.py
index <HASH>..<HASH> 100644
--- a/flask_github.py
+++ b/flask_github.py
@@ -173,7 +173,17 @@ class GitHub(object):
raise GitHubError(response)
if response.headers['Content-Type'].startswith('application/json'):
- return response.json()
+ result = response.json()
+ while response.links.get('next'):
+ response = self.session.request(
+ method, response.links['next']['url'], **kwargs)
+ if not status_code.startswith('2'):
+ raise GitHubError(response)
+ if response.headers['Content-Type'].startswith('application/json'):
+ result += response.json()
+ else:
+ raise GitHubError(response)
+ return result
else:
return response
|
manage pagniation when the response is splitted on several pages
|
py
|
diff --git a/bokeh/tests/test_properties.py b/bokeh/tests/test_properties.py
index <HASH>..<HASH> 100644
--- a/bokeh/tests/test_properties.py
+++ b/bokeh/tests/test_properties.py
@@ -414,6 +414,14 @@ class TestProperties(unittest.TestCase):
self.assertFalse(prop.is_valid(np.int32(1)))
self.assertFalse(prop.is_valid(np.int64(0)))
self.assertFalse(prop.is_valid(np.int64(1)))
+ self.assertFalse(prop.is_valid(np.uint8(0)))
+ self.assertFalse(prop.is_valid(np.uint8(1)))
+ self.assertFalse(prop.is_valid(np.uint16(0)))
+ self.assertFalse(prop.is_valid(np.uint16(1)))
+ self.assertFalse(prop.is_valid(np.uint32(0)))
+ self.assertFalse(prop.is_valid(np.uint32(1)))
+ self.assertFalse(prop.is_valid(np.uint64(0)))
+ self.assertFalse(prop.is_valid(np.uint64(1)))
self.assertFalse(prop.is_valid(np.float16(0)))
self.assertFalse(prop.is_valid(np.float16(1)))
self.assertFalse(prop.is_valid(np.float32(0)))
|
bokeh/tests/test_properties.py: Add some `numpy` based tests for `Bool` with unsigned integers.
|
py
|
diff --git a/scratch.py b/scratch.py
index <HASH>..<HASH> 100755
--- a/scratch.py
+++ b/scratch.py
@@ -70,17 +70,18 @@ class Scratch:
raise TypeError('Expected a dict')
message = 'sensor-update'
for key in data.keys():
- message = message+' "'+key+'" '+str(data[key])
+ message = message+' "'+str(key)+'" '+str(data[key])
self.send(message)
def broadcast(self, data):
"""Takes a list of message strings and writes a broadcast message to scratch"""
- if not isinstance(data, list):
- raise TypeError('Expected a list')
message = 'broadcast'
- for mess in data:
- message = message+' "'+mess+'"'
- self.send(message)
+ if isinstance(data, list):
+ for mess in data:
+ message = message+' "'+str(mess)+'"'
+ self.send(message)
+ else:
+ self.send(message+' "'+str(data)+'"')
def parse_message(self, message):
#TODO: parse sensorupdates with quotes in sensor names and values
|
removed type requirement for input to broadcast(), converted messages to strings before sending to Scratch
|
py
|
diff --git a/pydsl/Grammar/Symbol.py b/pydsl/Grammar/Symbol.py
index <HASH>..<HASH> 100644
--- a/pydsl/Grammar/Symbol.py
+++ b/pydsl/Grammar/Symbol.py
@@ -114,15 +114,6 @@ class StringTerminalSymbol(TerminalSymbol):
return "<StringTS: '" + self.definition + "'>"
-class CharTerminalSymbol(StringTerminalSymbol):
- def __init__(self, char):
- if len(char) != 1:
- raise TypeError
- StringTerminalSymbol.__init__(self, char)
-
- def __str__(self):
- return "<CharTS: '" + self.definition + "'>"
-
class WordTerminalSymbol(TerminalSymbol):#boundariesrules: priority, [max,min,fixedsize]
#If token is another grammar Word, it stores its semantic info
def __init__(self, name, definitionrequirementsdic, boundariesrules):
|
deleted CharTerminalSymbol (II)
|
py
|
diff --git a/message.py b/message.py
index <HASH>..<HASH> 100644
--- a/message.py
+++ b/message.py
@@ -22,12 +22,12 @@ class Message(object):
class TextMessage(Message):
def __init__(self, payload):
- super(TextMessage, self).__init__(OPCODE_TEXT, payload)
+ super(TextMessage, self).__init__(OPCODE_TEXT, payload.encode('utf-8'))
class BinaryMessage(Message):
def __init__(self, payload):
- super(TextMessage, self).__init__(OPCODE_BINARY, payload)
+ super(BinaryMessage, self).__init__(OPCODE_BINARY, payload)
OPCODE_CLASS_MAP = {
|
Text messages payloads are not UTF-8 encoded automatically
|
py
|
diff --git a/cleverhans/attacks.py b/cleverhans/attacks.py
index <HASH>..<HASH> 100644
--- a/cleverhans/attacks.py
+++ b/cleverhans/attacks.py
@@ -122,8 +122,14 @@ class Attack(object):
for name, value in feedable.items():
given_type = value.dtype
if isinstance(value, np.ndarray):
- new_shape = [None] + list(value.shape[1:])
- new_kwargs[name] = tf.placeholder(given_type, new_shape, name=name)
+ if value.ndim == 0:
+ # This is pretty clearly not a batch of data
+ new_kwargs[name] = tf.placeholder(given_type, shape=[], name=name)
+ else:
+ # Assume that this is a batch of data, make the first axis variable
+ # in size
+ new_shape = [None] + list(value.shape[1:])
+ new_kwargs[name] = tf.placeholder(given_type, new_shape, name=name)
elif isinstance(value, utils.known_number_types):
new_kwargs[name] = tf.placeholder(given_type, shape=[], name=name)
else:
|
This PR closes #<I> (structural problems in SPSA)
|
py
|
diff --git a/testapp/testapp/testmain/tests/test_webservices.py b/testapp/testapp/testmain/tests/test_webservices.py
index <HASH>..<HASH> 100644
--- a/testapp/testapp/testmain/tests/test_webservices.py
+++ b/testapp/testapp/testmain/tests/test_webservices.py
@@ -75,9 +75,10 @@ class AuthTicketTest(TestCase):
taxpayer.create_ticket('wsfe')
- with self.assertRaisesMessage(
+ with self.assertRaisesRegex(
exceptions.AfipException,
- 'ValidacionDeToken: No apareció CUIT en lista de relaciones:',
+ # Note: AFIP apparently edited this message and added a typo:
+ 'ValidacionDeToken: No apareci[oó] CUIT en lista de relaciones:',
):
models.populate_all()
|
AFIP added a typo to an error message Integration tests was failing due to a message that was altered to now contain a typo (!?)
|
py
|
diff --git a/salt/modules/file.py b/salt/modules/file.py
index <HASH>..<HASH> 100644
--- a/salt/modules/file.py
+++ b/salt/modules/file.py
@@ -138,7 +138,7 @@ def gid_to_group(gid):
try:
return grp.getgrgid(gid).gr_name
- except KeyError:
+ except (KeyError, NameError) as e:
return ''
@@ -204,7 +204,7 @@ def uid_to_user(uid):
'''
try:
return pwd.getpwuid(uid).pw_name
- except KeyError:
+ except (KeyError, NameError) as e:
return ''
|
catch NameError because of Windows
|
py
|
diff --git a/src/bezier/_implicitization.py b/src/bezier/_implicitization.py
index <HASH>..<HASH> 100644
--- a/src/bezier/_implicitization.py
+++ b/src/bezier/_implicitization.py
@@ -846,7 +846,7 @@ def bezier_roots(coeffs):
def lu_companion(top_row, value):
- r"""Compute an LU-factored :math:`C - t I` and it's 1-norm.
+ r"""Compute an LU-factored :math:`C - t I` and its 1-norm.
.. note::
|
Using possessive form of its in docstring.
|
py
|
diff --git a/build_libtcod.py b/build_libtcod.py
index <HASH>..<HASH> 100644
--- a/build_libtcod.py
+++ b/build_libtcod.py
@@ -95,10 +95,10 @@ define_macros = []
sources += walk_sources("tcod/")
sources += walk_sources("tdl/")
-sources += walk_sources("libtcod/src/libtcod")
+sources += ["libtcod/src/libtcod_c.c"]
+sources += ["libtcod/src/libtcod.cpp"]
sources += ["libtcod/src/vendor/glad.c"]
sources += ["libtcod/src/vendor/lodepng.cpp"]
-sources += ["libtcod/src/vendor/stb.c"]
sources += ["libtcod/src/vendor/utf8proc/utf8proc.c"]
sources += glob.glob("libtcod/src/vendor/zlib/*.c")
|
Switch builder back to using libtcod's static sources.
|
py
|
diff --git a/hererocks.py b/hererocks.py
index <HASH>..<HASH> 100755
--- a/hererocks.py
+++ b/hererocks.py
@@ -148,7 +148,7 @@ def fetch(versions, version, temp_dir):
print("Using {} from {}".format(capitalize(name), version))
result_dir = os.path.join(temp_dir, name)
- shutil.copytree(version, result_dir)
+ shutil.copytree(version, result_dir, ignore=lambda _, __: {".git"})
os.chdir(result_dir)
return result_dir
|
Do not copy .git subdirectory when installing from local sources
|
py
|
diff --git a/jupyter_server_proxy/handlers.py b/jupyter_server_proxy/handlers.py
index <HASH>..<HASH> 100644
--- a/jupyter_server_proxy/handlers.py
+++ b/jupyter_server_proxy/handlers.py
@@ -56,11 +56,16 @@ class RewritableResponse(HasTraits):
@observe('code')
def _observe_code(self, change):
- # Automatically update reason if code changes and previous reason was default.
- old_default_reason = httputil.responses.get(change['old'], 'Unknown')
- new_default_reason = httputil.responses.get(change['new'], 'Unknown')
- if self.reason == old_default_reason:
- self.reason = new_default_reason
+ # HTTP status codes are mapped to short descriptions in the
+ # httputil.responses dictionary, 200 maps to "OK", 403 maps to
+ # "Forbidden" etc.
+ #
+ # If code is updated and it previously had a reason matching its short
+ # description, we update reason to match the new code's short
+ # description.
+ #
+ if self.reason == httputil.responses.get(change['old'], 'Unknown'):
+ self.reason = httputil.responses.get(change['new'], 'Unknown')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
|
Improve comment on RewritableResponse observer
|
py
|
diff --git a/mot/model_building/parameter_functions/transformations.py b/mot/model_building/parameter_functions/transformations.py
index <HASH>..<HASH> 100644
--- a/mot/model_building/parameter_functions/transformations.py
+++ b/mot/model_building/parameter_functions/transformations.py
@@ -108,6 +108,19 @@ class IdentityTransform(AbstractTransformation):
return FormatAssignmentConstructor('{parameter_variable}')
+class PositiveTransform(AbstractTransformation):
+
+ def __init__(self, *args, **kwargs):
+ """The identity transform does no transformation and returns the input given."""
+ super(PositiveTransform, self).__init__(*args, **kwargs)
+
+ def get_cl_encode(self):
+ return FormatAssignmentConstructor('max({parameter_variable}, (mot_float_type)0)')
+
+ def get_cl_decode(self):
+ return FormatAssignmentConstructor('max({parameter_variable}, (mot_float_type)0)')
+
+
class ClampTransform(AbstractTransformation):
"""The clamp transformation limits the parameter between its lower and upper bound using the clamp function."""
|
Adds a positive constraint to the library
|
py
|
diff --git a/atmos/equations.py b/atmos/equations.py
index <HASH>..<HASH> 100644
--- a/atmos/equations.py
+++ b/atmos/equations.py
@@ -894,7 +894,7 @@ Neglects density effects of liquid and solid water""")
@assumes()
@overridden_by_assumptions('low water vapor', 'Tv equals T')
def T_from_Tv_rv(Tv, rv):
- return ne.evaluate('T/(1+rv/0.622)*(1+rv)')
+ return ne.evaluate('Tv/(1+rv/0.622)*(1+rv)')
@autodoc(
@@ -914,7 +914,7 @@ Neglects density effects of liquid and solid water""")
@assumes('low water vapor')
@overridden_by_assumptions('Tv equals T')
def T_from_Tv_rv_lwv(Tv, rv):
- return ne.evaluate('T/(1+(1/0.622-1)*rv)')
+ return ne.evaluate('Tv/(1+(1/0.622-1)*rv)')
@autodoc(equation=r'T_v = T',
|
corrected typo in T_from_Tv* equations
|
py
|
diff --git a/src/animanager/anime/db.py b/src/animanager/anime/db.py
index <HASH>..<HASH> 100644
--- a/src/animanager/anime/db.py
+++ b/src/animanager/anime/db.py
@@ -39,6 +39,7 @@ class AnimeDB:
self.dbfile = path
self.connect()
self._episode_types = None
+ self.cache = self.CacheDB()
def connect(self):
self.cnx = sqlite3.connect(self.dbfile)
@@ -54,6 +55,11 @@ class AnimeDB:
def close(self):
self.cnx.close()
+ class CacheDB:
+
+ def __init__(self):
+ self.cnx = sqlite3.connect(':memory:')
+
@property
def episode_types(self):
if self._episode_types:
|
Add CacheDB This will be needed.
|
py
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -25,7 +25,7 @@ from setuptools import setup
setup(
name='column',
version='0.2.0',
- url='https://www.vmware.com/products/openstack.html',
+ url='https://github.com/vmware/column',
license='BSD-2',
author='VMware',
author_email='openstack@vmware.com',
|
Update website URL to point to Github
|
py
|
diff --git a/estnltk/resolve_layer_dag.py b/estnltk/resolve_layer_dag.py
index <HASH>..<HASH> 100644
--- a/estnltk/resolve_layer_dag.py
+++ b/estnltk/resolve_layer_dag.py
@@ -76,13 +76,18 @@ from .taggers import ParagraphTokenizer
from .taggers.morph.morf import VabamorfTagger
from .taggers import MorphExtendedTagger
+# Load default configuration for morph analyser
+from .taggers.morph.morf_common import DEFAULT_PARAM_DISAMBIGUATE, DEFAULT_PARAM_GUESS
+from .taggers.morph.morf_common import DEFAULT_PARAM_PROPERNAME, DEFAULT_PARAM_PHONETIC
+from .taggers.morph.morf_common import DEFAULT_PARAM_COMPOUND
+
def make_resolver(
- disambiguate=True,
- guess=True,
- propername=True,
- phonetic=False,
- compound=True):
+ disambiguate=DEFAULT_PARAM_DISAMBIGUATE,
+ guess =DEFAULT_PARAM_GUESS,
+ propername =DEFAULT_PARAM_PROPERNAME,
+ phonetic =DEFAULT_PARAM_PHONETIC,
+ compound =DEFAULT_PARAM_COMPOUND):
vabamorf_tagger = VabamorfTagger(
disambiguate=disambiguate,
guess=guess,
|
Updated make_resolver: morph analysis default parameters are now taken from morf_common.py
|
py
|
diff --git a/oauth2client/client.py b/oauth2client/client.py
index <HASH>..<HASH> 100644
--- a/oauth2client/client.py
+++ b/oauth2client/client.py
@@ -2092,7 +2092,8 @@ class OAuth2WebServerFlow(Flow):
@_helpers.positional(2)
def flow_from_clientsecrets(filename, scope, redirect_uri=None,
message=None, cache=None, login_hint=None,
- device_uri=None, pkce=None, code_verifier=None):
+ device_uri=None, pkce=None, code_verifier=None,
+ prompt=None):
"""Create a Flow from a clientsecrets file.
Will create the right kind of Flow based on the contents of the
@@ -2141,7 +2142,13 @@ def flow_from_clientsecrets(filename, scope, redirect_uri=None,
'login_hint': login_hint,
}
revoke_uri = client_info.get('revoke_uri')
- optional = ('revoke_uri', 'device_uri', 'pkce', 'code_verifier')
+ optional = (
+ 'revoke_uri',
+ 'device_uri',
+ 'pkce',
+ 'code_verifier',
+ 'prompt'
+ )
for param in optional:
if locals()[param] is not None:
constructor_kwargs[param] = locals()[param]
|
Pass prompt='consent' from flow_from_clientsecrets (#<I>)
|
py
|
diff --git a/airflow/providers/http/hooks/http.py b/airflow/providers/http/hooks/http.py
index <HASH>..<HASH> 100644
--- a/airflow/providers/http/hooks/http.py
+++ b/airflow/providers/http/hooks/http.py
@@ -113,10 +113,7 @@ class HttpHook(BaseHook):
session = self.get_conn(headers)
- if self.base_url and not self.base_url.endswith('/') and endpoint and not endpoint.startswith('/'):
- url = self.base_url + '/' + endpoint
- else:
- url = (self.base_url or '') + (endpoint or '')
+ url = self.url_from_endpoint(endpoint)
if self.method == 'GET':
# GET uses params
@@ -215,6 +212,12 @@ class HttpHook(BaseHook):
return self._retry_obj(self.run, *args, **kwargs)
+ def url_from_endpoint(self, endpoint: Optional[str]) -> str:
+ """Combine base url with endpoint"""
+ if self.base_url and not self.base_url.endswith('/') and endpoint and not endpoint.startswith('/'):
+ return self.base_url + '/' + endpoint
+ return (self.base_url or '') + (endpoint or '')
+
def test_connection(self):
"""Test HTTP Connection"""
try:
|
Split out confusing path combination logic to separate method (#<I>) * Split out confusing path combination logic to separate method * Fix argument type
|
py
|
diff --git a/artifactory.py b/artifactory.py
index <HASH>..<HASH> 100755
--- a/artifactory.py
+++ b/artifactory.py
@@ -34,7 +34,10 @@ import re
import json
import dateutil.parser
import hashlib
-import requests.packages.urllib3 as urllib3
+try:
+ import requests.packages.urllib3 as urllib3
+except ImportError:
+ import urllib3
try:
import configparser
except ImportError:
|
make python <I>.x compatible requests on python >=<I> does not install urllib3 because it already exists in that version of python. This is the suggested workaround
|
py
|
diff --git a/dynaphopy/analysis/thermal_properties.py b/dynaphopy/analysis/thermal_properties.py
index <HASH>..<HASH> 100644
--- a/dynaphopy/analysis/thermal_properties.py
+++ b/dynaphopy/analysis/thermal_properties.py
@@ -9,7 +9,7 @@ h_bar = 6.626070040e-22 # J * ps
warnings.simplefilter("ignore")
-def get_dos(temp, frequency, power_spectrum, n_size, bose_einstein_statistics=False):
+def get_dos(temp, frequency, power_spectrum, n_size, bose_einstein_statistics=True):
conversion_factor = 1.60217662e-19 # eV/J
@@ -45,7 +45,7 @@ def get_free_energy(temperature, frequency, dos):
free_energy = np.nan_to_num([dos[i] * k_b * temperature * np.log(2 * np.sinh(h_bar * freq / (2 * k_b * temperature)))
for i, freq in enumerate(frequency)])
- free_energy[0] = 0
+# free_energy[0] = 0
free_energy = np.trapz(free_energy, frequency) * N_a / 1000 # KJ/K/mol
return free_energy
|
added normalization option to dos calculation
|
py
|
diff --git a/test/augmenters/test_arithmetic.py b/test/augmenters/test_arithmetic.py
index <HASH>..<HASH> 100644
--- a/test/augmenters/test_arithmetic.py
+++ b/test/augmenters/test_arithmetic.py
@@ -3492,6 +3492,22 @@ class Test_solarize(unittest.TestCase):
assert observed.dtype.name == "uint8"
assert np.array_equal(observed, expected)
+ def test_compare_with_pil(self):
+ import PIL.Image
+ import PIL.ImageOps
+
+ def _solarize_pil(image, threshold):
+ img = PIL.Image.fromarray(image)
+ return np.asarray(PIL.ImageOps.solarize(img, threshold))
+
+ image = np.mod(np.arange(20*20*3), 255).astype(np.uint8)\
+ .reshape((20, 20, 3))
+
+ for threshold in np.arange(256):
+ image_pil = _solarize_pil(image, threshold)
+ image_iaa = iaa.solarize(image, threshold)
+ assert np.array_equal(image_pil, image_iaa)
+
class Test_solarize_(unittest.TestCase):
@mock.patch("imgaug.augmenters.arithmetic.invert_")
|
Add test to compare solarize() with PIL
|
py
|
diff --git a/yfinance/base.py b/yfinance/base.py
index <HASH>..<HASH> 100644
--- a/yfinance/base.py
+++ b/yfinance/base.py
@@ -46,7 +46,7 @@ class TickerBase():
self.ticker = ticker.upper()
self.session = session or _requests
self._history = None
- self._base_url = 'https://query1.finance.yahoo.com'
+ self._base_url = 'https://query2.finance.yahoo.com'
self._scrape_url = 'https://finance.yahoo.com/quote'
self._fundamentals = False
|
Switched to using query2.finance.yahoo.com, which used HTTP/<I>
|
py
|
diff --git a/src/data_structures.py b/src/data_structures.py
index <HASH>..<HASH> 100644
--- a/src/data_structures.py
+++ b/src/data_structures.py
@@ -7,7 +7,7 @@ class Instance:
def __init__(self, features, target = None ):
self.features = np.array(features)
- if target:
+ if target != None:
self.targets = np.array(target)
else:
self.targets = None
|
Fix: check whether the targets are equal to None
|
py
|
diff --git a/photutils/aperture/mask.py b/photutils/aperture/mask.py
index <HASH>..<HASH> 100644
--- a/photutils/aperture/mask.py
+++ b/photutils/aperture/mask.py
@@ -154,9 +154,17 @@ class ApertureMask(object):
"""
data = np.asanyarray(data)
- cutout = data[self.bbox.slices]
- if cutout.shape != self.shape:
+ partial_overlap = False
+ if self.bbox.ixmin < 0 or self.bbox.iymin < 0:
+ partial_overlap = True
+
+ if not partial_overlap:
+ # try this for speed -- the result may still be a partial
+ # overlap, in which case the next block will be triggered
+ cutout = data[self.bbox.slices]
+
+ if partial_overlap or (cutout.shape != self.shape):
slices_large, slices_small = self._overlap_slices(data.shape)
if slices_small is None:
|
Fix aperture mask cutout to handle corner case
|
py
|
diff --git a/examples/HHTut/HHTut.py b/examples/HHTut/HHTut.py
index <HASH>..<HASH> 100644
--- a/examples/HHTut/HHTut.py
+++ b/examples/HHTut/HHTut.py
@@ -56,10 +56,10 @@ netParams['connParams'] = []
netParams['connParams'].append(
{'preTags': {'popLabel': 'PYR'}, 'postTags': {'popLabel': 'PYR'},
- 'connList': [[0,1],[3,1]],
- 'weight': [0.005, 0.001], # weight of each connection
+ 'connList': [[0,1],[3,1]], # list of connections
+ 'weight': [0.005, 0.001], # weight of each connection
'delay': '0.2+gauss(13.0,1.4)', # delay min=0.2, mean=13.0, var = 1.4
- 'threshold': 10}) # threshold
+ 'threshold': 10}) # threshold
netParams['connParams'].append(
|
finished fromListConn function; tested on simple HHTut example; added comments
|
py
|
diff --git a/test/testio.py b/test/testio.py
index <HASH>..<HASH> 100755
--- a/test/testio.py
+++ b/test/testio.py
@@ -12,15 +12,12 @@ except ImportError:
def test_readline(rf, fn):
f = rf.open(fn)
- br = BufferedReader(f)
- tr = TextIOWrapper(br)
+ tr = TextIOWrapper(BufferedReader(f))
while 1:
ln = tr.readline()
if not ln:
break
tr.close()
- br.close()
- f.close()
def main():
files = ['stest1.txt', 'stest2.txt']
|
testio: multiple close is not necessary
|
py
|
diff --git a/pypot/robot/__init__.py b/pypot/robot/__init__.py
index <HASH>..<HASH> 100644
--- a/pypot/robot/__init__.py
+++ b/pypot/robot/__init__.py
@@ -8,5 +8,5 @@ except ImportError:
try:
from ..vrep import from_vrep
-except ImportError:
+except (ImportError, OSError):
pass
|
Prevent an import error when fafailing to load the v-rep dynamical library.
|
py
|
diff --git a/pex/pip.py b/pex/pip.py
index <HASH>..<HASH> 100644
--- a/pex/pip.py
+++ b/pex/pip.py
@@ -603,10 +603,15 @@ class Pip(object):
manylinux=None, # type: Optional[str]
):
# type: (...) -> Job
+
# N.B.: Pip gives fair warning:
# WARNING: This command is only meant for debugging. Do not use this with automation for
# parsing and getting these details, since the output and options of this command may
# change without notice.
+ #
+ # We suppress the warning by capturing stderr below. The information there will be dumped
+ # only if the Pip command fails, which is what we want.
+
debug_command = ["debug"]
debug_command.extend(
self._iter_platform_args(
@@ -617,7 +622,9 @@ class Pip(object):
manylinux=manylinux,
)
)
- return self._spawn_pip_isolated_job(debug_command, pip_verbosity=1, stdout=subprocess.PIPE)
+ return self._spawn_pip_isolated_job(
+ debug_command, pip_verbosity=1, stdout=subprocess.PIPE, stderr=subprocess.PIPE
+ )
_PIP = None
|
Suppress `pip debug` warning. (#<I>) Pex accepts this warning in order to implement the `--pex-repository` feature. User's should not have to see the warning since they are just along for the ride.
|
py
|
diff --git a/master/buildbot/status/web/status_json.py b/master/buildbot/status/web/status_json.py
index <HASH>..<HASH> 100644
--- a/master/buildbot/status/web/status_json.py
+++ b/master/buildbot/status/web/status_json.py
@@ -47,7 +47,7 @@ FLAGS = """\
amount of useless data sent.
- callback
- Enable uses of JSONP as described in
- http://en.wikipedia.org/wiki/JSON#JSONP. Note that
+ http://en.wikipedia.org/wiki/JSONP. Note that
Access-Control-Allow-Origin:* is set in the HTTP response header so you
can use this in compatible browsers.
"""
|
Update pointer to wikipedia JSONP page.
|
py
|
diff --git a/testing/src/lib/abbreviation.py b/testing/src/lib/abbreviation.py
index <HASH>..<HASH> 100644
--- a/testing/src/lib/abbreviation.py
+++ b/testing/src/lib/abbreviation.py
@@ -1,7 +1,5 @@
import re
-__all__ = ["applySettings", "Abbreviation", "Expansion", "ABBREVIATION_OPTIONS"]
-
WORD_CHARS_REGEX_OPTION = "wordchars"
IMMEDIATE_OPTION = "immediate"
IGNORE_CASE_OPTION = "ignorecase"
@@ -79,7 +77,9 @@ class Abbreviation:
currentString = currentString.lower()
if self.abbreviation in currentString:
- stringBefore, stringAfter = currentString.split(self.abbreviation)
+ splitList = currentString.split(self.abbreviation)
+ stringBefore = ''.join(splitList[:-1])
+ stringAfter = splitList[-1]
# Check trigger character condition
if not self.settings[IMMEDIATE_OPTION]:
|
FIx bug where abbreviation appears more than once in buffer git-svn-id: <URL>
|
py
|
diff --git a/jaraco/functools.py b/jaraco/functools.py
index <HASH>..<HASH> 100644
--- a/jaraco/functools.py
+++ b/jaraco/functools.py
@@ -92,7 +92,7 @@ def once(func):
return wrapper
-def method_cache(method, cache_wrapper=None):
+def method_cache(method, cache_wrapper=functools.lru_cache()):
"""
Wrap lru_cache to support storing the cache data in the object instances.
@@ -159,7 +159,6 @@ def method_cache(method, cache_wrapper=None):
http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/
for another implementation and additional justification.
"""
- cache_wrapper = cache_wrapper or functools.lru_cache()
def wrapper(self, *args, **kwargs):
# it's the first call, replace the method with a cached, bound method
|
method_cache just accepts the lru_cache as the default value.
|
py
|
diff --git a/symfit/core/fit.py b/symfit/core/fit.py
index <HASH>..<HASH> 100644
--- a/symfit/core/fit.py
+++ b/symfit/core/fit.py
@@ -787,15 +787,8 @@ class TakesData(object):
for var, sigma in self.model.sigmas.items():
# print(var, sigma)
if not isinstance(self.data[sigma.name], Iterable):
-<<<<<<< HEAD
- try:
- self.data[sigma.name] *= np.ones(self.data[var.name].shape)
- except AttributeError:
- pass
-=======
self.data[sigma.name] *= np.ones(self.data[var.name].shape)
# If no attribute shape exists, data is also not an array
->>>>>>> create_TakesData
# If user gives a preference, use that. Otherwise, use True if at least one sigma is
# given, False if no sigma is given.
|
Somewhere, something went wrong merging
|
py
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -1,4 +1,12 @@
-from setuptools import setup, find_packages
+import os
+import sys
+from setuptools import setup, find_packages, Command
+
+
+class Doctest(Command):
+ if sys.argv[-1] == 'test':
+ print("Running docs make and make doctest")
+ os.system("make doctest -C docs/")
setup(name='Kytos OpenFlow Parser library',
version='0.1',
@@ -9,5 +17,8 @@ setup(name='Kytos OpenFlow Parser library',
license='MIT',
test_suite='tests',
packages=find_packages(exclude=["tests", "*v0x02*"]),
+ cmdclass={
+ 'doctests': Doctest
+ },
zip_safe=False)
|
Added doctest on setup.py test
|
py
|
diff --git a/microcosm_postgres/operations.py b/microcosm_postgres/operations.py
index <HASH>..<HASH> 100644
--- a/microcosm_postgres/operations.py
+++ b/microcosm_postgres/operations.py
@@ -85,7 +85,8 @@ def recreate_all(graph):
drop_all(graph)
create_all(graph)
- _metadata = MetaData(bind=graph.postgres, reflect=True)
+ _metadata = MetaData(bind=graph.postgres)
+ _metadata.reflect()
return
# Otherwise, truncate all existing tables
|
Remove deprecated usage of `reflect` constructor param Usage is deprecated; users are expected to explicitly call reflect() on the Metadata instance.
|
py
|
diff --git a/qiskit/aqua/quantum_instance.py b/qiskit/aqua/quantum_instance.py
index <HASH>..<HASH> 100644
--- a/qiskit/aqua/quantum_instance.py
+++ b/qiskit/aqua/quantum_instance.py
@@ -186,7 +186,8 @@ class QuantumInstance:
if os.environ.get('QISKIT_AQUA_CIRCUIT_CACHE', False) or circuit_caching:
if optimization_level is None or optimization_level == 0:
self._compile_config['optimization_level'] = 0
- skip_qobj_deepcopy = True
+ skip_qobj_deepcopy = True if os.environ.get('QISKIT_AQUA_CIRCUIT_CACHE', False) \
+ else skip_qobj_deepcopy
circuit_cache = CircuitCache(skip_qobj_deepcopy=skip_qobj_deepcopy,
cache_file=cache_file)
else:
|
re-use the original setting of skip qobj deepcopy
|
py
|
diff --git a/abilian/services/indexing/service.py b/abilian/services/indexing/service.py
index <HASH>..<HASH> 100644
--- a/abilian/services/indexing/service.py
+++ b/abilian/services/indexing/service.py
@@ -76,6 +76,9 @@ class IndexServiceState(ServiceState):
class WhooshIndexService(Service):
+ """
+ Index documents using whoosh
+ """
name = 'indexing'
AppStateClass = IndexServiceState
@@ -145,7 +148,7 @@ class WhooshIndexService(Service):
for name, schema in self.schemas.iteritems():
if current_app.testing:
- storage = RamStorage()
+ storage = TestingStorage()
else:
index_path = os.path.join(state.whoosh_base, name)
if not os.path.exists(index_path):
@@ -504,3 +507,18 @@ def index_update(index, items):
updated.add(object_key)
session.close()
+
+
+class TestingStorage(RamStorage):
+ """
+ RamStorage whoses temp_storage method returns another TestingStorage
+ instead of a FileStorage.
+
+ Reason is that FileStorage.temp_storage() creates temp file in
+
+ /tmp/index_name.tmp/, which is subject to race conditions when many
+ tests are ran in parallel, including different abilian-based packages.
+ """
+
+ def temp_storage(self, name=None):
+ return TestingStorage()
|
indexing: use a custom ramstorage during tests this should fix race conditions seen when running tests in parallel (seen when parallel means different abilian based packages)
|
py
|
diff --git a/eventsourcing/sqlite.py b/eventsourcing/sqlite.py
index <HASH>..<HASH> 100644
--- a/eventsourcing/sqlite.py
+++ b/eventsourcing/sqlite.py
@@ -277,7 +277,7 @@ class SQLiteApplicationRecorder(
self.select_notifications_filter_topics_statement = (
f"SELECT rowid, * FROM {self.events_table_name} "
- "WHERE (rowid>=?) AND (topic=?) ORDER BY rowid LIMIT ?"
+ "WHERE rowid>=? AND topic IN (%s) ORDER BY rowid LIMIT ?"
)
def construct_create_table_statements(self) -> List[str]:
@@ -305,9 +305,10 @@ class SQLiteApplicationRecorder(
if not topics:
c.execute(self.select_notifications_statement, [start, limit])
else:
- c.execute(self.select_notifications_filter_topics_statement, [start,
-
- topics[0], limit])
+ qst_marks = ",".join('?' * len(topics))
+ stmt = self.select_notifications_filter_topics_statement % qst_marks
+ params = [str(start)] + list(topics) + [str(limit)]
+ c.execute(stmt, params)
for row in c.fetchall():
notifications.append(
|
Fixed selection of notification in SQLite, to use IN clause, rather than single value.
|
py
|
diff --git a/parsl/app/app.py b/parsl/app/app.py
index <HASH>..<HASH> 100644
--- a/parsl/app/app.py
+++ b/parsl/app/app.py
@@ -75,17 +75,6 @@ class AppBase(metaclass=ABCMeta):
pass
-def app_wrapper(func):
-
- def wrapper(*args, **kwargs):
- logger.debug("App wrapper begins")
- x = func(*args, **kwargs)
- logger.debug("App wrapper ends")
- return x
-
- return wrapper
-
-
def App(apptype, data_flow_kernel=None, walltime=60, cache=False, executors='all'):
"""The App decorator function.
|
Remove dead code: app_wrapper (#<I>)
|
py
|
diff --git a/neurondm/neurondm/core.py b/neurondm/neurondm/core.py
index <HASH>..<HASH> 100644
--- a/neurondm/neurondm/core.py
+++ b/neurondm/neurondm/core.py
@@ -970,7 +970,7 @@ class Phenotype(graphBase): # this is really just a 2 tuple... # FIXME +/- nee
except ConnectionError:
#print(tc.red('WARNING:'), 'Phenotype unvalidated. No SciGraph was instance found at',
#self._sgv._basePath)
- log.warning('Phenotype unvalidated. No SciGraph was instance found at ', + self._sgv._basePath)
+ log.warning(f'Phenotype unvalidated. No SciGraph was instance found at {self._sgv._basePath}')
return subject
|
neurondm check phenotype log message bugfix string, + string != string + string so use fstrings so you can't possibly mess it up
|
py
|
diff --git a/holoviews/operation/element.py b/holoviews/operation/element.py
index <HASH>..<HASH> 100644
--- a/holoviews/operation/element.py
+++ b/holoviews/operation/element.py
@@ -619,12 +619,11 @@ class gridmatrix(param.ParameterizedFunction):
# Creates a unified Columns.data attribute
# to draw the data from
if isinstance(element.data, np.ndarray):
- if Columns.data_type == 'mapping':
- el_data = element.mapping()
+ if 'dataframe' in Columns.datatype:
+ el_data = element.table('dataframe')
else:
- el_data = element.dframe()
- else:
- el_data = element.data
+ el_data = element.table('dictionary')
+ el_data = element.data
# Get dimensions to plot against each other
dims = [d for d in element.dimensions()
|
Minor fix to gridmatrix operation
|
py
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-
+from setuptools import find_packages
try:
from setuptools import setup
except ImportError:
@@ -34,20 +34,19 @@ setup(
author="Wojciech Nowak",
author_email='mail@pythonic.ninja',
url='https://github.com/PythonicNinja/pydrill',
- packages=[
- 'pydrill',
- ],
- package_dir={'pydrill':
- 'pydrill'},
+ packages=find_packages(
+ where='.',
+ exclude=('test_*', )
+ ),
include_package_data=True,
install_requires=requirements,
- license="ISCL",
+ license="MIT",
zip_safe=False,
keywords='pydrill',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
- 'License :: OSI Approved :: ISC License (ISCL)',
+ 'License :: MIT Approved :: MIT License (MIT)',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
|
updated setup.py to use find_packages, license update in setup.py
|
py
|
diff --git a/better_exchook.py b/better_exchook.py
index <HASH>..<HASH> 100644
--- a/better_exchook.py
+++ b/better_exchook.py
@@ -35,6 +35,7 @@
from __future__ import print_function
import sys, os, os.path
+import threading
try:
from traceback import StackSummary, FrameSummary
except ImportError:
@@ -467,6 +468,7 @@ class Color:
return out
def format_tb(tb=None, limit=None, allLocals=None, allGlobals=None, withTitle=False, with_color=None):
+ is_at_exit = not threading.main_thread().is_alive()
color = Color(enable=with_color)
out = []
def output(s1, s2=None, **kwargs):
@@ -552,7 +554,11 @@ def format_tb(tb=None, limit=None, allLocals=None, allGlobals=None, withTitle=Fa
if source_code:
source_code = remove_indent_lines(replace_tab_indents(source_code)).rstrip()
output(" line: ", color.py_syntax_highlight(source_code), color="blue")
- if isinstance(f, DummyFrame) and not f.have_vars_available:
+ if is_at_exit:
+ # Better to not show __repr__ of some vars, as this might lead to crashes
+ # when native extensions are involved.
+ pass
+ elif isinstance(f, DummyFrame) and not f.have_vars_available:
pass
else:
output(color(' locals:', "blue"))
|
do not show vars when at exit
|
py
|
diff --git a/src/SLIP.py b/src/SLIP.py
index <HASH>..<HASH> 100644
--- a/src/SLIP.py
+++ b/src/SLIP.py
@@ -92,10 +92,6 @@ class Image:
self.N_Y = self.pe.N_Y # n_y
self.init()
- if not 'verbose' in self.pe.keys():
- self.pe.verbose = logging.WARN
- self.init_logging()
-
def get_pe(self, pe):
if type(pe) is tuple:
return ParameterSet({'N_X':pe[0], 'N_Y':pe[1]})
@@ -161,6 +157,10 @@ class Image:
self.f_mask = self.retina()
self.X, self.Y = np.meshgrid(np.arange(self.N_X), np.arange(self.N_Y))
+ if not 'verbose' in self.pe.keys():
+ self.pe.verbose = logging.WARN
+ self.init_logging()
+
def init_logging(self, filename='debug.log', name="SLIP"):
try:
PID = os.getpid()
|
setting verbose level at init
|
py
|
diff --git a/sepaxml/shared.py b/sepaxml/shared.py
index <HASH>..<HASH> 100644
--- a/sepaxml/shared.py
+++ b/sepaxml/shared.py
@@ -55,11 +55,13 @@ class SepaPaymentInitn:
def _finalize_batch(self):
raise NotImplementedError()
- def export(self, validate=True):
+ def export(self, validate=True, pretty_print=False):
"""
Method to output the xml as string. It will finalize the batches and
then calculate the checksums (amount sum and transaction count),
fill these into the group header and output the XML.
+
+ @param pretty_print: uses Python's xml.dom.minidom.Node.toprettyxml to make it easier to read for humans
"""
self._finalize_batch()
@@ -87,6 +89,12 @@ class SepaPaymentInitn:
# automatically if you write to a file, which we don't necessarily want.
out = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + ET.tostring(
self._xml, "utf-8")
+
+ if pretty_print:
+ from xml.dom import minidom
+ out_minidom = minidom.parseString(out)
+ out = out_minidom.toprettyxml(encoding="utf-8")
+
if validate:
try_valid_xml(out, self.schema)
return out
|
xml export: support pretty_print output (#<I>)
|
py
|
diff --git a/organizations/models.py b/organizations/models.py
index <HASH>..<HASH> 100644
--- a/organizations/models.py
+++ b/organizations/models.py
@@ -5,16 +5,6 @@ from django.utils.translation import ugettext_lazy as _
from organizations.managers import OrgManager, ActiveOrgManager
-try:
- from django_extensions.db.fields import AutoSlugField
-except ImportError:
- slug_field = models.SlugField
- slug_field_kwargs = {}
-else:
- slug_field = AutoSlugField
- slug_field_kwargs = {'populate_from': 'name', 'editable': True,
- 'blank': False}
-
class OrganizationsBase(models.Model):
created = models.DateTimeField(auto_now_add=True)
@@ -33,9 +23,8 @@ class Organization(OrganizationsBase):
"""
name = models.CharField(max_length=50,
help_text=_("The name of the organization"))
- slug = slug_field(max_length=50,
- help_text=_("""The name in all lowercase, suitable for URL
- identification"""), **slug_field_kwargs)
+ slug = models.SlugField(max_length=50, help_text=_("""The name in all
+ lowercase, suitable for URL identification"""))
users = models.ManyToManyField(User, through="OrganizationUser")
is_active = models.BooleanField(default=True)
|
Remove AutoSlugField with SlugField This conditional AutoSlugField/SlugField was a stupid design decision. If an organization slug exists already the user should be provided the option of changing it something else, rather than having it automatically incremented because the base slug already exists. Plus, it's an additional external dependency.
|
py
|
diff --git a/src/toil/batchSystems/mesos/batchSystem.py b/src/toil/batchSystems/mesos/batchSystem.py
index <HASH>..<HASH> 100644
--- a/src/toil/batchSystems/mesos/batchSystem.py
+++ b/src/toil/batchSystems/mesos/batchSystem.py
@@ -424,8 +424,7 @@ class MesosBatchSystem(BatchSystemLocalSupport,
jobTypes = self.jobQueues.sortedTypes
- # TODO: We may want to assert that numIssued >= numRunning
- if not jobTypes or len(self.getIssuedBatchJobIDs()) == len(self.getRunningBatchJobIDs()):
+ if not jobTypes:
log.debug('There are no queued tasks. Declining Mesos offers.')
# Without jobs, we can get stuck with no jobs and no new offers until we decline it.
self._declineAllOffers(driver, offers)
|
Remove linear-time bottleneck from Mesos batch system Previously the system had essentially 0 throughput when there were more than ~<I>-<I>k queued jobs. The existing check took linear time in the number of issued jobs, but was actually redundant for determining the number of queued jobs, because jobTypes contains *only* queued jobs.
|
py
|
diff --git a/template_parser.py b/template_parser.py
index <HASH>..<HASH> 100755
--- a/template_parser.py
+++ b/template_parser.py
@@ -280,9 +280,9 @@ def read_template_types(template_type, container_cmd, path_dirs):
host_config_new["Links"] = ["core-aaa-rabbitmq:rabbitmq"]
# add files volume
if "Binds" in host_config:
- host_config_new["Binds"].append("/files:/files:ro")
+ host_config_new["Binds"].append("/files:/files:rw")
else:
- host_config_new["Binds"] = ["/files:/files:ro"]
+ host_config_new["Binds"] = ["/files:/files:rw"]
if "Links" in host_config:
for rec in host_config["Links"]:
r = rec.split(":")
@@ -347,7 +347,7 @@ def read_template_types(template_type, container_cmd, path_dirs):
if not host_config_exists:
host_config = {}
if template_type not in ["visualization", "core", "active", "passive"]:
- host_config["Binds"] = ["/files:/files:ro"]
+ host_config["Binds"] = ["/files:/files:rw"]
try:
rabbitmq_host = "rabbitmq"
external_rabbit = False
|
be able to write out new files from plugins
|
py
|
diff --git a/see.py b/see.py
index <HASH>..<HASH> 100644
--- a/see.py
+++ b/see.py
@@ -26,7 +26,13 @@ Licensed under the GNU General Public License v3. {{{
}}}
"""
-__author__ = 'Liam Cooke'
+__author__ = """\
+Liam Cooke
+Bob Farrell
+Charlie Nolan
+Ed Page
+Gabriel Genellina
+"""
__version__ = '0.5.2.1'
__copyright__ = 'Copyright (c) 2009 Liam Cooke'
__license__ = 'GNU General Public License v3'
@@ -84,8 +90,8 @@ def see(obj=_NO_OBJ, pattern=None, r=None):
Use the pattern argument for shell-style pattern matching,
and r for regular expressions. For example:
- >>> see(23, pattern='h*')
- hash() help() hex()
+ >>> see(dict, pattern='*item*')
+ .items() .iteritems() .popitem()
Some unique symbols are used:
@@ -93,7 +99,7 @@ def see(obj=_NO_OBJ, pattern=None, r=None):
[] implements obj[key]
in implements membership tests (e.g. x in obj)
+obj unary positive operator (e.g. +2)
- -obj unary negative operator (e.g. -3)
+ -obj unary negative operator (e.g. -2)
"""
locals = obj is _NO_OBJ
|
added authors + changed see() docstring
|
py
|
diff --git a/blockcypher/utils.py b/blockcypher/utils.py
index <HASH>..<HASH> 100644
--- a/blockcypher/utils.py
+++ b/blockcypher/utils.py
@@ -12,7 +12,7 @@ HEX_CHARS_RE = re.compile('^[0-9a-f]*$')
def btc_to_satoshis(btc):
- return float(btc) * float(SATOSHIS_PER_BTC)
+ return int(float(btc) * SATOSHIS_PER_BTC)
def satoshis_to_btc(satoshis):
|
better handling of float->int
|
py
|
diff --git a/three/core.py b/three/core.py
index <HASH>..<HASH> 100644
--- a/three/core.py
+++ b/three/core.py
@@ -220,9 +220,9 @@ class Three(object):
else:
files = None
url = self._create_path('requests')
- self.request = requests.post(url, data=kwargs, files=files)
- content = self.request.content
- if self.request.status_code == 200:
+ self.post_response = requests.post(url, data=kwargs, files=files)
+ content = self.post_response.content
+ if self.post_response.status_code == 200:
conversion = True
else:
conversion = False
|
Do not override self.request in Three.post() requests.post() returns an object of Response type. Instead of overriding Three.request(), store the response with the name 'post_response'.
|
py
|
diff --git a/zinnia/__init__.py b/zinnia/__init__.py
index <HASH>..<HASH> 100644
--- a/zinnia/__init__.py
+++ b/zinnia/__init__.py
@@ -1,5 +1,5 @@
"""Zinnia"""
-__version__ = '0.19.dev0'
+__version__ = '0.19'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
|
Bumping to version <I>
|
py
|
diff --git a/docs/conf.py b/docs/conf.py
index <HASH>..<HASH> 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -50,10 +50,17 @@ copyright = u'2009, The Werkzeug Team'
# built documents.
import re
+try:
+ import werkzeug
+except ImportError:
+ sys.path.append(os.path.abspath('../'))
from werkzeug import __version__ as release
if 'dev' in release:
release = release[:release.find('dev') + 3]
-version = re.match(r'\d+\.\d+(?:\.\d+)?', release).group()
+if release == 'unknown':
+ version = release
+else:
+ version = re.match(r'\d+\.\d+(?:\.\d+)?', release).group()
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
|
fixed conf.py to allow building docs without a virtual environment
|
py
|
diff --git a/blockstore/blockstored.py b/blockstore/blockstored.py
index <HASH>..<HASH> 100644
--- a/blockstore/blockstored.py
+++ b/blockstore/blockstored.py
@@ -32,7 +32,8 @@ log = logging.getLogger()
log.setLevel(logging.DEBUG if config.DEBUG else logging.INFO)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG if config.DEBUG else logging.INFO)
-formatter = logging.Formatter('%(message)s')
+log_format = ('[%(levelname)s] [%(module)s:%(lineno)d] %(message)s' if config.DEBUG else '%(message)s')
+formatter = logging.Formatter( log_format )
console.setFormatter(formatter)
log.addHandler(console)
@@ -576,8 +577,17 @@ def run_server(foreground=False):
command, shell=True, preexec_fn=os.setsid)
log.info('Blockstored successfully started')
+ except IndexError, ie:
+ # indicates that we don't have the latest block
+ log.error("\n\nFailed to find the first blockstore record.\nPlease verify that your bitcoin provider has processed up to block 343883.\n Example: bitcoin-cli getblockcount")
+ try:
+ os.killpg(blockstored.pid, signal.SIGTERM)
+ except:
+ pass
+ exit(1)
+
except Exception as e:
- log.debug(e)
+ log.exception(e)
log.info('Exiting blockstored server')
try:
os.killpg(blockstored.pid, signal.SIGTERM)
|
Meaningful error messages: * in DEBUG logging priority, print module and line number * if blockstored attempts to connect to a bitcoind peer that has not processed our first block, then report a meaningful error that says so, as well as an example of how to verify that this is the case.
|
py
|
diff --git a/tensorlayer/layers.py b/tensorlayer/layers.py
index <HASH>..<HASH> 100644
--- a/tensorlayer/layers.py
+++ b/tensorlayer/layers.py
@@ -1942,6 +1942,7 @@ class DeformableConv2dLayer(Layer):
## this layer
self.all_layers.extend([self.outputs])
+ self.all_params.extend([W, b])
def AtrousConv1dLayer(net, n_filter=32, filter_size=2, stride=1, dilation=1, act=None,
padding='SAME', use_cudnn_on_gpu=None,data_format='NWC',
|
fix bug in deformable CNN fix bug in deformable CNN
|
py
|
diff --git a/openquake/server/db/actions.py b/openquake/server/db/actions.py
index <HASH>..<HASH> 100644
--- a/openquake/server/db/actions.py
+++ b/openquake/server/db/actions.py
@@ -268,6 +268,7 @@ DISPLAY_NAME = {
'hmaps': 'Hazard Maps',
'uhs': 'Uniform Hazard Spectra',
'disagg': 'Disaggregation Outputs',
+ 'disagg-stats': 'Disaggregation Statistics',
'realizations': 'Realizations',
'fullreport': 'Full Report',
}
|
Added label Disaggregation Statistics [skip CI]
|
py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.