diff
stringlengths
139
3.65k
message
stringlengths
8
627
diff_languages
stringclasses
1 value
diff --git a/snet_cli/mpe_client_command.py b/snet_cli/mpe_client_command.py index <HASH>..<HASH> 100644 --- a/snet_cli/mpe_client_command.py +++ b/snet_cli/mpe_client_command.py @@ -381,8 +381,8 @@ class MPEClientCommand(BlockchainCommand): def _call_check_price(self, service_metadata): pricing = service_metadata["pricing"] - if (pricing["price_model"] == "fixed_price" and pricing["price"] != self.args.price): - raise Exception("Service price is %s, but you set price %s"%(cogs2stragi(pricing["price"]), cogs2stragi(self.args.price))) + if (pricing["price_model"] == "fixed_price" and pricing["price_in_cogs"] != self.args.price): + raise Exception("Service price is %s, but you set price %s"%(cogs2stragi(pricing["price_in_cogs"]), cogs2stragi(self.args.price))) def call_server_statelessly(self): params = self._get_call_params()
change price to price_in_cogs in metadata 2
py
diff --git a/cobald/utility/concurrent/meta_runner.py b/cobald/utility/concurrent/meta_runner.py index <HASH>..<HASH> 100644 --- a/cobald/utility/concurrent/meta_runner.py +++ b/cobald/utility/concurrent/meta_runner.py @@ -22,6 +22,8 @@ class MetaRunner(object): self.runners = { runner.flavour: runner() for runner in (TrioRunner, AsyncioRunner, ThreadRunner) } + self.running = threading.Event() + self.running.clear() def register_payload(self, *payloads, flavour: ModuleType): """Queue one or more payload for execution after its runner is started""" @@ -33,6 +35,7 @@ class MetaRunner(object): """Run all runners until completion""" self._logger.info('starting all runners') try: + self.running.set() thread_runner = self.runners[threading] for runner in self.runners.values(): if runner is not thread_runner: @@ -45,6 +48,7 @@ class MetaRunner(object): for runner in self.runners.values(): runner.stop() self._logger.info('stopped all runners') + self.running.clear() if __name__ == "__main__":
MetaRunner has public flag indicating wheter it is running
py
diff --git a/source/awesome_tool/mvc/controllers/graphical_editor.py b/source/awesome_tool/mvc/controllers/graphical_editor.py index <HASH>..<HASH> 100644 --- a/source/awesome_tool/mvc/controllers/graphical_editor.py +++ b/source/awesome_tool/mvc/controllers/graphical_editor.py @@ -259,6 +259,10 @@ class GraphicalEditorController(ExtendedController): click = self.view.editor.screen_to_opengl_coordinates((event.x, event.y)) clicked_model = self._find_selection(event.x, event.y) + # When a new transition is created, the creation can be aborted with a right click + if self.selected_outcome is not None: + self._abort() + # If a connection (transition or data flow) was clicked if isinstance(clicked_model, TransitionModel) or isinstance(clicked_model, DataFlowModel): @@ -555,6 +559,12 @@ class GraphicalEditorController(ExtendedController): from_state_id = self.selected_outcome[0].state.state_id from_outcome_id = self.selected_outcome[1] to_state_id = to_state_m.state.state_id + + # Prevent accidental creation of transitions with double click on one outcome + if from_state_id == to_state_id and to_outcome_id is not None: + self._abort() + return + if to_outcome_id is None: responsible_parent_state = to_state_m.parent.state else:
Add more ways to abort transition creation - A right clicks stops the creation of a new transition - When the user double clicks on an outcome, the transition creation process is also aborted
py
diff --git a/pymatgen/analysis/local_env.py b/pymatgen/analysis/local_env.py index <HASH>..<HASH> 100644 --- a/pymatgen/analysis/local_env.py +++ b/pymatgen/analysis/local_env.py @@ -2634,15 +2634,20 @@ class CrystalNN(NearNeighbors): entry["weight"] = round(entry["weight"], 3) del entry["poly_info"] # trim - # remove entries with no weight - nn = [x for x in nn if x["weight"] > 0] + # remove entries with no weight, unless all weights are zero + if len([x for x in nn if x["weight"] == 0]) != len(nn): + nn = [x for x in nn if x["weight"] > 0] + else: + for x in nn: + x["weight"] = 1 # get the transition distances, i.e. all distinct weights dist_bins = [] for entry in nn: if not dist_bins or dist_bins[-1] != entry["weight"]: dist_bins.append(entry["weight"]) - dist_bins.append(0) + if dist_bins[-1] != 0: + dist_bins.append(0) # main algorithm to determine fingerprint from bond weights cn_scores = {} # CN -> score for that CN
Addressed short-comming in CrystalNN to not be able to address noble-gas materials.
py
diff --git a/flask2postman.py b/flask2postman.py index <HASH>..<HASH> 100644 --- a/flask2postman.py +++ b/flask2postman.py @@ -85,12 +85,18 @@ class Route: def main(): import os + import sys import json import logging from argparse import ArgumentParser from flask import Flask, current_app + sys.path.append(os.getcwd()) + if os.environ["VIRTUAL_ENV"]: + print("WARNING: Attempting to work in a virtualenv. If you encounter" + " problems, please install flask2postman inside the virtualenv.") + parser = ArgumentParser() parser.add_argument("flask_instance") parser.add_argument("-n", "--name", default=os.path.basename(os.getcwd()), @@ -106,8 +112,8 @@ def main(): try: app_path, app_name = args.flask_instance.rsplit('.', 1) app = getattr(__import__(app_path), app_name) - except Exception: - parser.error("can't import \"{}\"".format(args.flask_instance)) + except Exception as e: + parser.error("can't import \"{}\" ({})".format(args.flask_instance, str(e))) if not isinstance(app, Flask): parser.error("\"{}\" is not a Flask instance".format(args.flask_instance))
Be more verbose when an error occurs (or could occur)
py
diff --git a/python/ray/experimental/multiprocessing/pool.py b/python/ray/experimental/multiprocessing/pool.py index <HASH>..<HASH> 100644 --- a/python/ray/experimental/multiprocessing/pool.py +++ b/python/ray/experimental/multiprocessing/pool.py @@ -168,6 +168,8 @@ class IMapIterator: """Base class for OrderedIMapIterator and UnorderedIMapIterator.""" def __init__(self, pool, func, iterable, chunksize=None): + self._pool = pool + self._func = func self._next_chunk_index = 0 # List of bools indicating if the given chunk is ready or not for all # submitted chunks. Ordering mirrors that in the in the ResultThread. @@ -182,7 +184,7 @@ class IMapIterator: [], total_object_ids=self._total_chunks) self._result_thread.start() - for _ in range(len(pool._actor_pool)): + for _ in range(len(self._pool._actor_pool)): self._submit_next_chunk() def _submit_next_chunk(self):
Hotfix missing fields in multiprocessing.Pool (#<I>)
py
diff --git a/src/requirementslib/models/dependencies.py b/src/requirementslib/models/dependencies.py index <HASH>..<HASH> 100644 --- a/src/requirementslib/models/dependencies.py +++ b/src/requirementslib/models/dependencies.py @@ -393,13 +393,13 @@ def get_dependencies_from_index(dep, sources=None, pip_options=None, wheel_cache try: distutils.core.run_setup(dep.setup_py) except Exception: - pass + pass # FIXME: Needs to bubble this somehow to the user. requirements = None prev_tracker = os.environ.get('PIP_REQ_TRACKER') try: requirements = resolver._resolve_one(reqset, dep) except Exception: - requirements = [] + pass # FIXME: Needs to bubble this somehow to the user. finally: reqset.cleanup_files() if 'PIP_REQ_TRACKER' in os.environ: @@ -412,8 +412,11 @@ def get_dependencies_from_index(dep, sources=None, pip_options=None, wheel_cache pass # requirements = reqset.requirements.values() - reqs = set(requirements) - DEPENDENCY_CACHE[dep] = [format_requirement(r) for r in reqs] + if requirements is not None: + reqs = set(requirements) + DEPENDENCY_CACHE[dep] = [format_requirement(r) for r in reqs] + else: + reqs = set() return reqs
Add error-handling notes and don't cache on error
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -16,8 +16,7 @@ setup( author = "hMatoba", author_email = "[email protected]", description = "To simplify exif manipulations with python. " + - "Writing, reading, and more...Pyxif isn't a wrapper. " + - "To everywhere with Python(function'thumbnail'depends on PIL or Pillow).", + "Writing, reading, and more...", long_description = description, license = "MIT", keywords = ["exif", "jpeg"],
Edited setup.py.
py
diff --git a/i3pystatus/shell.py b/i3pystatus/shell.py index <HASH>..<HASH> 100644 --- a/i3pystatus/shell.py +++ b/i3pystatus/shell.py @@ -24,7 +24,7 @@ class Shell(IntervalModule): ) required = ("command",) - format = "{command}" + format = "{output}" def run(self): retvalue, out, stderr = run_through_shell(self.command, enable_shell=True) @@ -37,9 +37,7 @@ class Shell(IntervalModule): elif stderr: out = stderr - out = self.format.format(command=out) - self.output = { - "full_text": out if out else "Command `%s` returned %d" % (self.command, retvalue), + "full_text": self.format.format(output=out) if out else "Command `%s` returned %d" % (self.command, retvalue), "color": self.color if retvalue == 0 else self.error_color }
fix docs code discrepancy and error reporting with non empty format strings
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ from setuptools import find_packages import time -_version = "0.1.dev%s" % int(time.time()) +_version = "0.1" _packages = find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]) _short_description = "pylint-common is a Pylint plugin to improve Pylint error analysis of the" \ @@ -18,7 +18,7 @@ setup( name='pylint-common', description=_short_description, version=_version, packages=_packages, - install_requires=['pylint', 'astroid', 'pylint-plugin-utils'], + install_requires=['pylint>=1.0', 'astroid>=1.0', 'pylint-plugin-utils>=0.1'], license='GPLv2', keywords='pylint stdlib plugin' )
Setting versions for requirements and setting version to <I> for release
py
diff --git a/killer/killer.py b/killer/killer.py index <HASH>..<HASH> 100644 --- a/killer/killer.py +++ b/killer/killer.py @@ -34,7 +34,7 @@ import argparse import logging import time -from killer import __version__, WINDOWS, POSIX # , LINUX, OSX, BSD, WSL +from killer import __version__, WINDOWS, POSIX from killer.utils.log import configure_logging log = logging.getLogger(__name__) @@ -51,7 +51,13 @@ def get_killer(args): from killer.killer_windows import KillerWindows return KillerWindows(config_path=args.config, debug=args.debug) else: - raise NotImplementedError + # TODO: WSL + # TODO: OSX + # TODO: BSD + raise NotImplementedError("Your platform is not currently supported." + "If you would like support to be added, or " + "if your platform is supported and this is " + "a bug, please open an issue on GitHub!") def main():
More helpful error message for unsupported platforms
py
diff --git a/unyt/tests/test_unyt_array.py b/unyt/tests/test_unyt_array.py index <HASH>..<HASH> 100644 --- a/unyt/tests/test_unyt_array.py +++ b/unyt/tests/test_unyt_array.py @@ -1264,6 +1264,22 @@ def test_equivalencies(): assert data.value == .012 assert data.units == u.kg + data = 12*u.g + data = data.to_equivalent('kg', None) + assert data.value == .012 + assert data.units == u.kg + + # incorrect usate of the equivalence raises errors + + with pytest.raises(InvalidUnitEquivalence): + data.convert_to_equivalent('erg', 'thermal') + with pytest.raises(InvalidUnitEquivalence): + data.convert_to_equivalent('m', 'mass_energy') + with pytest.raises(InvalidUnitEquivalence): + data.to_equivalent('erg', 'thermal') + with pytest.raises(InvalidUnitEquivalence): + data.to_equivalent('m', 'mass_energy') + # Mass-energy mp = u.mp.copy()
expand coverage of incorrect equivalence usages
py
diff --git a/src/mistclient/model.py b/src/mistclient/model.py index <HASH>..<HASH> 100644 --- a/src/mistclient/model.py +++ b/src/mistclient/model.py @@ -378,7 +378,8 @@ class Cloud(object): machine_ready = False if machine_ready: - error = job.get('error', None) + error = job.get('error') or [ + log['error'] for log in job['logs'] if log['error']] if error: print "Finished with errors:" logs = job.get('logs', [])
Catch error in nested logs
py
diff --git a/ayrton/expansion.py b/ayrton/expansion.py index <HASH>..<HASH> 100644 --- a/ayrton/expansion.py +++ b/ayrton/expansion.py @@ -248,6 +248,18 @@ def default (parameter, word): # but tests have shown that it is not so return ans +# {parameter:?word} is automatically handled by Python's runtime +# NameError + +# {parameter:+word} +def replace_if_set (parameter, word): + value= get_var (parameter) + + if is_null (value): + return '' + else: + return word + def bash (s, single=False): data= backslash_descape (glob_expand (tilde_expand (brace_expand (s))))
[+] support for {parameter:+word}.
py
diff --git a/rejected/process.py b/rejected/process.py index <HASH>..<HASH> 100644 --- a/rejected/process.py +++ b/rejected/process.py @@ -291,8 +291,17 @@ class Process(multiprocessing.Process, state.State): settings = cfg.get('config', dict()) settings['_import_module'] = '.'.join(cfg['consumer'].split('.')[0:-1]) + kwargs = { + 'settings': settings, + 'process': self, + 'drop_invalid': cfg.get('drop_invalid_messages'), + 'message_type': cfg.get('message_type'), + 'error_exchange': cfg.get('error_exchange'), + 'error_max_retry': cfg.get('error_max_retry') + } + try: - return consumer_(settings=settings, process=self) + return consumer_(**kwargs) except Exception as error: LOGGER.exception('Error creating the consumer "%s": %s', cfg['consumer'], error) @@ -349,7 +358,8 @@ class Process(multiprocessing.Process, state.State): self.start_message_processing() try: - result = yield self.consumer._execute(message) + result = yield self.consumer._execute(message, + self.measurement) except Exception as error: LOGGER.exception('Unhandled exception from consumer in ' 'process. This should not happen. %s',
Use the new init kwargs and pass in the measurement to the consumer
py
diff --git a/tdubs.py b/tdubs.py index <HASH>..<HASH> 100644 --- a/tdubs.py +++ b/tdubs.py @@ -182,9 +182,9 @@ class Call(object): def formatted_args(self): """Format call arguments as a string. - >>> call = Call('arg1', 'arg2', kwarg1='kwarg1', kwarg2='kwarg2') + >>> call = Call('arg1', 'arg2', kwarg='kwarg') >>> call.formatted_args - ('arg1', 'arg2', kwarg2='kwarg2', kwarg1='kwarg1') + "('arg1', 'arg2', kwarg='kwarg')" """ arg_reprs = list(map(repr, self.args))
Dicts are unordered. Can't test like this.
py
diff --git a/more_itertools/more.py b/more_itertools/more.py index <HASH>..<HASH> 100644 --- a/more_itertools/more.py +++ b/more_itertools/more.py @@ -1214,6 +1214,19 @@ def context(obj): >>> file_obj.closed True + Be sure to iterate over the returned context manager in the outermost + loop of a nested loop structure:: + + >>> # Right + >>> file_obj = StringIO() + >>> consume(print(x, file=f) for f in context(file_obj) for x in it) + + >>> # Wrong + >>> file_obj = StringIO() + >>> consume(print(x, file=f) for x in it for f in context(file_obj)) + Traceback (most recent call last): + ... + ValueError: I/O operation on closed file. """ with obj as context_obj: yield context_obj
Add warning for context() and nested looping
py
diff --git a/cwltool/sandboxjs.py b/cwltool/sandboxjs.py index <HASH>..<HASH> 100644 --- a/cwltool/sandboxjs.py +++ b/cwltool/sandboxjs.py @@ -57,7 +57,8 @@ def new_js_proc(force_docker_pull=False): # type: (bool) -> subprocess.Popen res = resource_stream(__name__, 'cwlNodeEngine.js') - nodecode = res.read() + nodecode = res.read().decode('utf-8') + required_node_version, docker = (False,)*2 nodejs = None trynodes = ("nodejs", "node") @@ -238,7 +239,7 @@ def execjs(js, jslib, timeout=None, force_docker_pull=False, debug=False): # ty no_more_error.release() output_thread.join() error_thread.join() - if stdout_buf.getvalue().endswith("\n"): + if stdout_buf.getvalue().endswith("\n".encode()): rselect = [] no_more_output.release() no_more_error.release()
decoding byte data before sending to Subprocess and encoding \n before comparing
py
diff --git a/bananas/admin.py b/bananas/admin.py index <HASH>..<HASH> 100644 --- a/bananas/admin.py +++ b/bananas/admin.py @@ -256,8 +256,12 @@ class AdminView(View): tools.append((text, link)) return tools - def admin_view(self, view, perm=None): - view = self.__class__.as_view(action=view.__name__, admin=self.admin) + def admin_view(self, view, perm=None, **initkwargs): + view = self.__class__.as_view( + action=view.__name__, + admin=self.admin, + **initkwargs, + ) return self.admin.admin_view(view, perm=perm) def get_permission(self, perm):
Admin: allow initkwargs to be passed to admin view
py
diff --git a/ttkthemes/__init__.py b/ttkthemes/__init__.py index <HASH>..<HASH> 100644 --- a/ttkthemes/__init__.py +++ b/ttkthemes/__init__.py @@ -11,9 +11,12 @@ THEMES = [ "arc", "black", "blue", + "breeze", "clearlooks", "elegance", "equilux", + "itft1", + "equilux", "keramik", "kroc", "plastik", @@ -25,6 +28,7 @@ THEMES = [ "scidpink", "scidpurple", "scidsand", + "smog", "ubuntu", "winxpblue", ]
Update list of themes in __init__.py
py
diff --git a/examples/dqn_atari.py b/examples/dqn_atari.py index <HASH>..<HASH> 100644 --- a/examples/dqn_atari.py +++ b/examples/dqn_atari.py @@ -15,7 +15,7 @@ from rl.callbacks import FileLogger INPUT_SHAPE = (84, 84) -ENV_NAME = 'Breakout-v0' +ENV_NAME = 'Pong-v0' WINDOW_LENGTH = 4 @@ -84,11 +84,10 @@ weights_filename = 'dqn_{}_weights.h5f'.format(ENV_NAME) log_filename = 'dqn_{}_log.json'.format(ENV_NAME) callbacks = [ModelCheckpoint(weights_filename)] callbacks += [FileLogger(log_filename, save_continiously=False)] -dqn.fit(env, callbacks=callbacks, nb_steps=20000000, action_repetition=4, - nb_max_random_start_steps=30, log_interval=10000) +dqn.fit(env, callbacks=callbacks, nb_steps=20000000, nb_max_random_start_steps=30, log_interval=10000) # After training is done, we save the final weights one more time. dqn.save_weights(weights_filename, overwrite=True) # Finally, evaluate our algorithm for 5 episodes. -dqn.test(env, nb_episodes=10, action_repetition=4) +dqn.test(env, nb_episodes=10)
Attempt to use Pong without action repetion
py
diff --git a/nfc/dev/pn53x.py b/nfc/dev/pn53x.py index <HASH>..<HASH> 100644 --- a/nfc/dev/pn53x.py +++ b/nfc/dev/pn53x.py @@ -151,15 +151,15 @@ class pn53x(object): if frame[3] == 255 and frame[4] == 255: # extended information frame - LEN, LCS = frame[5] * 256 + frame[6], frame[7] - TFI, PD0 = frame[8], frame[9] + if sum(frame[5:8]) & 0xFF != 0: + raise FrameError("lenght checksum error") + LEN, TFI, PD0 = frame[5]*256+frame[6], frame[8], frame[9] else: # normal information frame - LEN, LCS = frame[3], frame[4] - TFI, PD0 = frame[5], frame[6] + if sum(frame[3:5]) & 0xFF != 0: + raise FrameError("lenght checksum error") + LEN, TFI, PD0 = frame[3], frame[5], frame[6] - if not (LEN + LCS) % 256 == 0: - raise FrameError("lenght checksum error") if not TFI == 0xd5: if not TFI == 0x7f: raise FrameError("invalid frame identifier")
bugfix: frame length checksum verification
py
diff --git a/holoviews/core/util.py b/holoviews/core/util.py index <HASH>..<HASH> 100644 --- a/holoviews/core/util.py +++ b/holoviews/core/util.py @@ -60,7 +60,7 @@ class HashableJSON(json.JSONEncoder): elif isinstance(obj, np.ndarray): return obj.tolist() if pd and isinstance(obj, (pd.Series, pd.DataFrame)): - return sorted(list(obj.to_dict().items())) + return repr(sorted(list(obj.to_dict().items()))) elif isinstance(obj, self.string_hashable): return str(obj) elif isinstance(obj, self.repr_hashable):
Using repr for pandas objects for Python 3 compatibility
py
diff --git a/classic.py b/classic.py index <HASH>..<HASH> 100644 --- a/classic.py +++ b/classic.py @@ -511,7 +511,7 @@ class ClassicPlayer(Player): class ClassicMediaInfo(MediaInfo): def get_info_by_path(self, path): self.l.info("Info for %s" % path) - p = subprocess.Popen(['mp3info', path, '-p', '%a\\n%t\\n%S'], + p = subprocess.Popen(['mp3info', '-p', '%a\\n%t\\n%S', path], stdout=subprocess.PIPE) artist, title, length = p.stdout.read().split("\n") length = int(length)
classic: fix order of mpg<I>
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,5 +1,5 @@ +from setuptools import setup -from distutils.core import setup setup( name = "javalang", @@ -27,5 +27,6 @@ code. javalang provies a lexer and parser targeting Java 7. The implementation is based on the Java language spec available at http://docs.oracle.com/javase/specs/jls/se7/html/. -""" +""", + zip_safe=False, )
Move to using setuptools instead of distutils in setup.py.
py
diff --git a/providers/youtube.py b/providers/youtube.py index <HASH>..<HASH> 100755 --- a/providers/youtube.py +++ b/providers/youtube.py @@ -77,7 +77,7 @@ class YouTube(Provider): filename = self.get_title() + '.video' else: #Title + last three letters of the format description lowercased - filename = self.get_title() + YouTube.FORMATS[self.format][-3:].lower() + filename = self.get_title() + '.' + YouTube.FORMATS[self.format][-3:].lower() self._debug('YouTube', 'get_filename', 'filename', filename) return filename
Insert a period between file name and extension.
py
diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index <HASH>..<HASH> 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -190,6 +190,27 @@ def test_group_apply_once_per_group(df, group_names): assert names == group_names +def test_group_apply_once_per_group2(capsys): + # GH: 31111 + # groupby-apply need to execute len(set(group_by_columns)) times + + expected = 2 # Number of times `apply` should call a function for the current test + + df = pd.DataFrame( + { + "group_by_column": [0, 0, 0, 0, 1, 1, 1, 1], + "test_column": ["0", "2", "4", "6", "8", "10", "12", "14"], + }, + index=["0", "2", "4", "6", "8", "10", "12", "14"], + ) + + df.groupby("group_by_column").apply(lambda df: print("function_called")) + + result = capsys.readouterr().out.count("function_called") + # If `groupby` behaves unexpectedly, this test will break + assert result == expected + + def test_apply_fast_slow_identical(): # GH 31613
TST: groupby apply called multiple times (#<I>) * :white_check_mark: * :white_check_mark: * reformatted accordingly, for linting issues * Fixed as per the review comments
py
diff --git a/benchexec/tools/smack.py b/benchexec/tools/smack.py index <HASH>..<HASH> 100644 --- a/benchexec/tools/smack.py +++ b/benchexec/tools/smack.py @@ -57,7 +57,7 @@ class Tool(benchexec.tools.template.BaseTool): Sets the name for SMACK, which gets displayed in the "Tool" row in BenchExec table headers. """ - return 'SMACK' + return 'SMACK+Corral' def cmdline(self, executable, options, tasks, propertyfile=None, rlimits={}): """
Updated SMACK to SMACK+Corral as our name
py
diff --git a/flask_security/utils.py b/flask_security/utils.py index <HASH>..<HASH> 100644 --- a/flask_security/utils.py +++ b/flask_security/utils.py @@ -78,7 +78,7 @@ def get_hmac(password): 'must not be None when the value of `SECURITY_PASSWORD_HASH` is ' 'set to "%s"' % _security.password_hash) - h = hmac.new(_security.password_salt, password, hashlib.sha512) + h = hmac.new(_security.password_salt, password.encode('utf-8'), hashlib.sha512) return base64.b64encode(h.digest())
Password should be encoded as 'utf-8' before creating hmac to support passwords with non-latin symbols
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -134,15 +134,17 @@ args = dict( 'Development Status :: 6 - Mature', 'Environment :: Console', 'Intended Audience :: Developers', - - # It seems that the license is not recognized by Pypi, so, not categorizing it for now. - # https://bitbucket.org/pypa/pypi/issues/369/the-eclipse-public-license-superseeded - # 'License :: OSI Approved :: Eclipse Public License', - + 'License :: OSI Approved :: Eclipse Public License 1.0 (EPL-1.0)', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Debuggers', ], entry_points={
Setup.py set license (EPL-<I>) and supported Python versions Should close #<I>
py
diff --git a/salt/fileserver/gitfs.py b/salt/fileserver/gitfs.py index <HASH>..<HASH> 100644 --- a/salt/fileserver/gitfs.py +++ b/salt/fileserver/gitfs.py @@ -92,7 +92,7 @@ def envs(): repos = init() for repo in repos: for ref in repo.refs: - if isinstance(ref, git.refs.head.Head): + if isinstance(ref, git.Head) or isinstance(ref, git.Tag): short = os.path.basename(ref.name) ret.add(short) return list(ret)
env lookup needs to support tags
py
diff --git a/openquake/commonlib/readinput.py b/openquake/commonlib/readinput.py index <HASH>..<HASH> 100644 --- a/openquake/commonlib/readinput.py +++ b/openquake/commonlib/readinput.py @@ -839,7 +839,7 @@ def get_composite_source_model(oqparam, monitor=None, in_memory=True, if oqparam.number_of_logic_tree_samples: logging.info('Considering {:,d} logic tree paths out of {:,d}'.format( oqparam.number_of_logic_tree_samples, p)) - else: + else: # full enumeration logging.info('Potential number of logic tree paths = {:,d}'.format(p)) if source_model_lt.on_each_source:
Added comment [skip CI]
py
diff --git a/pycm/pycm_obj.py b/pycm/pycm_obj.py index <HASH>..<HASH> 100644 --- a/pycm/pycm_obj.py +++ b/pycm/pycm_obj.py @@ -623,12 +623,20 @@ class ConfusionMatrix(): return not self.__eq__(other) def __copy__(self): + """ + Returns a copy of ConfusionMatrix. + :return: copy of ConfusionMatrix + """ _class = self.__class__ result = _class.__new__(_class) result.__dict__.update(self.__dict__) return result def copy(self): + """ + Returns a copy of ConfusionMatrix. + :return: copy of ConfusionMatrix + """ return self.__copy__() def relabel(self, mapping):
add : docstring added to both methods.
py
diff --git a/bingo/image.py b/bingo/image.py index <HASH>..<HASH> 100644 --- a/bingo/image.py +++ b/bingo/image.py @@ -66,7 +66,7 @@ def get_texts(bingo_fields, font): if bingo_field.is_middle(): text += _("\n{time}\nBingo #{board_id}").format( time=bingo_field.board.get_created(), - board_id=bingo_field.board.id) + board_id=bingo_field.board.board_id) texts.append(Text(draw, font, text)) return texts
fix: show the correct board_id on the images. The correct id is board.board_id and not board.id, as "id" is the internal id assigned by django, and "board_id" is the board number on the current site.
py
diff --git a/test/fixtures.py b/test/fixtures.py index <HASH>..<HASH> 100644 --- a/test/fixtures.py +++ b/test/fixtures.py @@ -123,7 +123,7 @@ class ZookeeperFixture(Fixture): # Party! self.out("Starting...") self.child.start() - self.child.wait_for(r"Snapshotting") + self.child.wait_for(r"binding to port") self.out("Done!") def close(self):
Change ZookeeperFixture wait_for regex to support newer zk version used with <I>
py
diff --git a/schedule/tests/test_utils.py b/schedule/tests/test_utils.py index <HASH>..<HASH> 100644 --- a/schedule/tests/test_utils.py +++ b/schedule/tests/test_utils.py @@ -30,7 +30,7 @@ class TestEventListManager(TestCase): 'title': 'Recent Event', 'start': datetime.datetime(2008, 1, 5, 9, 0), 'end': datetime.datetime(2008, 1, 5, 10, 0), - 'end_recurring_period' : datetime.datetime(2008, 5, 5, 0, 0), + 'end_recurring_period' : datetime.datetime(2009, 5, 5, 0, 0), 'rule': daily, 'calendar': cal })
Fixed eml test. Recurring period for the daily event had it begining before the occurrences we were checking started
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -7,6 +7,8 @@ # See LICENSE.txt or http://www.fsf.org/licensing/licenses/agpl-3.0.html from setuptools import setup +from os.path import realpath, dirname +from os import chdir import sys install_requires = [ @@ -19,7 +21,9 @@ install_requires = [ 'watchdog' # For lesscd ] -exec(open("datacats/version.py").read()) +chdir(dirname(realpath(__file__))) + +execfile("datacats/version.py") setup( name='datacats',
Change to directory of current file before getting version
py
diff --git a/yubico_client/yubico.py b/yubico_client/yubico.py index <HASH>..<HASH> 100644 --- a/yubico_client/yubico.py +++ b/yubico_client/yubico.py @@ -82,7 +82,7 @@ class Yubico(object): ' argument')) self.client_id = client_id - self.key = base64.b64decode(key) if key is not None else None + self.key = base64.b64decode(key.encode('ascii')) if key is not None else None self.verify_cert = verify_cert self.translate_otp = translate_otp self.api_urls = self._init_request_urls(api_urls=api_urls)
yubico.py: Convert key to byte string before passing it to b<I>decode In Python3 <= <I>, the base<I>.b<I>decode function only accepts byte strings, so we need to convert the key to one.
py
diff --git a/alot/commands/search.py b/alot/commands/search.py index <HASH>..<HASH> 100644 --- a/alot/commands/search.py +++ b/alot/commands/search.py @@ -199,11 +199,3 @@ class TagCommand(Command): # flush index if self.flush: ui.apply_command(commands.globals.FlushCommand()) - - # refresh buffer. - # TODO: This shouldn't be necessary but apparently it is: without the - # following call, the buffer is not updated by the refresh callback - # (given as afterwards parm above) because - # ui.dbman.count_messages(testquery) doesn't return 0 as expected - and - # as it does here. - refresh()
removed uneccesary refresh call not needed anymore
py
diff --git a/textract/cli.py b/textract/cli.py index <HASH>..<HASH> 100644 --- a/textract/cli.py +++ b/textract/cli.py @@ -13,6 +13,17 @@ from . import VERSION from .parsers import DEFAULT_ENCODING +class AddToNamespaceAction(argparse.Action): + """This adds KEY,VALUE arbitrary pairs to the argparse.Namespace object + """ + def __call__(self, parser, namespace, values, option_string=None): + key, val = values.strip().split('=') + if hasattr(namespace, key): + parser.error(( + 'Duplicate specification of the key "%(key)s" with --option.' + ) % locals()) + setattr(namespace, key, val) + # This function is necessary to enable autodocumentation of the script # output def get_parser(): @@ -44,6 +55,10 @@ def get_parser(): help='output raw text in this file', ) parser.add_argument( + '-O', '--option', type=str, action=AddToNamespaceAction, + help='add arbitrary options to various parsers of the form KEYWORD=VALUE', + ) + parser.add_argument( '-v', '--version', action='version', version='%(prog)s '+VERSION, )
added ability to specify arbitrary keyword arguments on the command line to pass to the various parsers
py
diff --git a/fedmsg/tests/test_meta.py b/fedmsg/tests/test_meta.py index <HASH>..<HASH> 100644 --- a/fedmsg/tests/test_meta.py +++ b/fedmsg/tests/test_meta.py @@ -137,6 +137,7 @@ class Base(unittest.TestCase): msg = None expected_title = None expected_subti = None + expected_markup = None expected_link = None expected_icon = None expected_secondary_icon = None @@ -162,6 +163,13 @@ class Base(unittest.TestCase): actual_title = fedmsg.meta.msg2title(self.msg, **self.config) eq_(actual_title, self.expected_title) + @skip_on(['msg', 'expected_markup']) + def test_markup(self): + """ Does fedmsg.meta produce the right html when markup=True? """ + actual_markup = fedmsg.meta.msg2subtitle( + self.msg, markup=True, **self.config) + eq_(actual_markup, self.expected_markup) + @skip_on(['msg', 'expected_subti']) def test_subtitle(self): """ Does fedmsg.meta produce the expected subtitle? """
Allow optional markup of msg2subtitle. This would be nice for embedded datagrepper results so that we can make links out of people's usernames, update title, badge names, etc..
py
diff --git a/tpm.py b/tpm.py index <HASH>..<HASH> 100644 --- a/tpm.py +++ b/tpm.py @@ -222,6 +222,33 @@ def getData(conn, TYPE, SEARCHSTRING=''): return get(conn, URL) +def getSubProjects(conn, ID): + """Get projcets that are subprojects of 'ID'.""" + if conn.api == 'v4': + URL = conn.url + conn.api + '/projects/' + str(ID) + '/subprojects.json' + # return data dictionary + return get(conn, URL) + else: + print(bcolors.FAIL + 'This functions only works with v4 API.' + + bcolors.ENDC) + sys.exit() + + +def getSubProjectsNewPwd(conn, ID): + """Get projcets that are subprojects of 'ID' and shows disabled=true + if the Users permissions does not allow to create a new Password in that + subproject.""" + if conn.api == 'v4': + URL = conn.url + conn.api + '/projects/' + str(ID) + \ + '/subprojects/new_pwd.json' + # return data dictionary + return get(conn, URL) + else: + print(bcolors.FAIL + 'This functions only works with v4 API.' + + bcolors.ENDC) + sys.exit() + + def getDetailData(conn, TYPE, ID): """Get more Details from an Entry.""" # check if type is password or projects
added new_pwd action for subprojects
py
diff --git a/test/queryservice_tests/test_env.py b/test/queryservice_tests/test_env.py index <HASH>..<HASH> 100644 --- a/test/queryservice_tests/test_env.py +++ b/test/queryservice_tests/test_env.py @@ -198,7 +198,7 @@ class VttabletTestEnv(TestEnv): self.conn = self.connect() self.txlogger = subprocess.Popen(['curl', '-s', '-N', 'http://localhost:9461/debug/txlog'], stdout=open('/tmp/vtocc_txlog.log', 'w')) self.txlog = framework.Tailer(open('/tmp/vtocc_txlog.log'), flush=self.tablet.flush) - self.log = framework.Tailer(open(os.path.join(self.tablet.tablet_dir, 'vttablet.INFO')), flush=self.tablet.flush) + self.log = framework.Tailer(open(os.path.join(environment.vtlogroot, 'vttablet.INFO')), flush=self.tablet.flush) querylog_file = '/tmp/vtocc_streamlog_%s.log' % self.tablet.port utils.run_bg(['curl', '-s', '-N', 'http://localhost:9461/debug/querylog?full=true'], stdout=open(querylog_file, 'w')) time.sleep(1)
Fixing this test after my path changes.
py
diff --git a/morango/constants/file.py b/morango/constants/file.py index <HASH>..<HASH> 100644 --- a/morango/constants/file.py +++ b/morango/constants/file.py @@ -1,6 +1,4 @@ -import pwd import os -SQLITE_VARIABLE_FILE_CACHE = os.path.join(pwd.getpwuid(os.getuid()).pw_dir, +SQLITE_VARIABLE_FILE_CACHE = os.path.join(os.path.expanduser('~'), 'SQLITE_MAX_VARIABLE_NUMBER.cache') -
pwd is not available in Windows
py
diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index <HASH>..<HASH> 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -128,7 +128,7 @@ line_width has been deprecated, use display.width instead (currently both are id pc_width_doc = """ : int Width of the display in characters. In case python/IPython is running in - a terminal this can be set to 0 and pandas will correctly auto-detect the + a terminal this can be set to None and pandas will correctly auto-detect the width. Note that the IPython notebook, IPython qtconsole, or IDLE do not run in a terminal and hence it is not possible to correctly detect the width. @@ -137,7 +137,7 @@ pc_width_doc = """ pc_height_doc = """ : int Height of the display in lines. In case python/IPython is running in a - terminal this can be set to 0 and pandas will auto-detect the width. + terminal this can be set to None and pandas will auto-detect the width. Note that the IPython notebook, IPython qtconsole, or IDLE do not run in a terminal, and hence it is not possible to correctly detect the height. """
BUG: for numerical option, sentry should be another Type, not 0
py
diff --git a/tests/test_config.py b/tests/test_config.py index <HASH>..<HASH> 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -3,6 +3,7 @@ import pytest from sqlalchemy.pool import NullPool import flask_sqlalchemy as fsa +from flask_sqlalchemy import _compat, utils class TestConfigKeys: @@ -71,7 +72,14 @@ class TestConfigKeys: errors or warnings. """ assert fsa.SQLAlchemy(app).get_engine() - assert len(recwarn) == 0 + if utils.sqlalchemy_version('==', '0.8.0') and not _compat.PY2: + # In CI, we test Python 3.6 and SA 0.8.0, which produces a warning for + # inspect.getargspec() + expected_warnings = 1 + else: + expected_warnings = 0 + + assert len(recwarn) == expected_warnings @pytest.fixture
fix py<I>-lowest test This only showed up after rebasing onto current maintenance branch.
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 @@ -2932,7 +2932,7 @@ def manage_file(name, .. code-block:: bash - salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' base '' + salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '' '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' base '' .. versionchanged:: Helium ``follow_symlinks`` option added
Typo in file.managed doc
py
diff --git a/validator/errorbundler.py b/validator/errorbundler.py index <HASH>..<HASH> 100644 --- a/validator/errorbundler.py +++ b/validator/errorbundler.py @@ -93,7 +93,7 @@ class ErrorBundle(object): def _save_message(self, stack, type_, message, context=None): "Stores a message in the appropriate message stack." - uid = uuid.uuid1().hex + uid = uuid.uuid4().hex message["uid"] = uid
Updated uuid1 to uuid4 for bug <I>
py
diff --git a/src/sos/workers.py b/src/sos/workers.py index <HASH>..<HASH> 100755 --- a/src/sos/workers.py +++ b/src/sos/workers.py @@ -176,6 +176,7 @@ class SoS_SubStep_Worker(mp.Process): # the worker process knows configuration file, command line argument etc super(SoS_SubStep_Worker, self).__init__(**kwargs) self.config = config + self.daemon = True env.logger.trace('worker init') def run(self):
Make substep worker a daemon process
py
diff --git a/dockermap/build/dockerfile.py b/dockermap/build/dockerfile.py index <HASH>..<HASH> 100644 --- a/dockermap/build/dockerfile.py +++ b/dockermap/build/dockerfile.py @@ -242,7 +242,7 @@ class DockerFile(DockerStringBuffer): context_path = prepare_path(ctx_path, replace_space, True, expandvars, expanduser) else: context_path = target_path - self.prefix('ADD', context_path, target_path) + self.prefix('ADD', source_path, target_path) self._files.append((source_path, context_path)) if remove_final: self._remove_files.add(target_path)
Correct source path in add_file.
py
diff --git a/buildozer/__init__.py b/buildozer/__init__.py index <HASH>..<HASH> 100644 --- a/buildozer/__init__.py +++ b/buildozer/__init__.py @@ -300,13 +300,13 @@ class Buildozer(object): adderror = errors.append if not get('app', 'title', ''): adderror('[app] "title" is missing') - if not get('app', 'package.name', ''): - adderror('[app] "package.name" is missing') if not get('app', 'source.dir', ''): adderror('[app] "source.dir" is missing') package_name = get('app', 'package.name', '') - if package_name[0] in map(str, range(10)): + if not package_name: + adderror('[app] "package.name" is missing') + elif package_name[0] in map(str, range(10)): adderror('[app] "package.name" may not start with a number.') version = get('app', 'version', '')
Rearranged package.name check to avoid crash Buildozer would previously crash if a package name was '', as it checked for zero length *and* tried to check if the first character was a number.
py
diff --git a/benchbuild/utils/download.py b/benchbuild/utils/download.py index <HASH>..<HASH> 100644 --- a/benchbuild/utils/download.py +++ b/benchbuild/utils/download.py @@ -12,6 +12,7 @@ Supported methods: """ import logging import os +from typing import Callable, List, Optional, Type from plumbum import local @@ -20,6 +21,7 @@ from benchbuild.utils.path import flocked LOG = logging.getLogger(__name__) +AnyC = Type[object] def get_hash_of_dirs(directory): """ @@ -261,14 +263,16 @@ def Git(repository, directory, rev=None, prefix=None, shallow_clone=True): return repository_loc -def with_git(repo, - target_dir=None, - limit=None, - refspec="HEAD", - clone=True, - rev_list_args=None, - shallow_clone=True, - version_filter=lambda version: True): +def with_git( + repo: str, + target_dir: str = None, + limit: Optional[int] = None, + refspec: str = "HEAD", + clone: bool = True, + rev_list_args: List[str] = None, + shallow_clone: bool = True, + version_filter: Callable[[str], bool] = lambda version: True +) -> Callable[[AnyC], AnyC]: """ Decorate a project class with git-based version information.
utils/download: add type annotations to with_git
py
diff --git a/acme_tiny.py b/acme_tiny.py index <HASH>..<HASH> 100644 --- a/acme_tiny.py +++ b/acme_tiny.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -import argparse, subprocess, json, os, urllib2, sys, base64, binascii, time, \ +import argparse, subprocess, json, os, os.path, urllib2, sys, base64, binascii, time, \ hashlib, re, copy, textwrap #CA = "https://acme-staging.api.letsencrypt.org" @@ -111,8 +111,7 @@ def get_crt(account_key, csr, acme_dir): # make the challenge file challenge = [c for c in json.loads(result)['challenges'] if c['type'] == "http-01"][0] keyauthorization = "{0}.{1}".format(challenge['token'], thumbprint) - acme_dir = acme_dir[:-1] if acme_dir.endswith("/") else acme_dir - wellknown_path = "{0}/{1}".format(acme_dir, challenge['token']) + wellknown_path = os.path.join(acme_dir, challenge['token']) wellknown_file = open(wellknown_path, "w") wellknown_file.write(keyauthorization) wellknown_file.close()
Join paths platform-neutrally Use os.path to join paths in a more platform-neutral fashion
py
diff --git a/tests/test_accuracy.py b/tests/test_accuracy.py index <HASH>..<HASH> 100644 --- a/tests/test_accuracy.py +++ b/tests/test_accuracy.py @@ -14,6 +14,7 @@ arch_data = { # (steps, [hit addrs], finished) } def emulate(arch): + print 'For', arch steps, hit_addrs, finished = arch_data[arch] filepath = test_location + arch + '/test_arrays' p = angr.Project(filepath, use_sim_procedures=False) @@ -33,6 +34,9 @@ def emulate(arch): else: raise ValueError("This pathgroup does not contain a path we can use for this test?") + for x in path.backtrace: + print x + nose.tools.assert_greater_equal(path.length, steps) for addr in hit_addrs: nose.tools.assert_in(addr, path.addr_backtrace)
Add debug printing so I can tell what the hell is going on
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -14,7 +14,7 @@ setup( author='Tim Heap', author_email='[email protected]', url='https://bitbucket.org/ionata/django-bleach', - packages=['django_bleach'], + packages=find_packages(), install_requires=['bleach'], package_data={}, classifiers=[
Use `find_packages()` instead of naming packages The `templatetags/` files were missed because they were not named. Using `find_packages()` will ensure this does not happen again.
py
diff --git a/bcbio/structural/cnvkit.py b/bcbio/structural/cnvkit.py index <HASH>..<HASH> 100644 --- a/bcbio/structural/cnvkit.py +++ b/bcbio/structural/cnvkit.py @@ -78,7 +78,7 @@ def _run_cnvkit_cancer(items, background, access_file): work_dir = _sv_workdir(items[0]) ckout = _run_cnvkit_shared(items[0], [paired.tumor_bam], [paired.normal_bam], access_file, work_dir, background_name=paired.normal_name) - ckout = theta.run(ckout, paired) + #ckout = theta.run(ckout, paired) return _associate_cnvkit_out(ckout, items) def _run_cnvkit_population(items, background, access_file):
CNVkit: skip TheTA post-processing until better tested and incorporate Eric's changes.
py
diff --git a/claripy/bv.py b/claripy/bv.py index <HASH>..<HASH> 100644 --- a/claripy/bv.py +++ b/claripy/bv.py @@ -286,10 +286,12 @@ def Concat(*args): return BVV(total_value, total_bits) def RotateRight(self, bits): - return LShR(self, bits) | (self << (self.size()-bits)) + bits_smaller = bits % self.size() + return LShR(self, bits_smaller) | (self << (self.size()-bits_smaller)) def RotateLeft(self, bits): - return (self << bits) | (LShR(self, (self.size()-bits))) + bits_smaller = bits % self.size() + return (self << bits_smaller) | (LShR(self, (self.size()-bits_smaller))) def Reverse(a): size = a.size()
Make rotateleft and rotateright work correctly for overlarge rotations
py
diff --git a/airflow/models.py b/airflow/models.py index <HASH>..<HASH> 100644 --- a/airflow/models.py +++ b/airflow/models.py @@ -131,7 +131,12 @@ class DagBag(object): Given a path to a python module, this method imports the module and look for dag objects whithin it. """ - dttm = datetime.fromtimestamp(os.path.getmtime(filepath)) + try: + # This failed before in what may have been a git sync + # race condition + dttm = datetime.fromtimestamp(os.path.getmtime(filepath)) + except: + dttm = datetime(2001, 1, 1) mod_name, file_ext = os.path.splitext(os.path.split(filepath)[-1]) mod_name = 'unusual_prefix_' + mod_name
Fixing file timestamp read race condition
py
diff --git a/prudentia/utils/provisioning.py b/prudentia/utils/provisioning.py index <HASH>..<HASH> 100644 --- a/prudentia/utils/provisioning.py +++ b/prudentia/utils/provisioning.py @@ -20,7 +20,8 @@ def run_playbook(playbook_file, inventory_file, loader, remote_user=C.DEFAULT_RE variable_manager = VariableManager() variable_manager.extra_vars = {} if extra_vars is None else extra_vars - inventory.HOSTS_PATTERNS_CACHE = {} # before each run clean up previous cached hosts + inventory.HOSTS_PATTERNS_CACHE = {} # clean up previous cached hosts + loader._FILE_CACHE = dict() # clean up previously read and cached file inv = inventory.Inventory( loader=loader, variable_manager=variable_manager, @@ -48,7 +49,8 @@ def run_play(play_ds, inventory_file, loader, remote_user, remote_pass, transpor variable_manager = VariableManager() variable_manager.extra_vars = {} if extra_vars is None else extra_vars - inventory.HOSTS_PATTERNS_CACHE = {} # before each run clean up previous cached hosts + inventory.HOSTS_PATTERNS_CACHE = {} # clean up previous cached hosts + loader._FILE_CACHE = dict() # clean up previously read and cached file inv = inventory.Inventory( loader=loader, variable_manager=variable_manager,
fix(run): Cleans up loader file cache before each run (avoids provisioning with cached playbooks)
py
diff --git a/volatility/vmi.py b/volatility/vmi.py index <HASH>..<HASH> 100644 --- a/volatility/vmi.py +++ b/volatility/vmi.py @@ -26,7 +26,7 @@ import volatility.addrspace as addrspace libvmi = None try: import libvmi - from libvmi import Libvmi, CR3 + from libvmi import Libvmi, X86Reg except ImportError: pass @@ -54,7 +54,7 @@ class VMIAddressSpace(addrspace.BaseAddressSpace): domain = config.LOCATION[len("vmi://"):] self.vmi = Libvmi(domain, partial=True) - self.dtb = self.vmi.get_vcpu_reg(CR3, 0) + self.dtb = self.vmi.get_vcpu_reg(X86Reg.CR3.value, 0) def close(self): self.vmi.destroy() @@ -67,10 +67,7 @@ class VMIAddressSpace(addrspace.BaseAddressSpace): return buffer def zread(self, addr, length): - buffer, bytes_read = self.vmi.read_pa(addr, length) - if bytes_read != length: - # fill with zeroes - buffer += bytes(length - bytes_read).decode() + buffer, bytes_read = self.vmi.read_pa(addr, length, padding=True) return buffer def write(self, addr, data):
fixed issues in volatility address space zread() method
py
diff --git a/hdbscan/hdbscan_.py b/hdbscan/hdbscan_.py index <HASH>..<HASH> 100644 --- a/hdbscan/hdbscan_.py +++ b/hdbscan/hdbscan_.py @@ -829,7 +829,12 @@ class HDBSCAN(BaseEstimator, ClusterMixin): if self.metric != 'precomputed': X = check_array(X, accept_sparse='csr') self._raw_data = X + elif issparse(X): + # Handle sparse precomputed distance matrices separately + X = check_array(X, accept_sparse='csr') else: + # Only non-sparse, precomputed distance matrices are allowed + # to have numpy.inf values indicating missing distances check_precomputed_distance_matrix(X) kwargs = self.get_params()
handle 2nd sparse matrix validation
py
diff --git a/src/ossos-pipeline/ossos/fitsviewer/displayable.py b/src/ossos-pipeline/ossos/fitsviewer/displayable.py index <HASH>..<HASH> 100644 --- a/src/ossos-pipeline/ossos/fitsviewer/displayable.py +++ b/src/ossos-pipeline/ossos/fitsviewer/displayable.py @@ -261,26 +261,32 @@ class Marker(object): self.circle = plt.Circle((x, y), radius, color="b", fill=False) self.crosshair_scaling = 2 - linewidth = 0.5 + + crosshair_colour = "w" + linewidth = 1 self.left_hair = plt.Line2D( self._get_left_x_extent(), self._get_horizontal_y_extent(), + color=crosshair_colour, linewidth=linewidth) self.right_hair = plt.Line2D( self._get_right_x_extent(), self._get_horizontal_y_extent(), + color=crosshair_colour, linewidth=linewidth) self.top_hair = plt.Line2D( self._get_vertical_x_extent(), self._get_top_y_extent(), + color=crosshair_colour, linewidth=linewidth) self.bottom_hair = plt.Line2D( self._get_vertical_x_extent(), self._get_bottom_y_extent(), + color=crosshair_colour, linewidth=linewidth) @property
Made crosshair white and slightly thicker to improve visibility.
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -19,8 +19,8 @@ with open(join(here, "README.rst"), encoding="utf-8") as f: REQUIRES = ["pytz"] -if sys.version_info == (2, 7): - REQUIRES.extend("enum34") +if sys.version_info.major < 3: + REQUIRES.extend(["enum34"]) setup( name="hdate",
Fix requirements for python <I>
py
diff --git a/addok/config/default.py b/addok/config/default.py index <HASH>..<HASH> 100644 --- a/addok/config/default.py +++ b/addok/config/default.py @@ -73,6 +73,8 @@ RESULTS_COLLECTORS_PYPATHS = [ 'addok.helpers.collectors.bucket_with_meaningful', 'addok.helpers.collectors.reduce_with_other_commons', 'addok.helpers.collectors.ensure_geohash_results_are_included_if_center_is_given', # noqa + 'addok.fuzzy.fuzzy_collector', + 'addok.autocomplete.autocomplete_meaningful_collector', 'addok.helpers.collectors.extend_results_extrapoling_relations', 'addok.helpers.collectors.extend_results_reducing_tokens', ]
fuzzy and autocomplete collectors in default processors
py
diff --git a/poetry/utils/env.py b/poetry/utils/env.py index <HASH>..<HASH> 100644 --- a/poetry/utils/env.py +++ b/poetry/utils/env.py @@ -723,6 +723,19 @@ class Env(object): """ bin_path = (self._bin_dir / bin).with_suffix(".exe" if self._is_windows else "") if not bin_path.exists(): + # On Windows, some executables can be in the base path + # This is especially true when installing Python with + # the official installer, where python.exe will be at + # the root of the env path. + # This is an edge case and should not be encountered + # in normal uses but this happens in the sonnet script + # that creates a fake virtual environment pointing to + # a base Python install. + if self._is_windows: + bin_path = (self._path / bin).with_suffix(".exe") + if bin_path.exists(): + return str(bin_path) + return bin return str(bin_path)
Add a small fix for virtual envs pointing at a base Python install
py
diff --git a/geth/wrapper.py b/geth/wrapper.py index <HASH>..<HASH> 100644 --- a/geth/wrapper.py +++ b/geth/wrapper.py @@ -145,6 +145,8 @@ def construct_popen_command(data_dir=None, suffix_kwargs=None, shh=None, allow_insecure_unlock=None, + tx_pool_global_slots=None, + tx_pool_price_limit=None, cache=None): if geth_executable is None: geth_executable = get_geth_binary_path() @@ -249,6 +251,12 @@ def construct_popen_command(data_dir=None, if allow_insecure_unlock: builder.append('--allow-insecure-unlock') + if tx_pool_global_slots is not None: + builder.extend(('--txpool.globalslots', tx_pool_global_slots)) + + if tx_pool_price_limit is not None: + builder.extend(('--txpool.pricelimit', tx_pool_price_limit)) + if cache: builder.extend(('--cache', cache))
feat: tx pool args (#<I>) * feat: tx pool args * fix: single quotes
py
diff --git a/dynetx/test/test_assortativity.py b/dynetx/test/test_assortativity.py index <HASH>..<HASH> 100644 --- a/dynetx/test/test_assortativity.py +++ b/dynetx/test/test_assortativity.py @@ -128,7 +128,6 @@ class ConformityTestCase(unittest.TestCase): for _, val in t.items(): self.assertIsInstance(val, list) for _, c in val: - print(c) self.assertTrue(-1 <= float("{:.4f}".format(c)) <= 1) os.remove("sliding_conformity.json")
:arrow_up: path bugfix
py
diff --git a/pysos/utils.py b/pysos/utils.py index <HASH>..<HASH> 100644 --- a/pysos/utils.py +++ b/pysos/utils.py @@ -203,13 +203,19 @@ class WorkflowDict(object): self.set(key, value) def __cmp_values__(self, A, B): - C = A == B - if isinstance(C, bool): - return C - elif hasattr(C, '__iter__'): - return all(C) - else: - env.logger.warning('Failed to compare "{}" and "{}"'.format(A, B)) + try: + C = A == B + if isinstance(C, bool): + return C + # numpy has this func + if hasattr(C, 'all'): + return C.all() + elif hasattr(C, '__iter__'): + return all(C) + else: + raise ValueError('Unknown comparison result "{}"'.format(short_repr(C))) + except Exception as e: + env.logger.warning('Failed to compare "{}" and "{}": {}'.format(short_repr(A), short_repr(B), e)) return False def check_readonly_vars(self):
Fix comparison of 2-d array in numpy
py
diff --git a/abilian/web/forms/fields.py b/abilian/web/forms/fields.py index <HASH>..<HASH> 100644 --- a/abilian/web/forms/fields.py +++ b/abilian/web/forms/fields.py @@ -509,7 +509,14 @@ class QuerySelect2Field(SelectFieldBase): def pre_validate(self, form): if not self.allow_blank or self.data is not None: - data = set(self.data if self.multiple else [self.data]) + data = self.data + if not self.multiple: + data = [data] if data is not None else [] + elif not data: + # multiple values: ensure empty list (data may be None) + data = [] + + data = set(data) valid = {obj for pk, obj in self._get_object_list()} if (data - valid): raise ValidationError(self.gettext('Not a valid choice'))
queryselect2field: fix TB when field.multiple and data is None
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,7 @@ #!/usr/bin/env python -from distutils.core import setup +from setuptools import setup + setup(name='dtw', version='1.0', @@ -10,5 +11,8 @@ setup(name='dtw', url='https://github.com/pierre-rouanet/dtw', license='GNU GENERAL PUBLIC LICENSE Version 3', + install_requires=['numpy'], + setup_requires=['setuptools_git >= 0.3', ], + py_modules=['dtw'], )
Switch from distils to setuptools in setup.py
py
diff --git a/bakery/project/views.py b/bakery/project/views.py index <HASH>..<HASH> 100644 --- a/bakery/project/views.py +++ b/bakery/project/views.py @@ -120,11 +120,7 @@ def setup(project_id): def fonts(project_id): # this page can be visible by others, not only by owner p = Project.query.get_or_404(project_id) - if p.config['local'].get('setup', None): - return render_template('project/fonts.html', project=p) - else: - return redirect(url_for('project.setup', project_id=p.id)) - + return render_template('project/fonts.html', project=p) @project.route('/<int:project_id>/license', methods=['GET']) @login_required
Allow fonts.html to be viewed before setup complete
py
diff --git a/ELiDE/ELiDE/board/arrow.py b/ELiDE/ELiDE/board/arrow.py index <HASH>..<HASH> 100644 --- a/ELiDE/ELiDE/board/arrow.py +++ b/ELiDE/ELiDE/board/arrow.py @@ -110,12 +110,16 @@ def _get_points_first_part(orig, dest, taillen): ow, oh = orig.size dx, dy = dest.center dw, dh = dest.size + # Flip the endpoints around so that the arrow faces up and right. + # We'll flip it back at the end as needed. xco = 1 if ox < dx else -1 yco = 1 if oy < dy else -1 ox *= xco dx *= xco oy *= yco dy *= yco + # Nudge my endpoints so that I start and end at the edge of + # a Spot. if dy - oy > dx - ox: topy = dy - dh / 2 boty = oy + oh / 2 @@ -126,6 +130,9 @@ def _get_points_first_part(orig, dest, taillen): rightx = dx - dw / 2 topy = dy boty = oy + # Degenerate cases. + # Also, these need to be handled specially to avoid + # division by zero later on. if rightx == leftx: return up_and_down(orig, dest, taillen) if topy == boty:
Add some comments to arrow.py
py
diff --git a/test/performance/test.py b/test/performance/test.py index <HASH>..<HASH> 100644 --- a/test/performance/test.py +++ b/test/performance/test.py @@ -71,8 +71,7 @@ def run_tests(build=None, data_dir='./'): print("Starting server with cache_size " + str(settings["cache_size"]) + " MB...", end=' ') sys.stdout.flush() - metacluster = driver.Metacluster() - serverFiles = driver.Files(metacluster, settings["name"], db_path=os.path.join(data_dir, settings["name"])) + serverFiles = driver.Files(server_name=settings["name"], db_path=os.path.join(data_dir, settings["name"])) with driver.Process(files=serverFiles, executable_path=executable_path, extra_options=['--cache-size', str(settings["cache_size"])]) as server:
Removed metacluster from performance test again
py
diff --git a/codenerix_pos/models.py b/codenerix_pos/models.py index <HASH>..<HASH> 100644 --- a/codenerix_pos/models.py +++ b/codenerix_pos/models.py @@ -167,6 +167,9 @@ class POSHardware(CodenerixModel): fields.append(('value', _("Value"))) return fields + def get_config(self): + return json.loads(self.config) + def save(self, *args, **kwargs): if 'doreset' in kwargs: doreset = kwargs.pop('doreset')
Return config of poshardware
py
diff --git a/thumbor/handlers/__init__.py b/thumbor/handlers/__init__.py index <HASH>..<HASH> 100644 --- a/thumbor/handlers/__init__.py +++ b/thumbor/handlers/__init__.py @@ -300,18 +300,20 @@ class ContextHandler(BaseHandler): def initialize(self, context): self.context = Context(context.server, context.config, context.modules.importer, self) - def _handle_request_exception(self, e): - try: - exc_info = sys.exc_info() - msg = traceback.format_exception(exc_info[0], exc_info[1], exc_info[2]) + def log_exception(self, *exc_info): + if isinstance(value, tornado.web.HTTPError): + # Delegate HTTPError's to the base class + # We don't want these through normal exception handling + return super(ContextHandler, self).log_exception(*exc_info) + + msg = traceback.format_exception(*exc_info) + try: if self.context.config.USE_CUSTOM_ERROR_HANDLING: self.context.modules.importer.error_handler.handle_error(context=self.context, handler=self, exception=exc_info) - finally: del exc_info logger.error('ERROR: %s' % "".join(msg)) - self.send_error(500) ##
Don't log HTTPError objects from tornado
py
diff --git a/csg/core.py b/csg/core.py index <HASH>..<HASH> 100644 --- a/csg/core.py +++ b/csg/core.py @@ -334,11 +334,12 @@ class CSG(object): for j in range(0, stacks): vertices = [] appendVertex(vertices, i * dTheta, j * dPhi) + i1, j1 = (i + 1) % slices, j + 1 if j > 0: - appendVertex(vertices, (i + 1) * dTheta, j * dPhi) + appendVertex(vertices, i1 * dTheta, j * dPhi) if j < stacks - 1: - appendVertex(vertices, (i + 1) * dTheta, (j + 1) * dPhi) - appendVertex(vertices, i * dTheta, (j + 1) * dPhi) + appendVertex(vertices, i1 * dTheta, j1 * dPhi) + appendVertex(vertices, i * dTheta, j1 * dPhi) polygons.append(Polygon(vertices)) return CSG.fromPolygons(polygons)
working on improving the accuracy of shapes with a periodicity along one direction
py
diff --git a/airflow/providers/google/cloud/example_dags/example_bigquery_queries.py b/airflow/providers/google/cloud/example_dags/example_bigquery_queries.py index <HASH>..<HASH> 100644 --- a/airflow/providers/google/cloud/example_dags/example_bigquery_queries.py +++ b/airflow/providers/google/cloud/example_dags/example_bigquery_queries.py @@ -105,7 +105,7 @@ for location in [None, LOCATION]: configuration={ "query": { "query": INSERT_ROWS_QUERY, - "useLegacySql": "False", + "useLegacySql": False, } }, location=location,
Fix typo in example (#<I>) False should not be passed as a string
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -13,7 +13,7 @@ config = { 'download_url': 'https://github.com/mikejarrett', 'author_email': '[email protected]', 'version': pipcheck.__version__, - 'install_requires': ['nose'], + 'install_requires': ['pip'], 'packages': ['pipcheck'], 'scripts': [], 'name': 'pip-checker',
Remove nose from required packages, add pip
py
diff --git a/tests/unit/modules/kmod_test.py b/tests/unit/modules/kmod_test.py index <HASH>..<HASH> 100644 --- a/tests/unit/modules/kmod_test.py +++ b/tests/unit/modules/kmod_test.py @@ -3,8 +3,11 @@ :codeauthor: :email:`Jayesh Kariya <[email protected]>` ''' +# Import Python libs +import os + # Import Salt Testing Libs -from salttesting import TestCase +from salttesting import TestCase, skipIf from salttesting.mock import MagicMock, patch # Import Salt Libs @@ -51,6 +54,7 @@ class KmodTestCase(TestCase): # 'mod_list' function tests: 1 + @skipIf(not os.path.isfile('/etc/modules'), '/etc/modules not present') def test_mod_list(self): ''' Tests return a list of the loaded module names
Skip kmod test if /etc/modules isn't present
py
diff --git a/auth_backends/__init__.py b/auth_backends/__init__.py index <HASH>..<HASH> 100644 --- a/auth_backends/__init__.py +++ b/auth_backends/__init__.py @@ -3,4 +3,4 @@ These package is designed to be used primarily with Open edX Django projects, but should be compatible with non-edX projects as well. """ -__version__ = '2.0.0' # pragma: no cover +__version__ = '2.0.1' # pragma: no cover
Create new Version for auth-backends for release
py
diff --git a/atrcopy/__init__.py b/atrcopy/__init__.py index <HASH>..<HASH> 100755 --- a/atrcopy/__init__.py +++ b/atrcopy/__init__.py @@ -1,4 +1,4 @@ -__version__ = "2.3.2" +__version__ = "2.3.3" try: import numpy as np
Updated version number to <I>
py
diff --git a/versionner/utils.py b/versionner/utils.py index <HASH>..<HASH> 100644 --- a/versionner/utils.py +++ b/versionner/utils.py @@ -3,11 +3,13 @@ import platform import sys -import pkg_resources +from distutils.version import LooseVersion def validate_python_version(): """Validate python interpreter version. Only 3.3+ allowed.""" - if pkg_resources.parse_version(platform.python_version()) < pkg_resources.parse_version('3.3.0'): + python_version = LooseVersion(platform.python_version()) + minimal_version = LooseVersion('3.3.0') + if python_version < minimal_version: print("Sorry, Python 3.3+ is required") sys.exit(1)
better way to compare versions - previous one failed on Ubuntu with python3 in version: <I>+ (look at + sign)
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -48,7 +48,7 @@ setup( # https://packaging.python.org/en/latest/requirements.html install_requires=[ - 'django>=1.8,<1.99' + 'django>=1.8,<1.9.99' ], extras_require={}, package_data={},
Fix django version in setup
py
diff --git a/ags_publishing_tools/api.py b/ags_publishing_tools/api.py index <HASH>..<HASH> 100644 --- a/ags_publishing_tools/api.py +++ b/ags_publishing_tools/api.py @@ -47,7 +47,7 @@ class Api: else: request = urllib2.Request(url) request.get_method = lambda: method - response = urllib2.urlopen(request, json.dumps(params)) + response = urllib2.urlopen(request, json.dumps(encoded_params)) # request.add_header('Content-Type', 'application/json') response_text = response.read()
Encodes post params BPFG-<I>
py
diff --git a/monstro/views/api/mixins.py b/monstro/views/api/mixins.py index <HASH>..<HASH> 100644 --- a/monstro/views/api/mixins.py +++ b/monstro/views/api/mixins.py @@ -2,7 +2,7 @@ class ModelAPIMixin(object): async def options(self, *args, **kwargs): self.finish({ - 'fields': await self.form_class.get_options(), + 'fields': await (await self.get_form_class()).get_options(), 'lookup_field': await self.get_lookup_field(), 'search_fields': await self.get_search_fields(), 'search_query_argument': await self.get_search_query_argument()
views.api: fixed obtaining form options.
py
diff --git a/aquarius/events/events_monitor.py b/aquarius/events/events_monitor.py index <HASH>..<HASH> 100644 --- a/aquarius/events/events_monitor.py +++ b/aquarius/events/events_monitor.py @@ -35,7 +35,7 @@ from aquarius.events.util import get_metadata_contract logger = logging.getLogger(__name__) -debug_log = logger.info +debug_log = logger.debug class EventsMonitor:
revert changing of debug log to info log.
py
diff --git a/usb1/testUSB1.py b/usb1/testUSB1.py index <HASH>..<HASH> 100644 --- a/usb1/testUSB1.py +++ b/usb1/testUSB1.py @@ -115,8 +115,7 @@ class USBTransferTests(unittest.TestCase): # No callback transfer.setControl(request_type, request, value, index, buff) - def _testSetBulkOrInterrupt(self, setter_id): - transfer = self.getTransfer() + def _testTransferSetter(self, transfer, setter_id): endpoint = 0x81 def callback(transfer): pass @@ -148,14 +147,14 @@ class USBTransferTests(unittest.TestCase): Simplest test: feed some data, must not raise. Also, test setBuffer/getBuffer. """ - self._testSetBulkOrInterrupt('setBulk') + self._testTransferSetter(self.getTransfer(), 'setBulk') def testSetInterrupt(self): """ Simplest test: feed some data, must not raise. Also, test setBuffer/getBuffer. """ - self._testSetBulkOrInterrupt('setInterrupt') + self._testTransferSetter(self.getTransfer(), 'setInterrupt') def testSetGetCallback(self): transfer = self.getTransfer()
testUSB1: Genericise USBTransfer.set{Bulk,Interrupt} test common method.
py
diff --git a/cassandra/metadata.py b/cassandra/metadata.py index <HASH>..<HASH> 100644 --- a/cassandra/metadata.py +++ b/cassandra/metadata.py @@ -309,7 +309,7 @@ class Metadata(object): # CREATE TABLE statement anyway). if "local_read_repair_chance" in options: val = options.pop("local_read_repair_chance") - options["dc_local_read_repair_chance"] = val + options["dclocal_read_repair_chance"] = val return options
Fix typo in dclocal_read_repair_chance Relates to PYTHON-<I>
py
diff --git a/ghettoq/backends/pyredis.py b/ghettoq/backends/pyredis.py index <HASH>..<HASH> 100644 --- a/ghettoq/backends/pyredis.py +++ b/ghettoq/backends/pyredis.py @@ -28,7 +28,7 @@ class RedisBackend(BaseBackend): database, timeout) def establish_connection(self): - self.port = self.port or DEFAULT_PORT + self.port = int(self.port) or DEFAULT_PORT return Redis(host=self.host, port=self.port, db=self.database, password=self.password)
cast port to int - solves problems when using celerypylons integration
py
diff --git a/salt/utils/network.py b/salt/utils/network.py index <HASH>..<HASH> 100644 --- a/salt/utils/network.py +++ b/salt/utils/network.py @@ -1886,14 +1886,14 @@ def dns_check(addr, port, safe=False, ipv6=None): if h[0] == socket.AF_INET6 and ipv6 is False: continue - candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) + candidate_addr = h[4][0] if h[0] != socket.AF_INET6 or ipv6 is not None: candidates.append(candidate_addr) try: s = socket.socket(h[0], socket.SOCK_STREAM) - s.connect((candidate_addr.strip('[]'), port)) + s.connect((candidate_addr), port)) s.close() resolved = candidate_addr
Don't ip_bracket addresses returned by check_dns. This ends up in opts['master_ip'] where it can cause problems. I found this while testng a git+pip based minion installation on Ubuntu Bionic. I'm not sure why it doesn't affect other targeted OS versions in the test framework. On Bionic, if 'salt' resolves to an IPv6 address, zmq fails to connect to the master, and complains about the bracketed address.
py
diff --git a/programs/thellier_gui.py b/programs/thellier_gui.py index <HASH>..<HASH> 100755 --- a/programs/thellier_gui.py +++ b/programs/thellier_gui.py @@ -4322,6 +4322,7 @@ You can combine multiple measurement files into one measurement file using Pmag # try to make a more meaningful name MagIC_results_data['pmag_results'][sample_or_site]["data_type"] = "i" + MagIC_results_data['pmag_results'][sample_or_site]["data_quality"] = "g" MagIC_results_data['pmag_results'][sample_or_site]["er_citation_names"] = "This study" if self.data_model != 3: # look for ages in er_ages - otherwise they are in sites.txt already # add ages @@ -4447,6 +4448,7 @@ You can combine multiple measurement files into one measurement file using Pmag if len(self.test_for_criteria()): new_data['criteria'] = 'IE-SPEC:IE-SAMP' new_data['result_quality'] = 'g' + new_data['result_type'] = 'i' self.samp_data = self.samp_container.df cond1 = self.samp_data['sample'].str.contains( sample_or_site + "$") == True
update Thellier GUI to definitely have result_type and result_quality when making MagIC tables #<I>
py
diff --git a/mechanicalsoup/browser.py b/mechanicalsoup/browser.py index <HASH>..<HASH> 100644 --- a/mechanicalsoup/browser.py +++ b/mechanicalsoup/browser.py @@ -162,9 +162,11 @@ class Browser(object): webbrowser.open('file://' + file.name) def close(self): - """Close the current session""" - self.session.cookies.clear() - self.session.close() + """Close the current session, if still open.""" + if self.session is not None: + self.session.cookies.clear() + self.session.close() + self.session = None def __del__(self): self.close()
Browser: allow close() to be called multiple times
py
diff --git a/test.py b/test.py index <HASH>..<HASH> 100755 --- a/test.py +++ b/test.py @@ -2,7 +2,11 @@ import glob import sgf -import StringIO + +try: + from StringIO import StringIO +except ImportError: + from io import StringIO for filename in glob.glob("examples/*.sgf"): @@ -17,12 +21,12 @@ for game in collection: for node in game: pass -out = StringIO.StringIO() +out = StringIO() collection[0].nodes[1].output(out) assert out.getvalue() == ";B[aa]" out.close() -out = StringIO.StringIO() +out = StringIO() collection.output(out) assert out.getvalue() == example out.close() @@ -31,7 +35,7 @@ example2 = "(;FF[4]GM[1]SZ[19];B[aa];W[bb](;B[cc];W[dd];B[ad];W[bd])" \ "(;B[hh];W[hg]))" collection = sgf.parse(example2) -out = StringIO.StringIO() +out = StringIO() collection.output(out) assert out.getvalue() == example2 out.close() @@ -39,7 +43,7 @@ out.close() example3 = "(;C[foo\\]\\\\])" collection = sgf.parse(example3) assert collection[0].nodes[0].properties["C"] == ["foo]\\"] -out = StringIO.StringIO() +out = StringIO() collection.output(out) assert out.getvalue() == example3 out.close()
attempt to make tests run in both Python 2 and 3
py
diff --git a/cumulus/storage.py b/cumulus/storage.py index <HASH>..<HASH> 100644 --- a/cumulus/storage.py +++ b/cumulus/storage.py @@ -120,7 +120,8 @@ class SwiftclientStorage(Auth, Storage): self.connection.set_object_metadata(container=self.container_name, obj=name, metadata=headers, - prefix='') + prefix='', + clear=True) else: # TODO gzipped content when using swift client self.connection.put_object(self.container_name, name,
use clear=True to ensure you are not sending headers that will cause the server to ignore your request
py
diff --git a/mamba/loader.py b/mamba/loader.py index <HASH>..<HASH> 100644 --- a/mamba/loader.py +++ b/mamba/loader.py @@ -12,6 +12,7 @@ class describe(object): def __init__(self, subject): self.subject = subject self.locals_before = None + self.context = _Context() def __enter__(self): frame = inspect.currentframe().f_back @@ -29,7 +30,7 @@ class describe(object): frame.f_locals['current_spec'].append(current) frame.f_locals['current_spec'] = current - return _Context() + return self.context @property def _skipped(self):
Instance context with constructor, thus it could be changed later
py
diff --git a/oauthlib/oauth2/rfc6749/grant_types/openid_connect.py b/oauthlib/oauth2/rfc6749/grant_types/openid_connect.py index <HASH>..<HASH> 100644 --- a/oauthlib/oauth2/rfc6749/grant_types/openid_connect.py +++ b/oauthlib/oauth2/rfc6749/grant_types/openid_connect.py @@ -141,6 +141,13 @@ class OpenIDConnectBase(object): def openid_authorization_validator(self, request): """Perform OpenID Connect specific authorization request validation. + nonce + OPTIONAL. String value used to associate a Client session with + an ID Token, and to mitigate replay attacks. The value is + passed through unmodified from the Authentication Request to + the ID Token. Sufficient entropy MUST be present in the nonce + values used to prevent attackers from guessing values + display OPTIONAL. ASCII string value that specifies how the Authorization Server displays the authentication and consent
Add nonce to docstring.
py
diff --git a/usr/share/lib/ipa/tests/SLES/Azure/test_sles_azure_services.py b/usr/share/lib/ipa/tests/SLES/Azure/test_sles_azure_services.py index <HASH>..<HASH> 100644 --- a/usr/share/lib/ipa/tests/SLES/Azure/test_sles_azure_services.py +++ b/usr/share/lib/ipa/tests/SLES/Azure/test_sles_azure_services.py @@ -2,7 +2,7 @@ import pytest @pytest.mark.parametrize('name', [ - ('waagent.service'), + ('waagent'), ]) def test_sles_azure_services(check_service, name): assert check_service(name)
Fix Azure service test on SLES <I> Sysvinit doesn't like the "*.service" extension used with systemctl.
py
diff --git a/pyemu/pst/pst_handler.py b/pyemu/pst/pst_handler.py index <HASH>..<HASH> 100644 --- a/pyemu/pst/pst_handler.py +++ b/pyemu/pst/pst_handler.py @@ -829,9 +829,11 @@ class Pst(object): actual_phi = ((self.res.loc[res_idxs[item], "residual"] * self.observation_data.loc [obs_idxs[item], "weight"])**2).sum() - weight_mult = np.sqrt(target_phis[item] / actual_phi) - self.observation_data.loc[obs_idxs[item], "weight"] *= weight_mult - + if actual_phi > 0.0: + weight_mult = np.sqrt(target_phis[item] / actual_phi) + self.observation_data.loc[obs_idxs[item], "weight"] *= weight_mult + else: + print("Pst.__reset_weights() warning: phi group {0} has zero phi, skipping...".format(item)) def adjust_weights(self,obs_dict=None, obsgrp_dict=None):
bug fix for zero-weight obs groups in reset_weights
py
diff --git a/sos/plugins/startup.py b/sos/plugins/startup.py index <HASH>..<HASH> 100644 --- a/sos/plugins/startup.py +++ b/sos/plugins/startup.py @@ -22,7 +22,7 @@ class startup(Plugin, RedHatPlugin): def setup(self): self.addCopySpec("/etc/rc.d") - self.collectExtOutput("LC_ALL=C /sbin/chkconfig --list", root_symlink = "chkconfig") + self.collectExtOutput("/sbin/chkconfig --list", root_symlink = "chkconfig") if self.getOption('servicestatus'): self.collectExtOutput("/sbin/service --status-all") self.collectExtOutput("/sbin/runlevel")
Fix collection of chkconfig output in startup module Remove "LC_ALL=C" from invocation ofchkconfig --list.
py
diff --git a/pwkit/cli/latexdriver.py b/pwkit/cli/latexdriver.py index <HASH>..<HASH> 100644 --- a/pwkit/cli/latexdriver.py +++ b/pwkit/cli/latexdriver.py @@ -351,7 +351,7 @@ def commandline(argv=None): bib_style = argv[2] auxpath = argv[3] assert auxpath.endswith('.aux') - bibpath = aux[:-4] + '.bib' + bibpath = auxpath[:-4] + '.bib' elif len(argv) == 5: bib_style = argv[2] auxpath = argv[3]
pwkit/cli/latexdriver.py: fix straight-up typo
py